EVOLUTION-MANAGER
Edit File: azureMonitorPlugin.4d0490a94b199a11f40c.js
(window.webpackJsonp=window.webpackJsonp||[]).push([[26],{CLTJ:function(e,t,r){"use strict";r.r(t);var a=r("Obii"),i=r("mrSG"),n=r("LvDl"),s=r.n(n),o=r("LzXI"),u=r("PbtU"),c=function(){function e(){}return e.createISO8601Duration=function(e,t){return s.a.includes(["hour","minute","h","m"],t)?"PT"+e+t[0].toUpperCase():"P"+e+t[0].toUpperCase()},e.createISO8601DurationFromInterval=function(t){var r=+t.slice(0,t.length-1),a=t[t.length-1];if(t.indexOf("ms")>-1)return e.createISO8601Duration(1,"m");if("s"===t[t.length-1]){var i=60*r%60;return i<1&&(i=1),e.createISO8601Duration(i,"m")}return e.createISO8601Duration(r,a)},e.findClosestTimeGrain=function(e,t){for(var r=s.a.filter(t,function(e){return"auto"!==e}),a=r[0],i=u.a.interval_to_ms(e),n=0;n<r.length;n++)i>u.a.interval_to_ms(r[n])&&(a=n+1<r.length?r[n+1]:r[n]);return a},e.createTimeGrainFromISO8601Duration=function(t){var r=1;"PT"===t.substring(0,2)&&(r=2);var a=t.substring(r,t.length-1),i=t.substring(t.length-1);return a+" "+e.timeUnitToText(+a,i)},e.timeUnitToText=function(e,t){var r="";return"S"===t&&(r="second"),"M"===t&&(r="minute"),"H"===t&&(r="hour"),"D"===t&&(r="day"),e>1?r+"s":r},e.createKbnUnitFromISO8601Duration=function(t){if("auto"===t)return"auto";var r=1;"PT"===t.substring(0,2)&&(r=2);var a=t.substring(r,t.length-1),i=t.substring(t.length-1);return a+e.timeUnitToKbn(+a,i)},e.timeUnitToKbn=function(e,t){return"S"===t?"s":"M"===t?"m":"H"===t?"h":"D"===t?"d":""},e}(),l=r("mkUw"),p=r("q1tI"),h=r.n(p),d=r("wZee"),m=r.n(d),g="prism-token";function f(e){var t=e.definition,r=e.language;return t&&(m.a.languages[r]=m.a.languages[r]||t),{renderDecoration:function(e,t,r){var a=e.children,i=e.decoration;if(i.type!==g)return r();var n="token "+i.data.get("types");return h.a.createElement("span",{className:n},a)},decorateNode:function(e,t,a){var n,s;if("paragraph"!==e.type)return[];var o=e.getTexts().toArray(),u=o.map(function(e){return e.text}).join("\n"),c=m.a.languages[r],l=m.a.tokenize(u,c),p=[],h=o.shift(),d=h,f=0,y=0,v=0;function b(t,r){var a,n,s=(r||"")+" "+(t.type||"")+" "+(t.alias||"");if("string"==typeof t||"string"==typeof t.content){h=d,f=y;var u="string"==typeof t?t:t.content,c=u.split("\n").length-1,l=u.length-c,m=v+l,x=h.text.length-f,w=l;for(y=f+w;x<w;)w=l-x,x=(d=o.shift()).text.length,y=w;if("string"!=typeof t||r){var M=e.createDecoration({anchor:{key:h.key,offset:f},focus:{key:d.key,offset:y},type:g,data:{types:s}});p.push(M)}v=m}else if(t.content&&t.content.length)try{for(var S=Object(i.__values)(t.content),C=S.next();!C.done;C=S.next()){b(C.value,s)}}catch(e){a={error:e}}finally{try{C&&!C.done&&(n=S.return)&&n.call(S)}finally{if(a)throw a.error}}}try{for(var x=Object(i.__values)(l),w=x.next();!w.done;w=x.next()){b(w.value)}}catch(e){n={error:e}}finally{try{w&&!w.done&&(s=x.return)&&s.call(x)}finally{if(n)throw n.error}}return p}}}var y=r("kDLi");var v=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.getRef=function(e){t.el=e},t}return Object(i.__extends)(t,e),t.prototype.componentDidUpdate=function(e){this.props.isSelected&&!e.isSelected&&function(e){if(e&&e.offsetParent){var t=e.offsetParent;(e.offsetTop>t.scrollTop+t.offsetHeight||e.offsetTop<t.scrollTop)&&(t.scrollTop=e.offsetTop-t.offsetTop)}}(this.el)},t.prototype.render=function(){var e=this.props,t=e.hint,r=e.isSelected,a=e.label,i=e.onClickItem,n=r?"typeahead-item typeahead-item__selected":"typeahead-item";return h.a.createElement("li",{ref:this.getRef,className:n,onClick:function(){return i(a)}},a,t&&r?h.a.createElement("div",{className:"typeahead-item-hint"},t):null)},t}(h.a.PureComponent),b=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(i.__extends)(t,e),t.prototype.render=function(){var e=this.props,t=e.items,r=e.label,a=e.selected,i=e.onClickItem;return h.a.createElement("li",{className:"typeahead-group"},h.a.createElement("div",{className:"typeahead-group__title"},r),h.a.createElement("ul",{className:"typeahead-group__list"},t.map(function(e){var t="object"==typeof e?e.text:e,r="object"==typeof e?e.display||e.text:e;return h.a.createElement(v,{key:t,onClickItem:i,isSelected:a.indexOf(t)>-1,hint:e.hint,label:r})})))},t}(h.a.PureComponent),x=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(i.__extends)(t,e),t.prototype.render=function(){var e=this.props,t=e.groupedItems,r=e.menuRef,a=e.selectedItems,n=e.onClickItem;return h.a.createElement("ul",{className:"typeahead",ref:r},t.map(function(e){return h.a.createElement(b,Object(i.__assign)({key:e.label,onClickItem:n,selected:a},e))}))},t}(h.a.PureComponent),w=r("WUic"),M=r("0aAt"),S=r("LBMm"),C=r("i8i4"),A=r.n(C);function I(e){return e?e.reduce(function(e,t){return e.concat(t.items)},[]):[]}var D=function(e){return M.n.create({document:(t=e,r=t.split("\n").map(function(e){return M.a.create({type:"paragraph",nodes:[M.m.create(e)]})}),M.d.create({nodes:r}))});var t,r},_=function(e){function t(t){var r=e.call(this,t)||this,a=t.index,i=void 0===a?0:a,n=t.prefix,s=void 0===n?"query":n;return r.node=document.createElement("div"),r.node.classList.add("slate-typeahead","slate-typeahead-"+s+"-"+i),document.body.appendChild(r.node),r}return Object(i.__extends)(t,e),t.prototype.componentWillUnmount=function(){document.body.removeChild(this.node)},t.prototype.render=function(){return A.a.createPortal(this.props.children,this.node)},t}(h.a.Component),N=function(e){function t(t,r){var a=e.call(this,t,r)||this;a.keybindingSrv=Object(w.a)(),a.onChange=function(e){var t=e.value,r=t.document!==a.state.value.document;a.setState({value:t},function(){r&&(requestAnimationFrame(function(){return a.onTypeahead()}),a.onChangeQuery())})},a.request=function(e){return a.props.request?a.props.request(e):fetch(e)},a.onChangeQuery=function(){var e=a.props.onQueryChange;e&&e(l.a.serialize(a.state.value))},a.onKeyDown=function(e,t,r){var i=a.state,n=i.typeaheadIndex,s=i.suggestions,o=e;switch(o.key){case"Escape":if(a.menuEl)return o.preventDefault(),o.stopPropagation(),a.resetTypeahead(),!0;break;case" ":if(o.ctrlKey)return o.preventDefault(),a.onTypeahead(!0),!0;break;case"Tab":case"Enter":if(a.menuEl){if(o.preventDefault(),!s||!s.length)return r();var u=I(s),c=u[Math.abs(n)%u.length||0];return a.applyTypeahead(t,c)}break;case"ArrowDown":a.menuEl&&(o.preventDefault(),a.setState({typeaheadIndex:n+1}));break;case"ArrowUp":a.menuEl&&(o.preventDefault(),a.setState({typeaheadIndex:Math.max(0,n-1)}))}return r()},a.onTypeahead=function(e,t){return void 0===e&&(e=!1),e},a.applyTypeahead=function(e,t){return{value:new M.n}},a.resetTypeahead=function(e){a.setState({suggestions:[],typeaheadIndex:0,typeaheadPrefix:"",typeaheadContext:null},e)},a.handleBlur=function(e,t,r){var i=a.props.onBlur;return a.resetTimer=setTimeout(a.resetTypeahead,100),i&&i(),a.restoreEscapeKeyBinding(),r()},a.handleFocus=function(e,t,r){var i=a.props.onFocus;return i&&i(),a.removeEscapeKeyBinding(),r()},a.onClickItem=function(e){var t=a.state.suggestions;if(t&&0!==t.length){var r=a.applyTypeahead();a.onChange(r)}},a.updateMenu=function(){var e=a.state.suggestions,t=a.menuEl,r=window.getSelection().anchorNode;if(t)if(e&&e.length>0){if(r&&r.parentElement){var i=r.parentElement.getBoundingClientRect(),n=window.scrollX,s=window.scrollY,o=window.innerHeight,u=i.left+n-2,c=i.top+s+i.height+4,l=o-c-10;requestAnimationFrame(function(){t.style.opacity=1,t.style.top=c+"px",t.style.left=u+"px",t.style.maxHeight=l+"px"})}}else t.removeAttribute("style")},a.menuRef=function(e){a.menuEl=e},a.renderMenu=function(){var e=a.props.portalPrefix,t=a.state.suggestions;if(!(t&&t.length>0))return null;var r=Math.max(a.state.typeaheadIndex,0),i=I(t);r=r%i.length||0;var n=(i.length>0?[i[r]]:[]).map(function(e){return"object"==typeof e?e.text:e});return h.a.createElement(_,{prefix:e},h.a.createElement(x,{menuRef:a.menuRef,selectedItems:n,onClickItem:a.onClickItem,groupedItems:t}))};var i=t.prismDefinition,n=void 0===i?{}:i,s=t.prismLanguage,o=void 0===s?"kusto":s;return a.plugins=[Object(y.BracesPlugin)(),Object(y.ClearPlugin)(),Object(y.RunnerPlugin)({handler:t.onPressEnter}),Object(y.NewlinePlugin)(),f({definition:n,language:o})],a.state={labelKeys:{},labelValues:{},suggestions:[],typeaheadIndex:0,typeaheadPrefix:"",value:D(t.initialQuery||"")},a}return Object(i.__extends)(t,e),t.prototype.componentDidMount=function(){this.updateMenu()},t.prototype.componentWillUnmount=function(){this.restoreEscapeKeyBinding(),clearTimeout(this.resetTimer)},t.prototype.componentDidUpdate=function(){this.updateMenu()},t.prototype.removeEscapeKeyBinding=function(){this.keybindingSrv.unbind("esc","keydown")},t.prototype.restoreEscapeKeyBinding=function(){this.keybindingSrv.setupGlobal()},t.prototype.render=function(){return h.a.createElement("div",{className:"slate-query-field"},this.renderMenu(),h.a.createElement(S.a,{autoCorrect:!1,onBlur:this.handleBlur,onKeyDown:this.onKeyDown,onChange:this.onChange,onFocus:this.handleFocus,placeholder:this.props.placeholder,plugins:this.plugins,spellCheck:!1,value:this.state.value}))},t}(h.a.Component),z=r("sEfC"),k=r.n(z),T=[{text:"!between",hint:"Matches the input that is outside the inclusive range."},{text:"as",hint:"Binds a name to the operator's input tabular expression."},{text:"between",hint:"Matches the input that is inside the inclusive range."},{text:"consume",hint:"The `consume` operator consumes the tabular data stream handed to it. It is\r\nmostly used for triggering the query side-effect without actually returning\r\nthe results back to the caller."},{text:"count",hint:"Returns the number of records in the input record set."},{text:"datatable",hint:"Returns a table whose schema and values are defined in the query itself."},{text:"distinct",hint:"Produces a table with the distinct combination of the provided columns of the input table."},{text:"evaluate",hint:"Invokes a service-side query extension (plugin)."},{text:"extend",hint:"Create calculated columns and append them to the result set."},{text:"externaldata",hint:"Returns a table whose schema is defined in the query itself, and whose data is read from an external raw file."},{text:"facet",hint:"Returns a set of tables, one for each specified column.\r\nEach table specifies the list of values taken by its column.\r\nAn additional table can be created by using the `with` clause."},{text:"find",hint:"Finds rows that match a predicate across a set of tables."},{text:"fork",hint:"Runs multiple consumer operators in parallel."},{text:"getschema",hint:"Produce a table that represents a tabular schema of the input."},{text:"in",hint:"Filters a recordset based on the provided set of values."},{text:"invoke",hint:"Invokes lambda that receives the source of `invoke` as tabular parameter argument."},{text:"join",hint:"Merge the rows of two tables to form a new table by matching values of the specified column(s) from each table."},{text:"limit",hint:"Return up to the specified number of rows."},{text:"make-series",hint:"Create series of specified aggregated values along specified axis."},{text:"mvexpand",hint:"Expands multi-value array or property bag."},{text:"order",hint:"Sort the rows of the input table into order by one or more columns."},{text:"parse",hint:"Evaluates a string expression and parses its value into one or more calculated columns."},{text:"print",hint:"Evaluates one or more scalar expressions and inserts the results (as a single-row table with as many columns as there are expressions) into the output."},{text:"project",hint:"Select the columns to include, rename or drop, and insert new computed columns."},{text:"project-away",hint:"Select what columns to exclude from the input."},{text:"project-rename",hint:"Renames columns in the result output."},{text:"range",hint:"Generates a single-column table of values."},{text:"reduce",hint:"Groups a set of strings together based on values similarity."},{text:"render",hint:"Instructs the user agent to render the results of the query in a particular way."},{text:"sample",hint:"Returns up to the specified number of random rows from the input table."},{text:"sample-distinct",hint:"Returns a single column that contains up to the specified number of distinct values of the requested column."},{text:"search",hint:"The search operator provides a multi-table/multi-column search experience."},{text:"serialize",hint:"Marks that order of the input row set is safe for window functions usage."},{text:"sort",hint:"Sort the rows of the input table into order by one or more columns."},{text:"summarize",hint:"Produces a table that aggregates the content of the input table."},{text:"take",hint:"Return up to the specified number of rows."},{text:"top",hint:"Returns the first *N* records sorted by the specified columns."},{text:"top-hitters",hint:"Returns an approximation of the first *N* results (assuming skewed distribution of the input)."},{text:"top-nested",hint:"Produces hierarchical top results, where each level is a drill-down based on previous level values."},{text:"union",hint:"Takes two or more tables and returns the rows of all of them."},{text:"where",hint:"Filters a table to the subset of rows that satisfy a predicate."}],R=[{text:"abs",hint:"Calculates the absolute value of the input."},{text:"acos",hint:"Returns the angle whose cosine is the specified number (the inverse operation of [`cos()`](cosfunction.md)) ."},{text:"ago",hint:"Subtracts the given timespan from the current UTC clock time."},{text:"any",hint:"Returns random non-empty value from the specified expression values."},{text:"arg_max",hint:"Finds a row in the group that maximizes *ExprToMaximize*, and returns the value of *ExprToReturn* (or `*` to return the entire row)."},{text:"arg_min",hint:"Finds a row in the group that minimizes *ExprToMinimize*, and returns the value of *ExprToReturn* (or `*` to return the entire row)."},{text:"argmax",hint:"Finds a row in the group that maximizes *ExprToMaximize*, and returns the value of *ExprToReturn* (or `*` to return the entire row)."},{text:"argmin",hint:"Finds a row in the group that minimizes *ExprToMinimize*, and returns the value of *ExprToReturn* (or `*` to return the entire row)."},{text:"array_concat",hint:"Concatenates a number of dynamic arrays to a single array."},{text:"array_length",hint:"Calculates the number of elements in a dynamic array."},{text:"array_slice",hint:"Extracts a slice of a dynamic array."},{text:"array_split",hint:"Splits an array to multiple arrays according to the split indices and packs the generated array in a dynamic array."},{text:"asin",hint:"Returns the angle whose sine is the specified number (the inverse operation of [`sin()`](sinfunction.md)) ."},{text:"assert",hint:"Checks for a condition; if the condition is false, outputs error messages and fails the query."},{text:"atan",hint:"Returns the angle whose tangent is the specified number (the inverse operation of [`tan()`](tanfunction.md)) ."},{text:"atan2",hint:"Calculates the angle, in radians, between the positive x-axis and the ray from the origin to the point (y, x)."},{text:"avg",hint:"Calculates the average of *Expr* across the group."},{text:"avgif",hint:"Calculates the [average](avg-aggfunction.md) of *Expr* across the group for which *Predicate* evaluates to `true`."},{text:"bag_keys",hint:"Enumerates all the root keys in a dynamic property-bag object."},{text:"base64_decodestring",hint:"Decodes a base64 string to a UTF-8 string"},{text:"base64_encodestring",hint:"Encodes a string as base64 string"},{text:"beta_cdf",hint:"Returns the standard cumulative beta distribution function."},{text:"beta_inv",hint:"Returns the inverse of the beta cumulative probability beta density function."},{text:"beta_pdf",hint:"Returns the probability density beta function."},{text:"bin",hint:"Rounds values down to an integer multiple of a given bin size."},{text:"bin_at",hint:"Rounds values down to a fixed-size 'bin', with control over the bin's starting point.\r\n(See also [`bin function`](./binfunction.md).)"},{text:"bin_auto",hint:"Rounds values down to a fixed-size 'bin', with control over the bin size and starting point provided by a query property."},{text:"binary_and",hint:"Returns a result of the bitwise `and` operation between two values."},{text:"binary_not",hint:"Returns a bitwise negation of the input value."},{text:"binary_or",hint:"Returns a result of the bitwise `or` operation of the two values."},{text:"binary_shift_left",hint:"Returns binary shift left operation on a pair of numbers."},{text:"binary_shift_right",hint:"Returns binary shift right operation on a pair of numbers."},{text:"binary_xor",hint:"Returns a result of the bitwise `xor` operation of the two values."},{text:"buildschema",hint:"Returns the minimal schema that admits all values of *DynamicExpr*."},{text:"case",hint:"Evaluates a list of predicates and returns the first result expression whose predicate is satisfied."},{text:"ceiling",hint:"Calculates the smallest integer greater than, or equal to, the specified numeric expression."},{text:"cluster",hint:"Changes the reference of the query to a remote cluster."},{text:"coalesce",hint:"Evaluates a list of expressions and returns the first non-null (or non-empty for string) expression."},{text:"cos",hint:"Returns the cosine function."},{text:"cot",hint:"Calculates the trigonometric cotangent of the specified angle, in radians."},{text:"count",hint:"Returns a count of the records per summarization group (or in total if summarization is done without grouping)."},{text:"countif",hint:"Returns a count of rows for which *Predicate* evaluates to `true`."},{text:"countof",hint:"Counts occurrences of a substring in a string. Plain string matches may overlap; regex matches do not."},{text:"current_principal",hint:"Returns the current principal running this query."},{text:"cursor_after",hint:"A predicate over the records of a table to compare their ingestion time\r\nagainst a database cursor."},{text:"cursor_before_or_at",hint:"A predicate over the records of a table to compare their ingestion time\r\nagainst a database cursor."},{text:"database",hint:"Changes the reference of the query to a specific database within the cluster scope."},{text:"datetime_add",hint:"Calculates a new [datetime](./scalar-data-types/datetime.md) from a specified datepart multiplied by a specified amount, added to a specified [datetime](./scalar-data-types/datetime.md)."},{text:"datetime_diff",hint:"Calculates calendarian difference between two [datetime](./scalar-data-types/datetime.md) values."},{text:"datetime_part",hint:"Extracts the requested date part as an integer value."},{text:"dayofmonth",hint:"Returns the integer number representing the day number of the given month"},{text:"dayofweek",hint:"Returns the integer number of days since the preceding Sunday, as a `timespan`."},{text:"dayofyear",hint:"Returns the integer number represents the day number of the given year."},{text:"dcount",hint:"Returns an estimate of the number of distinct values of *Expr* in the group."},{text:"dcount_hll",hint:"Calculates the dcount from hll results (which was generated by [hll](hll-aggfunction.md) or [hll_merge](hll-merge-aggfunction.md))."},{text:"dcountif",hint:"Returns an estimate of the number of distinct values of *Expr* of rows for which *Predicate* evaluates to `true`."},{text:"degrees",hint:"Converts angle value in radians into value in degrees, using formula `degrees = (180 / PI ) * angle_in_radians`"},{text:"distance",hint:"Returns the distance between two points in meters."},{text:"endofday",hint:"Returns the end of the day containing the date, shifted by an offset, if provided."},{text:"endofmonth",hint:"Returns the end of the month containing the date, shifted by an offset, if provided."},{text:"endofweek",hint:"Returns the end of the week containing the date, shifted by an offset, if provided."},{text:"endofyear",hint:"Returns the end of the year containing the date, shifted by an offset, if provided."},{text:"estimate_data_size",hint:"Returns an estimated data size of the selected columns of the tabular expression."},{text:"exp",hint:"The base-e exponential function of x, which is e raised to the power x: e^x."},{text:"exp10",hint:"The base-10 exponential function of x, which is 10 raised to the power x: 10^x. \r\n**Syntax**"},{text:"exp2",hint:"The base-2 exponential function of x, which is 2 raised to the power x: 2^x."},{text:"extent_id",hint:'Returns a unique identifier that identifies the data shard ("extent") that the current record resides in.'},{text:"extent_tags",hint:'Returns a dynamic array with the [tags](../management/extents-overview.md#extent-tagging) of the data shard ("extent") that the current record resides in.'},{text:"extract",hint:"Get a match for a [regular expression](./re2.md) from a text string."},{text:"extract_all",hint:"Get all matches for a [regular expression](./re2.md) from a text string."},{text:"extractjson",hint:"Get a specified element out of a JSON text using a path expression."},{text:"floor",hint:"An alias for [`bin()`](binfunction.md)."},{text:"format_datetime",hint:"Formats a datetime parameter based on the format pattern parameter."},{text:"format_timespan",hint:"Formats a timespan parameter based on the format pattern parameter."},{text:"gamma",hint:"Computes [gamma function](https://en.wikipedia.org/wiki/Gamma_function)"},{text:"getmonth",hint:"Get the month number (1-12) from a datetime."},{text:"gettype",hint:"Returns the runtime type of its single argument."},{text:"getyear",hint:"Returns the year part of the `datetime` argument."},{text:"hash",hint:"Returns a hash value for the input value."},{text:"hash_sha256",hint:"Returns a sha256 hash value for the input value."},{text:"hll",hint:"Calculates the Intermediate results of [dcount](dcount-aggfunction.md) across the group."},{text:"hll_merge",hint:"Merges hll results (scalar version of the aggregate version [`hll_merge()`](hll-merge-aggfunction.md))."},{text:"hourofday",hint:"Returns the integer number representing the hour number of the given date"},{text:"iff",hint:"Evaluates the first argument (the predicate), and returns the value of either the second or third arguments, depending on whether the predicate evaluated to `true` (second) or `false` (third)."},{text:"iif",hint:"Evaluates the first argument (the predicate), and returns the value of either the second or third arguments, depending on whether the predicate evaluated to `true` (second) or `false` (third)."},{text:"indexof",hint:"Function reports the zero-based index of the first occurrence of a specified string within input string."},{text:"ingestion_time",hint:"Retrieves the record's `$IngestionTime` hidden `datetime` column, or null."},{text:"iscolumnexists",hint:"Returns a boolean value indicating if the given string argument exists in the schema produced by the preceding tabular operator."},{text:"isempty",hint:"Returns `true` if the argument is an empty string or is null."},{text:"isfinite",hint:"Returns whether input is a finite value (is neither infinite nor NaN)."},{text:"isinf",hint:"Returns whether input is an infinite (positive or negative) value."},{text:"isnan",hint:"Returns whether input is Not-a-Number (NaN) value."},{text:"isnotempty",hint:"Returns `true` if the argument is not an empty string nor it is a null."},{text:"isnotnull",hint:"Returns `true` if the argument is not null."},{text:"isnull",hint:"Evaluates its sole argument and returns a `bool` value indicating if the argument evaluates to a null value."},{text:"log",hint:"Returns the natural logarithm function."},{text:"log10",hint:"Returns the common (base-10) logarithm function."},{text:"log2",hint:"Returns the base-2 logarithm function."},{text:"loggamma",hint:"Computes log of absolute value of the [gamma function](https://en.wikipedia.org/wiki/Gamma_function)"},{text:"make_datetime",hint:"Creates a [datetime](./scalar-data-types/datetime.md) scalar value from the specified date and time."},{text:"make_dictionary",hint:"Returns a `dynamic` (JSON) property-bag (dictionary) of all the values of *Expr* in the group."},{text:"make_string",hint:"Returns the string generated by the Unicode characters."},{text:"make_timespan",hint:"Creates a [timespan](./scalar-data-types/timespan.md) scalar value from the specified time period."},{text:"makelist",hint:"Returns a `dynamic` (JSON) array of all the values of *Expr* in the group."},{text:"makeset",hint:"Returns a `dynamic` (JSON) array of the set of distinct values that *Expr* takes in the group."},{text:"materialize",hint:"Allows caching a sub-query result during the time of query execution in a way that other subqueries can reference the partial result."},{text:"max",hint:"Returns the maximum value across the group."},{text:"max_of",hint:"Returns the maximum value of several evaluated numeric expressions."},{text:"merge_tdigests",hint:"Merges tdigest results (scalar version of the aggregate version [`merge_tdigests()`](merge-tdigests-aggfunction.md))."},{text:"min",hint:"Returns the minimum value agross the group."},{text:"min_of",hint:"Returns the minimum value of several evaluated numeric expressions."},{text:"monthofyear",hint:"Returns the integer number represents the month number of the given year."},{text:"next",hint:"Returns the value of a column in a row that it at some offset following the\r\ncurrent row in a [serialized row set](./windowsfunctions.md#serialized-row-set)."},{text:"not",hint:"Reverses the value of its `bool` argument."},{text:"now",hint:"Returns the current UTC clock time, optionally offset by a given timespan.\r\nThis function can be used multiple times in a statement and the clock time being referenced will be the same for all instances."},{text:"pack",hint:"Creates a `dynamic` object (property bag) from a list of names and values."},{text:"pack_all",hint:"Creates a `dynamic` object (property bag) from all the columns of the tabular expression."},{text:"pack_array",hint:"Packs all input values into a dynamic array."},{text:"parse_ipv4",hint:"Converts input to integer (signed 64-bit) number representation."},{text:"parse_json",hint:"Interprets a `string` as a [JSON value](https://json.org/)) and returns the value as [`dynamic`](./scalar-data-types/dynamic.md). \r\nIt is superior to using [extractjson() function](./extractjsonfunction.md)\r\nwhen you need to extract more than one element of a JSON compound object."},{text:"parse_path",hint:'Parses a file path `string` and returns a [`dynamic`](./scalar-data-types/dynamic.md) object that contains the following parts of the path: \r\nScheme, RootPath, DirectoryPath, DirectoryName, FileName, Extension, AlternateDataStreamName.\r\nIn addition to the simple paths with both types of slashes, supports paths with schemas (e.g. "file://..."), shared paths (e.g. "\\\\shareddrive\\users..."), long paths (e.g "\\\\?\\C:...""), alternate data streams (e.g. "file1.exe:file2.exe")'},{text:"parse_url",hint:"Parses an absolute URL `string` and returns a [`dynamic`](./scalar-data-types/dynamic.md) object contains all parts of the URL (Scheme, Host, Port, Path, Username, Password, Query Parameters, Fragment)."},{text:"parse_urlquery",hint:"Parses a url query `string` and returns a [`dynamic`](./scalar-data-types/dynamic.md) object contains the Query parameters."},{text:"parse_user_agent",hint:"Interprets a user-agent string, which identifies the user's browser and provides certain system details to servers hosting the websites the user visits. The result is returned as [`dynamic`](./scalar-data-types/dynamic.md)."},{text:"parse_version",hint:"Converts input string representation of version to a comparable decimal number."},{text:"parse_xml",hint:"Interprets a `string` as a XML value, converts the value to a [JSON value](https://json.org/) and returns the value as [`dynamic`](./scalar-data-types/dynamic.md)."},{text:"percentile",hint:"Returns an estimate for the specified [nearest-rank percentile](#nearest-rank-percentile) of the population defined by *Expr*. \r\nThe accuracy depends on the density of population in the region of the percentile."},{text:"percentile_tdigest",hint:"Calculates the percentile result from tdigest results (which was generated by [tdigest](tdigest-aggfunction.md) or [merge-tdigests](merge-tdigests-aggfunction.md))"},{text:"percentrank_tdigest",hint:"Calculates the approximate rank of the value in a set where rank is expressed as percentage of set's size. \r\nThis function can be viewed as the inverse of the percentile."},{text:"pi",hint:"Returns the constant value of Pi (π)."},{text:"point",hint:"Returns a dynamic array representation of a point."},{text:"pow",hint:"Returns a result of raising to power"},{text:"prev",hint:"Returns the value of a column in a row that it at some offset prior to the\r\ncurrent row in a [serialized row set](./windowsfunctions.md#serialized-row-set)."},{text:"radians",hint:"Converts angle value in degrees into value in radians, using formula `radians = (PI / 180 ) * angle_in_degrees`"},{text:"rand",hint:"Returns a random number."},{text:"range",hint:"Generates a dynamic array holding a series of equally-spaced values."},{text:"repeat",hint:"Generates a dynamic array holding a series of equal values."},{text:"replace",hint:"Replace all regex matches with another string."},{text:"reverse",hint:"Function makes reverse of input string."},{text:"round",hint:"Returns the rounded source to the specified precision."},{text:"row_cumsum",hint:"Calculates the cumulative sum of a column in a [serialized row set](./windowsfunctions.md#serialized-row-set)."},{text:"row_number",hint:"Returns the current row's index in a [serialized row set](./windowsfunctions.md#serialized-row-set).\r\nThe row index starts by default at `1` for the first row, and is incremented by `1` for each additional row.\r\nOptionally, the row index can start at a different value than `1`.\r\nAdditionally, the row index may be reset according to some provided predicate."},{text:"series_add",hint:"Calculates the element-wise addition of two numeric series inputs."},{text:"series_decompose",hint:"Applies a decomposition transformation on a series."},{text:"series_decompose_anomalies",hint:"Anomaly Detection based on series decomposition (refer to [series_decompose()](series-decomposefunction.md))"},{text:"series_decompose_forecast",hint:"Forecast based on series decomposition."},{text:"series_divide",hint:"Calculates the element-wise division of two numeric series inputs."},{text:"series_equals",hint:"Calculates the element-wise equals (`==`) logic operation of two numeric series inputs."},{text:"series_fill_backward",hint:"Performs backward fill interpolation of missing values in a series."},{text:"series_fill_const",hint:"Replaces missing values in a series with a specified constant value."},{text:"series_fill_forward",hint:"Performs forward fill interpolation of missing values in a series."},{text:"series_fill_linear",hint:"Performs linear interpolation of missing values in a series."},{text:"series_fir",hint:"Applies a Finite Impulse Response filter on a series."},{text:"series_fit_2lines",hint:"Applies two segments linear regression on a series, returning multiple columns."},{text:"series_fit_2lines_dynamic",hint:"Applies two segments linear regression on a series, returning dynamic object."},{text:"series_fit_line",hint:"Applies linear regression on a series, returning multiple columns."},{text:"series_fit_line_dynamic",hint:"Applies linear regression on a series, returning dynamic object."},{text:"series_greater",hint:"Calculates the element-wise greater (`>`) logic operation of two numeric series inputs."},{text:"series_greater_equals",hint:"Calculates the element-wise greater or equals (`>=`) logic operation of two numeric series inputs."},{text:"series_iir",hint:"Applies a Infinite Impulse Response filter on a series."},{text:"series_less",hint:"Calculates the element-wise less (`<`) logic operation of two numeric series inputs."},{text:"series_less_equals",hint:"Calculates the element-wise less or equal (`<=`) logic operation of two numeric series inputs."},{text:"series_multiply",hint:"Calculates the element-wise multiplication of two numeric series inputs."},{text:"series_not_equals",hint:"Calculates the element-wise not equals (`!=`) logic operation of two numeric series inputs."},{text:"series_outliers",hint:"Scores anomaly points in a series."},{text:"series_periods_detect",hint:"Finds the most significant periods that exist in a time series."},{text:"series_periods_validate",hint:"Checks whether a time series contains periodic patterns of given lengths."},{text:"series_seasonal",hint:"Calculates the seasonal component of a series according to the detected or given seasonal period."},{text:"series_stats",hint:"Returns statistics for a series in multiple columns."},{text:"series_stats_dynamic",hint:"Returns statistics for a series in dynamic object."},{text:"series_subtract",hint:"Calculates the element-wise subtraction of two numeric series inputs."},{text:"sign",hint:"Sign of a numeric expression"},{text:"sin",hint:"Returns the sine function."},{text:"split",hint:"Splits a given string according to a given delimiter and returns a string array with the contained substrings."},{text:"sqrt",hint:"Returns the square root function."},{text:"startofday",hint:"Returns the start of the day containing the date, shifted by an offset, if provided."},{text:"startofmonth",hint:"Returns the start of the month containing the date, shifted by an offset, if provided."},{text:"startofweek",hint:"Returns the start of the week containing the date, shifted by an offset, if provided."},{text:"startofyear",hint:"Returns the start of the year containing the date, shifted by an offset, if provided."},{text:"stdev",hint:"Calculates the standard deviation of *Expr* across the group, considering the group as a [sample](https://en.wikipedia.org/wiki/Sample_%28statistics%29)."},{text:"stdevif",hint:"Calculates the [stdev](stdev-aggfunction.md) of *Expr* across the group for which *Predicate* evaluates to `true`."},{text:"stdevp",hint:"Calculates the standard deviation of *Expr* across the group, considering the group as a [population](https://en.wikipedia.org/wiki/Statistical_population)."},{text:"strcat",hint:"Concatenates between 1 and 64 arguments."},{text:"strcat_array",hint:"Creates a concatenated string of array values using specified delimiter."},{text:"strcat_delim",hint:"Concatenates between 2 and 64 arguments, with delimiter, provided as first argument."},{text:"strcmp",hint:"Compares two strings."},{text:"string_size",hint:"Returns the size, in bytes, of the input string."},{text:"strlen",hint:"Returns the length, in characters, of the input string."},{text:"strrep",hint:"Repeats given [string](./scalar-data-types/string.md) provided amount of times."},{text:"substring",hint:"Extracts a substring from a source string starting from some index to the end of the string."},{text:"sum",hint:"Calculates the sum of *Expr* across the group."},{text:"sumif",hint:"Returns a sum of *Expr* for which *Predicate* evaluates to `true`."},{text:"table",hint:"References specific table using an query-time evaluated string-expression."},{text:"tan",hint:"Returns the tangent function."},{text:"tdigest",hint:"Calculates the Intermediate results of [`percentiles()`](percentiles-aggfunction.md) across the group."},{text:"tdigest_merge",hint:"Merges tdigest results (scalar version of the aggregate version [`tdigest_merge()`](tdigest-merge-aggfunction.md))."},{text:"tobool",hint:"Converts input to boolean (signed 8-bit) representation."},{text:"todatetime",hint:"Converts input to [datetime](./scalar-data-types/datetime.md) scalar."},{text:"todecimal",hint:"Converts input to decimal number representation."},{text:"todouble",hint:"Converts the input to a value of type `real`. (`todouble()` and `toreal()` are synonyms.)"},{text:"todynamic",hint:"Interprets a `string` as a [JSON value](https://json.org/) and returns the value as [`dynamic`](./scalar-data-types/dynamic.md)."},{text:"toguid",hint:"Converts input to [`guid`](./scalar-data-types/guid.md) representation."},{text:"tohex",hint:"Converts input to a hexadecimal string."},{text:"toint",hint:"Converts input to integer (signed 32-bit) number representation."},{text:"tolong",hint:"Converts input to long (signed 64-bit) number representation."},{text:"tolower",hint:"Converts input string to lower case."},{text:"toscalar",hint:"Returns a scalar constant value of the evaluated expression."},{text:"tostring",hint:"Converts input to a string representation."},{text:"totimespan",hint:"Converts input to [timespan](./scalar-data-types/timespan.md) scalar."},{text:"toupper",hint:"Converts a string to upper case."},{text:"translate",hint:"Replaces a set of characters ('searchList') with another set of characters ('replacementList') in a given a string.\r\nThe function searches for characters in the 'searchList' and replaces them with the corresponding characters in 'replacementList'"},{text:"treepath",hint:"Enumerates all the path expressions that identify leaves in a dynamic object."},{text:"trim",hint:"Removes all leading and trailing matches of the specified regular expression."},{text:"trim_end",hint:"Removes trailing match of the specified regular expression."},{text:"trim_start",hint:"Removes leading match of the specified regular expression."},{text:"url_decode",hint:"The function converts encoded URL into a to regular URL representation."},{text:"url_encode",hint:"The function converts characters of the input URL into a format that can be transmitted over the Internet."},{text:"variance",hint:"Calculates the variance of *Expr* across the group, considering the group as a [sample](https://en.wikipedia.org/wiki/Sample_%28statistics%29)."},{text:"varianceif",hint:"Calculates the [variance](variance-aggfunction.md) of *Expr* across the group for which *Predicate* evaluates to `true`."},{text:"variancep",hint:"Calculates the variance of *Expr* across the group, considering the group as a [population](https://en.wikipedia.org/wiki/Statistical_population)."},{text:"weekofyear",hint:"Returns the integer number represents the week number."},{text:"welch_test",hint:"Computes the p_value of the [Welch-test function](https://en.wikipedia.org/wiki/Welch%27s_t-test)"},{text:"zip",hint:"The `zip` function accepts any number of `dynamic` arrays, and returns an\r\narray whose elements are each an array holding the elements of the input\r\narrays of the same index."}],E=["by","on","contains","notcontains","containscs","notcontainscs","startswith","has","matches","regex","true","false","and","or","typeof","int","string","date","datetime","time","long","real","boolean","bool"],O=[{text:"$__timeFilter",display:"$__timeFilter()",hint:"Macro that uses the selected timerange in Grafana to filter the query."},{text:"$__timeTo",display:"$__timeTo()",hint:"Returns the From datetime from the Grafana picker. Example: datetime(2018-06-05T20:09:58.907Z)."},{text:"$__timeFrom",display:"$__timeFrom()",hint:"Returns the From datetime from the Grafana picker. Example: datetime(2018-06-05T18:09:58.907Z)."},{text:"$__escapeMulti",display:"$__escapeMulti()",hint:"Macro to escape multi-value template variables that contain illegal characters."},{text:"$__contains",display:"$__contains()",hint:"Macro for multi-value template variables."}],G={comment:{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0},"function-context":{pattern:/[a-z0-9_]+\([^)]*\)?/i,inside:{}},duration:{pattern:new RegExp(["SECONDS","MINUTES","HOURS","DAYS","WEEKS","MONTHS","YEARS"].join("?|")+"?","i"),alias:"number"},builtin:new RegExp("\\b(?:"+R.map(function(e){return e.text}).join("|")+")(?=\\s*\\()","i"),string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},keyword:new RegExp("\\b(?:"+E.join("|")+"|"+T.map(function(e){return e.text}).join("|")+"|\\*)\\b","i"),boolean:/\b(?:true|false)\b/,number:/\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/-|\+|\*|\/|>|<|==|<=?|>=?|<>|!~|~|=|\|/,punctuation:/[{};(),.:]/,variable:/(\[\[(.+?)\]\])|(\$(.+?))\b/};G["function-context"].inside={argument:{pattern:/[a-z0-9_]+(?=:)/i,alias:"symbol"},duration:G.duration,number:G.number,builtin:G.builtin,string:G.string,variable:G.variable};var j=G,q=100,F=function(){return{Databases:{Default:{}}}},L=function(e){return e.replace(/[{}[\]="(),!~+\-*/^%]/g,"").trim()},P=function(e){return{text:e}},V=function(e){function t(t,r){var a=e.call(this,t,r)||this;return a.onTypeahead=function(e){void 0===e&&(e=!1);var t=window.getSelection();if(t.anchorNode){var r=t.anchorNode.parentElement;if(null===r)return;if(!r.closest(".slate-query-field")||a.state.value.isBlurred)return;var i=t.getRangeAt(0),n=t.anchorNode.textContent;if(null===n)return;var s=i.startOffset,o=L(n.substr(0,s)),u=a.state.value.anchorOffset,c=a.state.value.anchorText.text.slice(0,u),p=[],h=r.classList,d=null;if(h.contains("function-context"))d="context-function",p=a.getColumnSuggestions();else if(c.match(/(where\s(\w+\b)?$)/i))d="context-where",p=a.getColumnSuggestions();else if(c.match(/(summarize\s(\w+\b)?$)/i))d="context-summarize",p=a.getFunctionSuggestions();else if(c.match(/(summarize\s(.+\s)?by\s+([^,\s]+,\s*)*([^,\s]+\b)?$)/i))d="context-summarize-by",p=a.getColumnSuggestions();else if(c.match(/(by\s+([^,\s]+,\s*)*([^,\s]+\b)?$)/i))d="context-by",p=a.getColumnSuggestions();else if(c.match(/(on\s(.+\b)?$)/i))d="context-join-on",p=a.getColumnSuggestions();else if(c.match(/(join\s+(\(\s+)?(\w+\b)?$)/i))d="context-join",p=a.getTableSuggestions();else if(c.match(/(distinct\s(.+\b)?$)/i))d="context-distinct",p=a.getColumnSuggestions();else if(c.match(/(database\(\"(\w+)\"\)\.(.+\b)?$)/i)){d="context-database-table";var m=a.getDBFromDatabaseFunction(c);console.log(m),p=a.getTableSuggestions(m),o=o.replace(".","")}else if(X(l.a.serialize(a.state.value)).match(/^\s*\w*$/i)){if(d="context-new",!a.schema)return a.fetchSchema(),void setTimeout(a.onTypeahead,0);p=a.getInitialSuggestions()}else if(!o||h.contains("argument")||e)!0===e&&(d="context-builtin-forced",c.match(/\s$/i)&&(o=""),p=a.getKeywordSuggestions());else{if(c.match(/\s$/i))return void(o="");o=function(e){var t=/(?:.*\s)?([^\s]+\s*)$/gi.exec(e);if(t&&t.length>1)return t[1];return""}(o),d="context-builtin",p=a.getKeywordSuggestions()}var g=0;o=o.toLowerCase();var f=p.map(function(e){return e.items&&o&&!e.skipFilter&&(e.items=e.items.filter(function(e){return e.text.length>=o.length}),e.prefixMatch?e.items=e.items.filter(function(e){return 0===e.text.toLowerCase().indexOf(o)}):e.items=e.items.filter(function(e){return e.text.toLowerCase().indexOf(o)>-1})),g+=e.items.length,e}).filter(function(e){return e.items.length>0});a.setState({typeaheadPrefix:o,typeaheadContext:d,typeaheadText:n,suggestions:g>0?f:[]})}},a.applyTypeahead=function(e,t){var r=a.state,i=r.typeaheadPrefix,n=r.typeaheadContext,s=r.typeaheadText,o=t.text||t,u=y.DOMUtil.getNextCharacter();"function"===t.type?u&&"("===u||(o+="("):"context-function"===n?u&&")"===u||(o+=")"):u&&" "===u||(o+=" ");var c=t.deleteBackwards||i.length,l=L(s).length-i.length,p=s.indexOf(i),h=i&&(l>0&&p>-1||o===s)?l+p:0;return a.resetTypeahead(function(){return e.deleteBackward(c).deleteForward(h).insertText(o).moveForward(0).focus()}),e},a.schema=F(),a.onTypeahead=k()(a.onTypeahead,q),a}return Object(i.__extends)(t,e),t.prototype.componentDidMount=function(){e.prototype.componentDidMount.call(this),this.fetchSchema()},t.prototype.getInitialSuggestions=function(){return this.getTableSuggestions()},t.prototype.getKeywordSuggestions=function(){return[{prefixMatch:!0,label:"Keywords",items:E.map(P)},{prefixMatch:!0,label:"Operators",items:T},{prefixMatch:!0,label:"Functions",items:R.map(function(e){return e.type="function",e})},{prefixMatch:!0,label:"Macros",items:O.map(function(e){return e.type="function",e})},{prefixMatch:!0,label:"Tables",items:s.a.map(this.schema.Databases.Default.Tables,function(e){return{text:e.Name}})}]},t.prototype.getFunctionSuggestions=function(){return[{prefixMatch:!0,label:"Functions",items:R.map(function(e){return e.type="function",e})},{prefixMatch:!0,label:"Macros",items:O.map(function(e){return e.type="function",e})}]},t.prototype.getTableSuggestions=function(e){return void 0===e&&(e="Default"),this.schema.Databases[e]?[{prefixMatch:!0,label:"Tables",items:s.a.map(this.schema.Databases[e].Tables,function(e){return{text:e.Name}})}]:[]},t.prototype.getColumnSuggestions=function(){var e=this.getTableFromContext();if(e){var t=this.schema.Databases.Default.Tables[e];if(t)return[{prefixMatch:!0,label:"Fields",items:s.a.map(t.OrderedColumns,function(e){return{text:e.Name,hint:e.Type}})}]}return[]},t.prototype.getTableFromContext=function(){var e=X(l.a.serialize(this.state.value)),t=/^\s*(\w+)\s*|/g.exec(e);return t&&t.length>1&&t[0]&&t[1]?t[1]:null},t.prototype.getDBFromDatabaseFunction=function(e){var t=/database\(\"(\w+)\"\)/gi.exec(e);return t&&t.length>1&&t[0]&&t[1]?t[1]:null},t.prototype.fetchSchema=function(){return Object(i.__awaiter)(this,void 0,void 0,function(){var e;return Object(i.__generator)(this,function(t){switch(t.label){case 0:return[4,this.props.getSchema()];case 1:return(e=t.sent())?("AppInsights"===e.Type&&(e=function(e){var t=F();return t.Databases.Default=e,t}(e)),this.schema=e):this.schema=F(),[2]}})})},t}(N);function X(e){var t=e.replace(/\/\/.*$/gm,"");return t=t.replace("\n"," ")}var Q=r("txxJ"),U=function(e){function t(t){var r=e.call(this,t)||this;return r.onChangeQuery=function(e){var t=r.props,a=t.index,i=t.change,n=r.state.query!==e;r.setState({edited:n,query:e}),i&&i(e,a)},r.onPressEnter=function(){var e=r.props.execute;e&&e()},r.state={edited:!1,query:t.query||""},r}return Object(i.__extends)(t,e),t.prototype.render=function(){var e=this.props,t=e.variables,r=e.getSchema,a=e.placeholder,i=this.state,n=i.edited,s=i.query;return h.a.createElement("div",{className:"gf-form-input",style:{height:"auto"}},h.a.createElement(V,{initialQuery:n?null:s,onPressEnter:this.onPressEnter,onQueryChange:this.onChangeQuery,prismLanguage:"kusto",prismDefinition:j,placeholder:a,templateVariables:t,getSchema:r}))},t.defaultProps={placeholder:"Enter a query"},t}(p.Component);Q.c.directive("kustoEditor",["reactDirective",function(e){return e(U,["change","database","execute","query","variables","placeholder",["getSchema",{watchDepth:"reference"}]])}]);var W=function(e){function t(t,r,i){var n=e.call(this,t,r)||this;return n.templateSrv=i,n.defaultDropdownValue="select",n.defaults={queryType:"Azure Monitor",azureMonitor:{resourceGroup:n.defaultDropdownValue,metricDefinition:n.defaultDropdownValue,resourceName:n.defaultDropdownValue,metricNamespace:n.defaultDropdownValue,metricName:n.defaultDropdownValue,dimensionFilter:"*",timeGrain:"auto",top:"10",aggOptions:[],timeGrains:[]},azureLogAnalytics:{query:["//change this example to create your own time series query","<table name> //the table to query (e.g. Usage, Heartbeat, Perf)","| where $__timeFilter(TimeGenerated) //this is a macro used to show the full chart’s time range, choose the datetime column here","| summarize count() by <group by column>, bin(TimeGenerated, $__interval) //change “group by column” to a column in your table, such as “Computer”. The $__interval macro is used to auto-select the time grain. Can also use 1h, 5m etc.","| order by TimeGenerated asc"].join("\n"),resultFormat:"time_series",workspace:n.datasource&&n.datasource.azureLogAnalyticsDatasource?n.datasource.azureLogAnalyticsDatasource.defaultOrFirstWorkspace:""},appInsights:{metricName:n.defaultDropdownValue,rawQuery:!1,rawQueryString:"",dimension:"none",timeGrain:"auto",timeColumn:"timestamp",valueColumn:""}},n.getWorkspaces=function(){return n.datasource.azureLogAnalyticsDatasource.getWorkspaces(n.target.subscription).then(function(e){return n.workspaces=e,e.length>0&&!n.target.azureLogAnalytics.workspace&&(n.datasource.azureLogAnalyticsDatasource.defaultOrFirstWorkspace&&(n.target.azureLogAnalytics.workspace=n.datasource.azureLogAnalyticsDatasource.defaultOrFirstWorkspace),n.target.azureLogAnalytics.workspace||(n.target.azureLogAnalytics.workspace=e[0].value)),n.workspaces}).catch(n.handleQueryCtrlError.bind(n))},n.getAzureLogAnalyticsSchema=function(){return n.getWorkspaces().then(function(){return n.datasource.azureLogAnalyticsDatasource.getSchema(n.target.azureLogAnalytics.workspace)}).catch(n.handleQueryCtrlError.bind(n))},n.onLogAnalyticsQueryChange=function(e){n.target.azureLogAnalytics.query=e},n.onLogAnalyticsQueryExecute=function(){n.panelCtrl.refresh()},n.onAppInsightsQueryChange=function(e){n.target.appInsights.rawQueryString=e},n.onAppInsightsQueryExecute=function(){return n.refresh()},n.getAppInsightsQuerySchema=function(){return n.datasource.appInsightsDatasource.getQuerySchema().catch(n.handleQueryCtrlError.bind(n))},s.a.defaultsDeep(n.target,n.defaults),n.migrateTimeGrains(),n.migrateToFromTimes(),n.migrateToDefaultNamespace(),n.migrateApplicationInsightsKeys(),n.panelCtrl.events.on(a.PanelEvents.dataReceived,n.onDataReceived.bind(n),t),n.panelCtrl.events.on(a.PanelEvents.dataError,n.onDataError.bind(n),t),n.resultFormats=[{text:"Time series",value:"time_series"},{text:"Table",value:"table"}],n.getSubscriptions(),"Azure Log Analytics"===n.target.queryType&&n.getWorkspaces(),n}return t.$inject=["$scope","$injector","templateSrv"],Object(i.__extends)(t,e),t.prototype.onDataReceived=function(e){this.lastQueryError=void 0,this.lastQuery="";var t=s.a.find(e,{refId:this.target.refId});t&&t.meta&&(this.lastQuery=t.meta.query)},t.prototype.onDataError=function(e){this.handleQueryCtrlError(e)},t.prototype.handleQueryCtrlError=function(e){e.query&&e.query.refId&&e.query.refId!==this.target.refId||(e.error&&e.error.data&&e.error.data.error&&e.error.data.error.innererror?e.error.data.error.innererror.innererror?this.lastQueryError=e.error.data.error.innererror.innererror.message:this.lastQueryError=e.error.data.error.innererror.message:e.error&&e.error.data&&e.error.data.error?this.lastQueryError=e.error.data.error.message:e.error&&e.error.data?this.lastQueryError=e.error.data.message:e.data&&e.data.error?this.lastQueryError=e.data.error.message:e.data&&e.data.message?this.lastQueryError=e.data.message:this.lastQueryError=e)},t.prototype.migrateTimeGrains=function(){this.target.azureMonitor.timeGrainUnit&&("auto"!==this.target.azureMonitor.timeGrain&&(this.target.azureMonitor.timeGrain=c.createISO8601Duration(this.target.azureMonitor.timeGrain,this.target.azureMonitor.timeGrainUnit)),delete this.target.azureMonitor.timeGrainUnit,this.onMetricNameChange()),this.target.appInsights.timeGrainUnit&&"auto"!==this.target.appInsights.timeGrain&&(this.target.appInsights.timeGrainCount?this.target.appInsights.timeGrain=c.createISO8601Duration(this.target.appInsights.timeGrainCount,this.target.appInsights.timeGrainUnit):(this.target.appInsights.timeGrainCount=this.target.appInsights.timeGrain,this.target.appInsights.timeGrain=c.createISO8601Duration(this.target.appInsights.timeGrain,this.target.appInsights.timeGrainUnit))),this.target.azureMonitor.timeGrains&&this.target.azureMonitor.timeGrains.length>0&&(!this.target.azureMonitor.allowedTimeGrainsMs||0===this.target.azureMonitor.allowedTimeGrainsMs.length)&&(this.target.azureMonitor.allowedTimeGrainsMs=this.convertTimeGrainsToMs(this.target.azureMonitor.timeGrains)),this.target.appInsights.timeGrains&&this.target.appInsights.timeGrains.length>0&&(!this.target.appInsights.allowedTimeGrainsMs||0===this.target.appInsights.allowedTimeGrainsMs.length)&&(this.target.appInsights.allowedTimeGrainsMs=this.convertTimeGrainsToMs(this.target.appInsights.timeGrains))},t.prototype.migrateToFromTimes=function(){this.target.azureLogAnalytics.query=this.target.azureLogAnalytics.query.replace(/\$__from\s/gi,"$__timeFrom() "),this.target.azureLogAnalytics.query=this.target.azureLogAnalytics.query.replace(/\$__to\s/gi,"$__timeTo() ")},t.prototype.migrateToDefaultNamespace=function(){return Object(i.__awaiter)(this,void 0,void 0,function(){return Object(i.__generator)(this,function(e){return this.target.azureMonitor.metricNamespace&&this.target.azureMonitor.metricNamespace!==this.defaultDropdownValue&&this.target.azureMonitor.metricDefinition?[2]:(this.target.azureMonitor.metricNamespace=this.target.azureMonitor.metricDefinition,[2])})})},t.prototype.migrateApplicationInsightsKeys=function(){var e=this.target.appInsights,t={xaxis:"timeColumn",yaxis:"valueColumn",spliton:"segmentColumn",groupBy:"dimension",groupByOptions:"dimensions",filter:"dimensionFilter"};for(var r in t)e[r]&&(e[t[r]]=e[r],delete e[r])},t.prototype.replace=function(e){return this.templateSrv.replace(e,this.panelCtrl.panel.scopedVars)},t.prototype.onQueryTypeChange=function(){if("Azure Log Analytics"===this.target.queryType)return this.getWorkspaces()},t.prototype.getSubscriptions=function(){var e=this;if(this.datasource.azureMonitorDatasource.isConfigured())return this.datasource.azureMonitorDatasource.getSubscriptions().then(function(t){return e.subscriptions=t,e.target.subscription||"Azure Monitor"!==e.target.queryType?e.target.subscription||"Azure Log Analytics"!==e.target.queryType||(e.target.subscription=e.datasource.azureLogAnalyticsDatasource.logAnalyticsSubscriptionId):e.target.subscription=e.datasource.azureMonitorDatasource.subscriptionId,!e.target.subscription&&e.subscriptions.length>0&&(e.target.subscription=e.subscriptions[0].value),e.subscriptions})},t.prototype.onSubscriptionChange=function(){if("Azure Log Analytics"===this.target.queryType)return this.getWorkspaces();"Azure Monitor"===this.target.queryType&&(this.target.azureMonitor.resourceGroup=this.defaultDropdownValue,this.target.azureMonitor.metricDefinition=this.defaultDropdownValue,this.target.azureMonitor.resourceName=this.defaultDropdownValue,this.target.azureMonitor.metricName=this.defaultDropdownValue,this.target.azureMonitor.aggregation="",this.target.azureMonitor.timeGrains=[],this.target.azureMonitor.timeGrain="",this.target.azureMonitor.dimensions=[],this.target.azureMonitor.dimension="")},t.prototype.getResourceGroups=function(e){if("Azure Monitor"===this.target.queryType&&this.datasource.azureMonitorDatasource.isConfigured())return this.datasource.getResourceGroups(this.replace(this.target.subscription||this.datasource.azureMonitorDatasource.subscriptionId)).catch(this.handleQueryCtrlError.bind(this))},t.prototype.getMetricDefinitions=function(e){if("Azure Monitor"===this.target.queryType&&this.target.azureMonitor.resourceGroup&&this.target.azureMonitor.resourceGroup!==this.defaultDropdownValue)return this.datasource.getMetricDefinitions(this.replace(this.target.subscription||this.datasource.azureMonitorDatasource.subscriptionId),this.replace(this.target.azureMonitor.resourceGroup)).catch(this.handleQueryCtrlError.bind(this))},t.prototype.getResourceNames=function(e){if("Azure Monitor"===this.target.queryType&&this.target.azureMonitor.resourceGroup&&this.target.azureMonitor.resourceGroup!==this.defaultDropdownValue&&this.target.azureMonitor.metricDefinition&&this.target.azureMonitor.metricDefinition!==this.defaultDropdownValue)return this.datasource.getResourceNames(this.replace(this.target.subscription||this.datasource.azureMonitorDatasource.subscriptionId),this.replace(this.target.azureMonitor.resourceGroup),this.replace(this.target.azureMonitor.metricDefinition)).catch(this.handleQueryCtrlError.bind(this))},t.prototype.getMetricNamespaces=function(){if("Azure Monitor"===this.target.queryType&&this.target.azureMonitor.resourceGroup&&this.target.azureMonitor.resourceGroup!==this.defaultDropdownValue&&this.target.azureMonitor.metricDefinition&&this.target.azureMonitor.metricDefinition!==this.defaultDropdownValue&&this.target.azureMonitor.resourceName&&this.target.azureMonitor.resourceName!==this.defaultDropdownValue)return this.datasource.getMetricNamespaces(this.replace(this.target.subscription||this.datasource.azureMonitorDatasource.subscriptionId),this.replace(this.target.azureMonitor.resourceGroup),this.replace(this.target.azureMonitor.metricDefinition),this.replace(this.target.azureMonitor.resourceName)).catch(this.handleQueryCtrlError.bind(this))},t.prototype.getMetricNames=function(){if("Azure Monitor"===this.target.queryType&&this.target.azureMonitor.resourceGroup&&this.target.azureMonitor.resourceGroup!==this.defaultDropdownValue&&this.target.azureMonitor.metricDefinition&&this.target.azureMonitor.metricDefinition!==this.defaultDropdownValue&&this.target.azureMonitor.resourceName&&this.target.azureMonitor.resourceName!==this.defaultDropdownValue&&this.target.azureMonitor.metricNamespace&&this.target.azureMonitor.metricNamespace!==this.defaultDropdownValue)return this.datasource.getMetricNames(this.replace(this.target.subscription||this.datasource.azureMonitorDatasource.subscriptionId),this.replace(this.target.azureMonitor.resourceGroup),this.replace(this.target.azureMonitor.metricDefinition),this.replace(this.target.azureMonitor.resourceName),this.replace(this.target.azureMonitor.metricNamespace)).catch(this.handleQueryCtrlError.bind(this))},t.prototype.onResourceGroupChange=function(){this.target.azureMonitor.metricDefinition=this.defaultDropdownValue,this.target.azureMonitor.resourceName=this.defaultDropdownValue,this.target.azureMonitor.metricNamespace=this.defaultDropdownValue,this.target.azureMonitor.metricName=this.defaultDropdownValue,this.target.azureMonitor.aggregation="",this.target.azureMonitor.timeGrains=[],this.target.azureMonitor.timeGrain="",this.target.azureMonitor.dimensions=[],this.target.azureMonitor.dimension="",this.refresh()},t.prototype.onMetricDefinitionChange=function(){this.target.azureMonitor.resourceName=this.defaultDropdownValue,this.target.azureMonitor.metricNamespace=this.defaultDropdownValue,this.target.azureMonitor.metricName=this.defaultDropdownValue,this.target.azureMonitor.aggregation="",this.target.azureMonitor.timeGrains=[],this.target.azureMonitor.timeGrain="",this.target.azureMonitor.dimensions=[],this.target.azureMonitor.dimension=""},t.prototype.onResourceNameChange=function(){this.target.azureMonitor.metricNamespace=this.defaultDropdownValue,this.target.azureMonitor.metricName=this.defaultDropdownValue,this.target.azureMonitor.aggregation="",this.target.azureMonitor.timeGrains=[],this.target.azureMonitor.timeGrain="",this.target.azureMonitor.dimensions=[],this.target.azureMonitor.dimension="",this.refresh()},t.prototype.onMetricNamespacesChange=function(){this.target.azureMonitor.metricName=this.defaultDropdownValue,this.target.azureMonitor.dimensions=[],this.target.azureMonitor.dimension=""},t.prototype.onMetricNameChange=function(){var e=this;return this.target.azureMonitor.metricName&&this.target.azureMonitor.metricName!==this.defaultDropdownValue?this.datasource.getMetricMetadata(this.replace(this.target.subscription),this.replace(this.target.azureMonitor.resourceGroup),this.replace(this.target.azureMonitor.metricDefinition),this.replace(this.target.azureMonitor.resourceName),this.replace(this.target.azureMonitor.metricNamespace),this.replace(this.target.azureMonitor.metricName)).then(function(t){return e.target.azureMonitor.aggOptions=t.supportedAggTypes||[t.primaryAggType],e.target.azureMonitor.aggregation=t.primaryAggType,e.target.azureMonitor.timeGrains=[{text:"auto",value:"auto"}].concat(t.supportedTimeGrains),e.target.azureMonitor.timeGrain="auto",e.target.azureMonitor.allowedTimeGrainsMs=e.convertTimeGrainsToMs(t.supportedTimeGrains||[]),e.target.azureMonitor.dimensions=t.dimensions,t.dimensions.length>0&&(e.target.azureMonitor.dimension=t.dimensions[0].value),e.refresh()}).catch(this.handleQueryCtrlError.bind(this)):Promise.resolve()},t.prototype.convertTimeGrainsToMs=function(e){var t=[];return e.forEach(function(e){"auto"!==e.value&&t.push(u.a.interval_to_ms(c.createKbnUnitFromISO8601Duration(e.value)))}),t},t.prototype.generateAutoUnits=function(e,t){return"auto"===e?c.findClosestTimeGrain(this.templateSrv.getBuiltInIntervalValue(),s.a.map(t,function(e){return c.createKbnUnitFromISO8601Duration(e.value)})||["1m","5m","15m","30m","1h","6h","12h","1d"]):""},t.prototype.getAzureMonitorAutoInterval=function(){return this.generateAutoUnits(this.target.azureMonitor.timeGrain,this.target.azureMonitor.timeGrains)},t.prototype.getApplicationInsightAutoInterval=function(){return this.generateAutoUnits(this.target.appInsights.timeGrain,this.target.appInsights.timeGrains)},Object.defineProperty(t.prototype,"templateVariables",{get:function(){return this.templateSrv.variables.map(function(e){return"$"+e.name})},enumerable:!0,configurable:!0}),t.prototype.getAppInsightsAutoInterval=function(){var e=this.templateSrv.getBuiltInIntervalValue();return"s"===e[e.length-1]?"1m":e},t.prototype.getAppInsightsMetricNames=function(){if(this.datasource.appInsightsDatasource.isConfigured())return this.datasource.getAppInsightsMetricNames().catch(this.handleQueryCtrlError.bind(this))},t.prototype.getAppInsightsColumns=function(){return this.datasource.getAppInsightsColumns(this.target.refId)},t.prototype.onAppInsightsColumnChange=function(){return this.refresh()},t.prototype.onAppInsightsMetricNameChange=function(){var e=this;if(this.target.appInsights.metricName&&this.target.appInsights.metricName!==this.defaultDropdownValue)return this.datasource.getAppInsightsMetricMetadata(this.replace(this.target.appInsights.metricName)).then(function(t){return e.target.appInsights.aggOptions=t.supportedAggTypes,e.target.appInsights.dimensions=t.supportedGroupBy,e.target.appInsights.aggregation=t.primaryAggType,e.refresh()}).catch(this.handleQueryCtrlError.bind(this))},t.prototype.getAppInsightsGroupBySegments=function(e){return s.a.map(this.target.appInsights.dimensions,function(e){return{text:e,value:e}})},t.prototype.resetAppInsightsGroupBy=function(){this.target.appInsights.dimension="none",this.refresh()},t.prototype.toggleEditorMode=function(){this.target.appInsights.rawQuery=!this.target.appInsights.rawQuery},t.prototype.updateTimeGrainType=function(){"specific"===this.target.appInsights.timeGrainType?(this.target.appInsights.timeGrainCount="1",this.target.appInsights.timeGrainUnit="minute",this.target.appInsights.timeGrain=c.createISO8601Duration(this.target.appInsights.timeGrainCount,this.target.appInsights.timeGrainUnit)):(this.target.appInsights.timeGrainCount="",this.target.appInsights.timeGrainUnit="")},t.prototype.updateAppInsightsTimeGrain=function(){this.target.appInsights.timeGrainUnit&&this.target.appInsights.timeGrainCount&&(this.target.appInsights.timeGrain=c.createISO8601Duration(this.target.appInsights.timeGrainCount,this.target.appInsights.timeGrainUnit)),this.refresh()},t.templateUrl="partials/query.editor.html",t}(o.QueryCtrl),B=function(){function e(){}return e.buildAzureMonitorGetMetricNamespacesUrl=function(e,t,r,a,i,n){if((a.match(/\//g)||[]).length>1){var s=i.split("/"),o=a.substring(a.lastIndexOf("/")+1);return e+"/"+t+"/resourceGroups/"+r+"/providers/"+a.substring(0,a.lastIndexOf("/"))+"/"+s[0]+"/"+o+"/"+s[1]+"/providers/microsoft.insights/metricNamespaces?api-version="+n}return e+"/"+t+"/resourceGroups/"+r+"/providers/"+a+"/"+i+"/providers/microsoft.insights/metricNamespaces?api-version="+n},e.buildAzureMonitorGetMetricNamesUrl=function(e,t,r,a,i,n,s){if((a.match(/\//g)||[]).length>1){var o=i.split("/"),u=a.substring(a.lastIndexOf("/")+1);return e+"/"+t+"/resourceGroups/"+r+"/providers/"+a.substring(0,a.lastIndexOf("/"))+"/"+o[0]+"/"+u+"/"+o[1]+"/providers/microsoft.insights/metricdefinitions?api-version="+s+"&metricnamespace="+encodeURIComponent(n)}return e+"/"+t+"/resourceGroups/"+r+"/providers/"+a+"/"+i+"/providers/microsoft.insights/metricdefinitions?api-version="+s+"&metricnamespace="+encodeURIComponent(n)},e}(),K=function(){function e(){}return e.parseResponseValues=function(e,t,r){var a=[];if(!e)return a;for(var i=0;i<e.data.value.length;i++)if(!s.a.find(a,["value",s.a.get(e.data.value[i],r)])){var n=s.a.get(e.data.value[i],r),o=s.a.get(e.data.value[i],t,n);a.push({text:o,value:n})}return a},e.parseResourceNames=function(e,t){var r=[];if(!e)return r;for(var a=0;a<e.data.value.length;a++)e.data.value[a].type===t&&r.push({text:e.data.value[a].name,value:e.data.value[a].name});return r},e.parseMetadata=function(t,r){var a=["None","Average","Minimum","Maximum","Total","Count"];if(!t)return{primaryAggType:"",supportedAggTypes:a,supportedTimeGrains:[],dimensions:[]};var i=s.a.find(t.data.value,function(e){return s.a.get(e,"name.value")===r});return{primaryAggType:i.primaryAggregationType,supportedAggTypes:i.supportedAggregationTypes||a,supportedTimeGrains:e.parseTimeGrains(i.metricAvailabilities||[]),dimensions:e.parseDimensions(i)}},e.parseTimeGrains=function(e){var t=[];return e?(e.forEach(function(e){e.timeGrain&&t.push({text:c.createTimeGrainFromISO8601Duration(e.timeGrain),value:e.timeGrain})}),t):t},e.parseDimensions=function(e){var t=[];if(!e.dimensions||0===e.dimensions.length)return t;e.isDimensionRequired||t.push({text:"None",value:"None"});for(var r=0;r<e.dimensions.length;r++){var a=e.dimensions[r].localizedValue,i=e.dimensions[r].value;t.push({text:a||i,value:i})}return t},e.parseSubscriptions=function(e){var t=[];if(!e)return t;for(var r=0;r<e.data.value.length;r++)s.a.find(t,["value",s.a.get(e.data.value[r],"subscriptionId")])||t.push({text:s.a.get(e.data.value[r],"displayName")+" - "+s.a.get(e.data.value[r],"subscriptionId"),value:s.a.get(e.data.value[r],"subscriptionId")});return t},e.parseSubscriptionsForSelect=function(e){var t=[];if(!e)return t;for(var r=0;r<e.data.value.length;r++)s.a.find(t,["value",s.a.get(e.data.value[r],"subscriptionId")])||t.push({label:s.a.get(e.data.value[r],"displayName")+" - "+s.a.get(e.data.value[r],"subscriptionId"),value:s.a.get(e.data.value[r],"subscriptionId")});return t},e.parseWorkspacesForSelect=function(e){var t=[];if(!e)return t;for(var r=0;r<e.data.value.length;r++)s.a.find(t,["value",s.a.get(e.data.value[r].properties,"customerId")])||t.push({label:s.a.get(e.data.value[r],"name"),value:s.a.get(e.data.value[r].properties,"customerId")});return t},e}(),J=function(){function e(e){this.cloudName=e,this.supportedMetricNamespaces={azuremonitor:["Microsoft.AnalysisServices/servers","Microsoft.ApiManagement/service","Microsoft.Automation/automationAccounts","Microsoft.Batch/batchAccounts","Microsoft.Cache/redis","Microsoft.ClassicCompute/virtualMachines","Microsoft.ClassicCompute/domainNames/slots/roles","Microsoft.CognitiveServices/accounts","Microsoft.Compute/virtualMachines","Microsoft.Compute/virtualMachineScaleSets","Microsoft.ContainerInstance/containerGroups","Microsoft.ContainerRegistry/registries","Microsoft.ContainerService/managedClusters","Microsoft.CustomerInsights/hubs","Microsoft.DataBoxEdge/dataBoxEdgeDevices","Microsoft.DataFactory/datafactories","Microsoft.DataFactory/factories","Microsoft.DataLakeAnalytics/accounts","Microsoft.DataLakeStore/accounts","Microsoft.DBforMariaDB/servers","Microsoft.DBforMySQL/servers","Microsoft.DBforPostgreSQL/servers","Microsoft.Devices/IotHubs","Microsoft.Devices/provisioningServices","Microsoft.DocumentDB/databaseAccounts","Microsoft.EventGrid/topics","Microsoft.EventGrid/eventSubscriptions","Microsoft.EventGrid/extensionTopics","Microsoft.EventHub/namespaces","Microsoft.EventHub/clusters","Microsoft.HDInsight/clusters","Microsoft.Insights/AutoscaleSettings","Microsoft.Insights/components","Microsoft.KeyVault/vaults","Microsoft.Kusto/clusters","Microsoft.LocationBasedServices/accounts","Microsoft.Logic/workflows","Microsoft.Logic/integrationServiceEnvironments","Microsoft.NetApp/netAppAccounts/capacityPools","Microsoft.NetApp/netAppAccounts/capacityPools/Volumes","Microsoft.Network/networkInterfaces","Microsoft.Network/loadBalancers","Microsoft.Network/dnsZones","Microsoft.Network/publicIPAddresses","Microsoft.Network/azureFirewalls","Microsoft.Network/applicationGateways","Microsoft.Network/virtualNetworkGateways","Microsoft.Network/expressRouteCircuits","Microsoft.Network/expressRouteCircuits/Peerings","Microsoft.Network/connections","Microsoft.Network/trafficManagerProfiles","Microsoft.Network/networkWatchers/connectionMonitors","Microsoft.Network/frontdoors","Microsoft.NotificationHubs/namespaces/notificationHubs","Microsoft.OperationalInsights/workspaces","Microsoft.PowerBIDedicated/capacities","Microsoft.Relay/namespaces","Microsoft.Search/searchServices","Microsoft.ServiceBus/namespaces","Microsoft.Sql/servers/databases","Microsoft.Sql/servers/elasticPools","Microsoft.Sql/managedInstances","Microsoft.Storage/storageAccounts","Microsoft.Storage/storageAccounts/blobServices","Microsoft.Storage/storageAccounts/fileServices","Microsoft.Storage/storageAccounts/queueServices","Microsoft.Storage/storageAccounts/tableServices","Microsoft.StorageSync/storageSyncServices","Microsoft.StorageSync/storageSyncServices/syncGroups","Microsoft.StorageSync/storageSyncServices/syncGroups/serverEndpoints","Microsoft.StorageSync/storageSyncServices/registeredServers","Microsoft.StreamAnalytics/streamingJobs","Microsoft.Web/serverfarms","Microsoft.Web/sites","Microsoft.Web/sites/slots","Microsoft.Web/hostingEnvironments/multiRolePools","Microsoft.Web/hostingEnvironments/workerPools"],govazuremonitor:["Microsoft.AnalysisServices/servers","Microsoft.ApiManagement/service","Microsoft.Batch/batchAccounts","Microsoft.Cache/redis","Microsoft.ClassicCompute/virtualMachines","Microsoft.ClassicCompute/domainNames/slots/roles","Microsoft.CognitiveServices/accounts","Microsoft.Compute/virtualMachines","Microsoft.Compute/virtualMachineScaleSets","Microsoft.ContainerRegistry/registries","Microsoft.DBforMySQL/servers","Microsoft.DBforPostgreSQL/servers","Microsoft.Devices/IotHubs","Microsoft.Devices/provisioningServices","Microsoft.EventGrid/topics","Microsoft.EventGrid/eventSubscriptions","Microsoft.EventGrid/extensionTopics","Microsoft.EventHub/namespaces","Microsoft.EventHub/clusters","Microsoft.Insights/AutoscaleSettings","Microsoft.KeyVault/vaults","Microsoft.Logic/workflows","Microsoft.Network/networkInterfaces","Microsoft.Network/loadBalancers","Microsoft.Network/dnsZones","Microsoft.Network/publicIPAddresses","Microsoft.Network/azureFirewalls","Microsoft.Network/applicationGateways","Microsoft.Network/virtualNetworkGateways","Microsoft.Network/expressRouteCircuits","Microsoft.Network/expressRouteCircuits/Peerings","Microsoft.Network/connections","Microsoft.Network/trafficManagerProfiles","Microsoft.Network/networkWatchers/connectionMonitors","Microsoft.Network/frontdoors","Microsoft.NotificationHubs/namespaces/notificationHubs","Microsoft.OperationalInsights/workspaces","Microsoft.PowerBIDedicated/capacities","Microsoft.Relay/namespaces","Microsoft.ServiceBus/namespaces","Microsoft.Sql/servers/databases","Microsoft.Sql/servers/elasticPools","Microsoft.Sql/managedInstances","Microsoft.Storage/storageAccounts","Microsoft.Storage/storageAccounts/blobServices","Microsoft.Storage/storageAccounts/fileServices","Microsoft.Storage/storageAccounts/queueServices","Microsoft.Storage/storageAccounts/tableServices","Microsoft.Web/serverfarms","Microsoft.Web/sites","Microsoft.Web/sites/slots","Microsoft.Web/hostingEnvironments/multiRolePools","Microsoft.Web/hostingEnvironments/workerPools"],germanyazuremonitor:["Microsoft.AnalysisServices/servers","Microsoft.Batch/batchAccounts","Microsoft.Cache/redis","Microsoft.ClassicCompute/virtualMachines","Microsoft.ClassicCompute/domainNames/slots/roles","Microsoft.Compute/virtualMachines","Microsoft.Compute/virtualMachineScaleSets","Microsoft.DBforMySQL/servers","Microsoft.DBforPostgreSQL/servers","Microsoft.Devices/IotHubs","Microsoft.Devices/provisioningServices","Microsoft.EventHub/namespaces","Microsoft.EventHub/clusters","Microsoft.Insights/AutoscaleSettings","Microsoft.KeyVault/vaults","Microsoft.Network/networkInterfaces","Microsoft.Network/loadBalancers","Microsoft.Network/dnsZones","Microsoft.Network/publicIPAddresses","Microsoft.Network/azureFirewalls","Microsoft.Network/applicationGateways","Microsoft.Network/virtualNetworkGateways","Microsoft.Network/expressRouteCircuits","Microsoft.Network/expressRouteCircuits/Peerings","Microsoft.Network/connections","Microsoft.Network/trafficManagerProfiles","Microsoft.Network/networkWatchers/connectionMonitors","Microsoft.Network/frontdoors","Microsoft.NotificationHubs/namespaces/notificationHubs","Microsoft.OperationalInsights/workspaces","Microsoft.PowerBIDedicated/capacities","Microsoft.Relay/namespaces","Microsoft.ServiceBus/namespaces","Microsoft.Sql/servers/databases","Microsoft.Sql/servers/elasticPools","Microsoft.Sql/managedInstances","Microsoft.Storage/storageAccounts","Microsoft.Storage/storageAccounts/blobServices","Microsoft.Storage/storageAccounts/fileServices","Microsoft.Storage/storageAccounts/queueServices","Microsoft.Storage/storageAccounts/tableServices","Microsoft.StreamAnalytics/streamingJobs","Microsoft.Web/serverfarms","Microsoft.Web/sites","Microsoft.Web/sites/slots","Microsoft.Web/hostingEnvironments/multiRolePools","Microsoft.Web/hostingEnvironments/workerPools"],chinaazuremonitor:["Microsoft.AnalysisServices/servers","Microsoft.Batch/batchAccounts","Microsoft.Cache/redis","Microsoft.ClassicCompute/virtualMachines","Microsoft.ClassicCompute/domainNames/slots/roles","Microsoft.CognitiveServices/accounts","Microsoft.Compute/virtualMachines","Microsoft.Compute/virtualMachineScaleSets","Microsoft.ContainerRegistry/registries","Microsoft.DBforMySQL/servers","Microsoft.DBforPostgreSQL/servers","Microsoft.Devices/IotHubs","Microsoft.Devices/provisioningServices","Microsoft.EventHub/namespaces","Microsoft.Insights/AutoscaleSettings","Microsoft.KeyVault/vaults","Microsoft.Logic/workflows","Microsoft.Network/networkInterfaces","Microsoft.Network/loadBalancers","Microsoft.Network/dnsZones","Microsoft.Network/publicIPAddresses","Microsoft.Network/azureFirewalls","Microsoft.Network/applicationGateways","Microsoft.Network/virtualNetworkGateways","Microsoft.Network/expressRouteCircuits","Microsoft.Network/expressRouteCircuits/Peerings","Microsoft.Network/connections","Microsoft.Network/trafficManagerProfiles","Microsoft.Network/networkWatchers/connectionMonitors","Microsoft.Network/frontdoors","Microsoft.NotificationHubs/namespaces/notificationHubs","Microsoft.PowerBIDedicated/capacities","Microsoft.Relay/namespaces","Microsoft.ServiceBus/namespaces","Microsoft.Sql/servers/databases","Microsoft.Sql/servers/elasticPools","Microsoft.Sql/managedInstances","Microsoft.Storage/storageAccounts","Microsoft.Storage/storageAccounts/blobServices","Microsoft.Storage/storageAccounts/fileServices","Microsoft.Storage/storageAccounts/queueServices","Microsoft.Storage/storageAccounts/tableServices","Microsoft.StreamAnalytics/streamingJobs","Microsoft.Web/serverfarms","Microsoft.Web/sites","Microsoft.Web/sites/slots","Microsoft.Web/hostingEnvironments/multiRolePools","Microsoft.Web/hostingEnvironments/workerPools"]}}return e.prototype.get=function(){return this.supportedMetricNamespaces[this.cloudName]},e}(),$=function(){function e(e,t,r){this.instanceSettings=e,this.backendSrv=t,this.templateSrv=r,this.apiVersion="2018-01-01",this.apiPreviewVersion="2017-12-01-preview",this.defaultDropdownValue="select",this.supportedMetricNamespaces=[],this.id=e.id,this.subscriptionId=e.jsonData.subscriptionId,this.cloudName=e.jsonData.cloudName||"azuremonitor",this.baseUrl="/"+this.cloudName+"/subscriptions",this.url=e.url,this.supportedMetricNamespaces=new J(this.cloudName).get()}return e.$inject=["instanceSettings","backendSrv","templateSrv"],e.prototype.isConfigured=function(){return!!this.subscriptionId&&this.subscriptionId.length>0},e.prototype.query=function(e){return Object(i.__awaiter)(this,void 0,Promise,function(){var t,r,n,o=this;return Object(i.__generator)(this,function(i){switch(i.label){case 0:return(t=s.a.filter(e.targets,function(e){return!0!==e.hide&&e.azureMonitor.resourceGroup&&e.azureMonitor.resourceGroup!==o.defaultDropdownValue&&e.azureMonitor.resourceName&&e.azureMonitor.resourceName!==o.defaultDropdownValue&&e.azureMonitor.metricDefinition&&e.azureMonitor.metricDefinition!==o.defaultDropdownValue&&e.azureMonitor.metricName&&e.azureMonitor.metricName!==o.defaultDropdownValue}).map(function(t){var r=t.azureMonitor;r.timeGrainUnit&&"auto"!==r.timeGrain&&(r.timeGrain=c.createISO8601Duration(r.timeGrain,r.timeGrainUnit));var a=o.templateSrv.replace(t.subscription||o.subscriptionId,e.scopedVars),i=o.templateSrv.replace(r.resourceGroup,e.scopedVars),n=o.templateSrv.replace(r.resourceName,e.scopedVars),s=o.templateSrv.replace(r.metricNamespace,e.scopedVars),u=o.templateSrv.replace(r.metricDefinition,e.scopedVars),l=o.templateSrv.replace((r.timeGrain||"").toString(),e.scopedVars),p=o.templateSrv.replace(r.aggregation,e.scopedVars),h=o.templateSrv.replace(r.top||"",e.scopedVars);return{refId:t.refId,intervalMs:e.intervalMs,datasourceId:o.id,subscription:a,queryType:"Azure Monitor",type:"timeSeriesQuery",raw:!1,azureMonitor:{resourceGroup:i,resourceName:n,metricDefinition:u,timeGrain:l,allowedTimeGrainsMs:r.allowedTimeGrainsMs,metricName:o.templateSrv.replace(r.metricName,e.scopedVars),metricNamespace:s&&s!==o.defaultDropdownValue?s:u,aggregation:p,dimension:o.templateSrv.replace(r.dimension,e.scopedVars),top:h||"10",dimensionFilter:o.templateSrv.replace(r.dimensionFilter,e.scopedVars),alias:r.alias,format:t.format}}}))&&0!==t.length?[4,this.backendSrv.datasourceRequest({url:"/api/tsdb/query",method:"POST",data:{from:e.range.from.valueOf().toString(),to:e.range.to.valueOf().toString(),queries:t}})]:[2,Promise.resolve([])];case 1:return r=i.sent().data,n=[],r.results?(Object.values(r.results).forEach(function(e){e.series&&e.series.forEach(function(t){var r={target:t.name,datapoints:t.points,refId:e.refId,meta:e.meta};n.push(Object(a.toDataFrame)(r))})}),[2,n]):[2,Promise.resolve([])]}})})},e.prototype.annotationQuery=function(e){},e.prototype.metricFindQuery=function(e){if(e.match(/^Subscriptions\(\)/i))return this.getSubscriptions();if(e.match(/^ResourceGroups\(\)/i))return this.getResourceGroups(this.subscriptionId);var t=e.match(/^ResourceGroups\(([^\)]+?)(,\s?([^,]+?))?\)/i);if(t)return this.getResourceGroups(this.toVariable(t[1]));var r=e.match(/^Namespaces\(([^\)]+?)(,\s?([^,]+?))?\)/i);if(r&&!r[3])return this.getMetricDefinitions(this.subscriptionId,this.toVariable(r[1]));var a=e.match(/^Namespaces\(([^,]+?),\s?([^,]+?)\)/i);if(a)return this.getMetricDefinitions(this.toVariable(a[1]),this.toVariable(a[2]));var i=e.match(/^ResourceNames\(([^,]+?),\s?([^,]+?)\)/i);if(i){var n=this.toVariable(i[1]),s=this.toVariable(i[2]);return this.getResourceNames(this.subscriptionId,n,s)}var o=e.match(/^ResourceNames\(([^,]+?),\s?([^,]+?),\s?(.+?)\)/i);if(o){var u=this.toVariable(o[1]);n=this.toVariable(o[2]),s=this.toVariable(o[3]);return this.getResourceNames(u,n,s)}var c=e.match(/^MetricNamespace\(([^,]+?),\s?([^,]+?),\s?([^,]+?)\)/i);if(c){n=this.toVariable(c[1]),s=this.toVariable(c[2]);var l=this.toVariable(c[3]);return this.getMetricNamespaces(this.subscriptionId,n,s,l)}var p=e.match(/^metricnamespace\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?)\)/i);if(p){u=this.toVariable(p[1]),n=this.toVariable(p[2]),s=this.toVariable(p[3]),l=this.toVariable(p[4]);return this.getMetricNamespaces(u,n,s,l)}var h=e.match(/^MetricNames\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?)\)/i);if(h&&-1===h[3].indexOf(",")){n=this.toVariable(h[1]),s=this.toVariable(h[2]),l=this.toVariable(h[3]);var d=this.toVariable(h[4]);return this.getMetricNames(this.subscriptionId,n,s,l,d)}var m=e.match(/^MetricNames\(([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?([^,]+?),\s?(.+?)\)/i);if(m){u=this.toVariable(m[1]),n=this.toVariable(m[2]),s=this.toVariable(m[3]),l=this.toVariable(m[4]),d=this.toVariable(m[5]);return this.getMetricNames(u,n,s,l,d)}},e.prototype.toVariable=function(e){return this.templateSrv.replace((e||"").trim())},e.prototype.getSubscriptions=function(e){var t="/"+(e||this.cloudName)+"/subscriptions?api-version=2019-03-01";return this.doRequest(t).then(function(e){return K.parseSubscriptions(e)})},e.prototype.getResourceGroups=function(e){var t=this.baseUrl+"/"+e+"/resourceGroups?api-version="+this.apiVersion;return this.doRequest(t).then(function(e){return K.parseResponseValues(e,"name","name")})},e.prototype.getMetricDefinitions=function(e,t){var r=this,a=this.baseUrl+"/"+e+"/resourceGroups/"+t+"/resources?api-version="+this.apiVersion;return this.doRequest(a).then(function(e){return K.parseResponseValues(e,"type","type")}).then(function(e){return s.a.filter(e,function(e){for(var t=0;t<r.supportedMetricNamespaces.length;t++)if(e.value.toLowerCase()===r.supportedMetricNamespaces[t].toLowerCase())return!0;return!1})}).then(function(e){for(var t=!1,r=0;r<e.length;r++)if("Microsoft.Storage/storageAccounts"===e[r].value){t=!0;break}return t&&(e.push({text:"Microsoft.Storage/storageAccounts/blobServices",value:"Microsoft.Storage/storageAccounts/blobServices"}),e.push({text:"Microsoft.Storage/storageAccounts/fileServices",value:"Microsoft.Storage/storageAccounts/fileServices"}),e.push({text:"Microsoft.Storage/storageAccounts/tableServices",value:"Microsoft.Storage/storageAccounts/tableServices"}),e.push({text:"Microsoft.Storage/storageAccounts/queueServices",value:"Microsoft.Storage/storageAccounts/queueServices"})),e})},e.prototype.getResourceNames=function(e,t,r){var a=this.baseUrl+"/"+e+"/resourceGroups/"+t+"/resources?api-version="+this.apiVersion;return this.doRequest(a).then(function(e){if(!s.a.startsWith(r,"Microsoft.Storage/storageAccounts/"))return K.parseResourceNames(e,r);for(var t=K.parseResourceNames(e,"Microsoft.Storage/storageAccounts"),a=0;a<t.length;a++)t[a].text+="/default",t[a].value+="/default";return t})},e.prototype.getMetricNamespaces=function(e,t,r,a){var i=B.buildAzureMonitorGetMetricNamespacesUrl(this.baseUrl,e,t,r,a,this.apiPreviewVersion);return this.doRequest(i).then(function(e){return K.parseResponseValues(e,"name","properties.metricNamespaceName")})},e.prototype.getMetricNames=function(e,t,r,a,i){var n=B.buildAzureMonitorGetMetricNamesUrl(this.baseUrl,e,t,r,a,i,this.apiVersion);return this.doRequest(n).then(function(e){return K.parseResponseValues(e,"name.localizedValue","name.value")})},e.prototype.getMetricMetadata=function(e,t,r,a,i,n){var s=B.buildAzureMonitorGetMetricNamesUrl(this.baseUrl,e,t,r,a,i,this.apiVersion);return this.doRequest(s).then(function(e){return K.parseMetadata(e,n)})},e.prototype.testDatasource=function(){if(!this.isValidConfigField(this.instanceSettings.jsonData.tenantId))return{status:"error",message:"The Tenant Id field is required."};if(!this.isValidConfigField(this.instanceSettings.jsonData.clientId))return{status:"error",message:"The Client Id field is required."};var e="/"+this.cloudName+"/subscriptions?api-version=2019-03-01";return this.doRequest(e).then(function(e){return 200===e.status?{status:"success",message:"Successfully queried the Azure Monitor service.",title:"Success"}:{status:"error",message:"Returned http status code "+e.status}}).catch(function(e){var t="Azure Monitor: ";return t+=e.statusText?e.statusText+": ":"",e.data&&e.data.error&&e.data.error.code?t+=e.data.error.code+". "+e.data.error.message:e.data&&e.data.error?t+=e.data.error:e.data?t+=e.data:t+="Cannot connect to Azure Monitor REST API.",{status:"error",message:t}})},e.prototype.isValidConfigField=function(e){return e&&e.length>0},e.prototype.doRequest=function(e,t){var r=this;return void 0===t&&(t=1),this.backendSrv.datasourceRequest({url:this.url+e,method:"GET"}).catch(function(a){if(t>0)return r.doRequest(e,t-1);throw a})},e}(),H=function(){function e(e){this.results=e}return e.prototype.parseQueryResult=function(){for(var e=[],t=[],r=0;r<this.results.length;r++)if(this.results[r].query.raw){var a=this.results[r].query.xaxis,i=this.results[r].query.yaxis,n=this.results[r].query.spliton;t=this.results[r].result.data.Tables[0].Columns;var o=this.results[r].result.data.Tables[0].Rows;e=s.a.concat(e,this.parseRawQueryResultRow(this.results[r].query,t,o,a,i,n))}else{var u=this.results[r].result.data.value,c=this.results[r].query.alias;e=s.a.concat(e,this.parseQueryResultRow(this.results[r].query,u,c))}return e},e.prototype.parseRawQueryResultRow=function(t,r,a,i,n,o){var u=[],c=s.a.map(r,function(e){return{text:e.ColumnName,value:e.ColumnName}}),l=r.findIndex(function(e){return e.ColumnName===i}),p=n.split(","),h={};s.a.forEach(p,function(e){h[e]=r.findIndex(function(t){return t.ColumnName===e})});var d=r.findIndex(function(e){return e.ColumnName===o}),m="timestamp"===i;return s.a.forEach(a,function(r){s.a.forEach(h,function(a,i){var n=-1===d?e.findOrCreateBucket(u,i):e.findOrCreateBucket(u,r[d]),s=m?e.dateTimeToEpoch(r[l]):r[l];n.datapoints.push([r[a],s]),n.refId=t.refId,n.query=t.query,n.columnsForDropdown=c})}),u},e.prototype.parseQueryResultRow=function(t,r,a){var i=[];if(e.isSingleValue(r)){var n=e.getMetricFieldKey(r),s=e.getKeyForAggregationField(r[n]),o=e.dateTimeToEpoch(r.end);return i.push({target:n,datapoints:[[r[n][s],o]],refId:t.refId,query:t.query}),i}if(e.hasSegmentsField(r.segments[0]))for(h=0;h<r.segments.length;h++){o=e.dateTimeToEpoch(r.segments[h].end);for(var u=0;u<r.segments[h].segments.length;u++){n=e.getMetricFieldKey(r.segments[h].segments[u]),s=e.getKeyForAggregationField(r.segments[h].segments[u][n]);var c=this.getTargetName(r.segments[h].segments[u],a),l=e.findOrCreateBucket(i,c);l.datapoints.push([r.segments[h].segments[u][n][s],o]),l.refId=t.refId,l.meta={query:t.query}}}else{for(var n=e.getMetricFieldKey(r.segments[0]),p=e.findOrCreateBucket(i,n),h=0;h<r.segments.length;h++){var o=e.dateTimeToEpoch(r.segments[h].end),s=e.getKeyForAggregationField(r.segments[h][n]);p.datapoints.push([r.segments[h][n][s],o])}p.refId=t.refId,p.query=t.query}return i},e.prototype.getTargetName=function(e,t){var r="",a="",i="";for(var n in e)s.a.isObject(e[n])?r=n:(a=n,i=e[n]);if(t){return t.replace(/\{\{([\s\S]+?)\}\}/g,function(e,t,n){var s=t||n;return"metric"===s?r:"groupbyname"===s?a:"groupbyvalue"===s?i:e})}return r+"{"+a+'="'+i+'"}'},e.isSingleValue=function(t){return!e.hasSegmentsField(t)},e.findOrCreateBucket=function(e,t){var r=s.a.find(e,["target",t]);return r||(r={target:t,datapoints:[]},e.push(r)),r},e.hasSegmentsField=function(e){var t=s.a.keys(e);return s.a.indexOf(t,"segments")>-1},e.getMetricFieldKey=function(e){var t=s.a.keys(e);return s.a.filter(s.a.without(t,"start","end"),function(t){return s.a.isObject(e[t])})[0]},e.getKeyForAggregationField=function(e){var t=s.a.keys(e);return s.a.intersection(t,["sum","avg","min","max","count","unique"])[0]},e.dateTimeToEpoch=function(e){return Object(a.dateTime)(e).valueOf()},e.parseMetricNames=function(t){var r=s.a.keys(t.data.metrics);return e.toTextValueList(r)},e.prototype.parseMetadata=function(e){var t=this.results.data.metrics[e];if(!t)throw Error("No data found for metric: "+e);return{primaryAggType:t.defaultAggregation,supportedAggTypes:t.supportedAggregations,supportedGroupBy:t.supportedGroupBy.all}},e.prototype.parseGroupBys=function(){return e.toTextValueList(this.results.supportedGroupBy)},e.prototype.parseQuerySchema=function(){var e={Type:"AppInsights",Tables:{}};if(this.results&&this.results.data&&this.results.data.Tables)for(var t=0;t<this.results.data.Tables[0].Rows.length;t++){var r=this.results.data.Tables[0].Rows[t],a=r[0],i=r[1],n=r[2];e.Tables[a]?e.Tables[a].OrderedColumns.push({Name:i,Type:n}):e.Tables[a]={Name:a,OrderedColumns:[{Name:i,Type:n}]}}return e},e.toTextValueList=function(e){for(var t=[],r=0;r<e.length;r++)t.push({text:e[r],value:e[r]});return t},e}(),Z=function(){function e(e,t,r){this.backendSrv=t,this.templateSrv=r,this.version="beta",this.logAnalyticsColumns={},this.id=e.id,this.applicationId=e.jsonData.appInsightsAppId,this.baseUrl="/appinsights/"+this.version+"/apps/"+this.applicationId,this.url=e.url}return e.$inject=["instanceSettings","backendSrv","templateSrv"],e.prototype.isConfigured=function(){return!!this.applicationId&&this.applicationId.length>0},e.prototype.createRawQueryRequest=function(e,t,r){return e.xaxis&&!e.timeColumn&&(e.timeColumn=e.xaxis),e.yaxis&&!e.valueColumn&&(e.valueColumn=e.yaxis),e.spliton&&!e.segmentColumn&&(e.segmentColumn=e.spliton),{type:"timeSeriesQuery",raw:!1,appInsights:{rawQuery:!0,rawQueryString:this.templateSrv.replace(e.rawQueryString,t.scopedVars),timeColumn:e.timeColumn,valueColumn:e.valueColumn,segmentColumn:e.segmentColumn}}},e.prototype.createMetricsRequest=function(e,t,r){return e.timeGrainCount?e.timeGrain=c.createISO8601Duration(e.timeGrainCount,e.timeGrainUnit):e.timeGrainUnit&&"auto"!==e.timeGrain&&(e.timeGrain=c.createISO8601Duration(e.timeGrain,e.timeGrainUnit)),e.groupBy&&!e.dimension&&(e.dimension=e.groupBy),e.filter&&!e.dimensionFilter&&(e.dimensionFilter=e.filter),{type:"timeSeriesQuery",raw:!1,appInsights:{rawQuery:!1,timeGrain:this.templateSrv.replace((e.timeGrain||"").toString(),t.scopedVars),allowedTimeGrainsMs:e.allowedTimeGrainsMs,metricName:this.templateSrv.replace(e.metricName,t.scopedVars),aggregation:this.templateSrv.replace(e.aggregation,t.scopedVars),dimension:this.templateSrv.replace(e.dimension,t.scopedVars),dimensionFilter:this.templateSrv.replace(e.dimensionFilter,t.scopedVars),alias:e.alias,format:r.format}}},e.prototype.query=function(e){return Object(i.__awaiter)(this,void 0,Promise,function(){var t,r,n,o=this;return Object(i.__generator)(this,function(i){switch(i.label){case 0:return(t=s.a.filter(e.targets,function(e){return!0!==e.hide}).map(function(t){var r,a=t.appInsights;return(r=a.rawQuery?o.createRawQueryRequest(a,e,t):o.createMetricsRequest(a,e,t)).refId=t.refId,r.intervalMs=e.intervalMs,r.datasourceId=o.id,r.queryType="Application Insights",r}))&&0!==t.length?[4,this.backendSrv.datasourceRequest({url:"/api/tsdb/query",method:"POST",data:{from:e.range.from.valueOf().toString(),to:e.range.to.valueOf().toString(),queries:t}})]:[2];case 1:return r=i.sent().data,n=[],r.results?(Object.values(r.results).forEach(function(e){if(e.meta&&e.meta.columns){var t=e.meta.columns;o.logAnalyticsColumns[e.refId]=s.a.map(t,function(e){return{text:e,value:e}})}e.series&&e.series.forEach(function(t){var r={target:t.name,datapoints:t.points,refId:e.refId,meta:e.meta};n.push(Object(a.toDataFrame)(r))})}),[2,n]):[2,Promise.resolve([])]}})})},e.prototype.doQueries=function(e){var t=this;return s.a.map(e,function(e){return t.doRequest(e.url).then(function(t){return{result:t,query:e}}).catch(function(t){throw{error:t,query:e}})})},e.prototype.annotationQuery=function(e){},e.prototype.metricFindQuery=function(e){if(e.match(/^AppInsightsMetricNames\(\)/i))return this.getMetricNames();var t=e.match(/^AppInsightsGroupBys\(([^\)]+?)(,\s?([^,]+?))?\)/i);if(t){var r=t[1];return this.getGroupBys(this.templateSrv.replace(r))}},e.prototype.testDatasource=function(){var e=this.baseUrl+"/metrics/metadata";return this.doRequest(e).then(function(e){return 200===e.status?{status:"success",message:"Successfully queried the Application Insights service.",title:"Success"}:{status:"error",message:"Returned http status code "+e.status}}).catch(function(e){var t="Application Insights: ";return t+=e.statusText?e.statusText+": ":"",e.data&&e.data.error&&"PathNotFoundError"===e.data.error.code?t+="Invalid Application Id for Application Insights service.":e.data&&e.data.error?t+=e.data.error.code+". "+e.data.error.message:t+="Cannot connect to Application Insights REST API.",{status:"error",message:t}})},e.prototype.doRequest=function(e,t){var r=this;return void 0===t&&(t=1),this.backendSrv.datasourceRequest({url:this.url+e,method:"GET"}).catch(function(a){if(t>0)return r.doRequest(e,t-1);throw a})},e.prototype.getMetricNames=function(){var e=this.baseUrl+"/metrics/metadata";return this.doRequest(e).then(H.parseMetricNames)},e.prototype.getMetricMetadata=function(e){var t=this.baseUrl+"/metrics/metadata";return this.doRequest(t).then(function(t){return new H(t).parseMetadata(e)})},e.prototype.getGroupBys=function(e){return this.getMetricMetadata(e).then(function(e){return new H(e).parseGroupBys()})},e.prototype.getQuerySchema=function(){var e=this.baseUrl+"/query/schema";return this.doRequest(e).then(function(e){return new H(e).parseQuerySchema()})},e}(),Y=function(){function e(e,t,r){this.rawQueryString=e,this.options=t,this.defaultTimeField=r}return e.prototype.generate=function(){var e=this,t=this.rawQueryString,r=/\$__([_a-zA-Z0-9]+)\(([^\)]*)\)/gi;t=(t=t.replace(r,function(t,r,a){return"contains"===r?e.getMultiContains(a):t})).replace(/\$__escapeMulti\(('[^]*')\)/gi,function(t,r){return e.escape(r)}),this.options&&(t=(t=t.replace(r,function(t,r,a){return"timeFilter"===r?e.getTimeFilter(a,e.options):"timeFrom"===r?e.getFrom(e.options):"timeTo"===r?e.getUntil(e.options):t})).replace(/\$__interval/gi,this.options.interval));var a=t;return{uriString:"query="+(t=encodeURIComponent(t)),rawQuery:a}},e.prototype.getFrom=function(e){var t=e.range.from;return"datetime("+Object(a.dateTime)(t).startOf("minute").toISOString()+")"},e.prototype.getUntil=function(e){if("now"===e.rangeRaw.to){var t=Date.now();return"datetime("+Object(a.dateTime)(t).startOf("minute").toISOString()+")"}var r=e.range.to;return"datetime("+Object(a.dateTime)(r).startOf("minute").toISOString()+")"},e.prototype.getTimeFilter=function(e,t){var r=e||this.defaultTimeField;return"now"===t.rangeRaw.to?r+" >= "+this.getFrom(t):r+" >= "+this.getFrom(t)+" and "+r+" <= "+this.getUntil(t)},e.prototype.getMultiContains=function(e){var t=e.indexOf(","),r=e.substring(0,t),a=e.substring(e.indexOf(",")+1);return a&&"all"===a.toLowerCase().trim()?"1 == 1":r.trim()+" in ("+a.trim()+")"},e.prototype.escape=function(e){return e.substring(1,e.length-1).split("','").map(function(e){return"@'"+e+"'"}).join(", ")},e}(),ee=function(){function e(e){this.results=e}return e.prototype.parseQueryResult=function(){for(var e=[],t=[],r=0;r<this.results.length;r++)if(0!==this.results[r].result.data.tables.length){t=this.results[r].result.data.tables[0].columns;var a=this.results[r].result.data.tables[0].rows;e="time_series"===this.results[r].query.resultFormat?s.a.concat(e,this.parseTimeSeriesResult(this.results[r].query,t,a)):s.a.concat(e,this.parseTableResult(this.results[r].query,t,a))}return e},e.prototype.parseTimeSeriesResult=function(t,r,a){for(var i=[],n=-1,o=-1,u=-1,c=0;c<r.length;c++)-1===n&&"datetime"===r[c].type&&(n=c),-1===o&&"string"===r[c].type&&(o=c),-1===u&&["int","long","real","double"].indexOf(r[c].type)>-1&&(u=c);if(-1===n)throw new Error("No datetime column found in the result. The Time Series format requires a time column.");return s.a.forEach(a,function(a){var s=e.dateTimeToEpoch(a[n]),c=o>-1?a[o]:r[u].name,l=e.findOrCreateBucket(i,c);l.datapoints.push([a[u],s]),l.refId=t.refId,l.meta={query:t.query}}),i},e.prototype.parseTableResult=function(e,t,r){return{type:"table",columns:s.a.map(t,function(e){return{text:e.name,type:e.type}}),rows:r,refId:e.refId,meta:{query:e.query}}},e.prototype.parseToVariables=function(){var e=this.parseQueryResult(),t=[];return s.a.forEach(e,function(e){s.a.forEach(s.a.flattenDeep(e.rows),function(e){t.push({text:e,value:e})})}),t},e.prototype.transformToAnnotations=function(t){var r=this.parseQueryResult(),a=[];return s.a.forEach(r,function(r){for(var i=-1,n=-1,o=-1,u=0;u<r.columns.length;u++)-1===i&&"datetime"===r.columns[u].type&&(i=u),-1===n&&"text"===r.columns[u].text.toLowerCase()&&(n=u),-1===o&&"tags"===r.columns[u].text.toLowerCase()&&(o=u);s.a.forEach(r.rows,function(r){a.push({annotation:t.annotation,time:Math.floor(e.dateTimeToEpoch(r[i])),text:r[n]?r[n].toString():"",tags:r[o]?r[o].trim().split(/\s*,\s*/):[]})})}),a},e.prototype.parseSchemaResult=function(){return{Plugins:[{Name:"pivot"}],Databases:this.createSchemaDatabaseWithTables()}},e.prototype.createSchemaDatabaseWithTables=function(){return{Default:{Name:"Default",Tables:this.createSchemaTables(),Functions:this.createSchemaFunctions()}}},e.prototype.createSchemaTables=function(){var e,t,r,a,n={};try{for(var s=Object(i.__values)(this.results.tables),o=s.next();!o.done;o=s.next()){var u=o.value;n[u.name]={Name:u.name,OrderedColumns:[]};try{for(var c=(r=void 0,Object(i.__values)(u.columns)),l=c.next();!l.done;l=c.next()){var p=l.value;n[u.name].OrderedColumns.push(this.convertToKustoColumn(p))}}catch(e){r={error:e}}finally{try{l&&!l.done&&(a=c.return)&&a.call(c)}finally{if(r)throw r.error}}}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}return n},e.prototype.convertToKustoColumn=function(e){return{Name:e.name,Type:e.type}},e.prototype.createSchemaFunctions=function(){var e,t,r={};try{for(var a=Object(i.__values)(this.results.functions),n=a.next();!n.done;n=a.next()){var s=n.value;r[s.name]={Name:s.name,Body:s.body,DocString:s.displayName,Folder:s.category,FunctionKind:"Unknown",InputParameters:[],OutputColumns:[]}}}catch(t){e={error:t}}finally{try{n&&!n.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}return r},e.findOrCreateBucket=function(e,t){var r=s.a.find(e,["target",t]);return r||(r={target:t,datapoints:[],refId:"",query:""},e.push(r)),r},e.dateTimeToEpoch=function(e){return Object(a.dateTime)(e).valueOf()},e}(),te=function(){function e(e,t,r){this.instanceSettings=e,this.backendSrv=t,this.templateSrv=r,this.id=e.id,this.baseUrl="/loganalyticsazure",this.url=e.url,this.defaultOrFirstWorkspace=this.instanceSettings.jsonData.logAnalyticsDefaultWorkspace,this.setWorkspaceUrl()}return e.$inject=["instanceSettings","backendSrv","templateSrv"],e.prototype.isConfigured=function(){return!!this.instanceSettings.jsonData.logAnalyticsSubscriptionId&&this.instanceSettings.jsonData.logAnalyticsSubscriptionId.length>0||!!this.instanceSettings.jsonData.azureLogAnalyticsSameAs},e.prototype.setWorkspaceUrl=function(){if(this.instanceSettings.jsonData.subscriptionId||this.instanceSettings.jsonData.azureLogAnalyticsSameAs){this.subscriptionId=this.instanceSettings.jsonData.subscriptionId;var e=this.instanceSettings.jsonData.cloudName||"azuremonitor";this.azureMonitorUrl="/"+e+"/subscriptions"}else this.subscriptionId=this.instanceSettings.jsonData.logAnalyticsSubscriptionId,this.azureMonitorUrl="/workspacesloganalytics/subscriptions"},e.prototype.getWorkspaces=function(e){var t=this.templateSrv.replace(e||this.subscriptionId),r=this.azureMonitorUrl+"/"+t+"/providers/Microsoft.OperationalInsights/workspaces?api-version=2017-04-26-preview";return this.doRequest(r).then(function(e){return s.a.map(e.data.value,function(e){return{text:e.name,value:e.properties.customerId}})||[]})},e.prototype.getSchema=function(e){if(!e)return Promise.resolve();var t=this.baseUrl+"/"+e+"/metadata";return this.doRequest(t).then(function(e){return new ee(e.data).parseSchemaResult()})},e.prototype.query=function(e){return Object(i.__awaiter)(this,void 0,void 0,function(){var t,r,a=this;return Object(i.__generator)(this,function(i){return(t=s.a.filter(e.targets,function(e){return!0!==e.hide}).map(function(t){var r=t.azureLogAnalytics,i=new Y(a.templateSrv.replace(r.query,e.scopedVars,a.interpolateVariable),e,"TimeGenerated").generate(),n=a.templateSrv.replace(r.workspace,e.scopedVars);!n&&a.defaultOrFirstWorkspace&&(n=a.defaultOrFirstWorkspace);var s=a.baseUrl+"/"+n+"/query?"+i.uriString;return{refId:t.refId,intervalMs:e.intervalMs,maxDataPoints:e.maxDataPoints,datasourceId:a.id,url:s,query:i.rawQuery,format:t.format,resultFormat:r.resultFormat}}))&&0!==t.length?(r=this.doQueries(t),[2,Promise.all(r).then(function(e){return new ee(e).parseQueryResult()})]):[2]})})},e.prototype.metricFindQuery=function(e){var t=this;return this.getDefaultOrFirstWorkspace().then(function(r){var a=t.buildQuery(e,null,r),i=t.doQueries(a);return Promise.all(i).then(function(e){return new ee(e).parseToVariables()}).catch(function(e){if(e.error&&e.error.data&&e.error.data.error&&e.error.data.error.innererror&&e.error.data.error.innererror.innererror)throw{message:e.error.data.error.innererror.innererror.message};if(e.error&&e.error.data&&e.error.data.error)throw{message:e.error.data.error.message}})})},e.prototype.buildQuery=function(e,t,r){var a=new Y(this.templateSrv.replace(e,{},this.interpolateVariable),t,"TimeGenerated").generate().uriString,i=this.baseUrl+"/"+r+"/query?"+a,n=[];return n.push({datasourceId:this.id,url:i,resultFormat:"table"}),n},e.prototype.interpolateVariable=function(e,t){return"string"==typeof e?t.multi||t.includeAll?"'"+e+"'":e:"number"==typeof e?e:s.a.map(e,function(t){return"number"==typeof e?e:"'"+t+"'"}).join(",")},e.prototype.getDefaultOrFirstWorkspace=function(){var e=this;return this.defaultOrFirstWorkspace?Promise.resolve(this.defaultOrFirstWorkspace):this.getWorkspaces(this.subscriptionId).then(function(t){return e.defaultOrFirstWorkspace=t[0].value,e.defaultOrFirstWorkspace})},e.prototype.annotationQuery=function(e){if(!e.annotation.rawQuery)return Promise.reject({message:"Query missing in annotation definition"});var t=this.buildQuery(e.annotation.rawQuery,e,e.annotation.workspace),r=this.doQueries(t);return Promise.all(r).then(function(t){return new ee(t).transformToAnnotations(e)})},e.prototype.doQueries=function(e){var t=this;return s.a.map(e,function(e){return t.doRequest(e.url).then(function(t){return{result:t,query:e}}).catch(function(t){throw{error:t,query:e}})})},e.prototype.doRequest=function(e,t){var r=this;return void 0===t&&(t=1),this.backendSrv.datasourceRequest({url:this.url+e,method:"GET"}).catch(function(a){if(t>0)return r.doRequest(e,t-1);throw a})},e.prototype.testDatasource=function(){var e=this,t=this.isValidConfig();return t||this.getDefaultOrFirstWorkspace().then(function(t){var r=e.baseUrl+"/"+t+"/metadata";return e.doRequest(r)}).then(function(e){return 200===e.status?{status:"success",message:"Successfully queried the Azure Log Analytics service.",title:"Success"}:{status:"error",message:"Returned http status code "+e.status}}).catch(function(t){var r="Azure Log Analytics: ";return t.config&&t.config.url&&t.config.url.indexOf("workspacesloganalytics")>-1&&(r="Azure Log Analytics requires access to Azure Monitor but had the following error: "),{status:"error",message:r=e.getErrorMessage(r,t)}})},e.prototype.getErrorMessage=function(e,t){return e+=t.statusText?t.statusText+": ":"",t.data&&t.data.error&&t.data.error.code?e+=t.data.error.code+". "+t.data.error.message:t.data&&t.data.error?e+=t.data.error:t.data?e+=t.data:e+="Cannot connect to Azure Log Analytics REST API.",e},e.prototype.isValidConfig=function(){if(!this.instanceSettings.jsonData.azureLogAnalyticsSameAs)return this.isValidConfigField(this.instanceSettings.jsonData.logAnalyticsSubscriptionId)?this.isValidConfigField(this.instanceSettings.jsonData.logAnalyticsTenantId)?this.isValidConfigField(this.instanceSettings.jsonData.logAnalyticsClientId)?void 0:{status:"error",message:"The Client Id field is required."}:{status:"error",message:"The Tenant Id field is required."}:{status:"error",message:"The Subscription Id field is required."}},e.prototype.isValidConfigField=function(e){return e&&e.length>0},e}(),re=function(e){function t(t,r,a){var i=e.call(this,t)||this;return i.backendSrv=r,i.templateSrv=a,i.azureMonitorDatasource=new $(t,i.backendSrv,i.templateSrv),i.appInsightsDatasource=new Z(t,i.backendSrv,i.templateSrv),i.azureLogAnalyticsDatasource=new te(t,i.backendSrv,i.templateSrv),i}return t.$inject=["instanceSettings","backendSrv","templateSrv"],Object(i.__extends)(t,e),t.prototype.query=function(e){return Object(i.__awaiter)(this,void 0,void 0,function(){var t,r,a,n,o,u,c;return Object(i.__generator)(this,function(i){return t=[],r=s.a.cloneDeep(e),a=s.a.cloneDeep(e),n=s.a.cloneDeep(e),r.targets=s.a.filter(r.targets,["queryType","Azure Monitor"]),a.targets=s.a.filter(a.targets,["queryType","Application Insights"]),n.targets=s.a.filter(n.targets,["queryType","Azure Log Analytics"]),r.targets.length>0&&(o=this.azureMonitorDatasource.query(r))&&t.push(o),a.targets.length>0&&(u=this.appInsightsDatasource.query(a))&&t.push(u),n.targets.length>0&&(c=this.azureLogAnalyticsDatasource.query(n))&&t.push(c),0===t.length?[2,Promise.resolve({data:[]})]:[2,Promise.all(t).then(function(e){return{data:s.a.flatten(e)}})]})})},t.prototype.annotationQuery=function(e){return Object(i.__awaiter)(this,void 0,void 0,function(){return Object(i.__generator)(this,function(t){return[2,this.azureLogAnalyticsDatasource.annotationQuery(e)]})})},t.prototype.metricFindQuery=function(e){return Object(i.__awaiter)(this,void 0,void 0,function(){var t,r,a;return Object(i.__generator)(this,function(i){return e?(t=this.appInsightsDatasource.metricFindQuery(e))?[2,t]:(r=this.azureMonitorDatasource.metricFindQuery(e))?[2,r]:(a=this.azureLogAnalyticsDatasource.metricFindQuery(e))?[2,a]:[2,Promise.resolve([])]:[2,Promise.resolve([])]})})},t.prototype.testDatasource=function(){return Object(i.__awaiter)(this,void 0,void 0,function(){var e;return Object(i.__generator)(this,function(t){return e=[],this.azureMonitorDatasource.isConfigured()&&e.push(this.azureMonitorDatasource.testDatasource()),this.appInsightsDatasource.isConfigured()&&e.push(this.appInsightsDatasource.testDatasource()),this.azureLogAnalyticsDatasource.isConfigured()&&e.push(this.azureLogAnalyticsDatasource.testDatasource()),0===e.length?[2,{status:"error",message:"Nothing configured. At least one of the API's must be configured.",title:"Error"}]:[2,Promise.all(e).then(function(e){for(var t="success",r="",a=0;a<e.length;a++)"success"!==e[a].status&&(t=e[a].status),r+=a+1+". "+e[a].message+" ";return{status:t,message:r,title:s.a.upperFirst(t)}})]})})},t.prototype.getResourceGroups=function(e){return this.azureMonitorDatasource.getResourceGroups(e)},t.prototype.getMetricDefinitions=function(e,t){return this.azureMonitorDatasource.getMetricDefinitions(e,t)},t.prototype.getResourceNames=function(e,t,r){return this.azureMonitorDatasource.getResourceNames(e,t,r)},t.prototype.getMetricNames=function(e,t,r,a,i){return this.azureMonitorDatasource.getMetricNames(e,t,r,a,i)},t.prototype.getMetricNamespaces=function(e,t,r,a){return this.azureMonitorDatasource.getMetricNamespaces(e,t,r,a)},t.prototype.getMetricMetadata=function(e,t,r,a,i,n){return this.azureMonitorDatasource.getMetricMetadata(e,t,r,a,i,n)},t.prototype.getAppInsightsMetricNames=function(){return this.appInsightsDatasource.getMetricNames()},t.prototype.getAppInsightsMetricMetadata=function(e){return this.appInsightsDatasource.getMetricMetadata(e)},t.prototype.getAppInsightsColumns=function(e){return this.appInsightsDatasource.logAnalyticsColumns[e]},t.prototype.getAzureLogAnalyticsWorkspaces=function(e){return this.azureLogAnalyticsDatasource.getWorkspaces(e)},t.prototype.getSubscriptions=function(){return this.azureMonitorDatasource.getSubscriptions()},t}(a.DataSourceApi),ae=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Object(i.__extends)(t,e),t.prototype.render=function(){var e=this.props,t=e.selectedAzureCloud,r=e.selectedSubscription,a=e.tenantId,i=e.clientId,n=e.clientSecret,s=e.clientSecretConfigured,o=e.azureCloudOptions,u=e.subscriptionOptions,c=e.onAzureCloudChange,l=e.onSubscriptionSelectChange,p=e.onTenantIdChange,d=e.onClientIdChange,m=e.onClientSecretChange,g=e.onResetClientSecret,f=e.onLoadSubscriptions,v=a&&i&&(n||s),b=f&&u;return h.a.createElement(h.a.Fragment,null,h.a.createElement("div",{className:"gf-form-group"},o&&h.a.createElement("div",{className:"gf-form-inline"},h.a.createElement("div",{className:"gf-form"},h.a.createElement(y.FormLabel,{className:"width-12",tooltip:"Choose an Azure Cloud."},"Azure Cloud"),h.a.createElement(y.Select,{className:"width-15",value:o.find(function(e){return e.value===t}),options:o,defaultValue:t,onChange:c}))),h.a.createElement("div",{className:"gf-form-inline"},h.a.createElement("div",{className:"gf-form"},h.a.createElement(y.FormLabel,{className:"width-12"},"Directory (tenant) ID"),h.a.createElement("div",{className:"width-15"},h.a.createElement(y.Input,{className:"width-30",placeholder:"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",value:a||"",onChange:p})))),h.a.createElement("div",{className:"gf-form-inline"},h.a.createElement("div",{className:"gf-form"},h.a.createElement(y.FormLabel,{className:"width-12"},"Application (client) ID"),h.a.createElement("div",{className:"width-15"},h.a.createElement(y.Input,{className:"width-30",placeholder:"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",value:i||"",onChange:d})))),s?h.a.createElement("div",{className:"gf-form-inline"},h.a.createElement("div",{className:"gf-form"},h.a.createElement(y.FormLabel,{className:"width-12"},"Client Secret"),h.a.createElement(y.Input,{className:"width-25",placeholder:"configured",disabled:!0})),h.a.createElement("div",{className:"gf-form"},h.a.createElement("div",{className:"max-width-30 gf-form-inline"},h.a.createElement(y.Button,{variant:"secondary",type:"button",onClick:g},"reset")))):h.a.createElement("div",{className:"gf-form-inline"},h.a.createElement("div",{className:"gf-form"},h.a.createElement(y.FormLabel,{className:"width-12"},"Client Secret"),h.a.createElement("div",{className:"width-15"},h.a.createElement(y.Input,{className:"width-30",placeholder:"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",value:n||"",onChange:m})))),b&&h.a.createElement(h.a.Fragment,null,h.a.createElement("div",{className:"gf-form-inline"},h.a.createElement("div",{className:"gf-form"},h.a.createElement(y.FormLabel,{className:"width-12"},"Default Subscription"),h.a.createElement("div",{className:"width-25"},h.a.createElement(y.Select,{value:u.find(function(e){return e.value===r}),options:u,defaultValue:r,onChange:l})))),h.a.createElement("div",{className:"gf-form-inline"},h.a.createElement("div",{className:"gf-form"},h.a.createElement("div",{className:"max-width-30 gf-form-inline"},h.a.createElement(y.Button,{variant:"secondary",size:"sm",type:"button",onClick:f,disabled:!v},"Load Subscriptions")))))))},t}(p.PureComponent),ie=[{value:"azuremonitor",label:"Azure"},{value:"govazuremonitor",label:"Azure US Government"},{value:"germanyazuremonitor",label:"Azure Germany"},{value:"chinaazuremonitor",label:"Azure China"}],ne=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.onAzureCloudSelect=function(e){t.props.onUpdateOption("cloudName",e.value)},t.onTenantIdChange=function(e){t.props.onUpdateOption("tenantId",e.target.value)},t.onClientIdChange=function(e){t.props.onUpdateOption("clientId",e.target.value)},t.onClientSecretChange=function(e){var r=t.props,a=r.options,i=r.makeSameAs;a.jsonData.azureLogAnalyticsSameAs&&e.target.value?i(e.target.value):t.props.onUpdateSecureOption("clientSecret",e.target.value)},t.onResetClientSecret=function(){t.props.onResetOptionKey("clientSecret")},t.onSubscriptionSelect=function(e){t.props.onUpdateOption("subscriptionId",e.value)},t}return Object(i.__extends)(t,e),t.prototype.render=function(){var e=this.props,t=e.options,r=e.subscriptions;return h.a.createElement(h.a.Fragment,null,h.a.createElement("h3",{className:"page-heading"},"Azure Monitor Details"),h.a.createElement(ae,{selectedAzureCloud:t.jsonData.cloudName||"azuremonitor",azureCloudOptions:ie,subscriptionOptions:r,selectedSubscription:t.jsonData.subscriptionId,tenantId:t.jsonData.tenantId,clientId:t.jsonData.clientId,clientSecret:t.secureJsonData.clientSecret,clientSecretConfigured:t.secureJsonFields.clientSecret,onAzureCloudChange:this.onAzureCloudSelect,onSubscriptionSelectChange:this.onSubscriptionSelect,onTenantIdChange:this.onTenantIdChange,onClientIdChange:this.onClientIdChange,onClientSecretChange:this.onClientSecretChange,onResetClientSecret:this.onResetClientSecret,onLoadSubscriptions:this.props.onLoadSubscriptions}))},t}(p.PureComponent),se=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.onLogAnalyticsTenantIdChange=function(e){t.props.onUpdateOption("logAnalyticsTenantId",e.target.value)},t.onLogAnalyticsClientIdChange=function(e){t.props.onUpdateOption("logAnalyticsClientId",e.target.value)},t.onLogAnalyticsClientSecretChange=function(e){t.props.onUpdateSecureOption("logAnalyticsClientSecret",e.target.value)},t.onLogAnalyticsSubscriptionSelect=function(e){t.props.onUpdateOption("logAnalyticsSubscriptionId",e.value)},t.onWorkspaceSelectChange=function(e){t.props.onUpdateOption("logAnalyticsDefaultWorkspace",e.value)},t.onAzureLogAnalyticsSameAsChange=function(){var e=t.props,r=e.options,a=e.onUpdateOptions,n=e.makeSameAs;!r.jsonData.azureLogAnalyticsSameAs&&r.secureJsonData.clientSecret?n():r.jsonData.azureLogAnalyticsSameAs?t.props.onUpdateOption("azureLogAnalyticsSameAs",!r.jsonData.azureLogAnalyticsSameAs):a(Object(i.__assign)(Object(i.__assign)({},r),{jsonData:Object(i.__assign)(Object(i.__assign)({},r.jsonData),{azureLogAnalyticsSameAs:!r.jsonData.azureLogAnalyticsSameAs}),secureJsonData:Object(i.__assign)(Object(i.__assign)({},r.secureJsonData),{clientSecret:""}),secureJsonFields:{clientSecret:!1}}))},t.onLogAnalyticsResetClientSecret=function(){t.props.onResetOptionKey("logAnalyticsClientSecret")},t.hasWorkspaceRequiredFields=function(){var e=t.props.options,r=e.jsonData,a=e.secureJsonData,i=e.secureJsonFields;return r.azureLogAnalyticsSameAs?r.tenantId&&r.clientId&&r.subscriptionId&&(a.clientSecret||i.clientSecret):r.logAnalyticsTenantId&&r.logAnalyticsTenantId.length&&r.logAnalyticsClientId&&r.logAnalyticsClientId.length&&r.logAnalyticsSubscriptionId&&(i.logAnalyticsClientSecret||a.logAnalyticsClientSecret)},t}return Object(i.__extends)(t,e),t.prototype.render=function(){var e=this,t=this.props,r=t.options,a=r.jsonData,n=r.secureJsonData,s=r.secureJsonFields,o=t.subscriptions,u=t.workspaces;a.hasOwnProperty("azureLogAnalyticsSameAs")||(a.azureLogAnalyticsSameAs=!0);var c=Object(i.__assign)({},a.azureLogAnalyticsSameAs&&{tooltip:"Workspaces are pulled from default subscription selected above."}),l=a.azureLogAnalyticsSameAs&&s&&!s.clientSecret&&!n.clientSecret;return h.a.createElement(h.a.Fragment,null,h.a.createElement("h3",{className:"page-heading"},"Azure Log Analytics API Details"),h.a.createElement(y.Switch,Object(i.__assign)({label:"Same details as Azure Monitor API",checked:a.azureLogAnalyticsSameAs,onChange:this.onAzureLogAnalyticsSameAsChange},c)),l&&h.a.createElement("div",{className:"grafana-info-box m-t-2"},h.a.createElement("div",{className:"alert-body"},h.a.createElement("p",null,"Re-enter your Azure Monitor Client Secret to use this setting."))),!a.azureLogAnalyticsSameAs&&h.a.createElement(ae,{subscriptionOptions:o,selectedSubscription:a.logAnalyticsSubscriptionId,tenantId:a.logAnalyticsTenantId,clientId:a.logAnalyticsClientId,clientSecret:n.logAnalyticsClientSecret,clientSecretConfigured:s.logAnalyticsClientSecret,onSubscriptionSelectChange:this.onLogAnalyticsSubscriptionSelect,onTenantIdChange:this.onLogAnalyticsTenantIdChange,onClientIdChange:this.onLogAnalyticsClientIdChange,onClientSecretChange:this.onLogAnalyticsClientSecretChange,onResetClientSecret:this.onLogAnalyticsResetClientSecret,onLoadSubscriptions:function(){return e.props.onLoadSubscriptions("workspacesloganalytics")}}),h.a.createElement("div",{className:"gf-form-group"},h.a.createElement("div",{className:"gf-form-inline"},h.a.createElement("div",{className:"gf-form"},h.a.createElement(y.FormLabel,{className:"width-12",tooltip:"Choose the default/preferred Workspace for Azure Log Analytics queries."},"Default Workspace"),h.a.createElement("div",{className:"width-25"},h.a.createElement(y.Select,{value:u.find(function(e){return e.value===a.logAnalyticsDefaultWorkspace}),options:u,defaultValue:a.logAnalyticsDefaultWorkspace,onChange:this.onWorkspaceSelectChange})))),h.a.createElement("div",{className:"gf-form-inline"},h.a.createElement("div",{className:"gf-form"},h.a.createElement("div",{className:"max-width-30 gf-form-inline"},h.a.createElement(y.Button,{variant:"secondary",size:"sm",type:"button",onClick:function(){return e.props.onLoadWorkspaces()},disabled:!this.hasWorkspaceRequiredFields()},"Load Workspaces"))))))},t}(p.PureComponent),oe=r("5kRJ"),ue=r("NXk7"),ce=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.onAppInsightsAppIdChange=function(e){t.props.onUpdateOption("appInsightsAppId",e.target.value)},t.onAppInsightsApiKeyChange=function(e){t.props.onUpdateSecureOption("appInsightsApiKey",e.target.value)},t.onAppInsightsResetApiKey=function(){t.props.onResetOptionKey("appInsightsApiKey")},t}return Object(i.__extends)(t,e),t.prototype.render=function(){var e=this.props.options;return h.a.createElement(h.a.Fragment,null,h.a.createElement("h3",{className:"page-heading"},"Application Insights Details"),h.a.createElement("div",{className:"gf-form-group"},e.secureJsonFields.appInsightsApiKey?h.a.createElement("div",{className:"gf-form-inline"},h.a.createElement("div",{className:"gf-form"},h.a.createElement(y.FormLabel,{className:"width-12"},"API Key"),h.a.createElement(y.Input,{className:"width-25",placeholder:"configured",disabled:!0})),h.a.createElement("div",{className:"gf-form"},h.a.createElement("div",{className:"max-width-30 gf-form-inline"},h.a.createElement(y.Button,{variant:"secondary",type:"button",onClick:this.onAppInsightsResetApiKey},"reset")))):h.a.createElement("div",{className:"gf-form-inline"},h.a.createElement("div",{className:"gf-form"},h.a.createElement(y.FormLabel,{className:"width-12"},"API Key"),h.a.createElement("div",{className:"width-15"},h.a.createElement(y.Input,{className:"width-30",placeholder:"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",value:e.secureJsonData.appInsightsApiKey||"",onChange:this.onAppInsightsApiKeyChange})))),h.a.createElement("div",{className:"gf-form-inline"},h.a.createElement("div",{className:"gf-form"},h.a.createElement(y.FormLabel,{className:"width-12"},"Application ID"),h.a.createElement("div",{className:"width-15"},h.a.createElement(y.Input,{className:"width-30",value:e.jsonData.appInsightsAppId||"",onChange:this.onAppInsightsAppIdChange}))))))},t}(p.PureComponent),le=r("sGFA"),pe=function(e){function t(t){var r=e.call(this,t)||this;return r.initPromise=null,r.backendSrv=null,r.templateSrv=null,r.init=function(){return Object(i.__awaiter)(r,void 0,void 0,function(){return Object(i.__generator)(this,function(e){switch(e.label){case 0:return[4,this.getSubscriptions()];case 1:return e.sent(),this.props.options.jsonData.azureLogAnalyticsSameAs?[3,3]:[4,this.getLogAnalyticsSubscriptions()];case 2:e.sent(),e.label=3;case 3:return[2]}})})},r.updateOption=function(e,t){Object(a.updateDatasourcePluginJsonDataOption)(r.props,e,t)},r.updateSecureOption=function(e,t){Object(a.updateDatasourcePluginSecureJsonDataOption)(r.props,e,t)},r.resetKey=function(e){Object(a.updateDatasourcePluginResetOption)(r.props,e)},r.makeSameAs=function(e){var t=r.props.options,a=e||t.secureJsonData.clientSecret;r.updateOptions(Object(i.__assign)(Object(i.__assign)({},t),{jsonData:Object(i.__assign)(Object(i.__assign)({},t.jsonData),{azureLogAnalyticsSameAs:!0,logAnalyticsSubscriptionId:t.jsonData.subscriptionId,logAnalyticsTenantId:t.jsonData.tenantId,logAnalyticsClientId:t.jsonData.clientId}),secureJsonData:Object(i.__assign)(Object(i.__assign)({},t.secureJsonData),{clientSecret:a,logAnalyticsClientSecret:a})}))},r.updateOptions=function(e){e.hasOwnProperty("secureJsonData")&&(e.secureJsonData.hasOwnProperty("clientSecret")&&0===e.secureJsonData.clientSecret.length&&delete e.secureJsonData.clientSecret,e.secureJsonData.hasOwnProperty("logAnalyticsClientSecret")&&0===e.secureJsonData.logAnalyticsClientSecret.length&&delete e.secureJsonData.logAnalyticsClientSecret,e.secureJsonData.hasOwnProperty("appInsightsApiKey")&&0===e.secureJsonData.appInsightsApiKey.length&&delete e.secureJsonData.appInsightsApiKey),r.props.onOptionsChange(Object(i.__assign)({},e))},r.hasNecessaryCredentials=function(){return!(!r.props.options.secureJsonFields.clientSecret&&!r.props.options.secureJsonData.clientSecret)&&!(!r.props.options.jsonData.clientId||!r.props.options.jsonData.tenantId)},r.logAnalyticsHasNecessaryCredentials=function(){return!(!r.props.options.secureJsonFields.logAnalyticsClientSecret&&!r.props.options.secureJsonData.logAnalyticsClientSecret)&&!(!r.props.options.jsonData.logAnalyticsClientId||!r.props.options.jsonData.logAnalyticsTenantId)},r.onLoadSubscriptions=function(e){return Object(i.__awaiter)(r,void 0,void 0,function(){var t=this;return Object(i.__generator)(this,function(r){switch(r.label){case 0:return[4,this.backendSrv.put("/api/datasources/"+this.props.options.id,this.props.options).then(function(e){Object(a.updateDatasourcePluginOption)(t.props,"version",e.version)})];case 1:return r.sent(),e&&"workspacesloganalytics"===e?this.getLogAnalyticsSubscriptions():this.getSubscriptions(),[2]}})})},r.loadSubscriptions=function(e){return Object(i.__awaiter)(r,void 0,void 0,function(){var t,r;return Object(i.__generator)(this,function(a){switch(a.label){case 0:return t="/"+(e||this.props.options.jsonData.cloudName)+"/subscriptions?api-version=2019-03-01",[4,this.backendSrv.datasourceRequest({url:this.props.options.url+t,method:"GET"})];case 1:return r=a.sent(),[2,K.parseSubscriptionsForSelect(r)]}})})},r.loadWorkspaces=function(e){return Object(i.__awaiter)(r,void 0,void 0,function(){var t,r,a,n,s,o,u,c;return Object(i.__generator)(this,function(i){switch(i.label){case 0:return t=this.props.options.jsonData,r=t.azureLogAnalyticsSameAs,a=t.cloudName,n=t.logAnalyticsSubscriptionId,s="",(o=this.templateSrv.replace(e||this.props.options.jsonData.subscriptionId))||r?s="/"+(a||"azuremonitor")+"/subscriptions":(o=n,s="/workspacesloganalytics/subscriptions"),u=s+"/"+o+"/providers/Microsoft.OperationalInsights/workspaces?api-version=2017-04-26-preview",[4,this.backendSrv.datasourceRequest({url:this.props.options.url+u,method:"GET"})];case 1:return c=i.sent(),[2,K.parseWorkspacesForSelect(c)]}})})},r.getSubscriptions=function(){return Object(i.__awaiter)(r,void 0,void 0,function(){var e;return Object(i.__generator)(this,function(t){switch(t.label){case 0:return this.hasNecessaryCredentials()?[4,this.loadSubscriptions()]:[2];case 1:return(e=t.sent()||[])&&e.length>0&&(this.setState({subscriptions:e}),this.updateOption("subscriptionId",this.props.options.jsonData.subscriptionId||e[0].value)),this.props.options.jsonData.subscriptionId&&this.props.options.jsonData.azureLogAnalyticsSameAs?[4,this.getWorkspaces()]:[3,3];case 2:t.sent(),t.label=3;case 3:return[2]}})})},r.getLogAnalyticsSubscriptions=function(){return Object(i.__awaiter)(r,void 0,void 0,function(){var e;return Object(i.__generator)(this,function(t){switch(t.label){case 0:return this.logAnalyticsHasNecessaryCredentials()?[4,this.loadSubscriptions("workspacesloganalytics")]:[2];case 1:return(e=t.sent()||[])&&e.length>0&&(this.setState({logAnalyticsSubscriptions:e}),this.updateOption("logAnalyticsSubscriptionId",this.props.options.jsonData.logAnalyticsSubscriptionId||e[0].value)),this.props.options.jsonData.logAnalyticsSubscriptionId?[4,this.getWorkspaces()]:[3,3];case 2:t.sent(),t.label=3;case 3:return[2]}})})},r.getWorkspaces=function(){return Object(i.__awaiter)(r,void 0,void 0,function(){var e,t;return Object(i.__generator)(this,function(r){switch(r.label){case 0:return(e=this.props.options.jsonData.azureLogAnalyticsSameAs&&this.props.options.jsonData.subscriptionId)||this.props.options.jsonData.logAnalyticsSubscriptionId?[4,this.loadWorkspaces(e?this.props.options.jsonData.subscriptionId:this.props.options.jsonData.logAnalyticsSubscriptionId)]:[2];case 1:return(t=r.sent()).length>0&&(this.setState({logAnalyticsWorkspaces:t}),this.updateOption("logAnalyticsDefaultWorkspace",this.props.options.jsonData.logAnalyticsDefaultWorkspace||t[0].value)),[2]}})})},r.state={subscriptions:[],logAnalyticsSubscriptions:[],logAnalyticsWorkspaces:[],subscriptionId:"",logAnalyticsSubscriptionId:""},r.backendSrv=Object(ue.b)(),r.templateSrv=new oe.a,r.props.options.id&&Object(a.updateDatasourcePluginOption)(r.props,"url","/api/datasources/proxy/"+r.props.options.id),r}return Object(i.__extends)(t,e),t.prototype.componentDidMount=function(){this.initPromise=Object(le.a)(this.init()),this.initPromise.promise.catch(function(e){e.isCanceled&&console.warn("Azure Monitor ConfigEditor has unmounted, intialization was canceled")})},t.prototype.componentWillUnmount=function(){this.initPromise.cancel()},t.prototype.render=function(){var e=this.state,t=e.subscriptions,r=e.logAnalyticsSubscriptions,a=e.logAnalyticsWorkspaces,i=this.props.options;return i.jsonData.cloudName=i.jsonData.cloudName||"azuremonitor",i.secureJsonData=i.secureJsonData||{},h.a.createElement(h.a.Fragment,null,h.a.createElement(ne,{options:i,subscriptions:t,makeSameAs:this.makeSameAs,onLoadSubscriptions:this.onLoadSubscriptions,onUpdateOption:this.updateOption,onUpdateSecureOption:this.updateSecureOption,onResetOptionKey:this.resetKey}),h.a.createElement(se,{options:i,workspaces:a,subscriptions:r,makeSameAs:this.makeSameAs,onUpdateOptions:this.updateOptions,onUpdateOption:this.updateOption,onUpdateSecureOption:this.updateSecureOption,onResetOptionKey:this.resetKey,onLoadSubscriptions:this.onLoadSubscriptions,onLoadWorkspaces:this.getWorkspaces}),h.a.createElement(ce,{options:i,onUpdateOption:this.updateOption,onUpdateSecureOption:this.updateSecureOption,onResetOptionKey:this.resetKey}))},t}(p.PureComponent),he=function(){function e(e){var t=this;this.templateSrv=e,this.defaultQuery='<your table>\n| where $__timeFilter() \n| project TimeGenerated, Text=YourTitleColumn, Tags="tag1,tag2"',this.getAzureLogAnalyticsSchema=function(){return t.getWorkspaces().then(function(){return t.datasource.azureLogAnalyticsDatasource.getSchema(t.annotation.workspace)}).catch(function(){})},this.onSubscriptionChange=function(){t.getWorkspaces(!0)},this.onLogAnalyticsQueryChange=function(e){t.annotation.rawQuery=e},this.annotation.queryType=this.annotation.queryType||"Azure Log Analytics",this.annotation.rawQuery=this.annotation.rawQuery||this.defaultQuery,this.initDropdowns()}return e.$inject=["templateSrv"],e.prototype.initDropdowns=function(){return Object(i.__awaiter)(this,void 0,void 0,function(){return Object(i.__generator)(this,function(e){switch(e.label){case 0:return[4,this.getSubscriptions()];case 1:return e.sent(),[4,this.getWorkspaces()];case 2:return e.sent(),[2]}})})},e.prototype.getSubscriptions=function(){return Object(i.__awaiter)(this,void 0,void 0,function(){var e=this;return Object(i.__generator)(this,function(t){return this.datasource.azureMonitorDatasource.isConfigured()?[2,this.datasource.azureMonitorDatasource.getSubscriptions().then(function(t){e.subscriptions=t,e.annotation.subscription||"Azure Log Analytics"!==e.annotation.queryType||(e.annotation.subscription=e.datasource.azureLogAnalyticsDatasource.subscriptionId),!e.annotation.subscription&&e.subscriptions.length>0&&(e.annotation.subscription=e.subscriptions[0].value)})]:[2]})})},e.prototype.getWorkspaces=function(e){return Object(i.__awaiter)(this,void 0,void 0,function(){var t=this;return Object(i.__generator)(this,function(r){return!e&&this.workspaces&&this.workspaces.length>0?[2,this.workspaces]:[2,this.datasource.getAzureLogAnalyticsWorkspaces(this.annotation.subscription).then(function(e){return t.workspaces=e,e.length>0&&!t.annotation.workspace&&(t.annotation.workspace=e[0].value),t.workspaces}).catch(function(){})]})})},Object.defineProperty(e.prototype,"templateVariables",{get:function(){return this.templateSrv.variables.map(function(e){return"$"+e.name})},enumerable:!0,configurable:!0}),e.templateUrl="partials/annotations.editor.html",e}();r.d(t,"plugin",function(){return de});var de=new a.DataSourcePlugin(re).setConfigEditor(pe).setQueryCtrl(W).setAnnotationQueryCtrl(he)},sGFA:function(e,t,r){"use strict";r.d(t,"a",function(){return a});var a=function(e){var t=!1;return{promise:new Promise(function(r,a){e.then(function(e){return t?a({isCanceled:!0}):r(e)}),e.catch(function(e){return a(t?{isCanceled:!0}:e)})}),cancel:function(){t=!0}}}}}]); //# sourceMappingURL=azureMonitorPlugin.4d0490a94b199a11f40c.js.map