/*! Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one or more contributor license agreements. * Licensed under the Elastic License 2.0; you may not use this file except in compliance with the Elastic License 2.0. */ (window.watcher_bundle_jsonpfunction=window.watcher_bundle_jsonpfunction||[]).push([[1],{35:function(e,t,a){e.exports=a(7)(1466)},36:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var s=a(27),i=a(37),n=s.__importDefault(a(39));t.default=function(e,t){n.default(e,t,i.isDeepEqual)}},37:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isDeepEqual=t.off=t.on=t.isClient=void 0;var s=a(27).__importDefault(a(38));t.isClient="object"==typeof window,t.on=function(e){for(var t=[],a=1;ae.length)&&-1!==e.indexOf(t)}function c(e){for(var t="";e;)t+="0",e-=1;return t}function l(e,t){var a=e+"+"+b(v(t).sort(),(function(e){return e+":"+t[e]})).join(",");return l.cache[a]||(l.cache[a]=Intl.NumberFormat(e,t)),l.cache[a]}function u(e,t,n){var o,r,d,h=t.useToLocaleString,g=t.useGrouping,m=g&&t.grouping.slice(),p=t.maximumSignificantDigits,j=t.minimumIntegerDigits||1,b=t.fractionDigits||0,x=t.groupingSeparator,w=t.decimalSeparator;if(h&&n){var f,y={minimumIntegerDigits:j,useGrouping:g};return b&&(y.maximumFractionDigits=b,y.minimumFractionDigits=b),p&&e>0&&(y.maximumSignificantDigits=p),s?(i||((f=E({},t)).useGrouping=!1,f.decimalSeparator=".",e=parseFloat(u(e,f),10)),l(n,y).format(e)):(a||((f=E({},t)).useGrouping=!1,f.decimalSeparator=".",e=parseFloat(u(e,f),10)),e.toLocaleString(n,y))}var O=(p?e.toPrecision(p+1):e.toFixed(b+1)).split("e");d=O[1]||"",r=(O=O[0].split("."))[1]||"";var v=(o=O[0]||"").length,k=r.length,M=v+k,T=o+r;(p&&M===p+1||!p&&k===b+1)&&((T=function(e){for(var t=e.split("").reverse(),a=0,s=!0;s&&a0?r.length<=S?(o+=r+=c(S-r.length),r=""):(o+=r.slice(0,S),r=r.slice(S)):S<0&&(r=c(Math.abs(S)-o.length)+o+r,o="0"),p||((r=r.slice(0,b)).lengtht.label.length?-1:e.label.length0,G=V?i.precision:0,$=G,K=i.minValue,Y=!1,X=i.maxValue,Z=!1,Q=i.useToLocaleString,ee=i.groupingSeparator,te=i.decimalSeparator,ae=i.grouping;Q=Q&&(t||s);var se=i.trim;g(se)&&(se=se.join(" ")),null===se&&(W||X||V)&&(se="all"),null!==se&&!0!==se&&"left"!==se&&"right"!==se||(se="large"),!1===se&&(se="");var ie=function(e){return e.test(se)},ne=/both/,oe=/^all|[^sm]all/,re=W>0||k([/large/,ne,oe],ie),ce=k([/small/,ne,oe],ie),le=k([/mid/,oe],ie),ue=k([/final/,oe],ie),de=b(J.match(I),(function(e,t){var a=F(e);return"*"===e.slice(0,1)&&(e=e.slice(1),"escape"!==a&&"general"!==a&&D.push(a)),{index:t,length:e.length,text:"",token:"escape"===a?e.replace(A.escape,"$1"):e,type:"escape"===a||"general"===a?null:a}})),he={index:0,length:0,token:"",text:"",type:null},ge=[];R&&de.reverse(),j(de,(function(e){if(e.type)return(he.type||he.text)&&ge.push(he),void(he=e);R?he.text=e.token+he.text:he.text+=e.token})),(he.type||he.text)&&ge.push(he),R&&ge.reverse();var me=y(n,f(w(x(ge,"type"))));if(!me.length)return x(ge,"text").join("");me=b(me,(function(e,t){var a,s=t+1===me.length,n=!t;a="years"===e||"months"===e?S.as(e):T.as(e);var o=Math.floor(a),r=a-o,c=p(ge,(function(t){return e===t.type}));return n&&X&&a>X&&(Z=!0),s&&K&&Math.abs(i.duration.as(e))1&&(H=!0),T.subtract(o,e),S.subtract(o,e),{rawValue:a,wholeValue:o,decimalValue:s?r:0,isSmallest:s,isLargest:n,type:e,tokenLength:c.length}}));var pe,je=q?Math.floor:Math.round,be=function(e,t){var a=Math.pow(10,t);return je(e*a)/a},xe=!1,we=!1,fe=function(e,t){var a={useGrouping:U,groupingSeparator:ee,decimalSeparator:te,grouping:ae,useToLocaleString:Q};return V&&(G<=0?(e.rawValue=0,e.wholeValue=0,e.decimalValue=0):(a.maximumSignificantDigits=G,e.significantDigits=G)),Z&&!we&&(e.isLargest?(e.wholeValue=X,e.decimalValue=0):(e.wholeValue=0,e.decimalValue=0)),Y&&!we&&(e.isSmallest?(e.wholeValue=K,e.decimalValue=0):(e.wholeValue=0,e.decimalValue=0)),e.isSmallest||e.significantDigits&&e.significantDigits-e.wholeValue.toString().length<=0?z<0?e.value=be(e.wholeValue,z):0===z?e.value=je(e.wholeValue+e.decimalValue):V?(e.value=q?be(e.rawValue,G-e.wholeValue.toString().length):e.rawValue,e.wholeValue&&(G-=e.wholeValue.toString().length)):(a.fractionDigits=z,e.value=q?e.wholeValue+be(e.decimalValue,z):e.wholeValue+e.decimalValue):V&&e.wholeValue?(e.value=Math.round(be(e.wholeValue,e.significantDigits-e.wholeValue.toString().length)),G-=e.wholeValue.toString().length):e.value=e.wholeValue,e.tokenLength>1&&(H||xe)&&(a.minimumIntegerDigits=e.tokenLength,we&&a.maximumSignificantDigits0||""===se||p(D,e.type)||p(L,e.type))&&(xe=!0),e.formattedValue=u(e.value,a,P),a.useGrouping=!1,a.decimalSeparator=".",e.formattedValueEn=u(e.value,a,"en"),2===e.tokenLength&&"milliseconds"===e.type&&(e.formattedValueMS=u(e.value,{minimumIntegerDigits:3,useGrouping:!1},"en").slice(0,2)),e};if((me=w(me=b(me,fe))).length>1){var ye=function(e){return p(me,(function(t){return t.type===e}))};j(o,(function(e){var t=ye(e.type);t&&j(e.targets,(function(e){var a=ye(e.type);a&&parseInt(t.formattedValueEn,10)===e.value&&(t.rawValue=0,t.wholeValue=0,t.decimalValue=0,a.rawValue+=1,a.wholeValue+=1,a.decimalValue=0,a.formattedValueEn=a.wholeValue.toString(),we=!0)}))}))}return we&&(xe=!1,G=$,me=w(me=b(me,fe))),!L||Z&&!i.trim?(re&&(me=O(me,(function(e){return!e.isSmallest&&!e.wholeValue&&!p(D,e.type)}))),W&&me.length&&(me=me.slice(0,W)),ce&&me.length>1&&(pe=function(e){return!e.wholeValue&&!p(D,e.type)&&!e.isLargest},me=O(me.slice().reverse(),pe).reverse()),le&&(me=w(me=b(me,(function(e,t){return t>0&&t ",Z=!1,Y=!1),M&&(t.value>0||""===se||p(D,t.type)||p(L,t.type))&&(a+="-",M=!1),"milliseconds"===e.type&&t.formattedValueMS?a+=t.formattedValueMS:a+=t.formattedValue,R||(a+=e.text),a}))).join("").replace(/(,| |:|\.)*$/,"").replace(/^(,| |:|\.)*/,""))}function A(){var e=this.duration,t=function(t){return e._data[t]},a=p(this.types,t),s=function(e,t){for(var a=e.length;a-=1;)if(t(e[a]))return e[a]}(this.types,t);switch(a){case"milliseconds":return"S __";case"seconds":case"minutes":return"*_MS_";case"hours":return"_HMS_";case"days":if(a===s)return"d __";case"weeks":return a===s?"w __":(null===this.trim&&(this.trim="both"),"w __, d __, h __");case"months":if(a===s)return"M __";case"years":return a===s?"y __":(null===this.trim&&(this.trim="both"),"y __, M __, d __");default:return null===this.trim&&(this.trim="both"),"y __, d __, h __, m __, s __"}}function F(e){if(!e)throw"Moment Duration Format init cannot find moment instance.";e.duration.format=S,e.duration.fn.format=_,e.duration.fn.format.defaults={trim:null,stopTrim:null,largest:null,maxValue:null,minValue:null,precision:0,trunc:!1,forceLength:null,userLocale:null,usePlural:!0,useLeftUnits:!1,useGrouping:!0,useSignificantDigits:!1,template:A,useToLocaleString:!0,groupingSeparator:",",decimalSeparator:".",grouping:[3]},e.updateLocale("en",h)}var I=function(e,t,a){return e.toLocaleString(t,a)};t=function(){try{(0).toLocaleString("i")}catch(e){return"RangeError"===e.name}return!1}()&&T(I),a=t&&M(I);var J=function(e,t,a){if("undefined"!=typeof window&&window&&window.Intl&&window.Intl.NumberFormat)return window.Intl.NumberFormat(t,a).format(e)};return s=T(J),i=s&&M(J),F(e),F},i=[a(25)],void 0===(n="function"==typeof(s=r)?s.apply(t,i):s)||(e.exports=n),o&&(o.momentDurationFormatSetup=o.moment?r(o.moment):r)},41:function(e,t,a){"use strict";a.r(t),a.d(t,"renderApp",(function(){return Zt}));var s=a(16),i=a.n(s),n=a(30),o=a(21),r=a(22),c=a(24),l=a(35),u=a.n(l);const d={services:{}},h=Object(s.createContext)(d);var g=a(36),m=a.n(g),p=a(17);const j=({children:e,component:t,render:a,...n})=>{const o=Object(s.useMemo)((()=>{if(t)return e=>Object(p.jsx)(i.a.Fragment,null,Object(p.jsx)(b,null),Object(p.jsx)(t,e))}),[t]);if(o)return Object(p.jsx)(c.Route,u()({},n,{component:o}));if(a||"function"==typeof e){const t="function"==typeof e?e:a;return Object(p.jsx)(c.Route,u()({},n,{render:e=>Object(p.jsx)(i.a.Fragment,null,Object(p.jsx)(b,null),t(e))}))}return Object(p.jsx)(c.Route,n,Object(p.jsx)(b,null),e)},b=()=>{const{executionContext:e}=Object(s.useContext)(h).services,t=Object(c.useRouteMatch)();return function(e,t){m()((()=>(null==e||e.set(t),()=>{null==e||e.clear()})),[t])}(e,{type:"application",page:t.path,id:Object.keys(t.params).length>0?JSON.stringify(t.params):void 0}),null};var x=a(28);const w=({children:e,...t})=>Object(p.jsx)(c.Router,t,Object(p.jsx)(x.CompatRouter,null,e));var f=a(19),y=a.n(f);const O=({legacySwitch:e=!0,children:t})=>{const a=Object(c.useRouteMatch)();return e?Object(p.jsx)(c.Switch,null,t):Object(p.jsx)(x.Routes,null,s.Children.map(t,(e=>{if(i.a.isValidElement(e)&&e.type===j){var s;const n=Object(f.replace)(null==e?void 0:e.props.path,a.url+"/",""),o="function"==typeof(null==e?void 0:e.props.children)?null==e?void 0:e.props.children:null==e?void 0:e.props.render;return Object(p.jsx)(x.Route,{path:n,element:Object(p.jsx)(i.a.Fragment,null,Object(p.jsx)(b,null),(null==e||null===(s=e.props)||void 0===s?void 0:s.component)&&Object(p.jsx)(e.props.component,null)||o&&o()||t)})}return e})))};var E=a(18),v=a(0),k=a(20);const M={text:v.i18n.translate("xpack.watcher.breadcrumb.listLabel",{defaultMessage:"Watcher"}),href:"/watches"},T={text:v.i18n.translate("xpack.watcher.breadcrumb.createLabel",{defaultMessage:"Create"})},S={text:v.i18n.translate("xpack.watcher.breadcrumb.editLabel",{defaultMessage:"Edit"})},_={text:v.i18n.translate("xpack.watcher.breadcrumb.statusLabel",{defaultMessage:"Status"})};class Settings{constructor(e){this.actionTypes=e.actionTypes}static fromUpstreamJson(e){const t=e.action_types;return new Settings({actionTypes:t})}}var A=a(4),F=a.n(A),I=a(23),J=a(2),L=a(29);class base_action_BaseAction{constructor(e={}){this.id=Object(f.get)(e,"id"),this.type=Object(f.get)(e,"type"),this.isNew=Object(f.get)(e,"isNew",!1)}get upstreamJson(){return{id:this.id,type:this.type}}get typeName(){return this.constructor.typeName}get iconClass(){return this.constructor.iconClass}get selectMessage(){return this.constructor.selectMessage}get simulateMessage(){return v.i18n.translate("xpack.watcher.models.baseAction.simulateMessage",{defaultMessage:"Action {id} simulated successfully",values:{id:this.id}})}get simulatePrompt(){return this.constructor.simulatePrompt}}F()(base_action_BaseAction,"typeName",v.i18n.translate("xpack.watcher.models.baseAction.typeName",{defaultMessage:"Action"})),F()(base_action_BaseAction,"iconClass","apps"),F()(base_action_BaseAction,"selectMessage",v.i18n.translate("xpack.watcher.models.baseAction.selectMessageText",{defaultMessage:"Perform an action."})),F()(base_action_BaseAction,"simulatePrompt",v.i18n.translate("xpack.watcher.models.baseAction.simulateButtonLabel",{defaultMessage:"Simulate this action now"}));class email_action_EmailAction extends base_action_BaseAction{constructor(e={}){super(e);const t=Object(f.get)(e,"to");this.to=Object(f.isArray)(t)?t:t&&[t];const a=v.i18n.translate("xpack.watcher.models.emailAction.defaultSubjectText",{defaultMessage:"Watch [{context}] has exceeded the threshold",values:{context:"{{ctx.metadata.name}}"}});this.subject=Object(f.get)(e,"subject",e.ignoreDefaults?null:a),this.body=Object(f.get)(e,"body")}validate(){const e={to:[]};return this.to&&this.to.length||e.to.push(v.i18n.translate("xpack.watcher.watchActions.email.emailRecipientIsRequiredValidationMessage",{defaultMessage:'"To" email address is required.'})),e}get upstreamJson(){const e=super.upstreamJson;return Object.assign(e,{to:this.to,subject:this.subject,body:this.body,email:{to:this.to&&this.to.length>0?this.to:void 0,subject:this.subject,body:{text:this.body}}}),e}get simulateMessage(){const e=this.to.join(", ");return v.i18n.translate("xpack.watcher.models.emailAction.simulateMessage",{defaultMessage:"Sample email sent to {toList}",values:{toList:e}})}get simulateFailMessage(){const e=this.to.join(", ");return v.i18n.translate("xpack.watcher.models.emailAction.simulateFailMessage",{defaultMessage:"Failed to send email to {toList}.",values:{toList:e}})}static fromUpstreamJson(e){return new email_action_EmailAction(e)}}F()(email_action_EmailAction,"typeName",v.i18n.translate("xpack.watcher.models.emailAction.typeName",{defaultMessage:"Email"})),F()(email_action_EmailAction,"iconClass","email"),F()(email_action_EmailAction,"selectMessage",v.i18n.translate("xpack.watcher.models.emailAction.selectMessageText",{defaultMessage:"Send an email from your server."})),F()(email_action_EmailAction,"simulatePrompt",v.i18n.translate("xpack.watcher.models.emailAction.simulateButtonLabel",{defaultMessage:"Send test email"}));class logging_action_LoggingAction extends base_action_BaseAction{constructor(e={}){super(e);const t=v.i18n.translate("xpack.watcher.models.loggingAction.defaultText",{defaultMessage:"Watch [{context}] has exceeded the threshold",values:{context:"{{ctx.metadata.name}}"}});this.text=Object(f.get)(e,"text",e.ignoreDefaults?null:t)}validate(){const e={text:[]};return this.text||e.text.push(v.i18n.translate("xpack.watcher.watchActions.logging.logTextIsRequiredValidationMessage",{defaultMessage:"Log text is required."})),e}get upstreamJson(){const e=super.upstreamJson;let t;return"string"==typeof this.text?this.text.trim()&&(t=this.text):t=this.text,Object.assign(e,{text:t,logging:{text:t}}),e}get simulateMessage(){return v.i18n.translate("xpack.watcher.models.loggingAction.simulateMessage",{defaultMessage:"Sample message logged"})}get simulateFailMessage(){return v.i18n.translate("xpack.watcher.models.loggingAction.simulateFailMessage",{defaultMessage:"Failed to log sample message."})}static fromUpstreamJson(e){return new logging_action_LoggingAction(e)}}F()(logging_action_LoggingAction,"typeName",v.i18n.translate("xpack.watcher.models.loggingAction.typeName",{defaultMessage:"Logging"})),F()(logging_action_LoggingAction,"iconClass","logsApp"),F()(logging_action_LoggingAction,"selectMessage",v.i18n.translate("xpack.watcher.models.loggingAction.selectMessageText",{defaultMessage:"Add an item to the logs."})),F()(logging_action_LoggingAction,"simulatePrompt",v.i18n.translate("xpack.watcher.models.loggingAction.simulateButtonLabel",{defaultMessage:"Log a sample message"}));class slack_action_SlackAction extends base_action_BaseAction{constructor(e={}){super(e);const t=Object(f.get)(e,"to");this.to=Object(f.isArray)(t)?t:t&&[t];const a=v.i18n.translate("xpack.watcher.models.slackAction.defaultText",{defaultMessage:"Watch [{context}] has exceeded the threshold",values:{context:"{{ctx.metadata.name}}"}});this.text=Object(f.get)(e,"text",e.ignoreDefaults?null:a)}validate(){return{to:[],text:[]}}get upstreamJson(){const e=super.upstreamJson,t=this.to&&this.to.length>0?this.to:void 0,a=this.text||t?{text:this.text,to:t}:{};return Object.assign(e,{to:t,text:this.text,slack:{message:a}}),e}get simulateMessage(){const e=this.to&&this.to.join(", ");return v.i18n.translate("xpack.watcher.models.slackAction.simulateMessage",{defaultMessage:"Sample Slack message sent {toList}.",values:{toList:e?`to ${e}`:""}})}get simulateFailMessage(){const e=this.to&&this.to.join(", ");return v.i18n.translate("xpack.watcher.models.slackAction.simulateFailMessage",{defaultMessage:"Failed to send sample Slack message {toList}.",values:{toList:e?`to ${e}`:""}})}static fromUpstreamJson(e){return new slack_action_SlackAction(e)}}F()(slack_action_SlackAction,"typeName",v.i18n.translate("xpack.watcher.models.slackAction.TypeName",{defaultMessage:"Slack"})),F()(slack_action_SlackAction,"iconClass","logoSlack"),F()(slack_action_SlackAction,"selectMessage",v.i18n.translate("xpack.watcher.models.slackAction.selectMessageText",{defaultMessage:"Send a message to a Slack user or channel."})),F()(slack_action_SlackAction,"simulatePrompt",v.i18n.translate("xpack.watcher.models.slackAction.simulateButtonLabel",{defaultMessage:"Send a sample message"}));class webhook_action_WebhookAction extends base_action_BaseAction{constructor(e={}){super(e);const t=JSON.stringify({message:"Watch [{{ctx.metadata.name}}] has exceeded the threshold"},null,2);this.body=Object(f.get)(e,"body",e.ignoreDefaults?null:t),this.method=Object(f.get)(e,"method"),this.host=Object(f.get)(e,"host"),this.port=Object(f.get)(e,"port"),this.scheme=Object(f.get)(e,"scheme","http"),this.path=Object(f.get)(e,"path"),this.username=Object(f.get)(e,"username"),this.password=Object(f.get)(e,"password"),this.contentType=Object(f.get)(e,"contentType"),this.fullPath=`${this.host}:${this.port}${this.path?"/"+this.path:""}`}validate(){const e={host:[],port:[],body:[],username:[],password:[]};if(this.host||e.host.push(v.i18n.translate("xpack.watcher.watchActions.webhook.hostIsRequiredValidationMessage",{defaultMessage:"Webhook host is required."})),this.port||e.port.push(v.i18n.translate("xpack.watcher.watchActions.webhook.portIsRequiredValidationMessage",{defaultMessage:"Webhook port is required."})),"application/json"===this.contentType&&"string"==typeof this.body&&""!==this.body){const t=v.i18n.translate("xpack.watcher.watchActions.webhook.invalidJsonValidationMessage",{defaultMessage:"Invalid JSON"});try{const a=JSON.parse(this.body);a&&"object"!=typeof a&&e.body.push(t)}catch(a){e.body.push(t)}}return this.username&&!this.password&&e.password.push(v.i18n.translate("xpack.watcher.watchActions.webhook.passwordIsRequiredIfUsernameValidationMessage",{defaultMessage:"Password is required."})),this.password&&!this.username&&e.username.push(v.i18n.translate("xpack.watcher.watchActions.webhook.usernameIsRequiredIfPasswordValidationMessage",{defaultMessage:"Username is required."})),e}get upstreamJson(){const e=super.upstreamJson;return Object.assign(e,{method:this.method,host:this.host,port:this.port,scheme:this.scheme,path:this.path,body:this.body,username:this.username,password:this.password,webhook:{host:this.host,port:this.port}}),e}get simulateMessage(){return v.i18n.translate("xpack.watcher.models.webhookAction.simulateMessage",{defaultMessage:"Sample request sent to {fullPath}",values:{fullPath:this.fullPath}})}get simulateFailMessage(){return v.i18n.translate("xpack.watcher.models.webhookAction.simulateFailMessage",{defaultMessage:"Failed to send request to {fullPath}.",values:{fullPath:this.fullPath}})}static fromUpstreamJson(e){return new webhook_action_WebhookAction(e)}}F()(webhook_action_WebhookAction,"typeName",v.i18n.translate("xpack.watcher.models.webhookAction.typeName",{defaultMessage:"Webhook"})),F()(webhook_action_WebhookAction,"iconClass","logoWebhook"),F()(webhook_action_WebhookAction,"selectMessage",v.i18n.translate("xpack.watcher.models.webhookAction.selectMessageText",{defaultMessage:"Send a request to a web service."})),F()(webhook_action_WebhookAction,"simulatePrompt",v.i18n.translate("xpack.watcher.models.webhookAction.simulateButtonLabel",{defaultMessage:"Send request"}));class index_action_IndexAction extends base_action_BaseAction{constructor(e={}){super(e),this.index=Object(f.get)(e,"index")}validate(){return{index:[]}}get upstreamJson(){const e=super.upstreamJson;return Object.assign(e,{index:{index:this.index}}),e}get simulateMessage(){const e=this.index||"";return v.i18n.translate("xpack.watcher.models.indexAction.simulateMessage",{defaultMessage:"Index {index} has been indexed.",values:{index:e}})}get simulateFailMessage(){const e=this.index||"";return v.i18n.translate("xpack.watcher.models.indexAction.simulateFailMessage",{defaultMessage:"Failed to index {index}.",values:{index:e}})}static fromUpstreamJson(e){return new index_action_IndexAction(e)}}F()(index_action_IndexAction,"typeName",v.i18n.translate("xpack.watcher.models.indexAction.typeName",{defaultMessage:"Index"})),F()(index_action_IndexAction,"iconClass","indexOpen"),F()(index_action_IndexAction,"selectMessage",v.i18n.translate("xpack.watcher.models.indexAction.selectMessageText",{defaultMessage:"Index data into Elasticsearch."})),F()(index_action_IndexAction,"simulatePrompt",v.i18n.translate("xpack.watcher.models.indexAction.simulateButtonLabel",{defaultMessage:"Index data"}));class pagerduty_action_PagerDutyAction extends base_action_BaseAction{constructor(e={}){super(e);const t=v.i18n.translate("xpack.watcher.models.pagerdutyAction.defaultDescriptionText",{defaultMessage:"Watch [{context}] has exceeded the threshold",values:{context:"{{ctx.metadata.name}}"}});this.description=Object(f.get)(e,"description",e.ignoreDefaults?null:t)}validate(){const e={description:[]};return this.description||e.description.push(v.i18n.translate("xpack.watcher.watchActions.pagerduty.descriptionIsRequiredValidationMessage",{defaultMessage:"PagerDuty description is required."})),e}get upstreamJson(){const e=super.upstreamJson;return Object.assign(e,{description:this.description,pagerduty:{description:this.description}}),e}get simulateMessage(){return v.i18n.translate("xpack.watcher.models.pagerDutyAction.simulateMessage",{defaultMessage:"PagerDuty event has been sent."})}get simulateFailMessage(){return v.i18n.translate("xpack.watcher.models.pagerDutyAction.simulateFailMessage",{defaultMessage:"Failed to send PagerDuty event."})}static fromUpstreamJson(e){return new pagerduty_action_PagerDutyAction(e)}}F()(pagerduty_action_PagerDutyAction,"typeName",v.i18n.translate("xpack.watcher.models.pagerDutyAction.typeName",{defaultMessage:"PagerDuty"})),F()(pagerduty_action_PagerDutyAction,"iconClass","apps"),F()(pagerduty_action_PagerDutyAction,"selectMessage",v.i18n.translate("xpack.watcher.models.pagerDutyAction.selectMessageText",{defaultMessage:"Create an event in PagerDuty."})),F()(pagerduty_action_PagerDutyAction,"simulatePrompt",v.i18n.translate("xpack.watcher.models.pagerDutyAction.simulateButtonLabel",{defaultMessage:"Send a PagerDuty event"}));class jira_action_JiraAction extends base_action_BaseAction{constructor(e={}){super(e);const t=v.i18n.translate("xpack.watcher.models.jiraAction.defaultSummaryText",{defaultMessage:"Watch [{context}] has exceeded the threshold",values:{context:"{{ctx.metadata.name}}"}});this.summary=Object(f.get)(e,"summary",e.ignoreDefaults?null:t),this.projectKey=Object(f.get)(e,"projectKey"),this.issueType=Object(f.get)(e,"issueType")}validate(){const e={projectKey:[],issueType:[],summary:[]};return this.projectKey||e.projectKey.push(v.i18n.translate("xpack.watcher.watchActions.jira.projectKeyIsRequiredValidationMessage",{defaultMessage:"Jira project key is required."})),this.issueType||e.issueType.push(v.i18n.translate("xpack.watcher.watchActions.jira.issueTypeNameIsRequiredValidationMessage",{defaultMessage:"Jira issue type is required."})),this.summary||e.summary.push(v.i18n.translate("xpack.watcher.watchActions.jira.summaryIsRequiredValidationMessage",{defaultMessage:"Jira summary is required."})),e}get upstreamJson(){const e=super.upstreamJson;return Object.assign(e,{projectKey:this.projectKey,issueType:this.issueType,summary:this.summary,jira:{fields:{project:{key:this.projectKey},issuetype:{name:this.issueType},summary:this.summary}}}),e}get simulateMessage(){return v.i18n.translate("xpack.watcher.models.jiraAction.simulateMessage",{defaultMessage:"Jira issue has been created."})}get simulateFailMessage(){return v.i18n.translate("xpack.watcher.models.jiraAction.simulateFailMessage",{defaultMessage:"Failed to create Jira issue."})}static fromUpstreamJson(e){return new jira_action_JiraAction(e)}}F()(jira_action_JiraAction,"typeName",v.i18n.translate("xpack.watcher.models.jiraAction.typeName",{defaultMessage:"Jira"})),F()(jira_action_JiraAction,"iconClass","apps"),F()(jira_action_JiraAction,"selectMessage",v.i18n.translate("xpack.watcher.models.jiraAction.selectMessageText",{defaultMessage:"Create an issue in Atlassian’s Jira Software."})),F()(jira_action_JiraAction,"simulatePrompt",v.i18n.translate("xpack.watcher.models.jiraAction.simulateButtonLabel",{defaultMessage:"Create a sample Jira issue"}));class unknown_action_UnknownAction extends base_action_BaseAction{constructor(e={}){super(e),this.actionJson=Object(f.get)(e,"actionJson")}get upstreamJson(){const e=super.upstreamJson;return Object.assign(e,{actionJson:this.actionJson}),e}static fromUpstreamJson(e){return new unknown_action_UnknownAction(e)}}const C={};Object(I.set)(C,J.c.EMAIL,email_action_EmailAction),Object(I.set)(C,J.c.LOGGING,logging_action_LoggingAction),Object(I.set)(C,J.c.SLACK,slack_action_SlackAction),Object(I.set)(C,J.c.WEBHOOK,webhook_action_WebhookAction),Object(I.set)(C,J.c.INDEX,index_action_IndexAction),Object(I.set)(C,J.c.PAGERDUTY,pagerduty_action_PagerDutyAction),Object(I.set)(C,J.c.JIRA,jira_action_JiraAction);class action_Action{static fromUpstreamJson(e){const t=Object(f.get)(e,"type");return(C[t]||unknown_action_UnknownAction).fromUpstreamJson(e)}}F()(action_Action,"getActionTypes",(()=>C));var W=a(25),D=a.n(W);function N(e){return e?D()(e):null}class action_status_ActionStatus{constructor(e={}){this.id=Object(f.get)(e,"id"),this.state=Object(f.get)(e,"state"),this.isAckable=Object(f.get)(e,"isAckable"),this.lastAcknowledged=N(Object(f.get)(e,"lastAcknowledged")),this.lastThrottled=N(Object(f.get)(e,"lastThrottled")),this.lastExecution=N(Object(f.get)(e,"lastExecution")),this.isLastExecutionSuccessful=Object(f.get)(e,"isLastExecutionSuccessful"),this.lastExecutionReason=Object(f.get)(e,"lastExecutionReason"),this.lastSuccessfulExecution=N(Object(f.get)(e,"lastSuccessfulExecution")),this.lastAcknowledged&&(this.lastAcknowledgedHumanized=this.lastAcknowledged.fromNow()),this.lastExecution&&(this.lastExecutionHumanized=this.lastExecution.fromNow()),this.lastThrottled&&(this.lastThrottledHumanized=this.lastThrottled.fromNow())}static fromUpstreamJson(e){return new action_status_ActionStatus(e)}}class watch_status_WatchStatus{constructor(e={}){this.id=Object(f.get)(e,"id"),this.state=Object(f.get)(e,"state"),this.comment=Object(f.get)(e,"comment"),this.isActive=Object(f.get)(e,"isActive"),this.lastExecution=N(Object(f.get)(e,"lastExecution")),this.lastChecked=N(Object(f.get)(e,"lastChecked")),this.lastMetCondition=N(Object(f.get)(e,"lastMetCondition"));const t=Object(f.get)(e,"actionStatuses",[]);this.actionStatuses=t.map((e=>action_status_ActionStatus.fromUpstreamJson(e)))}static fromUpstreamJson(e){return new watch_status_WatchStatus(e)}}class watch_errors_WatchErrors{constructor(e={}){this.actionErrors=Object(f.get)(e,"actions")}static fromUpstreamJson(e){return new watch_errors_WatchErrors(e)}}function P(e,t){const a=e.map((e=>e.id));let s,i=1;for(;void 0===s;){const e=`${t}_${i}`;a.includes(e)?i++:s=e}return s}class base_watch_BaseWatch{constructor(e={}){var t;F()(this,"updateWatchStatus",(e=>{this.watchStatus=e})),F()(this,"createAction",((e,t)=>{const a=action_Action.getActionTypes()[e];if(!Boolean(a))throw new Error(v.i18n.translate("xpack.watcher.models.baseWatch.createUnknownActionTypeErrorMessage",{defaultMessage:"Attempted to create unknown action type {type}.",values:{type:e}}));const s=new a({id:P(this.actions,e),type:e,...t});this.addAction(s)})),F()(this,"addAction",(e=>{(function(e,t){const a=Object(f.find)(e,{id:t.id});return Boolean(a)})(this.actions,e)&&(e.id=P(this.actions,e.type)),this.actions.push(e)})),F()(this,"deleteAction",(e=>{Object(f.remove)(this.actions,e)})),F()(this,"resetActions",(()=>{this.actions=[]})),F()(this,"isEqualTo",(e=>{const t={...this},a={...e};return Object(f.isEqual)(t,a)})),this.id=Object(f.get)(e,"id"),this.type=Object(f.get)(e,"type"),this.isNew=Object(f.get)(e,"isNew",!0),this.name=Object(f.get)(e,"name"),this.isSystemWatch=Boolean(Object(f.get)(e,"isSystemWatch")),this.watchStatus=watch_status_WatchStatus.fromUpstreamJson(Object(f.get)(e,"watchStatus")),this.watchErrors=watch_errors_WatchErrors.fromUpstreamJson(Object(f.get)(e,"watchErrors")),this.isActive=null===(t=this.watchStatus.isActive)||void 0===t||t;const a=Object(f.get)(e,"actions",[]);this.actions=a.map(action_Action.fromUpstreamJson)}get displayName(){return this.name?this.name:this.id}get searchValue(){return this,e=["id","name"],Object(f.values)(Object(f.pick)(this,e)).join("\n");var e}get typeName(){return this.constructor.typeName}get iconClass(){return this.constructor.iconClass}get selectMessage(){return this.constructor.selectMessage}get selectSortOrder(){return this.constructor.selectSortOrder}get upstreamJson(){return{id:this.id,name:this.name,type:this.type,isNew:this.isNew,isActive:this.isActive,actions:Object(f.map)(this.actions,(e=>e.upstreamJson))}}}F()(base_watch_BaseWatch,"typeName",v.i18n.translate("xpack.watcher.models.baseWatch.typeName",{defaultMessage:"Watch"})),F()(base_watch_BaseWatch,"iconClass",""),F()(base_watch_BaseWatch,"selectMessage",v.i18n.translate("xpack.watcher.models.baseWatch.selectMessageText",{defaultMessage:"Set up a new watch."})),F()(base_watch_BaseWatch,"isCreatable",!0),F()(base_watch_BaseWatch,"selectSortOrder",0);const R={trigger:{schedule:{interval:"30m"}},input:{search:{request:{body:{size:0,query:{match_all:{}}},indices:["*"]}}},condition:{compare:{"ctx.payload.hits.total":{gte:10}}},actions:{"my-logging-action":{logging:{text:"There are {{ctx.payload.hits.total}} documents in your index. Threshold is 10."}}}};class json_watch_JsonWatch extends base_watch_BaseWatch{constructor(e={}){e.type=J.n.JSON,e.id=void 0===e.id?Object(L.v4)():e.id,super(e);const t=Object(f.get)(e,"watch");this.watch=t||R,this.watchString=Object(f.get)(e,"watchString",JSON.stringify(t||R,null,2)),this.id=e.id}validate(){const e={},t={id:[],json:[]};if(e.errors=t,this.id?/^[A-Za-z0-9\-\_.]+$/.test(this.id)||t.id.push(v.i18n.translate("xpack.watcher.sections.watchEdit.json.error.invalidIdText",{defaultMessage:"ID can only contain letters, underscores, dashes, periods and numbers."})):t.id.push(v.i18n.translate("xpack.watcher.sections.watchEdit.json.error.requiredIdText",{defaultMessage:"ID is required"})),this.watchString&&""!==this.watchString)try{const e=JSON.parse(this.watchString);if(e&&"object"==typeof e){const{actions:a}=e;if(a){const e=Object.keys(a).find((e=>{const t=Object.keys(a[e]);let s;return Object.keys(J.c).forEach((e=>{t.includes(J.c[e])&&!t.includes(J.c.UNKNOWN)&&(s=J.c[e])})),!s}));e&&t.json.push(v.i18n.translate("xpack.watcher.sections.watchEdit.json.error.invalidActionType",{defaultMessage:'Unknown action type provided for action "{action}".',values:{action:e}}))}}}catch(e){t.json.push(v.i18n.translate("xpack.watcher.sections.watchEdit.json.error.invalidJsonText",{defaultMessage:"Invalid JSON"}))}else t.json.push(v.i18n.translate("xpack.watcher.sections.watchEdit.json.error.requiredJsonText",{defaultMessage:"JSON is required"}));return e}get upstreamJson(){const e=super.upstreamJson;return Object.assign(e,{watch:this.watch}),e}static fromUpstreamJson(e){return new json_watch_JsonWatch(e)}}function B(e=J.l.SECOND,t="0"){switch(e){case J.l.SECOND:return v.i18n.translate("xpack.watcher.timeUnits.secondLabel",{defaultMessage:"{timeValue, plural, one {second} other {seconds}}",values:{timeValue:t}});case J.l.MINUTE:return v.i18n.translate("xpack.watcher.timeUnits.minuteLabel",{defaultMessage:"{timeValue, plural, one {minute} other {minutes}}",values:{timeValue:t}});case J.l.HOUR:return v.i18n.translate("xpack.watcher.timeUnits.hourLabel",{defaultMessage:"{timeValue, plural, one {hour} other {hours}}",values:{timeValue:t}});case J.l.DAY:return v.i18n.translate("xpack.watcher.timeUnits.dayLabel",{defaultMessage:"{timeValue, plural, one {day} other {days}}",values:{timeValue:t}})}}F()(json_watch_JsonWatch,"typeName",v.i18n.translate("xpack.watcher.models.jsonWatch.typeName",{defaultMessage:"Advanced Watch"})),F()(json_watch_JsonWatch,"iconClass",""),F()(json_watch_JsonWatch,"selectMessage",v.i18n.translate("xpack.watcher.models.jsonWatch.selectMessageText",{defaultMessage:"Set up a custom watch in raw JSON."})),F()(json_watch_JsonWatch,"isCreatable",!0),F()(json_watch_JsonWatch,"selectSortOrder",100);const z={count:{text:"count()",fieldRequired:!1,value:J.d.COUNT,validNormalizedTypes:[]},avg:{text:"average()",fieldRequired:!0,validNormalizedTypes:["number"],value:J.d.AVERAGE},sum:{text:"sum()",fieldRequired:!0,validNormalizedTypes:["number"],value:J.d.SUM},min:{text:"min()",fieldRequired:!0,validNormalizedTypes:["number","date"],value:J.d.MIN},max:{text:"max()",fieldRequired:!0,validNormalizedTypes:["number","date"],value:J.d.MAX}},H={all:{text:v.i18n.translate("xpack.watcher.thresholdWatchExpression.groupByLabel.allDocumentsLabel",{defaultMessage:"all documents"}),sizeRequired:!1,value:"all",validNormalizedTypes:[]},top:{text:v.i18n.translate("xpack.watcher.thresholdWatchExpression.groupByLabel.topLabel",{defaultMessage:"top"}),sizeRequired:!0,value:"top",validNormalizedTypes:["number","date","keyword"]}},U={[J.e.GREATER_THAN]:{text:v.i18n.translate("xpack.watcher.thresholdWatchExpression.comparators.isAboveLabel",{defaultMessage:"Is above"}),value:J.e.GREATER_THAN,requiredValues:1},[J.e.GREATER_THAN_OR_EQUALS]:{text:v.i18n.translate("xpack.watcher.thresholdWatchExpression.comparators.isAboveOrEqualsLabel",{defaultMessage:"Is above or equals"}),value:J.e.GREATER_THAN_OR_EQUALS,requiredValues:1},[J.e.LESS_THAN]:{text:v.i18n.translate("xpack.watcher.thresholdWatchExpression.comparators.isBelowLabel",{defaultMessage:"Is below"}),value:J.e.LESS_THAN,requiredValues:1},[J.e.LESS_THAN_OR_EQUALS]:{text:v.i18n.translate("xpack.watcher.thresholdWatchExpression.comparators.isBelowOrEqualsLabel",{defaultMessage:"Is below or equals"}),value:J.e.LESS_THAN_OR_EQUALS,requiredValues:1},[J.e.BETWEEN]:{text:v.i18n.translate("xpack.watcher.thresholdWatchExpression.comparators.isBetweenLabel",{defaultMessage:"Is between"}),value:J.e.BETWEEN,requiredValues:2}},{BETWEEN:q}=J.e,V={AGG_TYPE:"count",TERM_SIZE:5,THRESHOLD_COMPARATOR:J.e.GREATER_THAN,TIME_WINDOW_SIZE:5,TIME_WINDOW_UNIT:"m",TRIGGER_INTERVAL_SIZE:1,TRIGGER_INTERVAL_UNIT:"m",THRESHOLD:[1e3,5e3],GROUP_BY:"all"};class threshold_watch_ThresholdWatch extends base_watch_BaseWatch{constructor(e={}){e.id=e.id||Object(L.v4)(),e.type=J.n.THRESHOLD,super(e),this.index=e.index,this.timeField=e.timeField,this.timeFields=e.timeFields||void 0,this.triggerIntervalSize=null==e.triggerIntervalSize?V.TRIGGER_INTERVAL_SIZE:e.triggerIntervalSize,this.triggerIntervalUnit=e.triggerIntervalUnit||V.TRIGGER_INTERVAL_UNIT,this.aggType=e.aggType||V.AGG_TYPE,this.aggField=e.aggField,this.termSize=null==e.termSize?V.TERM_SIZE:e.termSize,this.termField=e.termField,this.thresholdComparator=e.thresholdComparator||V.THRESHOLD_COMPARATOR,this.timeWindowSize=null==e.timeWindowSize?V.TIME_WINDOW_SIZE:e.timeWindowSize,this.timeWindowUnit=e.timeWindowUnit||V.TIME_WINDOW_UNIT,this.groupBy=e.groupBy||V.GROUP_BY,null!=this.termField&&(this.groupBy="top"),this.threshold=null==e.threshold?V.THRESHOLD:e.threshold}get hasTermsAgg(){return Boolean(this.termField)}get termOrder(){return this.thresholdComparator===J.e.GREATER_THAN?J.k.DESCENDING:J.k.ASCENDING}get titleDescription(){const e=v.i18n.translate("xpack.watcher.models.thresholdWatch.sendAlertOnSpecificConditionTitleDescription",{defaultMessage:"Send an alert when your specified condition is met."});if(isNaN(this.triggerIntervalSize))return e;const t=B(this.triggerIntervalUnit,this.triggerIntervalSize);return`${e} ${v.i18n.translate("xpack.watcher.models.thresholdWatch.thresholdWatchIntervalTitleDescription",{defaultMessage:"Your watch will run every {triggerIntervalSize} {timeUnitLabel}.",values:{triggerIntervalSize:this.triggerIntervalSize,timeUnitLabel:t}})}`}validate(){const e={},t={name:[],index:[],timeField:[],triggerIntervalSize:[],aggField:[],termSize:[],termField:[],timeWindowSize:[]};return e.errors=t,this.name||t.name.push(v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.error.requiredNameText",{defaultMessage:"Name is required."})),void 0!==this.index&&this.index.length<1&&t.index.push(v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.enterOneOrMoreIndicesValidationMessage",{defaultMessage:"Enter one or more indices."})),void 0!==this.index&&this.index.length>0&&void 0!==this.timeFields&&1===this.timeFields.length&&t.index.push(v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.invalidIndexValidationMessage",{defaultMessage:"Index does not have a time field."})),this.timeField||t.timeField.push(v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.timeFieldIsRequiredValidationText",{defaultMessage:"A time field is required."})),this.triggerIntervalSize||t.triggerIntervalSize.push(v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.intervalSizeIsRequiredValidationMessage",{defaultMessage:"Interval size is required."})),void 0!==this.triggerIntervalSize&&this.triggerIntervalSize<0&&t.triggerIntervalSize.push(v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.intervalSizeNegativeNumberValidationMessage",{defaultMessage:"Interval size cannot be a negative number."})),z[this.aggType].fieldRequired&&!this.aggField&&t.aggField.push(v.i18n.translate("xpack.watcher.watchEdit.thresholdWatchExpression.aggType.fieldIsRequiredValidationMessage",{defaultMessage:"This field is required."})),H[this.groupBy].sizeRequired&&(this.termSize||t.termSize.push(v.i18n.translate("xpack.watcher.thresholdWatchExpression.aggType.xpack.watcher.thresholdWatchExpression.groupBy.requiredValueValidationMessage",{defaultMessage:"A value is required."})),this.termField||t.termField.push(v.i18n.translate("xpack.watcher.thresholdWatchExpression.groupBy.requiredFieldValidationMessage",{defaultMessage:"This field is required."}))),Array.from(Array(U[this.thresholdComparator].requiredValues)).forEach(((e,a)=>{const s=`threshold${a}`;t[s]=[],null!=this.threshold[a]&&""!==this.threshold[a]||t[s].push(v.i18n.translate("xpack.watcher.thresholdWatchExpression.thresholdLevel.valueIsRequiredValidationMessage",{defaultMessage:"A value is required."}))})),this.thresholdComparator!==q||!this.threshold[0]||!this.threshold[1]||this.threshold[1]>this.threshold[0]||t.threshold1.push(v.i18n.translate("xpack.watcher.thresholdWatchExpression.thresholdLevel.secondValueMustBeGreaterMessage",{defaultMessage:"Value must be greater than {lowerBound}.",values:{lowerBound:this.threshold[0]}})),this.timeWindowSize||t.timeWindowSize.push(v.i18n.translate("xpack.watcher.thresholdWatchExpression.timeWindow.durationSizeIsRequiredValidationMessage",{defaultMessage:"Window duration size is required."})),e}get upstreamJson(){const e=super.upstreamJson;return Object.assign(e,{index:this.index,timeField:this.timeField,triggerIntervalSize:this.triggerIntervalSize,triggerIntervalUnit:this.triggerIntervalUnit,aggType:this.aggType,aggField:this.aggField,termSize:this.termSize,termField:this.termField,termOrder:this.termOrder,thresholdComparator:this.thresholdComparator,timeWindowSize:this.timeWindowSize,timeWindowUnit:this.timeWindowUnit,hasTermsAgg:this.hasTermsAgg,threshold:U[this.thresholdComparator].requiredValues>1?this.threshold:this.threshold[0]}),e}static fromUpstreamJson(e){return new threshold_watch_ThresholdWatch(e)}get DEFAULT_VALUES(){return V}}F()(threshold_watch_ThresholdWatch,"typeName",v.i18n.translate("xpack.watcher.models.thresholdWatch.typeName",{defaultMessage:"Threshold Alert"})),F()(threshold_watch_ThresholdWatch,"iconClass",""),F()(threshold_watch_ThresholdWatch,"selectMessage",v.i18n.translate("xpack.watcher.models.thresholdWatch.selectMessageText",{defaultMessage:"Send an alert on a specific condition"})),F()(threshold_watch_ThresholdWatch,"isCreatable",!0),F()(threshold_watch_ThresholdWatch,"selectSortOrder",1);class monitoring_watch_MonitoringWatch extends base_watch_BaseWatch{constructor(e={}){e.type=J.n.MONITORING,super(e)}get upstreamJson(){const e=super.upstreamJson;return Object.assign(e,{watch:this.watch}),e}static fromUpstreamJson(e){return new monitoring_watch_MonitoringWatch(e)}}F()(monitoring_watch_MonitoringWatch,"isCreatable",!1);const G={};Object(I.set)(G,J.n.JSON,json_watch_JsonWatch),Object(I.set)(G,J.n.THRESHOLD,threshold_watch_ThresholdWatch),Object(I.set)(G,J.n.MONITORING,monitoring_watch_MonitoringWatch);class watch_Watch{static fromUpstreamJson(e={}){const t=Object(f.get)(e,"type"),a=G[t];return Object.assign(e,{isNew:!1}),a.fromUpstreamJson(e)}}F()(watch_Watch,"getWatchTypes",(()=>G)),a(40);class watch_history_item_WatchHistoryItem{constructor(e={}){this.id=e.id,this.watchId=e.watchId,this.details=e.details,this.startTime=N(e.startTime),this.watchStatus=watch_status_WatchStatus.fromUpstreamJson(Object(f.get)(e,"watchStatus"))}static fromUpstreamJson(e){return new watch_history_item_WatchHistoryItem(e)}}const $=e=>Object(r.sendRequest)(X(),e),K=e=>Object(r.useRequest)(X(),e);let Y;const X=()=>Y,Z=J.j.API_ROOT,Q=({watches:e=[]})=>e.map((e=>watch_Watch.fromUpstreamJson(e))),ee=({watch:e={}})=>watch_Watch.fromUpstreamJson(e),te=({watchHistoryItems:e=[]})=>e.map((e=>watch_history_item_WatchHistoryItem.fromUpstreamJson(e))),ae=({watchHistoryItem:e})=>watch_history_item_WatchHistoryItem.fromUpstreamJson(e),se=async e=>$({path:`${Z}/watch/${e}/deactivate`,method:"put"}),ie=async e=>$({path:`${Z}/watch/${e}/activate`,method:"put"}),ne=async e=>await X().put(`${Z}/watch/${e.id}`,{body:JSON.stringify(e.upstreamJson)}),oe=async(e,t)=>$({path:`${Z}/watch/execute`,method:"put",body:JSON.stringify({executeDetails:e.upstreamJson,watch:t.upstreamJson})}),re=e=>null==e?void 0:e.visualizeData,ce=e=>Settings.fromUpstreamJson(e);let le;const ue=()=>{le.history.push({pathname:"/watches"})},de=()=>{le.history.push({pathname:"/watches/new-watch/threshold"})},he=()=>{le.history.push({pathname:"/watches/new-watch/json"})},ge=Object(s.createContext)(null),me=({links:e})=>({putWatchApiUrl:`${e.apis.putWatch}`,executeWatchApiUrl:`${e.apis.executeWatchActionModes}`,watcherGettingStartedUrl:`${e.watcher.ui}`,watchActionsConfigurationMap:{[J.c.SLACK]:`${e.watcher.slackAction}`,[J.c.PAGERDUTY]:`${e.watcher.pagerDutyAction}`,[J.c.JIRA]:`${e.watcher.jiraAction}`}}),pe=({children:e,value:t})=>{const{docLinks:a,...s}=t;return Object(p.jsx)(ge.Provider,{value:Object.freeze({...s,links:me(a)})},e)},je=()=>{const e=Object(s.useContext)(ge);if(!e)throw new Error('"useAppContext" can only be called inside of AppContext.Provider!');return e};function be({id:e}){return Object(p.jsx)(E.EuiEmptyPrompt,{iconType:"warning",title:Object(p.jsx)("h1",null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.pageErrorNotExist.title",defaultMessage:"Couldn't find watch"})),body:Object(p.jsx)("p",null,e?Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.pageErrorNotExist.description",defaultMessage:"A watch with ID '{id}' could not be found.",values:{id:e}}):Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.pageErrorNotExist.noWatchIdDescription",defaultMessage:"A watch could not be found."}))})}function xe(){return Object(p.jsx)(E.EuiEmptyPrompt,{iconType:"warning",title:Object(p.jsx)("h1",null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.pageErrorForbidden.title",defaultMessage:"You don't have privileges to use Watcher"}))})}function we(e){const t=(Array.isArray(e)?e:[e]).find((e=>!!e&&[403,404].includes(e.statusCode)));if(t)return t.statusCode}function fe({errorCode:e,id:t}){return 404===e?Object(p.jsx)(be,{id:t}):Object(p.jsx)(xe,null)}const ye=({watchesToDelete:e,callback:t})=>{const{toasts:a}=je(),s=e.length;if(!s)return null;const i=v.i18n.translate("xpack.watcher.deleteSelectedWatchesConfirmModal.descriptionText",{defaultMessage:"You can't recover {numWatchesToDelete, plural, one {a deleted watch} other {deleted watches}}.",values:{numWatchesToDelete:s}}),n=v.i18n.translate("xpack.watcher.deleteSelectedWatchesConfirmModal.deleteButtonLabel",{defaultMessage:"Delete {numWatchesToDelete, plural, one {watch} other {# watches}} ",values:{numWatchesToDelete:s}}),o=v.i18n.translate("xpack.watcher.deleteSelectedWatchesConfirmModal.cancelButtonLabel",{defaultMessage:"Cancel"});return Object(p.jsx)(E.EuiConfirmModal,{buttonColor:"danger","data-test-subj":"deleteWatchesConfirmation",title:n,onCancel:()=>t(),onConfirm:async()=>{const{successes:s,errors:i}=await(async e=>{const t=JSON.stringify({watchIds:e}),{results:a}=await X().post(`${Z}/watches/delete`,{body:t});return a})(e),n=s.length,o=i.length;t(s),n>0&&a.addSuccess(v.i18n.translate("xpack.watcher.sections.watchList.deleteSelectedWatchesSuccessNotification.descriptionText",{defaultMessage:"Deleted {numSuccesses, number} {numSuccesses, plural, one {watch} other {watches}}",values:{numSuccesses:n}})),o>0&&a.addDanger(v.i18n.translate("xpack.watcher.sections.watchList.deleteSelectedWatchesErrorNotification.descriptionText",{defaultMessage:"Failed to delete {numErrors, number} {numErrors, plural, one {watch} other {watches}}",values:{numErrors:o}}))},cancelButtonText:o,confirmButtonText:n},i)},Oe=({errorKey:e,isShowingErrors:t,errors:a,children:i,...n})=>Object(p.jsx)(E.EuiFormRow,u()({isInvalid:t&&a[e].length>0,error:a[e]},n),Object(p.jsx)(s.Fragment,null,s.Children.map(i,(e=>Object(s.cloneElement)(e))))),Ee={[J.m.ACTIVE]:"success",[J.m.INACTIVE]:"subdued",[J.m.CONFIG_ERROR]:"subdued",[J.m.ERROR]:"subdued"},ve=({state:e,size:t="s"})=>Object(p.jsx)(E.EuiFlexGroup,{gutterSize:"xs",alignItems:"center"},Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiIcon,{type:"dot",color:Ee[e]})),Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiText,{size:t},e))),ke={[J.b.OK]:"success",[J.b.ACKNOWLEDGED]:"success",[J.b.THROTTLED]:"warning",[J.b.UNKNOWN]:"subdued",[J.b.CONFIG_ERROR]:"danger",[J.b.ERROR]:"danger"},Me=({state:e,size:t="s"})=>Object(p.jsx)(E.EuiFlexGroup,{gutterSize:"xs",alignItems:"center"},Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiIcon,{type:"dot",color:ke[e]})),Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiText,{size:t},e))),Te=({children:e})=>Object(p.jsx)(E.EuiEmptyPrompt,{title:Object(p.jsx)(E.EuiLoadingSpinner,{size:"xl"}),body:Object(p.jsx)(E.EuiText,{color:"subdued"},e),"data-test-subj":"sectionLoading"}),Se=({title:e,error:t,...a})=>{const i=t.data||t,{error:n,cause:o,message:r}=i;return Object(p.jsx)(E.EuiCallOut,u()({title:e,color:"danger",iconType:"warning"},a),Object(p.jsx)("div",{"data-test-subj":"sectionErrorMessage"},r||n),o&&Object(p.jsx)(s.Fragment,null,Object(p.jsx)(E.EuiSpacer,{size:"m"}),Object(p.jsx)("ul",null,o.map(((e,t)=>Object(p.jsx)("li",{key:t},e))))))},_e=i.a.createContext({}),Ae=()=>{const{toasts:e}=je(),{watchDetail:t}=Object(s.useContext)(_e),[a,i]=Object(s.useState)([]),[n,o]=Object(s.useState)(!1),[r,c]=Object(s.useState)(null),{id:l,watchErrors:u,watchStatus:d,isSystemWatch:h}=t,g=u&&u.actionErrors,m=d&&d.actionStatuses,j=g&&Object.keys(g).length>0;Object(s.useEffect)((()=>{const e=m&&m.map((e=>{const t=g&&g[e.id];return{...e,errors:t||[]}}));i(e)}),[t,g,m]);const b=[{field:"id",name:v.i18n.translate("xpack.watcher.sections.watchDetail.watchTable.actionHeader",{defaultMessage:"Name"}),sortable:!0,truncateText:!1},{field:"state",name:Object(p.jsx)(E.EuiToolTip,{content:v.i18n.translate("xpack.watcher.sections.watchDetail.watchTable.stateHeader.tooltipText",{defaultMessage:"OK, acknowledged, throttled, or error."})},Object(p.jsx)("span",null,v.i18n.translate("xpack.watcher.sections.watchDetail.watchTable.stateHeader",{defaultMessage:"State"})," ",Object(p.jsx)(E.EuiIcon,{size:"s",color:"subdued",type:"questionInCircle",className:"eui-alignTop"}))),sortable:!0,truncateText:!0,render:e=>Object(p.jsx)(Me,{state:e})},{field:"lastExecution",name:Object(p.jsx)(E.EuiToolTip,{content:v.i18n.translate("xpack.watcher.sections.watchHistory.watchActionStatusTable.lastExecuted.tooltipText",{defaultMessage:"The last time this action was executed."})},Object(p.jsx)("span",null,v.i18n.translate("xpack.watcher.sections.watchHistory.watchActionStatusTable.lastExecuted",{defaultMessage:"Last executed"})," ",Object(p.jsx)(E.EuiIcon,{size:"s",color:"subdued",type:"questionInCircle",className:"eui-alignTop"}))),sortable:!0,truncateText:!1,render:e=>{var t;return null!==(t=null==e?void 0:e.format())&&void 0!==t?t:""}}],x={field:"errors",name:v.i18n.translate("xpack.watcher.sections.watchDetail.watchTable.errorsHeader",{defaultMessage:"Errors"}),render:(e,t)=>{const{id:a}=t;return e&&e.length>0?Object(p.jsx)(E.EuiButtonEmpty,{onClick:()=>c(a),"data-test-subj":"actionErrorsButton"},v.i18n.translate("xpack.watcher.sections.watchDetail.watchTable.errorsCellText",{defaultMessage:"{total, number} {total, plural, one {error} other {errors}}",values:{total:e.length}})):Object(p.jsx)(s.Fragment,null)}},w={actions:[{available:e=>e.isAckable&&!h,render:t=>{const{id:a}=t;return Object(p.jsx)(E.EuiToolTip,{content:v.i18n.translate("xpack.watcher.sections.watchDetail.watchTable.ackActionCellTooltipTitle",{defaultMessage:"Acknowledge watch action."})},Object(p.jsx)(E.EuiButtonEmpty,{iconType:"check",isLoading:n,"data-test-subj":"acknowledgeWatchButton",onClick:async()=>{o(!0);try{const e=await(async(e,t)=>{const{watchStatus:a}=await X().put(`${Z}/watch/${e}/action/${t}/acknowledge`);return watch_status_WatchStatus.fromUpstreamJson(a)})(l,a),t=e.actionStatuses.map((e=>{const t=g&&g[e.id];return{...e,errors:t||[]}}));return o(!1),i(t)}catch(a){o(!1),e.addDanger(v.i18n.translate("xpack.watcher.sections.watchDetail.watchTable.ackActionErrorMessage",{defaultMessage:"Error acknowledging action {actionId}",values:{actionId:t.id}}))}}},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchDetail.watchTable.ackActionCellTitle",defaultMessage:"Acknowledge"})))}}]},f=j?[...b,x,w]:[...b,w];return Object(p.jsx)("div",{"data-test-subj":"watchDetailSection"},r&&Object(p.jsx)(E.EuiFlyout,{size:"s","aria-labelledby":"flyoutActionErrorTitle","data-test-subj":"actionErrorsFlyout",onClose:()=>c(null)},Object(p.jsx)(E.EuiFlyoutHeader,{hasBorder:!0},Object(p.jsx)(E.EuiTitle,{size:"s"},Object(p.jsx)("h2",{id:"flyoutActionErrorTitle","data-test-subj":"title"},r))),Object(p.jsx)(E.EuiFlyoutBody,null,Object(p.jsx)(E.EuiCallOut,{title:v.i18n.translate("xpack.watcher.sections.watchDetail.actionErrorsCalloutTitle",{defaultMessage:"This action contains errors"}),color:"danger",iconType:"cross","data-test-subj":"errorMessage"},g[r].length>1?Object(p.jsx)("ul",null,g[r].map(((e,t)=>Object(p.jsx)("li",{key:`action-error-${t}`},e.message)))):Object(p.jsx)("p",null,g[r][0].message)))),Object(p.jsx)(E.EuiInMemoryTable,{items:a,itemId:"id",columns:f,pagination:J.g,sorting:!0,"data-test-subj":"watchActionStatusTable",message:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchDetail.watchTable.noWatchesMessage",defaultMessage:"No actions to show"})}))},Fe=[{value:"now-1h",text:v.i18n.translate("xpack.watcher.sections.watchHistory.timeSpan.1h",{defaultMessage:"Last one hour"})},{value:"now-24h",text:v.i18n.translate("xpack.watcher.sections.watchHistory.timeSpan.24h",{defaultMessage:"Last 24 hours"})},{value:"now-7d",text:v.i18n.translate("xpack.watcher.sections.watchHistory.timeSpan.7d",{defaultMessage:"Last 7 days"})},{value:"now-30d",text:v.i18n.translate("xpack.watcher.sections.watchHistory.timeSpan.30d",{defaultMessage:"Last 30 days"})},{value:"now-6M",text:v.i18n.translate("xpack.watcher.sections.watchHistory.timeSpan.6M",{defaultMessage:"Last 6 months"})},{value:"now-1y",text:v.i18n.translate("xpack.watcher.sections.watchHistory.timeSpan.1y",{defaultMessage:"Last 1 year"})}],Ie=()=>{const{watchDetail:e}=Object(s.useContext)(_e),[t,a]=Object(s.useState)(void 0),[i,n]=Object(s.useState)(void 0),[o,r]=Object(s.useState)(Fe[0].value);void 0===t&&a(e.watchStatus&&e.watchStatus.isActive||!1);const{error:c,data:l,isLoading:u}=(d=e.id,K({query:(h=o)?{startTime:h}:void 0,path:`${Z}/watch/${d}/history`,method:"get",deserializer:te}));var d,h;const{error:g,data:m}=(e=>K({path:e?`${Z}/history/${e}`:"",method:"get",deserializer:ae}))(i),j=m?JSON.stringify(m.details,null,2):"";if(c)return Object(p.jsx)(s.Fragment,null,Object(p.jsx)(E.EuiSpacer,{size:"s"}),Object(p.jsx)(Se,{title:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchHistory.watchExecutionErrorTitle",defaultMessage:"Error loading execution history"}),error:c}));const b=[{field:"startTime",name:v.i18n.translate("xpack.watcher.sections.watchHistory.watchTable.startTimeHeader",{defaultMessage:"Trigger time"}),sortable:!0,truncateText:!1,render:(e,t)=>{const a=e.format();return Object(p.jsx)(E.EuiLink,{"data-test-subj":`watchStartTimeColumn-${a}`,onClick:()=>n(t.id)},a)}},{field:"watchStatus.state",name:Object(p.jsx)(E.EuiToolTip,{content:v.i18n.translate("xpack.watcher.sections.watchHistory.watchTable.stateHeader.tooltipText",{defaultMessage:"Active or error state."})},Object(p.jsx)("span",null,v.i18n.translate("xpack.watcher.sections.watchHistory.watchTable.stateHeader",{defaultMessage:"State"})," ",Object(p.jsx)(E.EuiIcon,{size:"s",color:"subdued",type:"questionInCircle",className:"eui-alignTop"}))),sortable:!0,truncateText:!0,render:e=>Object(p.jsx)(ve,{state:e})},{field:"startTime",name:Object(p.jsx)(E.EuiToolTip,{content:v.i18n.translate("xpack.watcher.sections.watchHistory.watchTable.metConditionHeader.tooltipText",{defaultMessage:"Whether the condition was met and action taken."})},Object(p.jsx)("span",null,v.i18n.translate("xpack.watcher.sections.watchHistory.watchTable.metConditionHeader",{defaultMessage:"Condition met"})," ",Object(p.jsx)(E.EuiIcon,{size:"s",color:"subdued",type:"questionInCircle",className:"eui-alignTop"}))),sortable:!0,truncateText:!0,render:(e,t)=>{const{watchStatus:{lastExecution:a}}=t;if(e.isSame(a))return Object(p.jsx)(E.EuiIcon,{color:"green",type:"check"})}},{field:"watchStatus.comment",name:Object(p.jsx)(E.EuiToolTip,{content:v.i18n.translate("xpack.watcher.sections.watchHistory.watchTable.commentHeader.tooltipText",{defaultMessage:"Whether the action was throttled, acknowledged, or failed to execute."})},Object(p.jsx)("span",null,v.i18n.translate("xpack.watcher.sections.watchHistory.watchTable.commentHeader",{defaultMessage:"Comment"})," ",Object(p.jsx)(E.EuiIcon,{size:"s",color:"subdued",type:"questionInCircle",className:"eui-alignTop"}))),sortable:!0,truncateText:!0}];let x;if(void 0!==i&&(g&&(x=Object(p.jsx)(E.EuiFlyout,{"data-test-subj":"watchHistoryErrorDetailFlyout",onClose:()=>n(void 0),"aria-labelledby":"watchHistoryErrorDetailsFlyoutTitle",maxWidth:600},Object(p.jsx)(E.EuiFlyoutHeader,null,Object(p.jsx)(E.EuiTitle,{size:"s"},Object(p.jsx)("h3",{"data-test-subj":"title"},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchHistory.watchHistoryDetail.errorTitle",defaultMessage:"Execution details"})))),Object(p.jsx)(E.EuiFlyoutBody,null,Object(p.jsx)(Se,{title:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchHistory.watchHistoryDetailsErrorTitle",defaultMessage:"Error loading execution details"}),error:g,"data-test-subj":"errorMessage"})))),void 0!==m)){const e=[{field:"id",name:v.i18n.translate("xpack.watcher.sections.watchHistory.watchActionStatusTable.id",{defaultMessage:"Name"}),sortable:!0,truncateText:!1},{field:"state",name:Object(p.jsx)(E.EuiToolTip,{content:v.i18n.translate("xpack.watcher.sections.watchHistory.watchActionStatusTable.state.tooltipText",{defaultMessage:"OK, acknowledged, throttled, or error."})},Object(p.jsx)("span",null,v.i18n.translate("xpack.watcher.sections.watchHistory.watchActionStatusTable.state",{defaultMessage:"State"})," ",Object(p.jsx)(E.EuiIcon,{size:"s",color:"subdued",type:"questionInCircle",className:"eui-alignTop"}))),sortable:!0,truncateText:!0,render:e=>Object(p.jsx)(Me,{state:e})}];x=Object(p.jsx)(E.EuiFlyout,{"data-test-subj":"watchHistoryDetailFlyout",onClose:()=>n(void 0),"aria-labelledby":"watchHistoryDetailsFlyoutTitle",maxWidth:600},Object(p.jsx)(E.EuiFlyoutHeader,null,Object(p.jsx)(E.EuiTitle,{size:"s"},Object(p.jsx)("h3",{"data-test-subj":"title"},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchHistory.watchHistoryDetail.title",defaultMessage:"Executed on {date}",values:{date:m.startTime}})))),Object(p.jsx)(E.EuiFlyoutBody,null,Object(p.jsx)(E.EuiTitle,{size:"xs"},Object(p.jsx)("h4",null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchHistory.watchHistoryDetail.actionsTitle",defaultMessage:"Actions"}))),Object(p.jsx)(E.EuiInMemoryTable,{items:m.watchStatus.actionStatuses,itemId:"id",columns:e,message:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchHistory.watchTable.noWatchesMessage",defaultMessage:"No current status to show"}),"data-test-subj":"watchActionsTable"}),Object(p.jsx)(E.EuiSpacer,null),Object(p.jsx)(E.EuiTitle,{size:"xs"},Object(p.jsx)("h4",null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchHistory.watchHistoryDetail.jsonTitle",defaultMessage:"JSON"}))),Object(p.jsx)(E.EuiSpacer,{size:"s"}),Object(p.jsx)(E.EuiCodeBlock,{language:"json"},j)))}return Object(p.jsx)("div",{"data-test-subj":"watchHistorySection"},Object(p.jsx)(E.EuiFlexGroup,{gutterSize:"s",justifyContent:"flexStart",alignItems:"center"},Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiSelect,{options:Fe,value:o,onChange:e=>{const t=e.target.value;r(t)},"aria-label":v.i18n.translate("xpack.watcher.sections.watchHistory.changeTimespanSelectAriaLabel",{defaultMessage:"Change timespan of watch history"})}))),Object(p.jsx)(E.EuiSpacer,{size:"s"}),Object(p.jsx)(E.EuiInMemoryTable,{items:l||[],columns:b,pagination:J.g,sorting:!0,loading:u,"data-test-subj":"watchHistoryTable",message:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchHistory.watchTable.noCurrentStatus",defaultMessage:"No execution history to show"})}),x)},Je=[{id:"executionHistoryTab",name:v.i18n.translate("xpack.watcher.sections.watchStatus.executionHistoryTabLabel",{defaultMessage:"Execution history"})},{id:"actionStatusesTab",name:v.i18n.translate("xpack.watcher.sections.watchStatus.actionsTabLabel",{defaultMessage:"Action statuses"})}],Le=({match:{params:{id:e}}})=>{const{setBreadcrumbs:t,toasts:a}=je(),{error:n,data:o,isLoading:r}=(e=>K({path:`${Z}/watch/${e}`,method:"get",deserializer:ee}))(e),[c,l]=Object(s.useState)("executionHistoryTab"),[u,d]=Object(s.useState)(void 0),[h,g]=Object(s.useState)([]),[m,j]=Object(s.useState)(!1);Object(s.useEffect)((()=>{t([M,_])}),[e,t]);const b=we(n);if(r)return Object(p.jsx)(E.EuiPageContent_Deprecated,{verticalPosition:"center",horizontalPosition:"center",color:"subdued"},Object(p.jsx)(Te,null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchStatus.loadingWatchDetailsDescription",defaultMessage:"Loading watch details…"})));if(b)return Object(p.jsx)(E.EuiPageContent_Deprecated,{verticalPosition:"center",horizontalPosition:"center",color:"danger"},Object(p.jsx)(fe,{errorCode:b,id:e}));if(o){const{isSystemWatch:e,id:t,watchStatus:s,name:b}=o;void 0===u&&d(void 0!==s.isActive&&s.isActive);const x=u?Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchHistory.watchTable.deactivateWatchLabel",defaultMessage:"Deactivate"}):Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchHistory.watchTable.activateWatchLabel",defaultMessage:"Activate"}),w=async()=>{const e=u?se:ie;j(!0);const{error:s}=await e(t);if(j(!1),s){const e=u?v.i18n.translate("xpack.watcher.sections.watchList.toggleActivatationErrorNotification.deactivateDescriptionText",{defaultMessage:"Couldn't deactivate watch"}):v.i18n.translate("xpack.watcher.sections.watchList.toggleActivatationErrorNotification.activateDescriptionText",{defaultMessage:"Couldn't activate watch"});return a.addDanger(e)}d(!u)},f="executionHistoryTab"===c?Object(p.jsx)(Ie,null):"actionStatusesTab"===c?Object(p.jsx)(Ae,null):void 0;return Object(p.jsx)(_e.Provider,{value:{watchDetailError:n,watchDetail:o,isWatchDetailLoading:r}},Object(p.jsx)(i.a.Fragment,null,Object(p.jsx)(E.EuiPageHeader,{pageTitle:Object(p.jsx)(i.a.Fragment,null,Object(p.jsx)("span",{"data-test-subj":"pageTitle"},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchDetail.header",defaultMessage:"Current status for '{watch}'",values:{watch:b||t}})),e&&Object(p.jsx)(i.a.Fragment,null," ",Object(p.jsx)(E.EuiToolTip,{content:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchDetail.headerBadgeToolipText",defaultMessage:"You cannot deactivate or delete a system watch."})},Object(p.jsx)(E.EuiBadge,{color:"hollow"},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchDetail.headerBadgeText",defaultMessage:"System watch"}))))),bottomBorder:!0,rightSideItems:e?[]:[Object(p.jsx)(E.EuiButtonEmpty,{"data-test-subj":"toggleWatchActivationButton",onClick:()=>w(),isLoading:m},x),Object(p.jsx)(E.EuiButtonEmpty,{"data-test-subj":"deleteWatchButton",onClick:()=>{g([t])},color:"danger",disabled:!1},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchHistory.deleteWatchButtonLabel",defaultMessage:"Delete"}))],tabs:Je.map(((e,t)=>({onClick:()=>{l(e.id)},isSelected:e.id===c,key:t,"data-test-subj":"tab",label:e.name})))}),Object(p.jsx)(E.EuiSpacer,{size:"l"}),f,Object(p.jsx)(ye,{callback:e=>{e&&ue(),g([])},watchesToDelete:h})))}return null},Ce=i.a.createContext({}),We=(e,t)=>0===t?"now":`now+${t}${e}`;class execute_details_ExecuteDetails{constructor(e={}){this.triggeredTimeValue=e.triggeredTimeValue,this.triggeredTimeUnit=e.triggeredTimeUnit,this.scheduledTimeValue=e.scheduledTimeValue,this.scheduledTimeUnit=e.scheduledTimeUnit,this.ignoreCondition=e.ignoreCondition,this.alternativeInput=e.alternativeInput||"",this.actionModes=e.actionModes,this.recordExecution=e.recordExecution}validate(){const e={json:[]},t=v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.invalidJsonFieldError",{defaultMessage:"Invalid JSON"});if(""!==this.alternativeInput)try{const a=JSON.parse(this.alternativeInput);a&&"object"!=typeof a&&e.json.push(t)}catch(a){e.json.push(t)}return e}get upstreamJson(){return{triggerData:{triggeredTime:this.triggeredTimeValue&&""!==this.triggeredTimeValue?We(this.triggeredTimeUnit,this.triggeredTimeValue):void 0,scheduledTime:this.scheduledTimeValue&&""!==this.scheduledTimeValue?We(this.scheduledTimeUnit,this.scheduledTimeValue):void 0},ignoreCondition:this.ignoreCondition,alternativeInput:""!==this.alternativeInput?JSON.parse(this.alternativeInput):void 0,actionModes:this.actionModes,recordExecution:this.recordExecution}}}function De(e){return Object(f.intersection)(Object(f.keys)(e),Object(f.values)(J.c))[0]||J.c.UNKNOWN}function Ne(e,t){const{metadata:a={}}=t;Object(I.set)(a,"xpack.type",J.n.JSON);const s={...t,metadata:a};return e&&(s.metadata.name=e),s}class action_base_action_BaseAction{constructor(e,t){this.id=e.id,this.type=e.type,this.errors=t}get downstreamJson(){return{id:this.id,type:this.type}}get upstreamJson(){return{}}static getPropsFromDownstreamJson(e){return{id:e.id}}static getPropsFromUpstreamJson(e){return{id:e.id}}}class action_logging_action_LoggingAction extends action_base_action_BaseAction{constructor(e,t){e.type=J.c.LOGGING,super(e,t),this.text=e.text}get downstreamJson(){const e=super.downstreamJson;return Object.assign(e,{text:this.text}),e}static fromDownstreamJson(e){const t=super.getPropsFromDownstreamJson(e),{errors:a}=this.validateJson(e);return Object.assign(t,{text:e.text}),{action:new action_logging_action_LoggingAction(t,a),errors:a}}get upstreamJson(){const e=super.upstreamJson;return e[this.id]={logging:{text:this.text}},e}static fromUpstreamJson(e){const t=super.getPropsFromUpstreamJson(e),{errors:a}=this.validateJson(e.actionJson);return Object.assign(t,{text:e.actionJson.logging.text}),{action:new action_logging_action_LoggingAction(t,a),errors:a}}static validateJson(e){const t=[];return e.logging||t.push({code:J.f.ERR_PROP_MISSING,message:v.i18n.translate("xpack.watcher.models.loggingAction.actionJsonLoggingPropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJsonLogging} property",values:{actionJsonLogging:"actionJson.logging"}})}),e.logging&&!e.logging.text&&t.push({code:J.f.ERR_PROP_MISSING,message:v.i18n.translate("xpack.watcher.models.loggingAction.actionJsonLoggingTextPropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJsonLoggingText} property",values:{actionJsonLoggingText:"actionJson.logging.text"}})}),{errors:t.length?t:null}}}class action_email_action_EmailAction extends action_base_action_BaseAction{constructor(e,t){e.type=J.c.EMAIL,super(e,t),this.to=e.to,this.subject=e.subject,this.body=e.body}get downstreamJson(){const e=super.downstreamJson;return Object.assign(e,{to:this.to,subject:this.subject,body:this.body}),e}static fromDownstreamJson(e){const t=super.getPropsFromDownstreamJson(e),{errors:a}=this.validateJson(e);return Object.assign(t,{to:e.to,subject:e.subject,body:e.body}),{action:new action_email_action_EmailAction(t,a),errors:a}}get upstreamJson(){const e=super.upstreamJson,t={};return this.subject&&(t.subject=this.subject),this.body&&(t.body={text:this.body}),e[this.id]={email:{profile:"standard",to:this.to,...t}},e}static fromUpstreamJson(e){const t=super.getPropsFromUpstreamJson(e),{errors:a}=this.validateJson(e.actionJson),s={};return e.actionJson.email.subject&&(s.subject=e.actionJson.email.subject),e.actionJson.email.body&&(s.body=e.actionJson.email.body.text),Object.assign(t,{to:e.actionJson.email.to,subject:e.actionJson.email.subject,...s}),{action:new action_email_action_EmailAction(t,a),errors:a}}static validateJson(e){const t=[];if(!e.email){const e=v.i18n.translate("xpack.watcher.models.emailAction.actionJsonEmailPropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJsonEmail} property",values:{actionJsonEmail:"actionJson.email"}});t.push({code:J.f.ERR_PROP_MISSING,message:e})}if(e.email&&!e.email.to){const e=v.i18n.translate("xpack.watcher.models.emailAction.actionJsonEmailToPropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJsonEmailTo} property",values:{actionJsonEmailTo:"actionJson.email.to"}});t.push({code:J.f.ERR_PROP_MISSING,message:e})}return{errors:t.length?t:null}}}class action_slack_action_SlackAction extends action_base_action_BaseAction{constructor(e,t){e.type=J.c.SLACK,super(e,t),this.to=e.to,this.text=e.text}get downstreamJson(){const e=super.downstreamJson;return Object.assign(e,{to:this.to,text:this.text}),e}static fromDownstreamJson(e){const t=super.getPropsFromDownstreamJson(e),{errors:a}=this.validateJson(e);return Object.assign(t,{to:e.to,text:e.text}),{action:new action_slack_action_SlackAction(t,a),errors:a}}get upstreamJson(){const e=super.upstreamJson;return e[this.id]={slack:{message:{to:this.to,text:this.text}}},e}static fromUpstreamJson(e){const t=super.getPropsFromUpstreamJson(e),{errors:a}=this.validateJson(e.actionJson);return Object.assign(t,{to:e.actionJson.slack.message.to,text:e.actionJson.slack.message.text}),{action:new action_slack_action_SlackAction(t,a),errors:a}}static validateJson(e){const t=[];return e.slack||t.push({code:J.f.ERR_PROP_MISSING,message:v.i18n.translate("xpack.watcher.models.slackAction.actionJsonSlackPropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJsonSlack} property",values:{actionJsonSlack:"actionJson.slack"}})}),e.slack&&!e.slack.message&&t.push({code:J.f.ERR_PROP_MISSING,message:v.i18n.translate("xpack.watcher.models.slackAction.actionJsonSlackMessagePropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJsonSlackMessage} property",values:{actionJsonSlackMessage:"actionJson.slack.message"}})}),{errors:t.length?t:null}}}class action_index_action_IndexAction extends action_base_action_BaseAction{constructor(e,t){e.type=J.c.INDEX,super(e,t),this.index=e.index}get downstreamJson(){const e=super.downstreamJson;return Object.assign(e,{index:this.index}),e}static fromDownstreamJson(e){const t=super.getPropsFromDownstreamJson(e),{errors:a}=this.validateJson(e);return Object.assign(t,{index:e.index}),{action:new action_index_action_IndexAction(t,a),errors:a}}get upstreamJson(){const e=super.upstreamJson;return e[this.id]={index:this.index},e}static fromUpstreamJson(e){const t=super.getPropsFromUpstreamJson(e),{errors:a}=this.validateJson(e.actionJson);return Object.assign(t,{index:e.actionJson.index.index}),{action:new action_index_action_IndexAction(t,a),errors:a}}static validateJson(e){const t=[];return e.index||t.push({code:J.f.ERR_PROP_MISSING,message:v.i18n.translate("xpack.watcher.models.indexAction.actionJsonIndexPropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJsonIndex} property",values:{actionJsonIndex:"actionJson.index"}})}),{errors:t.length?t:null}}}class action_webhook_action_WebhookAction extends action_base_action_BaseAction{constructor(e,t){e.type=J.c.WEBHOOK,super(e,t),this.method=e.method,this.host=e.host,this.port=e.port,this.scheme=e.scheme,this.path=e.path,this.body=e.body,this.contentType=e.contentType,this.username=e.username,this.password=e.password}get downstreamJson(){const e=super.downstreamJson;return Object.assign(e,{method:this.method,host:this.host,port:this.port,scheme:this.scheme,path:this.path,body:this.body,contentType:this.contentType,username:this.username}),e}static fromDownstreamJson(e){const t=super.getPropsFromDownstreamJson(e),{errors:a}=this.validateJson(e);return Object.assign(t,{method:e.method,host:e.host,port:e.port,scheme:e.scheme,path:e.path,body:e.body,contentType:e.contentType,username:e.username,password:e.password}),{action:new action_webhook_action_WebhookAction(t,a),errors:a}}get upstreamJson(){const e=super.upstreamJson,t={};return this.path&&(t.path=this.path),this.method&&(t.method=this.method),this.scheme&&(t.scheme=this.scheme),this.body&&(t.body=this.body),this.contentType&&(t.headers={"Content-Type":this.contentType}),this.username&&this.password&&(t.auth={basic:{username:this.username,password:this.password}}),e[this.id]={webhook:{host:this.host,port:this.port,...t}},e}static fromUpstreamJson(e){const t=super.getPropsFromUpstreamJson(e),a=e&&e.actionJson&&e.actionJson.webhook,{errors:s}=this.validateJson(e.actionJson),{path:i,method:n,scheme:o,body:r,auth:c,headers:l}=a,u={};return i&&(u.path=i),n&&(u.method=n),o&&(u.scheme=o),r&&(u.body=r),l["Content-Type"]&&(u.contentType=l["Content-Type"]),c&&c.basic&&(u.username=c.basic.username),Object.assign(t,{host:e.actionJson.webhook.host,port:e.actionJson.webhook.port,...u}),{action:new action_webhook_action_WebhookAction(t,s),errors:s}}static validateJson(e){const t=[];return e.webhook&&!e.webhook.host&&t.push({code:J.f.ERR_PROP_MISSING,message:v.i18n.translate("xpack.watcher.models.loggingAction.actionJsonWebhookHostPropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJsonWebhookHost} property",values:{actionJsonWebhookHost:"actionJson.webhook.host"}})}),e.webhook&&!e.webhook.port&&t.push({code:J.f.ERR_PROP_MISSING,message:v.i18n.translate("xpack.watcher.models.loggingAction.actionJsonWebhookPortPropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJsonWebhookPort} property",values:{actionJsonWebhookPort:"actionJson.webhook.port"}})}),{errors:t.length?t:null}}}class action_pagerduty_action_PagerDutyAction extends action_base_action_BaseAction{constructor(e,t){e.type=J.c.PAGERDUTY,super(e,t),this.description=e.description}get downstreamJson(){const e=super.downstreamJson;return Object.assign(e,{description:this.description}),e}static fromDownstreamJson(e){const t=super.getPropsFromDownstreamJson(e),{errors:a}=this.validateJson(e);return Object.assign(t,{description:e.description}),{action:new action_pagerduty_action_PagerDutyAction(t,a),errors:a}}get upstreamJson(){const e=super.upstreamJson;return e[this.id]={pagerduty:{description:this.description}},e}static fromUpstreamJson(e){const t=super.getPropsFromUpstreamJson(e),{errors:a}=this.validateJson(e.actionJson);return Object.assign(t,{description:e.actionJson.pagerduty.description}),{action:new action_pagerduty_action_PagerDutyAction(t,a),errors:a}}static validateJson(e){const t=[];return e.pagerduty||t.push({code:J.f.ERR_PROP_MISSING,message:v.i18n.translate("xpack.watcher.models.pagerDutyAction.actionJsonPagerDutyPropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJsonPagerDuty} property",values:{actionJsonPagerDuty:"actionJson.pagerduty"}})}),e.pagerduty&&!e.pagerduty.description&&t.push({code:J.f.ERR_PROP_MISSING,message:v.i18n.translate("xpack.watcher.models.pagerDutyAction.actionJsonPagerDutyDescriptionPropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJsonPagerDutyText} property",values:{actionJsonPagerDutyText:"actionJson.pagerduty.description"}})}),{errors:t.length?t:null}}}class action_jira_action_JiraAction extends action_base_action_BaseAction{constructor(e,t){e.type=J.c.JIRA,super(e,t),this.projectKey=e.projectKey,this.issueType=e.issueType,this.summary=e.summary}get downstreamJson(){const e=super.downstreamJson;return Object.assign(e,{projectKey:this.projectKey,issueType:this.issueType,summary:this.summary}),e}static fromDownstreamJson(e){const t=super.getPropsFromDownstreamJson(e),{errors:a}=this.validateJson(e);return Object.assign(t,{projectKey:e.projectKey,issueType:e.issueType,summary:e.summary}),{action:new action_jira_action_JiraAction(t,a),errors:a}}get upstreamJson(){const e=super.upstreamJson;return e[this.id]={jira:{fields:{project:{key:this.projectKey},issuetype:{name:this.issueType},summary:this.summary}}},e}static fromUpstreamJson(e){const t=super.getPropsFromUpstreamJson(e),{errors:a}=this.validateJson(e.actionJson);return Object.assign(t,{projectKey:Object(f.get)(e,"actionJson.jira.fields.project.key"),issueType:Object(f.get)(e,"actionJson.jira.fields.issuetype.name"),summary:Object(f.get)(e,"actionJson.jira.fields.summary")}),{action:new action_jira_action_JiraAction(t,a),errors:a}}static validateJson(e){const t=[];return e.jira||t.push({code:J.f.ERR_PROP_MISSING,message:v.i18n.translate("xpack.watcher.models.jiraAction.actionJsonJiraPropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJsonJira} property",values:{actionJsonJira:"actionJson.jira"}})}),Object(f.get)(e,"jira.fields.project.key")||t.push({code:J.f.ERR_PROP_MISSING,message:v.i18n.translate("xpack.watcher.models.jiraAction.actionJsonJiraProjectKeyPropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJsonJiraProjectKey} property",values:{actionJsonJiraProjectKey:"actionJson.jira.fields.project.key"}})}),Object(f.get)(e,"jira.fields.issuetype.name")||t.push({code:J.f.ERR_PROP_MISSING,message:v.i18n.translate("xpack.watcher.models.jiraAction.actionJsonJiraIssueTypePropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJsonJiraIssueType} property",values:{actionJsonJiraIssueType:"actionJson.jira.fields.issuetype.name"}})}),Object(f.get)(e,"jira.fields.summary")||t.push({code:J.f.ERR_PROP_MISSING,message:v.i18n.translate("xpack.watcher.models.jiraAction.actionJsonJiraSummaryPropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJsonJiraSummary} property",values:{actionJsonJiraSummary:"actionJson.jira.fields.summary"}})}),{errors:t.length?t:null}}}class action_unknown_action_UnknownAction extends action_base_action_BaseAction{constructor(e,t){e.type=J.c.UNKNOWN,super(e,t),this.actionJson=e.actionJson}get downstreamJson(){const e=super.downstreamJson;return Object.assign(e,{actionJson:this.actionJson}),e}static fromDownstreamJson(e){const t=super.getPropsFromDownstreamJson(e);return Object.assign(t,{actionJson:e.actionJson}),new action_unknown_action_UnknownAction(t)}get upstreamJson(){const e=super.upstreamJson;return e[this.id]=this.actionJson,e}static fromUpstreamJson(e){const t=super.getPropsFromUpstreamJson(e),{errors:a}=this.validateJson(e);return Object.assign(t,{actionJson:e.actionJson}),{action:new action_unknown_action_UnknownAction(t,a),errors:a}}static validateJson(e){const t=[];return e.actionJson||t.push({code:J.f.ERR_PROP_MISSING,message:v.i18n.translate("xpack.watcher.models.unknownAction.actionJsonPropertyMissingBadRequestMessage",{defaultMessage:"JSON argument must contain an {actionJson} property",values:{actionJson:"actionJson"}})}),{errors:t.length?t:null}}}const Pe={};Object(I.set)(Pe,J.c.LOGGING,action_logging_action_LoggingAction),Object(I.set)(Pe,J.c.EMAIL,action_email_action_EmailAction),Object(I.set)(Pe,J.c.SLACK,action_slack_action_SlackAction),Object(I.set)(Pe,J.c.INDEX,action_index_action_IndexAction),Object(I.set)(Pe,J.c.WEBHOOK,action_webhook_action_WebhookAction),Object(I.set)(Pe,J.c.PAGERDUTY,action_pagerduty_action_PagerDutyAction),Object(I.set)(Pe,J.c.JIRA,action_jira_action_JiraAction),Object(I.set)(Pe,J.c.UNKNOWN,action_unknown_action_UnknownAction);class action_action_Action{static fromUpstreamJson(e){const t=De(e.actionJson),a=Pe[t]||action_unknown_action_UnknownAction,{action:s}=a.fromUpstreamJson(e);return s}static fromDownstreamJson(e){const t=Pe[e.type]||action_unknown_action_UnknownAction,{action:a}=t.fromDownstreamJson(e);return a}}function Re(e){const t={};return Object(f.forEach)(e,(e=>{const a=action_action_Action.fromDownstreamJson(e);Object.assign(t,a.upstreamJson)})),t}function Be(e){return e.replace(/\s+/g," ").trim()}F()(action_action_Action,"getActionTypes",(()=>Pe));const{BETWEEN:ze}=J.e;function He(e,t,a){let s="";return"count"!==e||a||(s=t===ze?"\n if (ctx.payload.hits.total >= params.threshold[0] && ctx.payload.hits.total <= params.threshold[1]) {\n return true;\n }\n\n return false;\n ":`\n if (ctx.payload.hits.total ${t} params.threshold) {\n return true;\n }\n\n return false;\n `),"count"===e&&a&&(s=t===ze?"\n ArrayList arr = ctx.payload.aggregations.bucketAgg.buckets;\n for (int i = 0; i < arr.length; i++) {\n if (arr[i].doc_count >= params.threshold[0] && arr[i].doc_count <= params.threshold[1]) {\n return true;\n }\n }\n\n return false;\n ":`\n ArrayList arr = ctx.payload.aggregations.bucketAgg.buckets;\n for (int i = 0; i < arr.length; i++) {\n if (arr[i].doc_count ${t} params.threshold) {\n return true;\n }\n }\n\n return false;\n `),"count"===e||a||(s=t===ze?"\n if (ctx.payload.aggregations.metricAgg.value >= params.threshold[0]\n && ctx.payload.aggregations.metricAgg.value <= params.threshold[1]) {\n return true;\n }\n\n return false;\n ":`\n if (ctx.payload.aggregations.metricAgg.value ${t} params.threshold) {\n return true;\n }\n\n return false;\n `),"count"!==e&&a&&(s=t===ze?"\n ArrayList arr = ctx.payload.aggregations.bucketAgg.buckets;\n for (int i = 0; i < arr.length; i++) {\n if (arr[i]['metricAgg'].value >= params.threshold[0] && arr[i]['metricAgg'].value <= params.threshold[1]) {\n return true;\n }\n }\n\n return false;\n ":`\n ArrayList arr = ctx.payload.aggregations.bucketAgg.buckets;\n for (int i = 0; i < arr.length; i++) {\n if (arr[i]['metricAgg'].value ${t} params.threshold) {\n return true;\n }\n }\n\n return false;\n `),Be(s)}function Ue(e){return{threshold:e}}function qe({aggType:e,thresholdComparator:t,hasTermsAgg:a,threshold:s}){return{script:{source:He(e,t,a),params:Ue(s)}}}function Ve(e){return Array.isArray(e)?e:[e]}function Ge(e,t,a){return{[a]:{gte:`{{ctx.trigger.scheduled_time}}||-${e}${t}`,lte:"{{ctx.trigger.scheduled_time}}",format:"strict_date_optional_time||epoch_millis"}}}function $e(e,t,a){return{bool:{filter:{range:Ge(e,t,a)}}}}function Ke(e,t,a,s,i,n,o,r){const c={size:0,query:$e(e,t,a)},l=function(e,t,a,s,i){if("count"===e&&!a)return null;if("count"===e&&a)return{bucketAgg:{terms:{field:a,size:s,order:{_count:i}}}};if("count"!==e&&!a){const a={metricAgg:{}};return Object(I.set)(a,`metricAgg.${e}`,{field:t}),a}if("count"!==e&&a){const n={bucketAgg:{terms:{field:a,size:s,order:{metricAgg:i}},aggs:{metricAgg:{}}}};return Object(I.set)(n,`bucketAgg.aggs.metricAgg.${e}`,{field:t}),n}}(s,i,n,o,r);return Boolean(l)&&(c.aggs=l),c}function Ye({index:e,timeWindowSize:t,timeWindowUnit:a,timeField:s,aggType:i,aggField:n,termField:o,termSize:r,termOrder:c}){return{search:{request:{body:Ke(t,a,s,i,n,o,r,c),indices:Ve(e)}}}}function Xe({index:e,timeField:t,triggerIntervalSize:a,triggerIntervalUnit:s,aggType:i,aggField:n,termSize:o,termField:r,thresholdComparator:c,timeWindowSize:l,timeWindowUnit:u,threshold:d}){return{watcherui:{index:e,time_field:t,trigger_interval_size:a,trigger_interval_unit:s,agg_type:i,agg_field:n,term_size:o,term_field:r,threshold_comparator:c,time_window_size:l,time_window_unit:u,threshold:d}}}const{BETWEEN:Ze}=J.e;function Qe(e,t,a){let s="";return"count"!==e||a||(s="\n HashMap result = new HashMap();\n result.result = ctx.payload.hits.total;\n\n return result;\n "),"count"===e&&a&&(s=t===Ze?"\n HashMap result = new HashMap();\n ArrayList arr = ctx.payload.aggregations.bucketAgg.buckets;\n ArrayList filteredHits = new ArrayList();\n\n for (int i = 0; i < arr.length; i++) {\n HashMap filteredHit = new HashMap();\n filteredHit.key = arr[i].key;\n filteredHit.value = arr[i].doc_count;\n if (filteredHit.value >= params.threshold[0] && filteredHit.value <= params.threshold[1]) {\n filteredHits.add(filteredHit);\n }\n }\n result.results = filteredHits;\n\n return result;\n ":`\n HashMap result = new HashMap();\n ArrayList arr = ctx.payload.aggregations.bucketAgg.buckets;\n ArrayList filteredHits = new ArrayList();\n\n for (int i = 0; i < arr.length; i++) {\n HashMap filteredHit = new HashMap();\n filteredHit.key = arr[i].key;\n filteredHit.value = arr[i].doc_count;\n if (filteredHit.value ${t} params.threshold) {\n filteredHits.add(filteredHit);\n }\n }\n result.results = filteredHits;\n\n return result;\n `),"count"===e||a||(s="\n HashMap result = new HashMap();\n result.result = ctx.payload.aggregations.metricAgg.value;\n\n return result;\n "),"count"!==e&&a&&(s=t===Ze?"\n HashMap result = new HashMap();\n ArrayList arr = ctx.payload.aggregations.bucketAgg.buckets;\n ArrayList filteredHits = new ArrayList();\n\n for (int i = 0; i < arr.length; i++) {\n HashMap filteredHit = new HashMap();\n filteredHit.key = arr[i].key;\n filteredHit.value = arr[i]['metricAgg'].value;\n if (filteredHit.value >= params.threshold[0] && filteredHit.value <= params.threshold[1]) {\n filteredHits.add(filteredHit);\n }\n }\n result.results = filteredHits;\n\n return result;\n ":`\n HashMap result = new HashMap();\n ArrayList arr = ctx.payload.aggregations.bucketAgg.buckets;\n ArrayList filteredHits = new ArrayList();\n\n for (int i = 0; i < arr.length; i++) {\n HashMap filteredHit = new HashMap();\n filteredHit.key = arr[i].key;\n filteredHit.value = arr[i]['metricAgg'].value;\n if (filteredHit.value ${t} params.threshold) {\n filteredHits.add(filteredHit);\n }\n }\n result.results = filteredHits;\n\n return result;\n `),Be(s)}function et(e){return{threshold:e}}function tt({aggType:e,thresholdComparator:t,hasTermsAgg:a,threshold:s}){return{script:{source:Qe(e,t,a),params:et(s)}}}function at(e,t){return{schedule:{interval:`${e}${t}`}}}function st({name:e,triggerIntervalSize:t,triggerIntervalUnit:a,index:s,timeWindowSize:i,timeWindowUnit:n,timeField:o,aggType:r,aggField:c,termField:l,termSize:u,termOrder:d,thresholdComparator:h,hasTermsAgg:g,threshold:m,actions:p,includeMetadata:j=!0}){const b={trigger:at(t,a),input:Ye({index:s,timeWindowSize:i,timeWindowUnit:n,timeField:o,aggType:r,aggField:c,termField:l,termSize:u,termOrder:d}),condition:qe({aggType:r,thresholdComparator:h,hasTermsAgg:g,threshold:m}),transform:tt({aggType:r,thresholdComparator:h,hasTermsAgg:g,threshold:m}),actions:Re(p)};return j&&(b.metadata={xpack:{type:J.n.THRESHOLD},...Xe({index:s,timeField:o,triggerIntervalSize:t,triggerIntervalUnit:a,aggType:r,aggField:c,termSize:u,termField:l,thresholdComparator:h,timeWindowSize:i,timeWindowUnit:n,threshold:m})},e&&(b.metadata.name=e)),b}function it(e){const t=Object.keys(e);let a;return Object.keys(J.c).forEach((e=>{t.includes(J.c[e])&&(a=J.c[e])})),a||J.c.UNKNOWN}function nt(e,t){if(e===J.c.SLACK)return t[e].message;if(e===J.c.JIRA){const a={};return a.projectKey=Object(f.get)(t[e],"fields.project.key"),a.issueType=Object(f.get)(t[e],"fields.issuetype.name"),a.summary=Object(f.get)(t[e],"fields.summary"),a}return t[e]}async function ot(e,t){try{await ne(e),t.addSuccess(e.isNew?v.i18n.translate("xpack.watcher.sections.watchEdit.json.createSuccessNotificationText",{defaultMessage:"Created '{watchDisplayName}'",values:{watchDisplayName:e.displayName}}):v.i18n.translate("xpack.watcher.sections.watchEdit.json.saveSuccessNotificationText",{defaultMessage:"Saved '{watchDisplayName}'",values:{watchDisplayName:e.displayName}})),ue()}catch(e){var a;return{error:null!==(a=null==e?void 0:e.response.data)&&void 0!==a?a:e.body||e}}}async function rt(e,t){const a=e.watch&&e.watch.actions?((s=e).resetActions(),Object.keys(s.watch.actions).forEach((e=>{const t=s.watch.actions[e],a=it(t),i={...nt(a,t),ignoreDefaults:!0};s.createAction(a,i)})),s):e;var s;if(a.type===J.n.JSON){const e=a.actions.reduce(((e,t)=>{if(t.validate){const a=t.validate(),s=Object.keys(a);if(!s.find((e=>a[e].length>=1)))return e;const i=s.map((e=>a[e])),n=i&&i.length?[].concat(...i):[];return[...e,...n]}return e}),[]);return e.length>0?{error:{data:{message:e,error:"validation"}}}:ot(a,t)}return ot(a,t)}class request_flyout_RequestFlyout extends s.PureComponent{getEsJson(e){return JSON.stringify(e,null,2)}render(){const{id:e,payload:t,close:a}=this.props,s=`PUT _watcher/watch/${e||""}\n${this.getEsJson(t)}`;return Object(p.jsx)(E.EuiFlyout,{maxWidth:480,onClose:a},Object(p.jsx)(E.EuiFlyoutHeader,null,Object(p.jsx)(E.EuiTitle,null,Object(p.jsx)("h2",null,e?Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.requestFlyout.namedTitle",defaultMessage:"Request for '{id}'",values:{id:e}}):Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.requestFlyout.unnamedTitle",defaultMessage:"Request"})))),Object(p.jsx)(E.EuiFlyoutBody,null,Object(p.jsx)(E.EuiText,null,Object(p.jsx)("p",null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.requestFlyout.descriptionText",defaultMessage:"This Elasticsearch request will create or update this watch."}))),Object(p.jsx)(E.EuiSpacer,null),Object(p.jsx)(E.EuiCodeBlock,{language:"json",isCopyable:!0},s)),Object(p.jsx)(E.EuiFlyoutFooter,null,Object(p.jsx)(E.EuiButtonEmpty,{iconType:"cross",onClick:a,flush:"left"},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.requestFlyout.closeButtonLabel",defaultMessage:"Close"}))))}}const{useXJsonMode:ct}=r.XJson,lt=()=>{const{links:{putWatchApiUrl:e},toasts:t}=je(),{watch:a,setWatchProperty:i}=Object(s.useContext)(Ce),{convertToJson:n,setXJson:r,xJson:c}=ct(a.watchString),{errors:l}=a.validate(),u=!!Object.keys(l).find((e=>l[e].length>=1)),[d,h]=Object(s.useState)(null),[g,m]=Object(s.useState)(!1),[j,b]=Object(s.useState)(null),[x,w]=Object(s.useState)(!1),f=!!d,y=v.i18n.translate("xpack.watcher.sections.watchEdit.json.form.actionValidationErrorMessage",{defaultMessage:"Invalid watch actions"}),O={...l,json:f?[...l.json,y]:[...l.json]};return Object(s.useEffect)((()=>{0===l.json.length&&i("watch",JSON.parse(a.watchString))}),[i,l,a]),Object(p.jsx)(s.Fragment,null,Object(p.jsx)(E.EuiForm,{isInvalid:f,error:d||[],"data-test-subj":"jsonWatchForm"},j&&Object(p.jsx)(s.Fragment,null,Object(p.jsx)(Se,{title:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.json.saveWatchErrorTitle",defaultMessage:"Error saving watch"}),error:j,"data-test-subj":"sectionError"}),Object(p.jsx)(E.EuiSpacer,null)),Object(p.jsx)(E.EuiFormRow,{id:"watchName",label:v.i18n.translate("xpack.watcher.sections.watchEdit.json.form.watchNameLabel",{defaultMessage:"Name (optional)"})},Object(p.jsx)(E.EuiFieldText,{id:"watchName",name:"name",value:a.name||"","data-test-subj":"nameInput",onChange:e=>{const t=e.target.value;i("name",t)},onBlur:()=>{a.name||i("name","")}})),Object(p.jsx)(Oe,{id:"watchId",label:v.i18n.translate("xpack.watcher.sections.watchEdit.json.form.watchIDLabel",{defaultMessage:"ID"}),errorKey:"id",isShowingErrors:u&&void 0!==a.id,errors:l},Object(p.jsx)(E.EuiFieldText,{id:"id",name:"id","data-test-subj":"idInput",value:a.id||"",readOnly:!a.isNew,onChange:e=>{i("id",e.target.value)},onBlur:()=>{a.id||i("id","")}})),Object(p.jsx)(E.EuiSpacer,{size:"m"}),Object(p.jsx)(Oe,{id:"watchJson",label:Object(p.jsx)(s.Fragment,null,v.i18n.translate("xpack.watcher.sections.watchEdit.json.form.watchJsonLabel",{defaultMessage:"Watch JSON"})," ","(",Object(p.jsx)(E.EuiLink,{href:e,target:"_blank"},v.i18n.translate("xpack.watcher.sections.watchEdit.json.form.watchJsonDocLink",{defaultMessage:"API syntax"})),")"),errorKey:"json",isShowingErrors:u||f,fullWidth:!0,errors:O},Object(p.jsx)(o.CodeEditor,{languageId:"json",value:c,"data-test-subj":"jsonEditor",height:500,options:{lineNumbers:"off",tabSize:2,automaticLayout:!0},"aria-label":v.i18n.translate("xpack.watcher.sections.watchEdit.json.form.watchJsonAriaLabel",{defaultMessage:"Code editor"}),onChange:e=>{d&&h(null),r(e),i("watchString",n(e))}})),Object(p.jsx)(E.EuiSpacer,null),Object(p.jsx)(E.EuiFlexGroup,{justifyContent:"spaceBetween",alignItems:"center"},Object(p.jsx)(E.EuiFlexGroup,{gutterSize:"m",alignItems:"center"},Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiButton,{"data-test-subj":"saveWatchButton",fill:!0,color:"success",type:"submit",iconType:"check",isLoading:x,isDisabled:u,onClick:async()=>{w(!0);const e=await rt(a,t);if(e&&e.error){const{data:t}=e.error;return w(!1),t&&"validation"===t.error?h(t.message):b(e.error)}}},a.isNew?Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.json.createButtonLabel",defaultMessage:"Create watch"}):Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.json.saveButtonLabel",defaultMessage:"Save watch"}))),Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiButtonEmpty,{"data-test-subj":"btnCancelWatch",onClick:()=>ue()},v.i18n.translate("xpack.watcher.sections.watchEdit.json.cancelButtonLabel",{defaultMessage:"Cancel"})))),Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiButtonEmpty,{onClick:()=>m(!g)},g?Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.json.hideRequestButtonLabel",defaultMessage:"Hide request"}):Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.json.showRequestButtonLabel",defaultMessage:"Show request"}))))),g?Object(p.jsx)(request_flyout_RequestFlyout,{id:a.id,payload:Ne(a.name,a.watch),close:()=>m(!1)}):null)},ut=({executeResults:e,executeDetails:t,onCloseFlyout:a,error:n})=>{var o;const{watch:r}=Object(s.useContext)(Ce),{actionModes:c}=t,l=e=>{switch(e){case"simulate":case"force_simulate":return v.i18n.translate("xpack.watcher.sections.watchEdit.simulateResults.table.statusColumnValue.notSimulated",{defaultMessage:"not simulated"});case"execute":case"force_execute":return v.i18n.translate("xpack.watcher.sections.watchEdit.simulateResults.table.statusColumnValue.notExecuted",{defaultMessage:"not executed"});case"skip":return v.i18n.translate("xpack.watcher.sections.watchEdit.simulateResults.table.statusColumnValue.throttled",{defaultMessage:"throttled"});default:return""}},u=(()=>{const t=r.watch&&r.watch.actions;if(e&&t){const a=e.watchStatus&&e.watchStatus.actionStatuses;return Object.keys(t).map((s=>{var i,n;const o=a.find((e=>e.id===s)),r=null===(i=e.details)||void 0===i||null===(n=i.result)||void 0===n?void 0:n.condition.met;return{actionId:s,actionType:it(t[s]),actionMode:c[s],actionState:o&&o.state,actionReason:o&&o.lastExecutionReason,actionStatus:r&&e.details.result.actions.find((e=>e.id===s)).status||l(c[s])}}))}return[]})(),d=[{field:"actionId",name:v.i18n.translate("xpack.watcher.sections.watchEdit.simulateResults.table.actionColumnLabel",{defaultMessage:"ID"}),sortable:!0,truncateText:!0},{field:"actionType",name:v.i18n.translate("xpack.watcher.sections.watchEdit.simulateResults.table.typeColumnLabel",{defaultMessage:"Type"}),truncateText:!0},{field:"actionMode",name:v.i18n.translate("xpack.watcher.sections.watchEdit.simulateResults.table.modeColumnLabel",{defaultMessage:"Mode"})},{field:"actionState",name:v.i18n.translate("xpack.watcher.sections.watchEdit.simulateResults.table.stateColumnLabel",{defaultMessage:"State"}),dataType:"string",render:(e,t)=>Object(p.jsx)(Me,{state:e})},{field:"actionReason",name:v.i18n.translate("xpack.watcher.sections.watchEdit.simulateResults.table.reasonColumnLabel",{defaultMessage:"Reason"})},{field:"actionStatus",name:v.i18n.translate("xpack.watcher.sections.watchEdit.simulateResults.table.statusColumnLabel",{defaultMessage:"Status"})}],h=Object(p.jsx)(E.EuiTitle,{size:"s"},Object(p.jsx)("h2",{id:"simulateResultsFlyOutTitle","data-test-subj":"simulateResultsFlyoutTitle"},v.i18n.translate("xpack.watcher.sections.watchEdit.simulateResults.title",{defaultMessage:"Simulation results"})));if(n)return Object(p.jsx)(E.EuiFlyout,{onClose:()=>{a()},"aria-labelledby":"simulateResultsFlyOutTitle"},Object(p.jsx)(E.EuiFlyoutHeader,{hasBorder:!0},h),Object(p.jsx)(E.EuiFlyoutBody,null,Object(p.jsx)(Se,{title:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.simulateResults.errorTitle",defaultMessage:"Cannot simulate watch"}),error:n})));if(!e)return null;const{details:g}=e,m=(null==g||null===(o=g.result)||void 0===o?void 0:o.condition.met)&&Object(p.jsx)(i.a.Fragment,null,Object(p.jsx)(E.EuiIcon,{color:"green",type:"check","data-test-subj":"conditionMetStatus"})," ",Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.simulateResults.conditionMetStatus",defaultMessage:"Condition met"}))||Object(p.jsx)(i.a.Fragment,null,Object(p.jsx)(E.EuiIcon,{color:"subdued",type:"cross","data-test-subj":"conditionNotMetStatus"})," ",Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.simulateResults.conditionNotMetStatus",defaultMessage:"Condition not met"}));return Object(p.jsx)(E.EuiFlyout,{onClose:()=>{a()},"data-test-subj":"simulateResultsFlyout","aria-labelledby":"simulateResultsFlyOutTitle"},Object(p.jsx)(E.EuiFlyoutHeader,{hasBorder:!0},h,Object(p.jsx)(E.EuiSpacer,{size:"s"}),m),Object(p.jsx)(E.EuiFlyoutBody,null,u&&u.length>0&&Object(p.jsx)(s.Fragment,null,Object(p.jsx)(E.EuiText,null,Object(p.jsx)("h5",null,v.i18n.translate("xpack.watcher.sections.watchEdit.simulateResults.actionsSectionTitle",{defaultMessage:"Actions"}))),Object(p.jsx)(E.EuiSpacer,{size:"m"}),Object(p.jsx)(E.EuiBasicTable,{columns:d,items:u,"data-test-subj":"simulateResultsTable"}),Object(p.jsx)(E.EuiSpacer,{size:"l"})),Object(p.jsx)(E.EuiText,null,Object(p.jsx)("h5",null,v.i18n.translate("xpack.watcher.sections.watchEdit.simulateResults.simulationOutputSectionTitle",{defaultMessage:"Simulation output"}))),Object(p.jsx)(E.EuiSpacer,{size:"l"}),Object(p.jsx)(E.EuiCodeBlock,{language:"json"},JSON.stringify(g,null,2))))},{useXJsonMode:dt}=r.XJson,ht=Object.keys(J.a).map((e=>({text:J.a[e],value:J.a[e]}))),gt=(e="0")=>Object.entries(J.l).filter((([e])=>e!==J.l.DAY)).map((([t,a])=>({text:B(a,e),value:a}))),mt=({executeWatchErrors:e,hasExecuteWatchErrors:t,executeDetails:a,setExecuteDetails:i,watchActions:n})=>{const{links:{executeWatchApiUrl:r}}=je(),{watch:c}=Object(s.useContext)(Ce),[l,u]=Object(s.useState)(null),[d,h]=Object(s.useState)(!1),[g,m]=Object(s.useState)(null),{errors:j}=c.validate(),b=j.json.length>=1,{actionModes:x,scheduledTimeValue:w,scheduledTimeUnit:f,triggeredTimeValue:y,alternativeInput:O,ignoreCondition:M}=a,{setXJson:T,convertToJson:S,xJson:_}=dt(O),A=[{field:"actionId",name:v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.table.idColumnLabel",{defaultMessage:"ID"}),sortable:!0,truncateText:!0},{field:"type",name:v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.table.typeColumnLabel",{defaultMessage:"Type"}),truncateText:!0},{field:"actionMode",name:v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.table.modeColumnLabel",{defaultMessage:"Mode"}),render:({},e)=>Object(p.jsx)(E.EuiSelect,{options:ht,value:x[e.actionId],"data-test-subj":"actionModesSelect",onChange:t=>{i(new execute_details_ExecuteDetails({...a,actionModes:{...x,[e.actionId]:t.target.value}}))},"aria-label":v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.table.modeSelectLabel",{defaultMessage:"Action modes"})})}];return Object(p.jsx)(s.Fragment,null,Object(p.jsx)(E.EuiText,null,Object(p.jsx)("p",null,v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.pageDescription",{defaultMessage:"Use the simulator to override the watch schedule, condition, actions, and input results."}))),Object(p.jsx)(E.EuiSpacer,{size:"l"}),Object(p.jsx)(E.EuiForm,{"data-test-subj":"jsonWatchSimulateForm"},Object(p.jsx)(E.EuiDescribedFormGroup,{fullWidth:!0,title:Object(p.jsx)("h2",null,v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.triggerOverridesTitle",{defaultMessage:"Trigger"})),description:v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.triggerOverridesDescription",{defaultMessage:"Set the time and date for starting the watch."})},Object(p.jsx)(E.EuiFormRow,{label:v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.scheduledTimeFieldLabel",{defaultMessage:"Schedule every"})},Object(p.jsx)(E.EuiFlexGroup,null,Object(p.jsx)(E.EuiFlexItem,null,Object(p.jsx)(E.EuiFieldNumber,{value:null==w||""===w?w:parseInt(w,10),min:0,"data-test-subj":"scheduledTimeInput",onChange:e=>{const t=e.target.value;i(new execute_details_ExecuteDetails({...a,scheduledTimeValue:""===t?t:parseInt(t,10)}))}})),Object(p.jsx)(E.EuiFlexItem,null,Object(p.jsx)(E.EuiSelect,{value:f,options:gt(w),onChange:e=>{i(new execute_details_ExecuteDetails({...a,scheduledTimeUnit:e.target.value}))}})))),Object(p.jsx)(E.EuiFormRow,{label:v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.triggeredTimeFieldLabel",{defaultMessage:"Trigger after"})},Object(p.jsx)(E.EuiFieldNumber,{value:null==y||""===y?y:parseInt(y,10),min:0,"data-test-subj":"triggeredTimeInput",append:Object(p.jsx)(E.EuiText,{size:"s"},B(J.l.SECOND,y)),onChange:e=>{const t=e.target.value;i(new execute_details_ExecuteDetails({...a,triggeredTimeValue:""===t?t:parseInt(t,10),triggeredTimeUnit:J.l.SECOND}))}}))),Object(p.jsx)(E.EuiDescribedFormGroup,{fullWidth:!0,title:Object(p.jsx)("h2",null,v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.conditionOverridesTitle",{defaultMessage:"Condition"})),description:v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.conditionOverridesDescription",{defaultMessage:"Execute the watch when the condition is met. Otherwise, ignore the condition and run the watch on a fixed schedule."})},Object(p.jsx)(E.EuiSwitch,{label:v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.ignoreConditionFieldLabel",{defaultMessage:"Ignore condition"}),checked:M,"data-test-subj":"ignoreConditionSwitch",onChange:e=>{i(new execute_details_ExecuteDetails({...a,ignoreCondition:e.target.checked}))}})),Object(p.jsx)(E.EuiDescribedFormGroup,{fullWidth:!0,title:Object(p.jsx)("h2",null,v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.actionOverridesTitle",{defaultMessage:"Actions"})),description:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.simulate.form.actionOverridesDescription",defaultMessage:"Allow the watch to execute or skip actions. {actionsLink}",values:{actionsLink:Object(p.jsx)(E.EuiLink,{href:r,target:"_blank"},v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.actionOverridesDescription.linkLabel",{defaultMessage:"Learn about actions."}))}})},Object(p.jsx)(E.EuiFormRow,{label:v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.actionModesFieldLabel",{defaultMessage:"Action modes"}),fullWidth:!0},Object(p.jsx)(E.EuiBasicTable,{items:n,itemId:"simulateExecutionActionModesTable",columns:A}))),Object(p.jsx)(E.EuiDescribedFormGroup,{fullWidth:!0,title:Object(p.jsx)("h2",null,v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.inputOverridesTitle",{defaultMessage:"Input"})),description:v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.inputOverridesDescription",{defaultMessage:"Enter JSON data to override the watch payload that comes from running the input."})},Object(p.jsx)(Oe,{id:"executeWatchJson",label:v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.alternativeInputFieldLabel",{defaultMessage:"Alternative input"}),errorKey:"json",isShowingErrors:t,fullWidth:!0,errors:e},Object(p.jsx)(o.CodeEditor,{languageId:"json",value:_,"data-test-subj":"jsonEditor",height:200,options:{fontSize:12,tabSize:2,scrollBeyondLastLine:!1},"aria-label":v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.alternativeInputAriaLabel",{defaultMessage:"Code editor"}),onChange:e=>{T(e),i(new execute_details_ExecuteDetails({...a,alternativeInput:S(e)}))}}))),Object(p.jsx)(E.EuiButton,{iconType:"play","data-test-subj":"simulateWatchButton",fill:!0,type:"submit",isLoading:d,isDisabled:t||b,onClick:async()=>{h(!0);const{data:e,error:t}=await oe(a,c);if(h(!1),t)return m(t);const s=watch_history_item_WatchHistoryItem.fromUpstreamJson(e.watchHistoryItem);u(s)}},v.i18n.translate("xpack.watcher.sections.watchEdit.simulate.form.saveButtonLabel",{defaultMessage:"Simulate watch"}))),Object(p.jsx)(ut,{executeResults:l,executeDetails:a,error:g,onCloseFlyout:()=>{u(null),m(null)}}))},pt="watchEditTab",jt="watchSimulateTab",bt=[{id:pt,name:v.i18n.translate("xpack.watcher.sections.watchEdit.json.editTabLabel",{defaultMessage:"Edit"})},{id:jt,name:v.i18n.translate("xpack.watcher.sections.watchEdit.json.simulateTabLabel",{defaultMessage:"Simulate"})}],xt={triggeredTimeValue:0,triggeredTimeUnit:J.l.SECOND,scheduledTimeValue:0,scheduledTimeUnit:J.l.SECOND,ignoreCondition:!1};function wt(e){return e.reduce(((e,t)=>(t.actionId&&(e[t&&t.actionId]=t.actionMode),e)),{})}const ft=({pageTitle:e})=>{const{watch:t}=Object(s.useContext)(Ce),a=function(e){const t=e.watch&&e.watch.actions||{};return Object.keys(t).map((e=>({actionId:e,type:De(t[e]),actionMode:J.a.SIMULATE})))}(t),[i,n]=Object(s.useState)(pt),[o,r]=Object(s.useState)(new execute_details_ExecuteDetails({...xt,actionModes:wt(a)})),c=o.validate(),l=!!Object.keys(c).find((e=>c[e].length>=1));return Object(p.jsx)(E.EuiPageContentBody_Deprecated,{restrictWidth:!0,style:{width:"100%"}},Object(p.jsx)(E.EuiPageHeader,{pageTitle:Object(p.jsx)("span",{"data-test-subj":"pageTitle"},e),bottomBorder:!0,tabs:bt.map(((e,t)=>({onClick:()=>{n(e.id),r(new execute_details_ExecuteDetails({...o,actionModes:wt(a)}))},isSelected:e.id===i,key:t,"data-test-subj":"tab",label:e.name})))}),Object(p.jsx)(E.EuiSpacer,{size:"l"}),i===jt&&Object(p.jsx)(mt,{executeDetails:o,setExecuteDetails:e=>r(e),executeWatchErrors:c,hasExecuteWatchErrors:l,watchActions:a}),i===pt&&Object(p.jsx)(lt,null))},yt=({pageTitle:e})=>{const{watch:t}=Object(s.useContext)(Ce),{history:a}=je(),i=Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.monitoring.edit.calloutDescriptionText",defaultMessage:"Watch '{watchName}' is a system watch and cannot be edited.",values:{watchName:t.name}});return Object(p.jsx)(E.EuiPageContent_Deprecated,{verticalPosition:"center",horizontalPosition:"center",color:"subdued"},Object(p.jsx)(E.EuiEmptyPrompt,{iconType:"",title:Object(p.jsx)("h1",null,e),body:Object(p.jsx)("p",null,i),actions:[Object(p.jsx)(E.EuiLink,Object(o.reactRouterNavigate)(a,`/watches/watch/${t.id}/status`),Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.monitoring.header.watchLinkTitle",defaultMessage:"View watch status"}))]}))};var Ot=a(31),Et=a(26),vt=a.n(Et),kt=a(32),Mt=a.n(kt);class VisualizeOptions{constructor(e={}){this.rangeFrom=e.rangeFrom,this.rangeTo=e.rangeTo,this.interval=e.interval,this.timezone=e.timezone}get upstreamJson(){return{rangeFrom:this.rangeFrom,rangeTo:this.rangeTo,interval:this.interval,timezone:this.timezone}}}const Tt=e=>{const t="dateFormat:tz";if(!e.isDefault(t))return e.get(t);return Mt.a.tz.guess()||Mt()().format("Z")},St=e=>{const t=`now-${5*e.timeWindowSize}${e.timeWindowUnit}`,a=vt.a.parse(t),s=vt.a.parse("now");return{min:a?a.valueOf():0,max:s?s.valueOf():0}},_t=()=>{const{createTimeBuckets:e,theme:t,uiSettings:a}=je(),{watch:i}=Object(s.useContext)(Ce),n=t.useChartsTheme(),{index:o,timeField:r,triggerIntervalSize:c,triggerIntervalUnit:l,aggType:u,aggField:d,termSize:h,termField:g,thresholdComparator:m,timeWindowSize:j,timeWindowUnit:b,groupBy:x,threshold:w}=i,f=Object(s.useMemo)((()=>St(i)),[i]),y=e();y.setBounds(f);const O=y.getInterval().expression,v=new VisualizeOptions({rangeFrom:f.min,rangeTo:f.max,interval:O,timezone:Tt(a)}),M=new threshold_watch_ThresholdWatch({...i,actions:[]}),{isInitialRequest:T,isLoading:S,data:_,error:A,resendRequest:F}=((e,t)=>K({path:`${Z}/watch/visualize`,method:"post",body:JSON.stringify({watch:e.upstreamJson,options:t.upstreamJson}),deserializer:re}))(M,v);if(Object(s.useEffect)((()=>{T||F()}),[o,r,c,l,u,d,h,g,m,j,b,x,w]),T&&S)return Object(p.jsx)(E.EuiEmptyPrompt,{title:Object(p.jsx)(E.EuiLoadingChart,{size:"xl"}),body:Object(p.jsx)(E.EuiText,{color:"subdued"},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.loadingWatchVisualizationDescription",defaultMessage:"Loading watch visualization…"}))});if(A)return Object(p.jsx)(s.Fragment,null,Object(p.jsx)(E.EuiSpacer,{size:"l"}),Object(p.jsx)(Se,{title:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.errorLoadingWatchVisualizationTitle",defaultMessage:"Cannot load watch visualization"}),error:A}),Object(p.jsx)(E.EuiSpacer,{size:"l"}));if(_){const t=Object.keys(_),s=Tt(a),o=(e=>e.threshold.slice(0,U[e.thresholdComparator].requiredValues))(i);let r=o[o.length-1];Object.values(_).forEach((e=>{e.forEach((([,e])=>{e>r&&(r=e)}))}));const c=t=>Mt()(t).tz(s).format(((e,t)=>{const a=St(e);return t.setBounds(a),t})(i,e()).getScaledDateFormat()),l=z[i.aggType].text;return Object(p.jsx)("div",{"data-test-subj":"watchVisualizationChart"},Object(p.jsx)(E.EuiSpacer,{size:"l"}),t.length?Object(p.jsx)(Ot.Chart,{size:["100%",300],renderer:"canvas"},Object(p.jsx)(Ot.Settings,{theme:[{lineSeriesStyle:{line:{strokeWidth:3},point:{visible:!1}}},n],xDomain:f,showLegend:!!i.termField,showLegendExtra:!0,legendPosition:Ot.Position.Bottom}),Object(p.jsx)(Ot.Axis,{id:"bottom",position:Ot.Position.Bottom,showOverlappingTicks:!0,tickFormat:c}),Object(p.jsx)(Ot.Axis,{domain:{max:r,min:NaN},id:"left",title:l,position:Ot.Position.Left}),t.map((e=>Object(p.jsx)(Ot.LineSeries,{key:e,id:e,xScaleType:Ot.ScaleType.Time,yScaleType:Ot.ScaleType.Linear,data:_[e],xAccessor:0,yAccessors:[1],timeZone:s}))),o.map(((e,t)=>{const a=0===t?"threshold":`threshold${t}`;return Object(p.jsx)(Ot.LineAnnotation,{key:a,id:a,domainType:Ot.AnnotationDomainType.YDomain,dataValues:[{dataValue:i.threshold[t],details:a}]})}))):Object(p.jsx)(E.EuiCallOut,{title:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.thresholdPreviewChart.noDataTitle",defaultMessage:"No data"}),color:"warning"},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.thresholdPreviewChart.dataDoesNotExistTextMessage",defaultMessage:"Your index and condition did not return any data."})),Object(p.jsx)(E.EuiSpacer,{size:"l"}))}return null},At=v.i18n.translate("xpack.watcher.sections.watchEdit.actions.disabledOptionLabel",{defaultMessage:"Disabled. Configure your elasticsearch.yml."}),Ft=({settings:e,isLoading:t})=>{const{addAction:a}=Object(s.useContext)(Ce),[i,n]=Object(s.useState)(!1),o=action_Action.getActionTypes(),r=Object.entries(o).map((([t,{typeName:a,iconClass:s,selectMessage:i}])=>({type:t,typeName:a,iconClass:s,selectMessage:i,isEnabled:!(e&&e.actionTypes&&e.actionTypes[t]&&void 0!==e.actionTypes[t].enabled)||e.actionTypes[t].enabled}))),c=Object(p.jsx)(E.EuiButton,{"data-test-subj":"addWatchActionButton",iconType:"arrowDown",iconSide:"right",onClick:()=>n(!i)},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.actions.addActionButtonLabel",defaultMessage:"Add action"}));return Object(p.jsx)(E.EuiPopover,{id:"watchActionPanel",button:c,isOpen:i,closePopover:()=>n(!1),panelPaddingSize:"none",anchorPosition:"downLeft"},Object(p.jsx)(E.EuiContextMenuPanel,{items:r.map(((e,t)=>{const s=e.type===J.c.EMAIL&&!e.isEnabled,i=s?At:e.selectMessage;return Object(p.jsx)(E.EuiContextMenuItem,{key:`${e.type}-${t}`,disabled:s,"data-test-subj":`${e.type}ActionButton`,onClick:()=>{a({type:e.type,defaults:{isNew:!0}}),n(!1)}},Object(p.jsx)(E.EuiFlexGroup,{responsive:!1},Object(p.jsx)(E.EuiFlexItem,{grow:!1,className:"watcherThresholdWatchActionContextMenuItem"},Object(p.jsx)(E.EuiIcon,{type:e.iconClass})),Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)("strong",null,e.typeName),Object(p.jsx)(E.EuiSpacer,{size:"xs"}),Object(p.jsx)(E.EuiText,{size:"s"},Object(p.jsx)("p",null,i)))))}))}))},It=["head","get","post","put","delete"],Jt=["http","https"],Lt={[J.c.LOGGING]:({action:e,editAction:t,errors:a,hasErrors:s})=>{const{text:i}=e;return Object(p.jsx)(Oe,{id:"loggingText",errorKey:"text",fullWidth:!0,errors:a,isShowingErrors:s&&void 0!==i,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.loggingAction.logTextFieldLabel",{defaultMessage:"Log text"})},Object(p.jsx)(E.EuiFieldText,{fullWidth:!0,name:"text",value:i||"","data-test-subj":"loggingTextInput",onChange:e=>{t({key:"text",value:e.target.value})},onBlur:()=>{i||t({key:"text",value:""})}}))},[J.c.SLACK]:({action:e,editAction:t,children:a})=>{const{text:i,to:n}=e,o=n?n.map((e=>({label:e}))):[];return Object(p.jsx)(s.Fragment,null,a,Object(p.jsx)(E.EuiFormRow,{fullWidth:!0,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.slackAction.recipientTextFieldLabel",{defaultMessage:"Recipient (optional)"})},Object(p.jsx)(E.EuiComboBox,{noSuggestions:!0,fullWidth:!0,selectedOptions:o,"data-test-subj":"slackRecipientComboBox",onCreateOption:e=>{const a=[...o,{label:e}];t({key:"to",value:a.map((e=>e.label))})},onChange:e=>{t({key:"to",value:e.map((e=>e.label))})}})),Object(p.jsx)(E.EuiFormRow,{fullWidth:!0,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.slackAction.messageTextAreaFieldLabel",{defaultMessage:"Message (optional)"})},Object(p.jsx)(E.EuiTextArea,{fullWidth:!0,name:"text",value:i,"data-test-subj":"slackMessageTextarea",onChange:e=>{t({key:"text",value:e.target.value})}})))},[J.c.EMAIL]:({action:e,editAction:t,errors:a,hasErrors:i})=>{const{to:n,subject:o,body:r}=e,c=n?n.map((e=>({label:e}))):[];return Object(p.jsx)(s.Fragment,null,Object(p.jsx)(Oe,{id:"emailRecipient",errorKey:"to",fullWidth:!0,errors:a,isShowingErrors:i&&void 0!==n,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.emailAction.recipientTextFieldLabel",{defaultMessage:"To email address"})},Object(p.jsx)(E.EuiComboBox,{noSuggestions:!0,fullWidth:!0,"data-test-subj":"toEmailAddressInput",selectedOptions:c,onCreateOption:e=>{const a=[...c,{label:e}];t({key:"to",value:a.map((e=>e.label))})},onChange:e=>{t({key:"to",value:e.map((e=>e.label))})},onBlur:()=>{n||t({key:"to",value:[]})}})),Object(p.jsx)(E.EuiFormRow,{fullWidth:!0,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.emailAction.subjectTextFieldLabel",{defaultMessage:"Subject (optional)"})},Object(p.jsx)(E.EuiFieldText,{fullWidth:!0,name:"subject","data-test-subj":"emailSubjectInput",value:o||"",onChange:e=>{t({key:"subject",value:e.target.value})}})),Object(p.jsx)(E.EuiFormRow,{fullWidth:!0,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.emailAction.bodyTextAreaFieldLabel",{defaultMessage:"Body"})},Object(p.jsx)(E.EuiTextArea,{fullWidth:!0,value:r||"",name:"body","data-test-subj":"emailBodyInput",onChange:e=>{t({key:"body",value:e.target.value})}})))},[J.c.INDEX]:({action:e,editAction:t,errors:a,hasErrors:s})=>{const{index:i}=e;return Object(p.jsx)(Oe,{id:"indexName",errorKey:"index",fullWidth:!0,errors:a,isShowingErrors:s&&void 0!==i,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.indexAction.indexFieldLabel",{defaultMessage:"Index"})},Object(p.jsx)(E.EuiFieldText,{fullWidth:!0,name:"index","data-test-subj":"indexInput",value:i||"",onChange:e=>{t({key:"index",value:e.target.value})},onBlur:()=>{i||t({key:"index",value:""})}}))},[J.c.WEBHOOK]:({action:e,editAction:t,errors:a,hasErrors:i})=>{const{method:n,host:r,port:c,scheme:l,path:u,body:d,username:h,password:g}=e;return Object(s.useEffect)((()=>{t({key:"contentType",value:"application/json"})}),[t]),Object(p.jsx)(s.Fragment,null,Object(p.jsx)(E.EuiFlexGroup,{justifyContent:"spaceBetween"},Object(p.jsx)(E.EuiFlexItem,null,Object(p.jsx)(E.EuiFormRow,{label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.webhookAction.methodFieldLabel",{defaultMessage:"Method"})},Object(p.jsx)(E.EuiSelect,{name:"method",value:n||"get","data-test-subj":"webhookMethodSelect",options:It.map((e=>({text:e.toUpperCase(),value:e}))),onChange:e=>{t({key:"method",value:e.target.value})}}))),Object(p.jsx)(E.EuiFlexItem,null,Object(p.jsx)(E.EuiFormRow,{label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.webhookAction.schemeFieldLabel",{defaultMessage:"Scheme"})},Object(p.jsx)(E.EuiSelect,{name:"scheme",value:l,"data-test-subj":"webhookSchemeSelect",options:Jt.map((e=>({text:e,value:e}))),onChange:e=>{t({key:"scheme",value:e.target.value})}}))),Object(p.jsx)(E.EuiFlexItem,null,Object(p.jsx)(Oe,{id:"webhookHost",errorKey:"host",fullWidth:!0,errors:a,isShowingErrors:i&&void 0!==r,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.webhookAction.hostFieldLabel",{defaultMessage:"Host"})},Object(p.jsx)(E.EuiFieldText,{fullWidth:!0,name:"host",value:r||"","data-test-subj":"webhookHostInput",onChange:e=>{t({key:"host",value:e.target.value})},onBlur:()=>{r||t({key:"host",value:""})}}))),Object(p.jsx)(E.EuiFlexItem,null,Object(p.jsx)(Oe,{id:"webhookPort",errorKey:"port",fullWidth:!0,errors:a,isShowingErrors:i&&void 0!==c,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.webhookAction.methodPortLabel",{defaultMessage:"Port"})},Object(p.jsx)(E.EuiFieldNumber,{prepend:":",fullWidth:!0,name:"port",value:c||"","data-test-subj":"webhookPortInput",onChange:e=>{t({key:"port",value:parseInt(e.target.value,10)})},onBlur:()=>{c||t({key:"port",value:""})}}))),Object(p.jsx)(E.EuiFlexItem,null,Object(p.jsx)(E.EuiFormRow,{fullWidth:!0,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.webhookAction.pathFieldLabel",{defaultMessage:"Path (optional)"})},Object(p.jsx)(E.EuiFieldText,{prepend:"/",fullWidth:!0,name:"path",value:u||"","data-test-subj":"webhookPathInput",onChange:e=>{t({key:"path",value:e.target.value})}})))),Object(p.jsx)(E.EuiFlexGroup,null,Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(Oe,{id:"webhookBasicAuthUsername",errorKey:"username",isShowingErrors:i,errors:a,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.webhookAction.basicAuthUsername",{defaultMessage:"Username (optional)"})},Object(p.jsx)(E.EuiFieldText,{name:"username",value:h||"","data-test-subj":"webhookUsernameInput",onChange:e=>{t({key:"username",value:e.target.value})}}))),Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(Oe,{id:"webhookBasicAuthPassword",errorKey:"password",isShowingErrors:i,errors:a,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.webhookAction.basicAuthPassword",{defaultMessage:"Password (optional)"})},Object(p.jsx)(E.EuiFieldPassword,{name:"password",value:g||"","data-test-subj":"webhookPasswordInput",onChange:e=>{t({key:"password",value:e.target.value})}})))),Object(p.jsx)(E.EuiSpacer,{size:"s"}),Object(p.jsx)(Oe,{id:"webhookBody",label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.webhookAction.bodyFieldLabel",{defaultMessage:"Body"}),errorKey:"body",isShowingErrors:i,fullWidth:!0,errors:a},Object(p.jsx)(o.CodeEditor,{languageId:"json",value:d||"","data-test-subj":"webhookBodyEditor",height:200,options:{lineNumbers:"off",tabSize:2,scrollBeyondLastLine:!1},"aria-label":v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.webhookAction.bodyCodeEditorAriaLabel",{defaultMessage:"Code editor"}),onChange:e=>{t({key:"body",value:e})}})))},[J.c.PAGERDUTY]:({errors:e,hasErrors:t,action:a,editAction:i,children:n})=>{const{description:o}=a;return Object(p.jsx)(s.Fragment,null,n,Object(p.jsx)(Oe,{id:"pagerDutyDescription",errorKey:"description",fullWidth:!0,errors:e,isShowingErrors:t&&void 0!==o,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.pagerDutyAction.descriptionFieldLabel",{defaultMessage:"Description"})},Object(p.jsx)(E.EuiFieldText,{fullWidth:!0,name:"description",value:o||"","data-test-subj":"pagerdutyDescriptionInput",onChange:e=>{i({key:"description",value:e.target.value})},onBlur:()=>{o||i({key:"description",value:""})}})))},[J.c.JIRA]:({action:e,editAction:t,errors:a,hasErrors:i,children:n})=>{const{projectKey:o,issueType:r,summary:c}=e;return Object(p.jsx)(s.Fragment,null,n,Object(p.jsx)(Oe,{id:"jiraProjectKey",errorKey:"projectKey",fullWidth:!0,errors:a,isShowingErrors:i&&void 0!==o,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.jiraAction.projectKeyFieldLabel",{defaultMessage:"Project key"})},Object(p.jsx)(E.EuiFieldText,{fullWidth:!0,name:"projectKey",value:o||"","data-test-subj":"jiraProjectKeyInput",onChange:e=>{t({key:"projectKey",value:e.target.value})},onBlur:()=>{o||t({key:"projectKey",value:""})}})),Object(p.jsx)(Oe,{id:"jiraIssueType",errorKey:"issueType",fullWidth:!0,errors:a,isShowingErrors:i&&void 0!==r,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.jiraAction.issueTypeFieldLabel",{defaultMessage:"Issue type"})},Object(p.jsx)(E.EuiFieldText,{fullWidth:!0,value:r||"",name:"issueType","data-test-subj":"jiraIssueTypeInput",onChange:e=>{t({key:"issueType",value:e.target.value})},onBlur:()=>{r||t({key:"issueType",value:""})}})),Object(p.jsx)(Oe,{id:"jiraSummary",errorKey:"summary",fullWidth:!0,errors:a,isShowingErrors:i&&void 0!==c,label:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.jiraAction.summaryFieldLabel",{defaultMessage:"Summary"})},Object(p.jsx)(E.EuiFieldText,{fullWidth:!0,value:c||"",name:"summary","data-test-subj":"jiraSummaryInput",onChange:e=>{t({key:"summary",value:e.target.value})},onBlur:()=>{c||t({key:"summary",value:""})}})))}},Ct=({settings:e,actionErrors:t})=>{const{links:{watchActionsConfigurationMap:a},toasts:i}=je(),{watch:n,setWatchProperty:o}=Object(s.useContext)(Ce),{actions:r}=n,[c,l]=Object(s.useState)({}),[u,d]=Object(s.useState)(null);return r&&r.length>=1?r.map((h=>{const g=Lt[h.type],m=t[h.id],j=!!Object.keys(m).find((e=>m[e].length>=1));return Object(p.jsx)(E.EuiAccordion,{initialIsOpen:h.isNew||j,key:h.id,id:h.id,className:"euiAccordionForm",buttonContentClassName:"euiAccordionForm__button","data-test-subj":"watchActionAccordion",buttonContent:Object(p.jsx)(E.EuiFlexGroup,{gutterSize:"s",alignItems:"center"},Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiIcon,{type:h.iconClass,size:"m"})),Object(p.jsx)(E.EuiFlexItem,null,Object(p.jsx)(E.EuiTitle,{size:"s",className:"euiAccordionForm__title"},Object(p.jsx)("h6",null,h.typeName)))),extraAction:Object(p.jsx)(E.EuiButtonIcon,{iconType:"cross",color:"danger",className:"euiAccordionForm__extraAction","aria-label":v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.accordion.deleteIconAriaLabel",{defaultMessage:"Delete"}),onClick:()=>{const e=r.filter((e=>e.id!==h.id));o("actions",e)}}),paddingSize:"l"},u&&u[h.id]&&Object(p.jsx)(s.Fragment,null,Object(p.jsx)(Se,{title:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.threshold.accordion.simulateResultsErrorTitle",defaultMessage:"Error testing action"}),error:u[h.id]}),Object(p.jsx)(E.EuiSpacer,{size:"s"})),Object(p.jsx)(E.EuiForm,null,Object(p.jsx)(g,{action:h,errors:m,hasErrors:j,editAction:e=>{const t=r.map((t=>{if(t.id===h.id){const t=action_Action.getActionTypes()[h.type],{key:a,value:s}=e;return new t({...h,[a]:s})}return t}));o("actions",t)}},e&&!1===e.actionTypes[h.type].enabled?Object(p.jsx)(s.Fragment,null,Object(p.jsx)(E.EuiCallOut,{title:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.actions.actionConfigurationWarningTitleText",{defaultMessage:"Account may not be configured"}),color:"warning",iconType:"help"},Object(p.jsx)(E.EuiText,null,Object(p.jsx)("p",null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.threshold.actions.actionConfigurationWarningDescriptionText",defaultMessage:"To create this action, you must configure at least one {accountType} account. {docLink}",values:{accountType:h.typeName,docLink:Object(p.jsx)(E.EuiLink,{href:a[h.type],target:"_blank"},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.threshold.actions.actionConfigurationWarningHelpLinkText",defaultMessage:"Learn more."}))}})))),Object(p.jsx)(E.EuiSpacer,null)):null),Object(p.jsx)(E.EuiButton,{type:"submit",isDisabled:j,isLoading:c[h.id],"data-test-subj":"simulateActionButton",onClick:async()=>{const e=n.actions.filter((e=>e.id===h.id)),t=new execute_details_ExecuteDetails({ignoreCondition:!0,recordExecution:!1,actionModes:{[h.id]:J.a.FORCE_EXECUTE}}),a=new threshold_watch_ThresholdWatch({...n,actions:e});l({[h.id]:!0}),d(null);const{data:s,error:o}=await oe(t,a);if(l({[h.id]:!1}),o)return d({[h.id]:o});const r=watch_history_item_WatchHistoryItem.fromUpstreamJson(s.watchHistoryItem).watchStatus.actionStatuses.find((e=>e.id===h.id));if(r&&!1===r.isLastExecutionSuccessful){const e=r.lastExecutionReason||h.simulateFailMessage;return i.addDanger(e)}return i.addSuccess(h.simulateMessage)}},h.simulatePrompt)))})):null},Wt=({actionErrors:e})=>{const{watch:t}=Object(s.useContext)(Ce),{data:a,isLoading:i}=K({path:`${Z}/settings`,method:"get",deserializer:ce});return Object(p.jsx)("div",{"data-test-subj":"watchActionsPanel"},Object(p.jsx)(E.EuiFlexGroup,{justifyContent:"spaceBetween",alignItems:"center"},Object(p.jsx)(E.EuiFlexItem,null,Object(p.jsx)(E.EuiTitle,{size:"s"},Object(p.jsx)("h2",null,v.i18n.translate("xpack.watcher.sections.watchEdit.actions.title",{defaultMessage:"Perform {watchActionsCount, plural, one{# action} other {# actions}} when condition is met",values:{watchActionsCount:t.actions.length}})))),Object(p.jsx)(E.EuiFlexItem,{className:"watcherThresholdWatchActionDropdownContainer"},Object(p.jsx)(Ft,{settings:a,isLoading:i}))),Object(p.jsx)(E.EuiSpacer,{size:"l"}),Object(p.jsx)(Ct,{settings:a,actionErrors:e}))},Dt=["aggField","termSize","termField","threshold0","threshold1","timeWindowSize"],Nt=["aggType","aggField","termSize","termField","thresholdComparator","timeWindowSize","timeWindowUnit","triggerIntervalSize","triggerIntervalUnit","threshold","groupBy"],Pt=v.i18n.translate("xpack.watcher.thresholdWatchExpression.fixErrorInExpressionBelowValidationMessage",{defaultMessage:"Expression contains errors."}),Rt={text:v.i18n.translate("xpack.watcher.sections.watchEdit.titlePanel.timeFieldOptionLabel",{defaultMessage:"Select a field"}),value:""},Bt=e=>Object.entries(J.l).map((([t,a])=>({text:B(a,e),value:a}))),zt=async e=>await(async e=>{const{fields:t}=await X().post(`${Z}/fields`,{body:JSON.stringify({indexes:e})});return t})(e),Ht=e=>{const t=[Rt];return e.forEach((e=>{"date"===e.type&&t.push({text:e.name,value:e.name})})),t},Ut=({pageTitle:e})=>{const{toasts:t}=je(),[a,i]=Object(s.useState)([]),[n,o]=Object(s.useState)([]),[r,c]=Object(s.useState)([]),[l,u]=Object(s.useState)([Rt]),[d,h]=Object(s.useState)(!1),[g,m]=Object(s.useState)(!1),[j,b]=Object(s.useState)(!1),[x,w]=Object(s.useState)(!1),[f,O]=Object(s.useState)(!1),[M,T]=Object(s.useState)(null),[S,_]=Object(s.useState)(!1),[A,F]=Object(s.useState)(!1),[I,J]=Object(s.useState)(!1),{watch:L,setWatchProperty:C}=Object(s.useContext)(Ce);Object(s.useEffect)((()=>{(async()=>{if(L.index&&L.index.length>0){const e=await zt(L.index),t=Ht(e);o(e),u(t),C("timeFields",t)}(async()=>{const{data:e}=await(async()=>$({path:`${Z}/indices/index_patterns`,method:"get"}))();i(e)})()})()}),[]);const{errors:W}=L.validate(),D=!!Object.keys(W).find((e=>W[e].length>=1)),N=L.actions.reduce(((e,t)=>{const a=t.validate();return e[t.id]=a,e}),{}),P=!!Object.keys(N).find((e=>!!Object.keys(N[e]).find((t=>N[e][t].length>=1)))),R=!!Object.keys(W).find((e=>Dt.includes(e)&&W[e].length>=1)),q=L.index&&L.index.length>0&&L.timeField,V=v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.andLabel",{defaultMessage:"AND"}),G={...L.upstreamJson,includeMetadata:!1};return Object(p.jsx)(E.EuiPageContentBody_Deprecated,{restrictWidth:!0,style:{width:"100%"}},Object(p.jsx)(E.EuiPageHeader,{pageTitle:Object(p.jsx)("span",{"data-test-subj":"pageTitle"},e),description:L.titleDescription,bottomBorder:!0}),Object(p.jsx)(E.EuiSpacer,{size:"l"}),Object(p.jsx)(E.EuiForm,{"data-test-subj":"thresholdWatchForm"},M&&Object(p.jsx)(s.Fragment,null,Object(p.jsx)(Se,{title:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.json.saveWatchErrorTitle",defaultMessage:"Error saving watch"}),error:M}),Object(p.jsx)(E.EuiSpacer,null)),Object(p.jsx)(Oe,{id:"watchName",label:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.titlePanel.watchNameLabel",defaultMessage:"Name"}),errorKey:"name",isShowingErrors:D&&void 0!==L.name,errors:W},Object(p.jsx)(E.EuiFieldText,{name:"name","data-test-subj":"nameInput",value:L.name||"",onChange:e=>{C("name",e.target.value)},onBlur:()=>{L.name||C("name","")}})),Object(p.jsx)(E.EuiSpacer,null),Object(p.jsx)(E.EuiFlexGroup,{justifyContent:"spaceBetween"},Object(p.jsx)(E.EuiFlexItem,null,Object(p.jsx)(Oe,{id:"indexSelectSearchBox",fullWidth:!0,label:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.titlePanel.indicesToQueryLabel",defaultMessage:"Indices to query"}),errorKey:"index",isShowingErrors:D&&void 0!==L.index,errors:W,helpText:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.titlePanel.howToBroadenSearchQueryDescription",defaultMessage:"Use * to broaden your query."})},Object(p.jsx)(E.EuiComboBox,{fullWidth:!0,async:!0,isLoading:A,noSuggestions:!r.length,options:r,"data-test-subj":"indicesComboBox",selectedOptions:(L.index||[]).map((e=>({label:e,value:e}))),onChange:async e=>{C("index",e.map((e=>e.value)));const t=e.map((e=>e.value));if(0===t.length)return u(Ht([])),C("timeFields",[]),void Nt.forEach((e=>{C(e,null)}));const a=await zt(t),s=Ht(a);o(a),C("timeFields",s),u(s)},onSearchChange:async e=>{F(!0),c(await(async(e,t)=>{const a=[];if(!e)return a;const s=await(async e=>{e.startsWith("*")||(e=`*${e}`),e.endsWith("*")||(e=`${e}*`);const t=JSON.stringify({pattern:e}),{indices:a}=await X().post(`${Z}/indices`,{body:t});return a})(e),i=t.filter((t=>t.includes(e)));if(s.length||i.length){const e=y.a.uniq([...s,...i]);a.push({label:v.i18n.translate("xpack.watcher.sections.watchEdit.titlePanel.indicesAndIndexPatternsLabel",{defaultMessage:"Based on your indices and index patterns"}),options:e.map((e=>({label:e,value:e}))).sort(((e,t)=>String(e.label).localeCompare(t.label)))})}return a.push({label:v.i18n.translate("xpack.watcher.sections.watchEdit.titlePanel.chooseLabel",{defaultMessage:"Choose…"}),options:[{key:"UNIQUE_CHOOSE_KEY",value:e,label:e}]}),a})(e,a)),F(!1)},onBlur:()=>{L.index||C("index",[])}}))),Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(Oe,{id:"timeField",fullWidth:!0,label:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.titlePanel.timeFieldLabel",defaultMessage:"Time field"}),errorKey:"timeField",isShowingErrors:D&&void 0!==L.timeField,errors:W},Object(p.jsx)(E.EuiSelect,{options:l,fullWidth:!0,name:"watchTimeField","data-test-subj":"watchTimeFieldSelect",value:L.timeField,onChange:e=>{C("timeField",e.target.value)},onBlur:()=>{void 0===L.timeField&&C("timeField","")}}))),Object(p.jsx)(E.EuiFlexItem,null,Object(p.jsx)(Oe,{id:"watchInterval",fullWidth:!0,label:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.titlePanel.watchIntervalLabel",defaultMessage:"Run watch every"}),errorKey:"triggerIntervalSize",isShowingErrors:D&&void 0!==L.triggerIntervalSize,errors:W},Object(p.jsx)(E.EuiFlexGroup,null,Object(p.jsx)(E.EuiFlexItem,null,Object(p.jsx)(E.EuiFieldNumber,{fullWidth:!0,min:1,value:L.triggerIntervalSize,"data-test-subj":"triggerIntervalSizeInput",onChange:e=>{const{value:t}=e.target,a=""!==t?parseInt(t,10):t;C("triggerIntervalSize",a)},onBlur:e=>{void 0===L.triggerIntervalSize&&C("triggerIntervalSize","")}})),Object(p.jsx)(E.EuiFlexItem,null,Object(p.jsx)(E.EuiSelect,{fullWidth:!0,value:L.triggerIntervalUnit,"aria-label":v.i18n.translate("xpack.watcher.sections.watchEdit.titlePanel.durationAriaLabel",{defaultMessage:"Duration time unit"}),onChange:e=>{C("triggerIntervalUnit",e.target.value)},options:Bt(L.triggerIntervalSize)})))))),Object(p.jsx)(E.EuiSpacer,null),q?Object(p.jsx)(s.Fragment,null,Object(p.jsx)(E.EuiTitle,{size:"s"},Object(p.jsx)("h2",{"data-test-subj":"watchConditionTitle"},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.watchConditionSectionTitle",defaultMessage:"Match the following condition"}))),Object(p.jsx)(E.EuiSpacer,{size:"m"}),Object(p.jsx)(E.EuiFlexGroup,{gutterSize:"s"},Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiPopover,{id:"aggTypePopover",button:Object(p.jsx)(E.EuiExpression,{description:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.whenLabel",{defaultMessage:"when"}),value:z[L.aggType].text,isActive:f,onClick:()=>{O(!0)}}),isOpen:f,closePopover:()=>{O(!1)},ownFocus:!0,anchorPosition:"downLeft"},Object(p.jsx)("div",null,Object(p.jsx)(E.EuiPopoverTitle,null,v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.whenButtonLabel",{defaultMessage:"when"})),Object(p.jsx)(E.EuiSelect,{value:L.aggType,onChange:e=>{C("aggType",e.target.value),O(!1)},options:Object.values(z).map((({text:e,value:t})=>({text:e,value:t})))})))),L.aggType&&z[L.aggType].fieldRequired?Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiPopover,{id:"aggFieldPopover",button:Object(p.jsx)(E.EuiExpression,{description:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.ofLabel",{defaultMessage:"of"}),value:L.aggField||Rt.text,isActive:d||!L.aggField,onClick:()=>{h(!0)},color:L.aggField?"success":"danger"}),isOpen:d,closePopover:()=>{h(!1)},anchorPosition:"downLeft"},Object(p.jsx)("div",null,Object(p.jsx)(E.EuiPopoverTitle,null,v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.ofButtonLabel",{defaultMessage:"of"})),Object(p.jsx)(E.EuiFlexGroup,null,Object(p.jsx)(E.EuiFlexItem,{grow:!1,className:"watcherThresholdAlertAggFieldContainer"},Object(p.jsx)(Oe,{errorKey:"aggField",isShowingErrors:D&&void 0!==L.aggField,errors:W},Object(p.jsx)(E.EuiComboBox,{singleSelection:{asPlainText:!0},placeholder:Rt.text,options:n.reduce(((e,t)=>(z[L.aggType].validNormalizedTypes.includes(t.normalizedType)&&e.push({label:t.name}),e)),[]),selectedOptions:L.aggField?[{label:L.aggField}]:[],onChange:e=>{C("aggField",1===e.length?e[0].label:void 0),h(!1)}}))))))):null,Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiPopover,{id:"groupByPopover",button:Object(p.jsx)(E.EuiExpression,{description:`${H[L.groupBy].sizeRequired?v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.groupedOverLabel",{defaultMessage:"grouped over"}):v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.overLabel",{defaultMessage:"over"})}`,value:`${H[L.groupBy].text} ${H[L.groupBy].sizeRequired?`${L.termSize||""} ${L.termField?`'${L.termField}'`:""}`:""}`,isActive:g||"top"===L.groupBy&&!(L.termSize&&L.termField),onClick:()=>{m(!0)},color:"all"===L.groupBy||L.termSize&&L.termField?"success":"danger"}),isOpen:g,closePopover:()=>{m(!1)},ownFocus:!0,anchorPosition:"downLeft"},Object(p.jsx)("div",null,Object(p.jsx)(E.EuiPopoverTitle,null,v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.overButtonLabel",{defaultMessage:"over"})),Object(p.jsx)(E.EuiFlexGroup,null,Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiSelect,{value:L.groupBy,onChange:e=>{C("termSize",null),C("termField",null),C("groupBy",e.target.value)},options:Object.values(H).map((({text:e,value:t})=>({text:e,value:t})))})),H[L.groupBy].sizeRequired?Object(p.jsx)(s.Fragment,null,Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(Oe,{errorKey:"termSize",isShowingErrors:D,errors:W},Object(p.jsx)(E.EuiFieldNumber,{value:L.termSize,onChange:e=>{C("termSize",e.target.value)},min:1}))),Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(Oe,{errorKey:"termField",isShowingErrors:D&&void 0!==L.termField,errors:W},Object(p.jsx)(E.EuiSelect,{value:L.termField||"",onChange:e=>{C("termField",e.target.value)},options:n.reduce(((e,t)=>(H[L.groupBy].validNormalizedTypes.includes(t.normalizedType)&&e.push({text:t.name,value:t.name}),e)),[Rt])})))):null)))),Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiPopover,{id:"watchThresholdPopover",button:Object(p.jsx)(E.EuiExpression,{"data-test-subj":"watchThresholdButton",description:U[L.thresholdComparator].text,value:L.threshold.slice(0,U[L.thresholdComparator].requiredValues).join(` ${V} `),isActive:Boolean(j||W.threshold0.length||W.threshold1&&W.threshold1.length),onClick:()=>{b(!0)},color:W.threshold0.length||W.threshold1&&W.threshold1.length?"danger":"success"}),isOpen:j,closePopover:()=>{b(!1)},ownFocus:!0,anchorPosition:"downLeft"},Object(p.jsx)("div",null,Object(p.jsx)(E.EuiPopoverTitle,null,U[L.thresholdComparator].text),Object(p.jsx)(E.EuiFlexGroup,null,Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiSelect,{value:L.thresholdComparator,onChange:e=>{C("thresholdComparator",e.target.value)},options:Object.values(U).map((({text:e,value:t})=>({text:e,value:t})))})),Array.from(Array(U[L.thresholdComparator].requiredValues)).map(((e,t)=>Object(p.jsx)(s.Fragment,{key:`threshold${t}`},t>0?Object(p.jsx)(E.EuiFlexItem,{grow:!1,className:"watcherThresholdWatchInBetweenComparatorText"},Object(p.jsx)(E.EuiText,null,V),D&&Object(p.jsx)(E.EuiSpacer,null)):null,Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(Oe,{errorKey:`threshold${t}`,isShowingErrors:D,errors:W},Object(p.jsx)(E.EuiFieldNumber,{"data-test-subj":"watchThresholdInput",value:null==L.threshold[t]?"":L.threshold[t],min:0,step:.1,onChange:e=>{const{value:a}=e.target,s=""!==a?parseFloat(a):a,i=[...L.threshold];i[t]=s,C("threshold",i)}})))))))))),Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiPopover,{id:"watchDurationPopover",button:Object(p.jsx)(E.EuiExpression,{description:v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.forTheLastLabel",{defaultMessage:"for the last"}),value:`${L.timeWindowSize} ${B(L.timeWindowUnit,parseInt(L.timeWindowSize,10).toString())}`,isActive:x||!L.timeWindowSize,onClick:()=>{w(!0)},color:L.timeWindowSize?"success":"danger"}),isOpen:x,closePopover:()=>{w(!1)},ownFocus:!0,anchorPosition:"downLeft"},Object(p.jsx)("div",null,Object(p.jsx)(E.EuiPopoverTitle,null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.threshold.forTheLastButtonLabel",defaultMessage:"For the last"})),Object(p.jsx)(E.EuiFlexGroup,null,Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(Oe,{errorKey:"timeWindowSize",isShowingErrors:D,errors:W},Object(p.jsx)(E.EuiFieldNumber,{min:1,value:L.timeWindowSize||"",onChange:e=>{const{value:t}=e.target,a=""!==t?parseInt(t,10):t;C("timeWindowSize",a)}}))),Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiSelect,{value:L.timeWindowUnit,onChange:e=>{C("timeWindowUnit",e.target.value)},options:Bt(L.timeWindowSize)}))))))),R?Object(p.jsx)(s.Fragment,null,Object(p.jsx)(E.EuiSpacer,{size:"m"}),Object(p.jsx)(E.EuiText,{color:"danger",size:"s"},Pt),Object(p.jsx)(E.EuiSpacer,{size:"m"})):null,D?null:Object(p.jsx)(s.Fragment,null,Object(p.jsx)(_t,null),Object(p.jsx)(Wt,{actionErrors:N})),Object(p.jsx)(E.EuiSpacer,null)):null,Object(p.jsx)(E.EuiFlexGroup,{justifyContent:"spaceBetween",alignItems:"center"},Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiFlexGroup,{gutterSize:"m",alignItems:"center"},Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiButton,{fill:!0,color:"success","data-test-subj":"saveWatchButton",type:"submit",iconType:"check",disabled:D||P,isLoading:S,onClick:async()=>{_(!0);const e=await rt(L,t);if(e&&e.error)return _(!1),T(e.error)}},L.isNew?Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.threshold.createButtonLabel",defaultMessage:"Create alert"}):Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.threshold.saveButtonLabel",defaultMessage:"Save alert"}))),Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiButtonEmpty,{onClick:()=>ue()},v.i18n.translate("xpack.watcher.sections.watchEdit.threshold.cancelButtonLabel",{defaultMessage:"Cancel"}))))),Object(p.jsx)(E.EuiFlexItem,{grow:!1},Object(p.jsx)(E.EuiButtonEmpty,{onClick:()=>J(!I)},I?Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.json.hideRequestButtonLabel",defaultMessage:"Hide request"}):Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.json.showRequestButtonLabel",defaultMessage:"Show request"}))))),I?Object(p.jsx)(request_flyout_RequestFlyout,{id:L.id,payload:st(G),close:()=>J(!1)}):null)},qt=(e,t)=>{const{command:a,payload:s}=t,{watch:i}=e;switch(a){case"setWatch":return{...e,watch:s};case"setProperty":const{property:t,value:a}=s;return Object(f.isEqual)(i[t],a)?e:{...e,watch:new(watch_Watch.getWatchTypes()[i.type])({...i,[t]:a})};case"addAction":const{type:n,defaults:o}=s,r=new(watch_Watch.getWatchTypes()[i.type])(i);return r.createAction(n,o),{...e,watch:r};case"setError":return{...e,loadError:s}}},Vt=({match:{params:{id:e,type:t}}})=>{const{setBreadcrumbs:a}=je(),[{watch:i,loadError:n},o]=Object(s.useReducer)(qt,{watch:null});Object(s.useEffect)((()=>{(async()=>{if(e)try{const t=await(async e=>{const{watch:t}=await X().get(`${Z}/watch/${e}`);return watch_Watch.fromUpstreamJson(t)})(e);o({command:"setWatch",payload:t})}catch(e){o({command:"setError",payload:e.body})}else if(t){const e=watch_Watch.getWatchTypes()[t];e&&o({command:"setWatch",payload:new e})}})()}),[e,t]),Object(s.useEffect)((()=>{a([M,e?S:T])}),[e,a]);const c=we(n);if(c)return Object(p.jsx)(E.EuiPageContent_Deprecated,{verticalPosition:"center",horizontalPosition:"center",color:"danger"},Object(p.jsx)(fe,{errorCode:c,id:e}));if(n)return Object(p.jsx)(r.PageError,{title:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.errorTitle",defaultMessage:"Error loading watch"}),error:n});if(!i)return Object(p.jsx)(E.EuiPageContent_Deprecated,{verticalPosition:"center",horizontalPosition:"center",color:"subdued"},Object(p.jsx)(Te,null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchEdit.loadingWatchDescription",defaultMessage:"Loading watch…"})));const l=(e=>{if(e.isNew){const t=e.typeName.toLowerCase();return v.i18n.translate("xpack.watcher.sections.watchEdit.json.titlePanel.createNewTypeOfWatchTitle",{defaultMessage:"Create {typeName}",values:{typeName:t}})}return v.i18n.translate("xpack.watcher.sections.watchEdit.json.titlePanel.editWatchTitle",{defaultMessage:"Edit {watchName}",values:{watchName:e.name?e.name:e.id}})})(i);let u=null;switch(i.type){case J.n.THRESHOLD:u=Ut;break;case J.n.MONITORING:u=yt;break;case J.n.JSON:default:u=ft}return Object(p.jsx)(Ce.Provider,{value:{watch:i,setWatchProperty:(e,t)=>{o({command:"setProperty",payload:{property:e,value:t}})},addAction:e=>{o({command:"addAction",payload:e})}}},Object(p.jsx)(u,{pageTitle:l}))},Gt=()=>{const{setBreadcrumbs:e,history:t,links:{watcherGettingStartedUrl:a}}=je(),[n,c]=Object(s.useState)(""),[l,d]=Object(s.useState)(null),[h,g]=Object(s.useState)([]),[m,j]=Object(s.useState)([]),[b,x]=Object(s.useState)([]),[w,f]=Object(s.useState)({pageIndex:0,pageSize:J.g.initialPageSize});Object(s.useEffect)((()=>{e([M])}),[e]);const{isLoading:y,data:O,error:T}=(S=J.i.WATCH_LIST,K({path:`${Z}/watches`,method:"get",pollIntervalMs:S,deserializer:Q}));var S;const[_,A]=Object(s.useState)(!1),F=Object(s.useMemo)((()=>O?O.filter((e=>!b.includes(e.id))):void 0),[O,b]),I=Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.subhead",defaultMessage:"Watch for changes or anomalies in your data and take action if needed."}),L=Object(p.jsx)(E.EuiPopover,{id:"createWatchPanel",button:Object(p.jsx)(E.EuiButton,{fill:!0,"data-test-subj":"createWatchButton",iconType:"arrowDown",iconSide:"right",onClick:()=>A(!_)},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.createWatchButtonLabel",defaultMessage:"Create"})),isOpen:_,closePopover:()=>A(!1),panelPaddingSize:"none",anchorPosition:"downCenter"},Object(p.jsx)(E.EuiContextMenuPanel,{items:[J.n.THRESHOLD,J.n.JSON].map((e=>Object(p.jsx)(E.EuiContextMenuItem,{key:e,"data-test-subj":`${e}WatchCreateLink`,onClick:()=>{A(!1),(e===J.n.THRESHOLD?de:he)()}},e===J.n.THRESHOLD?Object(p.jsx)(s.Fragment,null,Object(p.jsx)(E.EuiText,{size:"m"},Object(p.jsx)("span",null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.createThresholdAlertButtonLabel",defaultMessage:"Create threshold alert"}))),Object(p.jsx)(E.EuiText,{size:"s",color:"subdued"},Object(p.jsx)("span",null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.createThresholdAlertButtonTooltip",defaultMessage:"Send an alert on a specified condition."})))):Object(p.jsx)(s.Fragment,null,Object(p.jsx)(E.EuiText,{size:"m"},Object(p.jsx)("span",null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.createAdvancedWatchButtonLabel",defaultMessage:"Create advanced watch"}))),Object(p.jsx)(E.EuiText,{size:"s",color:"subdued"},Object(p.jsx)("span",null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.createAdvancedWatchTooltip",defaultMessage:"Set up a custom watch in JSON."})))))))}));if(y)return Object(p.jsx)(E.EuiPageContent_Deprecated,{verticalPosition:"center",horizontalPosition:"center",color:"subdued"},Object(p.jsx)(Te,null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.loadingWatchesDescription",defaultMessage:"Loading watches…"})));const C=we(T);if(C)return Object(p.jsx)(E.EuiPageContent_Deprecated,{verticalPosition:"center",horizontalPosition:"center",color:"danger"},Object(p.jsx)(fe,{errorCode:C}));if(T)return Object(p.jsx)(r.PageError,{title:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.errorTitle",defaultMessage:"Error loading watches"}),error:T});if(F&&0===F.length){const e=Object(p.jsx)(E.EuiText,{color:"subdued"},Object(p.jsx)("p",null,I," ",Object(p.jsx)(E.EuiLink,{href:a,target:"_blank"},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.watcherLearnMoreLinkText",defaultMessage:"Learn more."}))));return Object(p.jsx)(E.EuiPageContent_Deprecated,{verticalPosition:"center",horizontalPosition:"center",color:"subdued"},Object(p.jsx)(E.EuiEmptyPrompt,{iconType:"managementApp",title:Object(p.jsx)("h1",null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.emptyPromptTitle",defaultMessage:"You don’t have any watches yet"})),body:e,actions:L,"data-test-subj":"emptyPrompt"}))}let W;if(F){const e=[{field:"id",name:v.i18n.translate("xpack.watcher.sections.watchList.watchTable.idHeader",{defaultMessage:"ID"}),sortable:!0,truncateText:!1,render:e=>Object(p.jsx)(E.EuiLink,u()({"data-test-subj":`watchIdColumn-${e}`},Object(o.reactRouterNavigate)(t,`/watches/watch/${e}/status`)),e)},{field:"name",name:v.i18n.translate("xpack.watcher.sections.watchList.watchTable.nameHeader",{defaultMessage:"Name"}),render:(e,t)=>Object(p.jsx)("span",{"data-test-subj":`watchNameColumn-${t.id}`},e),sortable:!0,truncateText:!1},{field:"watchStatus.state",name:Object(p.jsx)(E.EuiToolTip,{content:v.i18n.translate("xpack.watcher.sections.watchList.watchTable.stateHeader.tooltipText",{defaultMessage:"Active, inactive, or error."})},Object(p.jsx)("span",null,v.i18n.translate("xpack.watcher.sections.watchList.watchTable.stateHeader",{defaultMessage:"State"})," ",Object(p.jsx)(E.EuiIcon,{size:"s",color:"subdued",type:"questionInCircle",className:"eui-alignTop"}))),sortable:!0,width:"130px",render:e=>Object(p.jsx)(ve,{state:e})},{field:"watchStatus.lastMetCondition",name:Object(p.jsx)(E.EuiToolTip,{content:v.i18n.translate("xpack.watcher.sections.watchList.watchTable.lastFiredHeader.tooltipText",{defaultMessage:"The last time the condition was met and action taken."})},Object(p.jsx)("span",null,v.i18n.translate("xpack.watcher.sections.watchList.watchTable.lastFiredHeader",{defaultMessage:"Condition last met"})," ",Object(p.jsx)(E.EuiIcon,{size:"s",color:"subdued",type:"questionInCircle",className:"eui-alignTop"}))),sortable:!0,truncateText:!0,width:"160px",render:e=>e?e.fromNow():e},{field:"watchStatus.lastChecked",name:Object(p.jsx)(E.EuiToolTip,{content:v.i18n.translate("xpack.watcher.sections.watchList.watchTable.lastTriggeredHeader.tooltipText",{defaultMessage:"The last time the condition was checked."})},Object(p.jsx)("span",null,v.i18n.translate("xpack.watcher.sections.watchList.watchTable.lastTriggeredHeader",{defaultMessage:"Last checked"})," ",Object(p.jsx)(E.EuiIcon,{size:"s",color:"subdued",type:"questionInCircle",className:"eui-alignTop"}))),sortable:!0,truncateText:!0,width:"160px",render:e=>e?e.fromNow():e},{field:"watchStatus.comment",name:Object(p.jsx)(E.EuiToolTip,{content:v.i18n.translate("xpack.watcher.sections.watchList.watchTable.commentHeader.tooltipText",{defaultMessage:"Whether any actions have been acknowledged, throttled, or failed to execute."})},Object(p.jsx)("span",null,v.i18n.translate("xpack.watcher.sections.watchList.watchTable.commentHeader",{defaultMessage:"Comment"})," ",Object(p.jsx)(E.EuiIcon,{size:"s",color:"subdued",type:"questionInCircle",className:"eui-alignTop"}))),sortable:!0,truncateText:!0},{name:v.i18n.translate("xpack.watcher.sections.watchList.watchTable.actionHeader",{defaultMessage:"Actions"}),width:"75px",actions:[{render:e=>{const a=v.i18n.translate("xpack.watcher.sections.watchList.watchTable.actionEditTooltipLabel",{defaultMessage:"Edit"});return Object(p.jsx)(E.EuiToolTip,{content:a,delay:"long"},Object(p.jsx)(E.EuiButtonIcon,u()({isDisabled:e.isSystemWatch,"aria-label":v.i18n.translate("xpack.watcher.sections.watchList.watchTable.actionEditAriaLabel",{defaultMessage:"Edit watch '{name}'",values:{name:e.name}}),iconType:"pencil",color:"primary"},Object(o.reactRouterNavigate)(t,`/watches/watch/${e.id}/edit`),{"data-test-subj":"editWatchButton"})))}},{render:e=>{const t=v.i18n.translate("xpack.watcher.sections.watchList.watchTable.actionDeleteTooltipLabel",{defaultMessage:"Delete"});return Object(p.jsx)(E.EuiToolTip,{content:t,delay:"long"},Object(p.jsx)(E.EuiButtonIcon,{isDisabled:e.isSystemWatch,"aria-label":v.i18n.translate("xpack.watcher.sections.watchList.watchTable.actionDeleteAriaLabel",{defaultMessage:"Delete watch '{name}'",values:{name:e.name}}),iconType:"trash",color:"danger",onClick:()=>{j([e.id])},"data-test-subj":"deleteWatchButton"}))}}]}],a={onSelectionChange:g,selectable:e=>!e.isSystemWatch,selectableMessage:e=>e?"":v.i18n.translate("xpack.watcher.sections.watchList.watchTable.disabledWatchTooltipText",{defaultMessage:"This watch is read-only"})},s={onChange:({queryText:e,error:t})=>{t?d(t.message):(c(e),d(null))},query:n,box:{incremental:!0},toolsLeft:h.length>0?Object(p.jsx)(E.EuiButton,{"data-test-subj":"btnDeleteWatches",onClick:()=>{j(h.map((e=>e.id)))},color:"danger"},h.length>1?Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.deleteMultipleWatchesButtonLabel",defaultMessage:"Delete watches"}):Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.deleteSingleWatchButtonLabel",defaultMessage:"Delete watch"})):void 0,toolsRight:L};W=Object(p.jsx)("div",{"data-test-subj":"watchesTableContainer"},Object(p.jsx)(E.EuiInMemoryTable,{onTableChange:({page:{index:e,size:t}})=>f({pageIndex:e,pageSize:t}),items:F,itemId:"id",columns:e,search:s,pagination:{...J.g,pageIndex:w.pageIndex,pageSize:w.pageSize},sorting:{sort:{field:"name",direction:"asc"}},selection:a,isSelectable:!0,childrenBetween:l&&Object(p.jsx)(i.a.Fragment,null,Object(p.jsx)(E.EuiCallOut,{"data-test-subj":"watcherListSearchError",iconType:"warning",color:"danger",title:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.watchTable.errorOnSearch",defaultMessage:"Invalid search: {queryError}",values:{queryError:l}})}),Object(p.jsx)(E.EuiSpacer,null)),message:Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.watchTable.noWatchesMessage",defaultMessage:"No watches to show"}),rowProps:()=>({"data-test-subj":"row"}),cellProps:()=>({"data-test-subj":"cell"}),"data-test-subj":"watchesTable"}))}return Object(p.jsx)(i.a.Fragment,null,Object(p.jsx)(E.EuiPageHeader,{pageTitle:Object(p.jsx)("span",{"data-test-subj":"appTitle"},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.header",defaultMessage:"Watcher"})),bottomBorder:!0,rightSideItems:[Object(p.jsx)(E.EuiButtonEmpty,{href:a,target:"_blank",iconType:"help","data-test-subj":"documentationLink"},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.sections.watchList.watcherGettingStartedDocsLinkText",defaultMessage:"Watcher docs"}))],description:I}),Object(p.jsx)(ye,{callback:e=>{e&&x([...b,...m]),j([])},watchesToDelete:m}),Object(p.jsx)(E.EuiSpacer,{size:"l"}),W)},$t=({message:e,licenseManagementLocator:t})=>{const a=null==t?void 0:t.useUrl({page:"dashboard"}),s=a?Object(p.jsx)(E.EuiLink,{href:a},Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.app.licenseErrorLinkText",defaultMessage:"Manage your license"})):void 0,n=a?Object(p.jsx)("p",null,e):Object(p.jsx)(i.a.Fragment,null,Object(p.jsx)("p",null,e),Object(p.jsx)("p",null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.app.licenseErrorBody",defaultMessage:"Contact your administrator to change your license."})));return Object(p.jsx)(E.EuiPageContent_Deprecated,{verticalPosition:"center",horizontalPosition:"center",color:"danger"},Object(p.jsx)(E.EuiEmptyPrompt,{iconType:"warning",title:Object(p.jsx)("h1",null,Object(p.jsx)(k.FormattedMessage,{id:"xpack.watcher.app.licenseErrorTitle",defaultMessage:"License error"})),body:n,actions:[s]}))},Kt=Object(c.withRouter)((({children:e,history:t})=>(le={history:t},e))),Yt=e=>{const[{valid:t,message:a},i]=Object(s.useState)({valid:!0});return Object(s.useEffect)((()=>{const t=e.licenseStatus$.subscribe(i);return()=>t.unsubscribe()}),[e.licenseStatus$]),t?Object(p.jsx)(w,{history:e.history},Object(p.jsx)(Kt,null,Object(p.jsx)(pe,{value:e},Object(p.jsx)(Xt,null)))):Object(p.jsx)($t,{licenseManagementLocator:e.licenseManagementLocator,message:a})},Xt=()=>Object(p.jsx)(O,null,Object(p.jsx)(j,{exact:!0,path:"/watches",component:Gt}),Object(p.jsx)(j,{exact:!0,path:"/watches/watch/:id/status",component:Le}),Object(p.jsx)(j,{exact:!0,path:"/watches/watch/:id/edit",component:Vt}),Object(p.jsx)(j,{exact:!0,path:"/watches/new-watch/:type(json|threshold)",component:Vt}),Object(p.jsx)(c.Redirect,{exact:!0,from:"/",to:"/watches"}),Object(p.jsx)(c.Redirect,{exact:!0,from:"",to:"/watches"})),Zt=e=>{const{I18nContext:t,element:a,theme$:s,...i}=e;var r;return r=i.http,Y=r,Object(n.render)(Object(p.jsx)(t,null,Object(p.jsx)(o.KibanaContextProvider,{services:{uiSettings:e.uiSettings,settings:e.settings,theme:e.theme}},Object(p.jsx)(o.KibanaThemeProvider,{theme$:s},Object(p.jsx)(Yt,i)))),a),()=>{Object(n.unmountComponentAtNode)(a)}}}}]);