@fc-components/monaco-editor 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2164 @@
1
+ import React, { useRef, useEffect } from 'react';
2
+ import MonacoEditor from 'react-monaco-editor';
3
+ import * as monaco from 'monaco-editor';
4
+ import { languages, editor, KeyMod, KeyCode, Range, MarkerSeverity } from 'monaco-editor';
5
+ import { promLanguageDefinition } from 'monaco-promql';
6
+ import { parser, LabelMatchers, VectorSelector, PromQL, FunctionCallBody, StringLiteral, UnquotedLabelMatcher, BinaryExpr, NumberDurationLiteralInDurationContext, MatrixSelector, GroupingLabels, AggregateModifier, AggregateExpr, Identifier, LabelName, MatchOp, EqlSingle, EqlRegex, Neq, NeqRegex } from '@fc-components/lezer-metricsql';
7
+ import { v4 } from 'uuid';
8
+ import { css } from '@emotion/css';
9
+ import UFuzzy from '@leeoniya/ufuzzy';
10
+
11
+ function _arrayLikeToArray(r, a) {
12
+ (null == a || a > r.length) && (a = r.length);
13
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
14
+ return n;
15
+ }
16
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
17
+ try {
18
+ var i = n[a](c),
19
+ u = i.value;
20
+ } catch (n) {
21
+ return void e(n);
22
+ }
23
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
24
+ }
25
+ function _asyncToGenerator(n) {
26
+ return function () {
27
+ var t = this,
28
+ e = arguments;
29
+ return new Promise(function (r, o) {
30
+ var a = n.apply(t, e);
31
+ function _next(n) {
32
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
33
+ }
34
+ function _throw(n) {
35
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
36
+ }
37
+ _next(void 0);
38
+ });
39
+ };
40
+ }
41
+ function _construct(t, e, r) {
42
+ if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
43
+ var o = [null];
44
+ o.push.apply(o, e);
45
+ var p = new (t.bind.apply(t, o))();
46
+ return r && _setPrototypeOf(p, r.prototype), p;
47
+ }
48
+ function _defineProperties(e, r) {
49
+ for (var t = 0; t < r.length; t++) {
50
+ var o = r[t];
51
+ o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
52
+ }
53
+ }
54
+ function _createClass(e, r, t) {
55
+ return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
56
+ writable: !1
57
+ }), e;
58
+ }
59
+ function _createForOfIteratorHelperLoose(r, e) {
60
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
61
+ if (t) return (t = t.call(r)).next.bind(t);
62
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
63
+ t && (r = t);
64
+ var o = 0;
65
+ return function () {
66
+ return o >= r.length ? {
67
+ done: !0
68
+ } : {
69
+ done: !1,
70
+ value: r[o++]
71
+ };
72
+ };
73
+ }
74
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
75
+ }
76
+ function _extends() {
77
+ return _extends = Object.assign ? Object.assign.bind() : function (n) {
78
+ for (var e = 1; e < arguments.length; e++) {
79
+ var t = arguments[e];
80
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
81
+ }
82
+ return n;
83
+ }, _extends.apply(null, arguments);
84
+ }
85
+ function _getPrototypeOf(t) {
86
+ return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
87
+ return t.__proto__ || Object.getPrototypeOf(t);
88
+ }, _getPrototypeOf(t);
89
+ }
90
+ function _inheritsLoose(t, o) {
91
+ t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
92
+ }
93
+ function _isNativeFunction(t) {
94
+ try {
95
+ return -1 !== Function.toString.call(t).indexOf("[native code]");
96
+ } catch (n) {
97
+ return "function" == typeof t;
98
+ }
99
+ }
100
+ function _isNativeReflectConstruct() {
101
+ try {
102
+ var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
103
+ } catch (t) {}
104
+ return (_isNativeReflectConstruct = function () {
105
+ return !!t;
106
+ })();
107
+ }
108
+ function _objectWithoutPropertiesLoose(r, e) {
109
+ if (null == r) return {};
110
+ var t = {};
111
+ for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
112
+ if (-1 !== e.indexOf(n)) continue;
113
+ t[n] = r[n];
114
+ }
115
+ return t;
116
+ }
117
+ function _regenerator() {
118
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
119
+ var e,
120
+ t,
121
+ r = "function" == typeof Symbol ? Symbol : {},
122
+ n = r.iterator || "@@iterator",
123
+ o = r.toStringTag || "@@toStringTag";
124
+ function i(r, n, o, i) {
125
+ var c = n && n.prototype instanceof Generator ? n : Generator,
126
+ u = Object.create(c.prototype);
127
+ return _regeneratorDefine(u, "_invoke", function (r, n, o) {
128
+ var i,
129
+ c,
130
+ u,
131
+ f = 0,
132
+ p = o || [],
133
+ y = !1,
134
+ G = {
135
+ p: 0,
136
+ n: 0,
137
+ v: e,
138
+ a: d,
139
+ f: d.bind(e, 4),
140
+ d: function (t, r) {
141
+ return i = t, c = 0, u = e, G.n = r, a;
142
+ }
143
+ };
144
+ function d(r, n) {
145
+ for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
146
+ var o,
147
+ i = p[t],
148
+ d = G.p,
149
+ l = i[2];
150
+ r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
151
+ }
152
+ if (o || r > 1) return a;
153
+ throw y = !0, n;
154
+ }
155
+ return function (o, p, l) {
156
+ if (f > 1) throw TypeError("Generator is already running");
157
+ for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
158
+ i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
159
+ try {
160
+ if (f = 2, i) {
161
+ if (c || (o = "next"), t = i[o]) {
162
+ if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
163
+ if (!t.done) return t;
164
+ u = t.value, c < 2 && (c = 0);
165
+ } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
166
+ i = e;
167
+ } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
168
+ } catch (t) {
169
+ i = e, c = 1, u = t;
170
+ } finally {
171
+ f = 1;
172
+ }
173
+ }
174
+ return {
175
+ value: t,
176
+ done: y
177
+ };
178
+ };
179
+ }(r, o, i), !0), u;
180
+ }
181
+ var a = {};
182
+ function Generator() {}
183
+ function GeneratorFunction() {}
184
+ function GeneratorFunctionPrototype() {}
185
+ t = Object.getPrototypeOf;
186
+ var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
187
+ return this;
188
+ }), t),
189
+ u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
190
+ function f(e) {
191
+ return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
192
+ }
193
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
194
+ return this;
195
+ }), _regeneratorDefine(u, "toString", function () {
196
+ return "[object Generator]";
197
+ }), (_regenerator = function () {
198
+ return {
199
+ w: i,
200
+ m: f
201
+ };
202
+ })();
203
+ }
204
+ function _regeneratorDefine(e, r, n, t) {
205
+ var i = Object.defineProperty;
206
+ try {
207
+ i({}, "", {});
208
+ } catch (e) {
209
+ i = 0;
210
+ }
211
+ _regeneratorDefine = function (e, r, n, t) {
212
+ if (r) i ? i(e, r, {
213
+ value: n,
214
+ enumerable: !t,
215
+ configurable: !t,
216
+ writable: !t
217
+ }) : e[r] = n;else {
218
+ function o(r, n) {
219
+ _regeneratorDefine(e, r, function (e) {
220
+ return this._invoke(r, n, e);
221
+ });
222
+ }
223
+ o("next", 0), o("throw", 1), o("return", 2);
224
+ }
225
+ }, _regeneratorDefine(e, r, n, t);
226
+ }
227
+ function _setPrototypeOf(t, e) {
228
+ return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
229
+ return t.__proto__ = e, t;
230
+ }, _setPrototypeOf(t, e);
231
+ }
232
+ function _toPrimitive(t, r) {
233
+ if ("object" != typeof t || !t) return t;
234
+ var e = t[Symbol.toPrimitive];
235
+ if (void 0 !== e) {
236
+ var i = e.call(t, r || "default");
237
+ if ("object" != typeof i) return i;
238
+ throw new TypeError("@@toPrimitive must return a primitive value.");
239
+ }
240
+ return ("string" === r ? String : Number)(t);
241
+ }
242
+ function _toPropertyKey(t) {
243
+ var i = _toPrimitive(t, "string");
244
+ return "symbol" == typeof i ? i : i + "";
245
+ }
246
+ function _unsupportedIterableToArray(r, a) {
247
+ if (r) {
248
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
249
+ var t = {}.toString.call(r).slice(8, -1);
250
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
251
+ }
252
+ }
253
+ function _wrapNativeSuper(t) {
254
+ var r = "function" == typeof Map ? new Map() : void 0;
255
+ return _wrapNativeSuper = function (t) {
256
+ if (null === t || !_isNativeFunction(t)) return t;
257
+ if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
258
+ if (void 0 !== r) {
259
+ if (r.has(t)) return r.get(t);
260
+ r.set(t, Wrapper);
261
+ }
262
+ function Wrapper() {
263
+ return _construct(t, arguments, _getPrototypeOf(this).constructor);
264
+ }
265
+ return Wrapper.prototype = Object.create(t.prototype, {
266
+ constructor: {
267
+ value: Wrapper,
268
+ enumerable: !1,
269
+ writable: !0,
270
+ configurable: !0
271
+ }
272
+ }), _setPrototypeOf(Wrapper, t);
273
+ }, _wrapNativeSuper(t);
274
+ }
275
+
276
+ var languageConfiguration = {
277
+ // the default separators except `@$`
278
+ wordPattern: /(-?\d*\.\d\w*)|([^`~!#%^&*()\-=+\[{\]}\\|;:'",.<>\/?\s]+)/g,
279
+ // Not possible to make comments in PromQL syntax
280
+ comments: {
281
+ lineComment: '#'
282
+ },
283
+ brackets: [['{', '}'], ['[', ']'], ['(', ')']],
284
+ autoClosingPairs: [{
285
+ open: '{',
286
+ close: '}'
287
+ }, {
288
+ open: '[',
289
+ close: ']'
290
+ }, {
291
+ open: '(',
292
+ close: ')'
293
+ }, {
294
+ open: '"',
295
+ close: '"'
296
+ }, {
297
+ open: "'",
298
+ close: "'"
299
+ }],
300
+ surroundingPairs: [{
301
+ open: '{',
302
+ close: '}'
303
+ }, {
304
+ open: '[',
305
+ close: ']'
306
+ }, {
307
+ open: '(',
308
+ close: ')'
309
+ }, {
310
+ open: '"',
311
+ close: '"'
312
+ }, {
313
+ open: "'",
314
+ close: "'"
315
+ }, {
316
+ open: '<',
317
+ close: '>'
318
+ }],
319
+ folding: {}
320
+ };
321
+ // PromQL Aggregation Operators
322
+ // (https://prometheus.io/docs/prometheus/latest/querying/operators/#aggregation-operators)
323
+ var aggregations = ['sum', 'min', 'max', 'avg', 'group', 'stddev', 'stdvar', 'count', 'count_values', 'bottomk', 'topk', 'quantile', 'quantiles', 'distinct', 'geomean', 'histogram', 'mad', 'mode',
324
+ // metricsql aggregations
325
+ 'any', 'bottomk_avg', 'bottomk_max', 'bottomk_median', 'bottomk_last', 'bottomk_min', 'topk_avg', 'topk_max', 'topk_median', 'topk_last', 'topk_min', 'outliers_mad', 'outliersk', 'share', 'sum2', 'zscore'];
326
+ // PromQL functions
327
+ // (https://prometheus.io/docs/prometheus/latest/querying/functions/)
328
+ var functions = ['abs', 'absent', 'ceil', 'changes', 'clamp_max', 'clamp_min', 'day_of_month', 'day_of_week', 'days_in_month', 'delta', 'deriv', 'exp', 'floor', 'histogram_quantile', 'histogram_avg', 'histogram_count', 'histogram_sum', 'histogram_fraction', 'histogram_stddev', 'histogram_stdvar', 'holt_winters', 'hour', 'idelta', 'increase', 'irate', 'label_join', 'label_replace', 'ln', 'log2', 'log10', 'minute', 'month', 'predict_linear', 'rate', 'resets', 'round', 'scalar', 'sort', 'sort_desc', 'sqrt', 'time', 'timestamp', 'vector', 'year',
329
+ // metricsql functions
330
+ 'aggr_over_time', 'alias', 'ascent_over_time', 'bitmap_and', 'bitmap_or', 'bitmap_xor', 'buckets_limit', 'changes_prometheus', 'count_eq_over_time', 'count_gt_over_time', 'count_le_over_time', 'count_ne_over_time', 'decreases_over_time', 'default_rollup', 'delta_prometheus', 'deriv_fast', 'descent_over_time', 'distinct_over_time', 'drop_common_labels', 'duration_over_time', 'first_over_time', 'geomean_over_time', 'histogram_avg', 'histogram_over_time', 'histogram_quantiles', 'histogram_share', 'hoeffding_bound_lower', 'hoeffding_bound_upper', 'ideriv', 'increase_prometheus', 'increase_pure', 'increases_over_time', 'integrate', 'interpolate', 'keep_last_value', 'keep_next_value', 'label_copy', 'label_del', 'label_graphite_group', 'label_keep', 'label_lowercase', 'label_map', 'label_match', 'label_mismatch', 'label_move', 'label_set', 'label_transform', 'label_uppercase', 'label_value', 'lag', 'lifetime', 'limit_offset', 'mad_over_time', 'median_over_time', 'mode_over_time', 'now', 'prometheus_buckets', 'quantiles_over_time', 'rand', 'rand_exponential', 'rand_normal', 'range_avg', 'range_first', 'range_last', 'range_linear_regression', 'range_mad', 'range_max', 'range_min', 'range_normalize', 'range_over_time', 'range_quantile', 'range_stddev', 'range_stdvar', 'range_sum', 'range_trim_outliers', 'range_trim_spikes', 'range_trim_zscore', 'range_zscore', 'rate_over_sum', 'remove_resets', 'rollup', 'rollup_candlestick', 'rollup_delta', 'rollup_deriv', 'rollup_increase', 'rollup_rate', 'rollup_scrape_interval', 'running_avg', 'running_max', 'running_min', 'running_sum', 'scrape_interval', 'share_eq_over_time', 'share_gt_over_time', 'share_le_over_time', 'smooth_exponential', 'smooth_exponential', 'sort_by_label_desc', 'sort_by_label_numeric', 'sort_by_label_numeric_desc', 'stale_samples_over_time', 'step', 'sum2_over_time', 'tfirst_over_time', 'timestamp_with_name', 'timezone_offset', 'tlast_change_over_time', 'tlast_over_time', 'tmax_over_time', 'tmin_over_time', 'union', 'zscore_over_time', 'avg_daily', 'median_daily', 'avg_weekly', 'median_weekly', 'median_weekly_with_trends'];
331
+ // PromQL specific functions: Aggregations over time
332
+ // (https://prometheus.io/docs/prometheus/latest/querying/functions/#aggregation_over_time)
333
+ var aggregationsOverTime = [];
334
+ for (var _i = 0, aggregations_1 = aggregations; _i < aggregations_1.length; _i++) {
335
+ var agg = aggregations_1[_i];
336
+ aggregationsOverTime.push(agg + '_over_time');
337
+ }
338
+ // PromQL vector matching + the by and without clauses
339
+ // (https://prometheus.io/docs/prometheus/latest/querying/operators/#vector-matching)
340
+ var vectorMatching = ['on', 'ignoring', 'group_right', 'group_left', 'by', 'without'];
341
+ // Produce a regex matching elements : (elt1|elt2|...)
342
+ var vectorMatchingRegex = '(' + /*#__PURE__*/vectorMatching.reduce(function (prev, curr) {
343
+ return prev + '|' + curr;
344
+ }) + ')';
345
+ // PromQL Operators
346
+ // (https://prometheus.io/docs/prometheus/latest/querying/operators/)
347
+ var operators = ['+', '-', '*', '/', '%', '^', '==', '!=', '>', '<', '>=', '<=', 'and', 'or', 'unless'];
348
+ // PromQL offset modifier
349
+ // (https://prometheus.io/docs/prometheus/latest/querying/basics/#offset-modifier)
350
+ var offsetModifier = ['offset'];
351
+ // Merging all the keywords in one list
352
+ var keywords = /*#__PURE__*/aggregations.concat(functions).concat(aggregationsOverTime).concat(vectorMatching).concat(offsetModifier);
353
+ // noinspection JSUnusedGlobalSymbols
354
+ var language = {
355
+ ignoreCase: false,
356
+ defaultToken: '',
357
+ tokenPostfix: '.promql',
358
+ keywords: keywords,
359
+ operators: operators,
360
+ vectorMatching: vectorMatchingRegex,
361
+ // we include these common regular expressions
362
+ symbols: /[=><!~?:&|+\-*\/^%]+/,
363
+ escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
364
+ digits: /\d+(_+\d+)*/,
365
+ octaldigits: /[0-7]+(_+[0-7]+)*/,
366
+ binarydigits: /[0-1]+(_+[0-1]+)*/,
367
+ hexdigits: /[[0-9a-fA-F]+(_+[0-9a-fA-F]+)*/,
368
+ integersuffix: /(ll|LL|u|U|l|L)?(ll|LL|u|U|l|L)?/,
369
+ floatsuffix: /[fFlL]?/,
370
+ // The main tokenizer for our languages
371
+ tokenizer: {
372
+ root: [
373
+ // 'by', 'without' and vector matching
374
+ [/@vectorMatching\s*(?=\()/, 'type', '@clauses'],
375
+ // labels
376
+ [/[a-z_]\w*(?=\s*(=|!=|=~|!~))/, 'tag'],
377
+ // comments
378
+ [/(^#.*$)/, 'comment'],
379
+ // all keywords have the same color
380
+ [/[a-zA-Z_]\w*/, {
381
+ cases: {
382
+ '@keywords': 'type',
383
+ '@default': 'identifier'
384
+ }
385
+ }],
386
+ // strings
387
+ [/"([^"\\]|\\.)*$/, 'string.invalid'], [/'([^'\\]|\\.)*$/, 'string.invalid'], [/"/, 'string', '@string_double'], [/'/, 'string', '@string_single'], [/`/, 'string', '@string_backtick'],
388
+ // whitespace
389
+ {
390
+ include: '@whitespace'
391
+ },
392
+ // delimiters and operators
393
+ [/[{}()\[\]]/, '@brackets'], [/[<>](?!@symbols)/, '@brackets'], [/@symbols/, {
394
+ cases: {
395
+ '@operators': 'delimiter',
396
+ '@default': ''
397
+ }
398
+ }],
399
+ // numbers
400
+ [/\d+[smhdwy]/, 'number'], [/\d*\d+[eE]([\-+]?\d+)?(@floatsuffix)/, 'number.float'], [/\d*\.\d+([eE][\-+]?\d+)?(@floatsuffix)/, 'number.float'], [/0[xX][0-9a-fA-F']*[0-9a-fA-F](@integersuffix)/, 'number.hex'], [/0[0-7']*[0-7](@integersuffix)/, 'number.octal'], [/0[bB][0-1']*[0-1](@integersuffix)/, 'number.binary'], [/\d[\d']*\d(@integersuffix)/, 'number'], [/\d(@integersuffix)/, 'number']],
401
+ string_double: [[/[^\\"]+/, 'string'], [/@escapes/, 'string.escape'], [/\\./, 'string.escape.invalid'], [/"/, 'string', '@pop']],
402
+ string_single: [[/[^\\']+/, 'string'], [/@escapes/, 'string.escape'], [/\\./, 'string.escape.invalid'], [/'/, 'string', '@pop']],
403
+ string_backtick: [[/[^\\`$]+/, 'string'], [/@escapes/, 'string.escape'], [/\\./, 'string.escape.invalid'], [/`/, 'string', '@pop']],
404
+ clauses: [[/[^(,)]/, 'tag'], [/\)/, 'identifier', '@pop']],
405
+ whitespace: [[/[ \t\r\n]+/, 'white']]
406
+ }
407
+ };
408
+ var TRIGONOMETRIC_FUNCTIONS = [{
409
+ label: 'acos',
410
+ insertText: 'acos',
411
+ detail: 'acos(v instant-vector)',
412
+ documentation: 'calculates the arccosine of all elements in v'
413
+ }, {
414
+ label: 'acosh',
415
+ insertText: 'acosh',
416
+ detail: 'acosh(v instant-vector)',
417
+ documentation: 'calculates the inverse hyperbolic cosine of all elements in v'
418
+ }, {
419
+ label: 'asin',
420
+ insertText: 'asin',
421
+ detail: 'asin(v instant-vector)',
422
+ documentation: 'calculates the arcsine of all elements in v'
423
+ }, {
424
+ label: 'asinh',
425
+ insertText: 'asinh',
426
+ detail: 'asinh(v instant-vector)',
427
+ documentation: 'calculates the inverse hyperbolic sine of all elements in v'
428
+ }, {
429
+ label: 'atan',
430
+ insertText: 'atan',
431
+ detail: 'atan(v instant-vector)',
432
+ documentation: 'calculates the arctangent of all elements in v'
433
+ }, {
434
+ label: 'atanh',
435
+ insertText: 'atanh',
436
+ detail: 'atanh(v instant-vector)',
437
+ documentation: 'calculates the inverse hyperbolic tangent of all elements in v'
438
+ }, {
439
+ label: 'cos',
440
+ insertText: 'cos',
441
+ detail: 'cos(v instant-vector)',
442
+ documentation: 'calculates the cosine of all elements in v'
443
+ }, {
444
+ label: 'cosh',
445
+ insertText: 'cosh',
446
+ detail: 'cosh(v instant-vector)',
447
+ documentation: 'calculates the hyperbolic cosine of all elements in v'
448
+ }, {
449
+ label: 'sin',
450
+ insertText: 'sin',
451
+ detail: 'sin(v instant-vector)',
452
+ documentation: 'calculates the sine of all elements in v'
453
+ }, {
454
+ label: 'sinh',
455
+ insertText: 'sinh',
456
+ detail: 'sinh(v instant-vector)',
457
+ documentation: 'calculates the hyperbolic sine of all elements in v'
458
+ }, {
459
+ label: 'tan',
460
+ insertText: 'tan',
461
+ detail: 'tan(v instant-vector)',
462
+ documentation: 'calculates the tangent of all elements in v'
463
+ }, {
464
+ label: 'tanh',
465
+ insertText: 'tanh',
466
+ detail: 'tanh(v instant-vector)',
467
+ documentation: 'calculates the hyperbolic tangent of all elements in v'
468
+ }];
469
+ var AGGREGATION_OPERATORS = [{
470
+ label: 'sum',
471
+ insertText: 'sum',
472
+ documentation: 'Calculate sum over dimensions'
473
+ }, {
474
+ label: 'min',
475
+ insertText: 'min',
476
+ documentation: 'Select minimum over dimensions'
477
+ }, {
478
+ label: 'max',
479
+ insertText: 'max',
480
+ documentation: 'Select maximum over dimensions'
481
+ }, {
482
+ label: 'avg',
483
+ insertText: 'avg',
484
+ documentation: 'Calculate the average over dimensions'
485
+ }, {
486
+ label: 'group',
487
+ insertText: 'group',
488
+ documentation: 'All values in the resulting vector are 1'
489
+ }, {
490
+ label: 'stddev',
491
+ insertText: 'stddev',
492
+ documentation: 'Calculate population standard deviation over dimensions'
493
+ }, {
494
+ label: 'stdvar',
495
+ insertText: 'stdvar',
496
+ documentation: 'Calculate population standard variance over dimensions'
497
+ }, {
498
+ label: 'count',
499
+ insertText: 'count',
500
+ documentation: 'Count number of elements in the vector'
501
+ }, {
502
+ label: 'count_values',
503
+ insertText: 'count_values',
504
+ documentation: 'Count number of elements with the same value'
505
+ }, {
506
+ label: 'bottomk',
507
+ insertText: 'bottomk',
508
+ documentation: 'Smallest k elements by sample value'
509
+ }, {
510
+ label: 'topk',
511
+ insertText: 'topk',
512
+ documentation: 'Largest k elements by sample value'
513
+ }, {
514
+ label: 'quantile',
515
+ insertText: 'quantile',
516
+ documentation: 'Calculate φ-quantile (0 ≤ φ ≤ 1) over dimensions'
517
+ }];
518
+ var FUNCTIONS = /*#__PURE__*/[].concat(AGGREGATION_OPERATORS, TRIGONOMETRIC_FUNCTIONS, [{
519
+ insertText: 'abs',
520
+ label: 'abs',
521
+ detail: 'abs(v instant-vector)',
522
+ documentation: 'Returns the input vector with all sample values converted to their absolute value.'
523
+ }, {
524
+ insertText: 'absent',
525
+ label: 'absent',
526
+ detail: 'absent(v instant-vector)',
527
+ documentation: 'Returns an empty vector if the vector passed to it has any elements and a 1-element vector with the value 1 if the vector passed to it has no elements. This is useful for alerting on when no time series exist for a given metric name and label combination.'
528
+ }, {
529
+ insertText: 'absent_over_time',
530
+ label: 'absent_over_time',
531
+ detail: 'absent(v range-vector)',
532
+ documentation: 'Returns an empty vector if the range vector passed to it has any elements and a 1-element vector with the value 1 if the range vector passed to it has no elements.'
533
+ }, {
534
+ insertText: 'ceil',
535
+ label: 'ceil',
536
+ detail: 'ceil(v instant-vector)',
537
+ documentation: 'Rounds the sample values of all elements in `v` up to the nearest integer.'
538
+ }, {
539
+ insertText: 'changes',
540
+ label: 'changes',
541
+ detail: 'changes(v range-vector)',
542
+ documentation: 'For each input time series, `changes(v range-vector)` returns the number of times its value has changed within the provided time range as an instant vector.'
543
+ }, {
544
+ insertText: 'clamp',
545
+ label: 'clamp',
546
+ detail: 'clamp(v instant-vector, min scalar, max scalar)',
547
+ documentation: 'Clamps the sample values of all elements in `v` to have a lower limit of `min` and an upper limit of `max`.'
548
+ }, {
549
+ insertText: 'clamp_max',
550
+ label: 'clamp_max',
551
+ detail: 'clamp_max(v instant-vector, max scalar)',
552
+ documentation: 'Clamps the sample values of all elements in `v` to have an upper limit of `max`.'
553
+ }, {
554
+ insertText: 'clamp_min',
555
+ label: 'clamp_min',
556
+ detail: 'clamp_min(v instant-vector, min scalar)',
557
+ documentation: 'Clamps the sample values of all elements in `v` to have a lower limit of `min`.'
558
+ }, {
559
+ insertText: 'count_scalar',
560
+ label: 'count_scalar',
561
+ detail: 'count_scalar(v instant-vector)',
562
+ documentation: 'Returns the number of elements in a time series vector as a scalar. This is in contrast to the `count()` aggregation operator, which always returns a vector (an empty one if the input vector is empty) and allows grouping by labels via a `by` clause.'
563
+ }, {
564
+ insertText: 'deg',
565
+ label: 'deg',
566
+ detail: 'deg(v instant-vector)',
567
+ documentation: 'Converts radians to degrees for all elements in v'
568
+ }, {
569
+ insertText: 'day_of_month',
570
+ label: 'day_of_month',
571
+ detail: 'day_of_month(v=vector(time()) instant-vector)',
572
+ documentation: 'Returns the day of the month for each of the given times in UTC. Returned values are from 1 to 31.'
573
+ }, {
574
+ insertText: 'day_of_week',
575
+ label: 'day_of_week',
576
+ detail: 'day_of_week(v=vector(time()) instant-vector)',
577
+ documentation: 'Returns the day of the week for each of the given times in UTC. Returned values are from 0 to 6, where 0 means Sunday etc.'
578
+ }, {
579
+ insertText: 'day_of_year',
580
+ label: 'day_of_year',
581
+ detail: 'day_of_year(v=vector(time()) instant-vector)',
582
+ documentation: 'Returns the day of the year for each of the given times in UTC. Returned values are from 1 to 365 for non-leap years, and 1 to 366 in leap years.'
583
+ }, {
584
+ insertText: 'days_in_month',
585
+ label: 'days_in_month',
586
+ detail: 'days_in_month(v=vector(time()) instant-vector)',
587
+ documentation: 'Returns number of days in the month for each of the given times in UTC. Returned values are from 28 to 31.'
588
+ }, {
589
+ insertText: 'delta',
590
+ label: 'delta',
591
+ detail: 'delta(v range-vector)',
592
+ documentation: 'Calculates the difference between the first and last value of each time series element in a range vector `v`, returning an instant vector with the given deltas and equivalent labels. The delta is extrapolated to cover the full time range as specified in the range vector selector, so that it is possible to get a non-integer result even if the sample values are all integers.'
593
+ }, {
594
+ insertText: 'deriv',
595
+ label: 'deriv',
596
+ detail: 'deriv(v range-vector)',
597
+ documentation: 'Calculates the per-second derivative of the time series in a range vector `v`, using simple linear regression.'
598
+ }, {
599
+ insertText: 'drop_common_labels',
600
+ label: 'drop_common_labels',
601
+ detail: 'drop_common_labels(instant-vector)',
602
+ documentation: 'Drops all labels that have the same name and value across all series in the input vector.'
603
+ }, {
604
+ insertText: 'exp',
605
+ label: 'exp',
606
+ detail: 'exp(v instant-vector)',
607
+ documentation: 'Calculates the exponential function for all elements in `v`.\nSpecial cases are:\n* `Exp(+Inf) = +Inf` \n* `Exp(NaN) = NaN`'
608
+ }, {
609
+ insertText: 'floor',
610
+ label: 'floor',
611
+ detail: 'floor(v instant-vector)',
612
+ documentation: 'Rounds the sample values of all elements in `v` down to the nearest integer.'
613
+ }, {
614
+ insertText: 'histogram_quantile',
615
+ label: 'histogram_quantile',
616
+ detail: 'histogram_quantile(φ float, b instant-vector)',
617
+ documentation: 'Calculates the φ-quantile (0 ≤ φ ≤ 1) from the buckets `b` of a histogram. The samples in `b` are the counts of observations in each bucket. Each sample must have a label `le` where the label value denotes the inclusive upper bound of the bucket. (Samples without such a label are silently ignored.) The histogram metric type automatically provides time series with the `_bucket` suffix and the appropriate labels.'
618
+ }, {
619
+ insertText: 'holt_winters',
620
+ label: 'holt_winters',
621
+ detail: 'holt_winters(v range-vector, sf scalar, tf scalar)',
622
+ documentation: 'Produces a smoothed value for time series based on the range in `v`. The lower the smoothing factor `sf`, the more importance is given to old data. The higher the trend factor `tf`, the more trends in the data is considered. Both `sf` and `tf` must be between 0 and 1.'
623
+ }, {
624
+ insertText: 'hour',
625
+ label: 'hour',
626
+ detail: 'hour(v=vector(time()) instant-vector)',
627
+ documentation: 'Returns the hour of the day for each of the given times in UTC. Returned values are from 0 to 23.'
628
+ }, {
629
+ insertText: 'idelta',
630
+ label: 'idelta',
631
+ detail: 'idelta(v range-vector)',
632
+ documentation: 'Calculates the difference between the last two samples in the range vector `v`, returning an instant vector with the given deltas and equivalent labels.'
633
+ }, {
634
+ insertText: 'increase',
635
+ label: 'increase',
636
+ detail: 'increase(v range-vector)',
637
+ documentation: 'Calculates the increase in the time series in the range vector. Breaks in monotonicity (such as counter resets due to target restarts) are automatically adjusted for. The increase is extrapolated to cover the full time range as specified in the range vector selector, so that it is possible to get a non-integer result even if a counter increases only by integer increments.'
638
+ }, {
639
+ insertText: 'irate',
640
+ label: 'irate',
641
+ detail: 'irate(v range-vector)',
642
+ documentation: 'Calculates the per-second instant rate of increase of the time series in the range vector. This is based on the last two data points. Breaks in monotonicity (such as counter resets due to target restarts) are automatically adjusted for.'
643
+ }, {
644
+ insertText: 'label_join',
645
+ label: 'label_join',
646
+ detail: 'label_join(v instant-vector, dst_label string, separator string, src_label_1 string, src_label_2 string, ...)',
647
+ documentation: 'For each timeseries in `v`, joins all the values of all the `src_labels` using `separator` and returns the timeseries with the label `dst_label` containing the joined value. There can be any number of `src_labels` in this function.'
648
+ }, {
649
+ insertText: 'label_replace',
650
+ label: 'label_replace',
651
+ detail: 'label_replace(v instant-vector, dst_label string, replacement string, src_label string, regex string)',
652
+ documentation: "For each timeseries in `v`, `label_replace(v instant-vector, dst_label string, replacement string, src_label string, regex string)` matches the regular expression `regex` against the label `src_label`. If it matches, then the timeseries is returned with the label `dst_label` replaced by the expansion of `replacement`. `$1` is replaced with the first matching subgroup, `$2` with the second etc. If the regular expression doesn't match then the timeseries is returned unchanged."
653
+ }, {
654
+ insertText: 'ln',
655
+ label: 'ln',
656
+ detail: 'ln(v instant-vector)',
657
+ documentation: 'Calculates the natural logarithm for all elements in `v`.\nSpecial cases are:\n * `ln(+Inf) = +Inf`\n * `ln(0) = -Inf`\n * `ln(x < 0) = NaN`\n * `ln(NaN) = NaN`'
658
+ }, {
659
+ insertText: 'log2',
660
+ label: 'log2',
661
+ detail: 'log2(v instant-vector)',
662
+ documentation: 'Calculates the binary logarithm for all elements in `v`. The special cases are equivalent to those in `ln`.'
663
+ }, {
664
+ insertText: 'log10',
665
+ label: 'log10',
666
+ detail: 'log10(v instant-vector)',
667
+ documentation: 'Calculates the decimal logarithm for all elements in `v`. The special cases are equivalent to those in `ln`.'
668
+ }, {
669
+ insertText: 'minute',
670
+ label: 'minute',
671
+ detail: 'minute(v=vector(time()) instant-vector)',
672
+ documentation: 'Returns the minute of the hour for each of the given times in UTC. Returned values are from 0 to 59.'
673
+ }, {
674
+ insertText: 'month',
675
+ label: 'month',
676
+ detail: 'month(v=vector(time()) instant-vector)',
677
+ documentation: 'Returns the month of the year for each of the given times in UTC. Returned values are from 1 to 12, where 1 means January etc.'
678
+ }, {
679
+ insertText: 'pi',
680
+ label: 'pi',
681
+ detail: 'pi()',
682
+ documentation: 'Returns pi'
683
+ }, {
684
+ insertText: 'predict_linear',
685
+ label: 'predict_linear',
686
+ detail: 'predict_linear(v range-vector, t scalar)',
687
+ documentation: 'Predicts the value of time series `t` seconds from now, based on the range vector `v`, using simple linear regression.'
688
+ }, {
689
+ insertText: 'rad',
690
+ label: 'rad',
691
+ detail: 'rad(v instant-vector)',
692
+ documentation: 'Converts degrees to radians for all elements in v'
693
+ }, {
694
+ insertText: 'rate',
695
+ label: 'rate',
696
+ detail: 'rate(v range-vector)',
697
+ documentation: "Calculates the per-second average rate of increase of the time series in the range vector. Breaks in monotonicity (such as counter resets due to target restarts) are automatically adjusted for. Also, the calculation extrapolates to the ends of the time range, allowing for missed scrapes or imperfect alignment of scrape cycles with the range's time period."
698
+ }, {
699
+ insertText: 'resets',
700
+ label: 'resets',
701
+ detail: 'resets(v range-vector)',
702
+ documentation: 'For each input time series, `resets(v range-vector)` returns the number of counter resets within the provided time range as an instant vector. Any decrease in the value between two consecutive samples is interpreted as a counter reset.'
703
+ }, {
704
+ insertText: 'round',
705
+ label: 'round',
706
+ detail: 'round(v instant-vector, to_nearest=1 scalar)',
707
+ documentation: 'Rounds the sample values of all elements in `v` to the nearest integer. Ties are resolved by rounding up. The optional `to_nearest` argument allows specifying the nearest multiple to which the sample values should be rounded. This multiple may also be a fraction.'
708
+ }, {
709
+ insertText: 'scalar',
710
+ label: 'scalar',
711
+ detail: 'scalar(v instant-vector)',
712
+ documentation: 'Given a single-element input vector, `scalar(v instant-vector)` returns the sample value of that single element as a scalar. If the input vector does not have exactly one element, `scalar` will return `NaN`.'
713
+ }, {
714
+ insertText: 'sgn',
715
+ label: 'sgn',
716
+ detail: 'sgn(v instant-vector)',
717
+ documentation: 'Returns a vector with all sample values converted to their sign, defined as this: 1 if v is positive, -1 if v is negative and 0 if v is equal to zero.'
718
+ }, {
719
+ insertText: 'sort',
720
+ label: 'sort',
721
+ detail: 'sort(v instant-vector)',
722
+ documentation: 'Returns vector elements sorted by their sample values, in ascending order.'
723
+ }, {
724
+ insertText: 'sort_desc',
725
+ label: 'sort_desc',
726
+ detail: 'sort_desc(v instant-vector)',
727
+ documentation: 'Returns vector elements sorted by their sample values, in descending order.'
728
+ }, {
729
+ insertText: 'sqrt',
730
+ label: 'sqrt',
731
+ detail: 'sqrt(v instant-vector)',
732
+ documentation: 'Calculates the square root of all elements in `v`.'
733
+ }, {
734
+ insertText: 'time',
735
+ label: 'time',
736
+ detail: 'time()',
737
+ documentation: 'Returns the number of seconds since January 1, 1970 UTC. Note that this does not actually return the current time, but the time at which the expression is to be evaluated.'
738
+ }, {
739
+ insertText: 'timestamp',
740
+ label: 'timestamp',
741
+ detail: 'timestamp(v instant-vector)',
742
+ documentation: 'Returns the timestamp of each of the samples of the given vector as the number of seconds since January 1, 1970 UTC.'
743
+ }, {
744
+ insertText: 'vector',
745
+ label: 'vector',
746
+ detail: 'vector(s scalar)',
747
+ documentation: 'Returns the scalar `s` as a vector with no labels.'
748
+ }, {
749
+ insertText: 'year',
750
+ label: 'year',
751
+ detail: 'year(v=vector(time()) instant-vector)',
752
+ documentation: 'Returns the year for each of the given times in UTC.'
753
+ }, {
754
+ insertText: 'avg_over_time',
755
+ label: 'avg_over_time',
756
+ detail: 'avg_over_time(range-vector)',
757
+ documentation: 'The average value of all points in the specified interval.'
758
+ }, {
759
+ insertText: 'min_over_time',
760
+ label: 'min_over_time',
761
+ detail: 'min_over_time(range-vector)',
762
+ documentation: 'The minimum value of all points in the specified interval.'
763
+ }, {
764
+ insertText: 'max_over_time',
765
+ label: 'max_over_time',
766
+ detail: 'max_over_time(range-vector)',
767
+ documentation: 'The maximum value of all points in the specified interval.'
768
+ }, {
769
+ insertText: 'sum_over_time',
770
+ label: 'sum_over_time',
771
+ detail: 'sum_over_time(range-vector)',
772
+ documentation: 'The sum of all values in the specified interval.'
773
+ }, {
774
+ insertText: 'count_over_time',
775
+ label: 'count_over_time',
776
+ detail: 'count_over_time(range-vector)',
777
+ documentation: 'The count of all values in the specified interval.'
778
+ }, {
779
+ insertText: 'quantile_over_time',
780
+ label: 'quantile_over_time',
781
+ detail: 'quantile_over_time(scalar, range-vector)',
782
+ documentation: 'The φ-quantile (0 ≤ φ ≤ 1) of the values in the specified interval.'
783
+ }, {
784
+ insertText: 'stddev_over_time',
785
+ label: 'stddev_over_time',
786
+ detail: 'stddev_over_time(range-vector)',
787
+ documentation: 'The population standard deviation of the values in the specified interval.'
788
+ }, {
789
+ insertText: 'stdvar_over_time',
790
+ label: 'stdvar_over_time',
791
+ detail: 'stdvar_over_time(range-vector)',
792
+ documentation: 'The population standard variance of the values in the specified interval.'
793
+ }, {
794
+ insertText: 'last_over_time',
795
+ label: 'last_over_time',
796
+ detail: 'last_over_time(range-vector)',
797
+ documentation: 'The most recent point value in specified interval.'
798
+ }, {
799
+ insertText: 'present_over_time',
800
+ label: 'present_over_time',
801
+ detail: 'present_over_time(range-vector)',
802
+ documentation: 'The value 1 for any series in the specified interval.'
803
+ }, {
804
+ insertText: 'histogram_avg',
805
+ label: 'histogram_avg',
806
+ detail: 'histogram_avg(v instant-vector)',
807
+ documentation: 'Returns the arithmetic average of observed values stored in a native histogram. Samples that are not native histograms are ignored and do not show up in the returned vector.'
808
+ }, {
809
+ insertText: 'histogram_count',
810
+ label: 'histogram_count',
811
+ detail: 'histogram_count(v instant-vector)',
812
+ documentation: 'Returns the count of observations stored in a native histogram.'
813
+ }, {
814
+ insertText: 'histogram_sum',
815
+ label: 'histogram_sum',
816
+ detail: 'histogram_sum(v instant-vector)',
817
+ documentation: 'Returns the sum of observations stored in a native histogram.'
818
+ }, {
819
+ insertText: 'histogram_fraction',
820
+ label: 'histogram_fraction',
821
+ detail: 'histogram_fraction(lower scalar, upper scalar, v instant-vector)',
822
+ documentation: 'Returns the estimated fraction of observations between the provided lower and upper values.'
823
+ }, {
824
+ insertText: 'histogram_stddev',
825
+ label: 'histogram_stddev',
826
+ detail: 'histogram_stddev(v instant-vector)',
827
+ documentation: 'Returns the estimated standard deviation of observations in a native histogram, based on the geometric mean of the buckets where the observations lie.'
828
+ }, {
829
+ insertText: 'histogram_stdvar',
830
+ label: 'histogram_stdvar',
831
+ detail: 'histogram_stdvar(v instant-vector)',
832
+ documentation: 'Returns the estimated standard variance of observations in a native histogram.'
833
+ }]);
834
+
835
+ var NeverCaseError = /*#__PURE__*/function (_Error) {
836
+ function NeverCaseError(_value) {
837
+ return _Error.call(this, 'should never happen') || this;
838
+ }
839
+ _inheritsLoose(NeverCaseError, _Error);
840
+ return NeverCaseError;
841
+ }(/*#__PURE__*/_wrapNativeSuper(Error));
842
+ // based on the openmetrics-documentation, the 3 symbols we have to handle are:
843
+ // - \n ... the newline character
844
+ // - \ ... the backslash character
845
+ // - " ... the double-quote character
846
+ function escapeLabelValueInExactSelector(labelValue) {
847
+ return labelValue.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/"/g, '\\"');
848
+ }
849
+ function makeSelector(metricName, labels, labelName) {
850
+ if (!labels || labels.length === 0) {
851
+ return metricName;
852
+ }
853
+ var allLabels = [].concat(labels).filter(function (label) {
854
+ return label.name !== labelName && label.value !== '';
855
+ });
856
+ var allLabelTexts = allLabels.map(function (label) {
857
+ return "" + label.name + label.op + "\"" + escapeLabelValueInExactSelector(label.value) + "\"";
858
+ });
859
+ return "{" + allLabelTexts.join(',') + "}";
860
+ }
861
+
862
+ var DEFAULT_SERIES_LIMIT = '40000';
863
+ var badRequest = 400;
864
+ var unprocessableEntity = 422;
865
+ var serviceUnavailable = 503;
866
+ var CODE_MODE_SUGGESTIONS_INCOMPLETE_EVENT = 'codeModeSuggestionsIncomplete';
867
+ var DataProvider = /*#__PURE__*/function () {
868
+ function DataProvider(params) {
869
+ var _this = this;
870
+ this.lookbackInterval = 60 * 60 * 1000 * 12; // 12 hours
871
+ this.variablesNames = [];
872
+ this.httpMethod = 'GET';
873
+ this.apiPrefix = '/api/v1';
874
+ this.customRequest = function (input, init) {
875
+ return fetch(input, init);
876
+ };
877
+ this.fetchSeries = /*#__PURE__*/function () {
878
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(selector, withLimit) {
879
+ var end, start, url, urlParams, request;
880
+ return _regenerator().w(function (_context) {
881
+ while (1) switch (_context.n) {
882
+ case 0:
883
+ end = new Date();
884
+ start = new Date(end.getTime() - _this.lookbackInterval);
885
+ url = _this.apiPrefix + "/series";
886
+ urlParams = {
887
+ start: start.toISOString(),
888
+ end: end.toISOString()
889
+ };
890
+ if (selector) {
891
+ urlParams['match[]'] = selector;
892
+ }
893
+ if (withLimit !== 'none') {
894
+ urlParams = _extends({}, urlParams, {
895
+ limit: withLimit != null ? withLimit : DEFAULT_SERIES_LIMIT
896
+ });
897
+ }
898
+ request = _this.buildRequest(url, new URLSearchParams(urlParams));
899
+ _context.n = 1;
900
+ return _this.request(request.uri, {
901
+ method: _this.httpMethod,
902
+ body: request.body
903
+ })["catch"](function () {
904
+ return [];
905
+ });
906
+ case 1:
907
+ return _context.a(2, _context.v);
908
+ }
909
+ }, _callee);
910
+ }));
911
+ return function (_x, _x2) {
912
+ return _ref.apply(this, arguments);
913
+ };
914
+ }();
915
+ this.fetchLabels = /*#__PURE__*/function () {
916
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(selector) {
917
+ var end, start, url, urlParams, request;
918
+ return _regenerator().w(function (_context2) {
919
+ while (1) switch (_context2.n) {
920
+ case 0:
921
+ end = new Date();
922
+ start = new Date(end.getTime() - _this.lookbackInterval);
923
+ url = _this.apiPrefix + "/labels";
924
+ urlParams = {
925
+ start: start.toISOString(),
926
+ end: end.toISOString()
927
+ };
928
+ if (selector) {
929
+ urlParams['match[]'] = selector;
930
+ }
931
+ request = _this.buildRequest(url, new URLSearchParams(urlParams));
932
+ _context2.n = 1;
933
+ return _this.request(request.uri, {
934
+ method: _this.httpMethod,
935
+ body: request.body
936
+ }).then(function (res) {
937
+ _this.labelKeys = res;
938
+ return res;
939
+ })["catch"](function () {
940
+ return [];
941
+ });
942
+ case 1:
943
+ return _context2.a(2, _context2.v);
944
+ }
945
+ }, _callee2);
946
+ }));
947
+ return function (_x3) {
948
+ return _ref2.apply(this, arguments);
949
+ };
950
+ }();
951
+ this.fetchLabelValues = /*#__PURE__*/function () {
952
+ var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(labelName, selector) {
953
+ var end, start, url, urlParams, request;
954
+ return _regenerator().w(function (_context3) {
955
+ while (1) switch (_context3.n) {
956
+ case 0:
957
+ end = new Date();
958
+ start = new Date(end.getTime() - _this.lookbackInterval);
959
+ url = _this.apiPrefix + "/label/" + labelName + "/values";
960
+ urlParams = {
961
+ start: start.toISOString(),
962
+ end: end.toISOString()
963
+ };
964
+ if (selector) {
965
+ urlParams['match[]'] = selector;
966
+ }
967
+ request = _this.buildRequest(url, new URLSearchParams(urlParams));
968
+ _context3.n = 1;
969
+ return _this.request(request.uri, {
970
+ method: _this.httpMethod,
971
+ body: request.body
972
+ })["catch"](function () {
973
+ return [];
974
+ });
975
+ case 1:
976
+ return _context3.a(2, _context3.v);
977
+ }
978
+ }, _callee3);
979
+ }));
980
+ return function (_x4, _x5) {
981
+ return _ref3.apply(this, arguments);
982
+ };
983
+ }();
984
+ this.start = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4() {
985
+ var _t;
986
+ return _regenerator().w(function (_context4) {
987
+ while (1) switch (_context4.n) {
988
+ case 0:
989
+ _context4.n = 1;
990
+ return _this.fetchLabelValues('__name__', makeSelector('', [], '__name__'));
991
+ case 1:
992
+ _t = _context4.v;
993
+ if (_t) {
994
+ _context4.n = 2;
995
+ break;
996
+ }
997
+ _t = [];
998
+ case 2:
999
+ _this.metrics = _t;
1000
+ return _context4.a(2, Promise.all([_this.loadMetricsMetadata()]));
1001
+ }
1002
+ }, _callee4);
1003
+ }));
1004
+ this.inputInRange = '';
1005
+ this.metricNamesSuggestionLimit = 1000;
1006
+ this.suggestionsIncomplete = false;
1007
+ this.url = params.url ? params.url : '';
1008
+ this.errorHandler = params.httpErrorHandler;
1009
+ if (params.lookbackInterval) {
1010
+ this.lookbackInterval = params.lookbackInterval;
1011
+ }
1012
+ if (params.variablesNames) {
1013
+ this.variablesNames = [].concat(params.variablesNames);
1014
+ }
1015
+ if (params.request) {
1016
+ this.customRequest = params.request;
1017
+ }
1018
+ if (params.httpMethod) {
1019
+ this.httpMethod = params.httpMethod;
1020
+ }
1021
+ if (params.apiPrefix) {
1022
+ this.apiPrefix = params.apiPrefix;
1023
+ }
1024
+ this.metrics = [];
1025
+ this.labelKeys = [];
1026
+ }
1027
+ var _proto = DataProvider.prototype;
1028
+ _proto.getVariablesNames = function getVariablesNames() {
1029
+ return this.variablesNames;
1030
+ };
1031
+ _proto.setVariablesNames = function setVariablesNames(variablesNames) {
1032
+ this.variablesNames = [].concat(variablesNames);
1033
+ };
1034
+ _proto.buildRequest = function buildRequest(endpoint, params) {
1035
+ var uri = endpoint;
1036
+ var body = params;
1037
+ if (this.httpMethod === 'GET') {
1038
+ uri = uri + "?" + params;
1039
+ body = null;
1040
+ }
1041
+ return {
1042
+ uri: uri,
1043
+ body: body
1044
+ };
1045
+ };
1046
+ _proto.request = function request(resource, init) {
1047
+ var _this2 = this;
1048
+ return this.customRequest(this.url + resource, init).then(function (res) {
1049
+ if (!res.ok && ![badRequest, unprocessableEntity, serviceUnavailable].includes(res.status)) {
1050
+ throw new Error(res.statusText);
1051
+ }
1052
+ return res;
1053
+ }).then(function (res) {
1054
+ return res.json();
1055
+ }).then(function (apiRes) {
1056
+ if (apiRes.status === 'error') {
1057
+ var error = new Error(apiRes.error !== undefined ? apiRes.error : 'missing "error" field in response JSON');
1058
+ if (_this2.errorHandler) {
1059
+ _this2.errorHandler(error);
1060
+ }
1061
+ throw error;
1062
+ }
1063
+ if (apiRes.data === undefined) {
1064
+ var _error = new Error(apiRes.error !== undefined ? apiRes.error : 'missing "data" field in response JSON');
1065
+ if (_this2.errorHandler) {
1066
+ _this2.errorHandler(_error);
1067
+ }
1068
+ throw _error;
1069
+ }
1070
+ return apiRes.data;
1071
+ })["catch"](function (error) {
1072
+ if (_this2.errorHandler) {
1073
+ _this2.errorHandler(error);
1074
+ }
1075
+ throw error;
1076
+ });
1077
+ };
1078
+ _proto.getAllMetricNames = function getAllMetricNames() {
1079
+ return this.metrics;
1080
+ };
1081
+ _proto.loadMetricsMetadata = /*#__PURE__*/function () {
1082
+ var _loadMetricsMetadata = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5() {
1083
+ var request;
1084
+ return _regenerator().w(function (_context5) {
1085
+ while (1) switch (_context5.n) {
1086
+ case 0:
1087
+ request = this.buildRequest(this.apiPrefix + "/metadata", new URLSearchParams({}));
1088
+ _context5.n = 1;
1089
+ return this.request(request.uri, {
1090
+ method: this.httpMethod,
1091
+ body: request.body
1092
+ })["catch"](function () {
1093
+ return {};
1094
+ });
1095
+ case 1:
1096
+ this.metricsMetadata = _context5.v;
1097
+ case 2:
1098
+ return _context5.a(2);
1099
+ }
1100
+ }, _callee5, this);
1101
+ }));
1102
+ function loadMetricsMetadata() {
1103
+ return _loadMetricsMetadata.apply(this, arguments);
1104
+ }
1105
+ return loadMetricsMetadata;
1106
+ }();
1107
+ _proto.metricNamesToMetrics = function metricNamesToMetrics(metricNames) {
1108
+ var _this3 = this;
1109
+ var result = metricNames.map(function (m) {
1110
+ var _this3$metricsMetadat, _metaItem$help, _metaItem$type;
1111
+ var metaItem = (_this3$metricsMetadat = _this3.metricsMetadata) == null ? void 0 : _this3$metricsMetadat[m];
1112
+ return {
1113
+ name: m,
1114
+ help: (_metaItem$help = metaItem == null ? void 0 : metaItem.help) != null ? _metaItem$help : '',
1115
+ type: (_metaItem$type = metaItem == null ? void 0 : metaItem.type) != null ? _metaItem$type : ''
1116
+ };
1117
+ });
1118
+ return result;
1119
+ };
1120
+ _proto.setInputInRange = function setInputInRange(textInput) {
1121
+ this.inputInRange = textInput;
1122
+ };
1123
+ _proto.enableAutocompleteSuggestionsUpdate = function enableAutocompleteSuggestionsUpdate() {
1124
+ this.suggestionsIncomplete = true;
1125
+ dispatchEvent(new CustomEvent(CODE_MODE_SUGGESTIONS_INCOMPLETE_EVENT, {
1126
+ detail: {
1127
+ limit: this.metricNamesSuggestionLimit
1128
+ }
1129
+ }));
1130
+ };
1131
+ return _createClass(DataProvider, [{
1132
+ key: "monacoSettings",
1133
+ get: function get() {
1134
+ return {
1135
+ /**
1136
+ * Enable autocomplete suggestions update on every input change.
1137
+ *
1138
+ * @remarks
1139
+ * If fuzzy search is used in `getCompletions` to trim down results to improve performance,
1140
+ * we need to instruct Monaco to update the completions on every input change, so that the
1141
+ * completions reflect the current input.
1142
+ */
1143
+ enableAutocompleteSuggestionsUpdate: this.enableAutocompleteSuggestionsUpdate.bind(this),
1144
+ inputInRange: this.inputInRange,
1145
+ setInputInRange: this.setInputInRange.bind(this),
1146
+ suggestionsIncomplete: this.suggestionsIncomplete
1147
+ };
1148
+ }
1149
+ }]);
1150
+ }();
1151
+
1152
+ function move(node, direction) {
1153
+ switch (direction) {
1154
+ case 'parent':
1155
+ return node.parent;
1156
+ case 'firstChild':
1157
+ return node.firstChild;
1158
+ case 'lastChild':
1159
+ return node.lastChild;
1160
+ case 'nextSibling':
1161
+ return node.nextSibling;
1162
+ default:
1163
+ throw new NeverCaseError(direction);
1164
+ }
1165
+ }
1166
+ function walk(node, path) {
1167
+ var current = node;
1168
+ for (var _iterator = _createForOfIteratorHelperLoose(path), _step; !(_step = _iterator()).done;) {
1169
+ var _step$value = _step.value,
1170
+ direction = _step$value[0],
1171
+ expectedType = _step$value[1];
1172
+ current = move(current, direction);
1173
+ if (current === null) {
1174
+ // we could not move in the direction, we stop
1175
+ return null;
1176
+ }
1177
+ if (current.type.id !== expectedType) {
1178
+ // the reached node has wrong type, we stop
1179
+ return null;
1180
+ }
1181
+ }
1182
+ return current;
1183
+ }
1184
+ function getNodeText(node, text) {
1185
+ return text.slice(node.from, node.to);
1186
+ }
1187
+ function parsePromQLStringLiteral(text) {
1188
+ // if it is a string-literal, it is inside quotes of some kind
1189
+ var inside = text.slice(1, text.length - 1);
1190
+ // FIXME: support https://prometheus.io/docs/prometheus/latest/querying/basics/#string-literals
1191
+ // FIXME: maybe check other promql code, if all is supported or not
1192
+ // for now we do only some very simple un-escaping
1193
+ // we start with double-quotes
1194
+ if (text.startsWith('"') && text.endsWith('"')) {
1195
+ // NOTE: this is not 100% perfect, we only unescape the double-quote,
1196
+ // there might be other characters too
1197
+ return inside.replace(/\\"/, '"');
1198
+ }
1199
+ // then single-quote
1200
+ if (text.startsWith("'") && text.endsWith("'")) {
1201
+ // NOTE: this is not 100% perfect, we only unescape the single-quote,
1202
+ // there might be other characters too
1203
+ return inside.replace(/\\'/, "'");
1204
+ }
1205
+ // then backticks
1206
+ if (text.startsWith('`') && text.endsWith('`')) {
1207
+ return inside;
1208
+ }
1209
+ throw new Error('FIXME: invalid string literal');
1210
+ }
1211
+ function isPathMatch(resolverPath, cursorPath) {
1212
+ return resolverPath.every(function (item, index) {
1213
+ return item === cursorPath[index];
1214
+ });
1215
+ }
1216
+ var ERROR_NODE_NAME = 0; // this is used as error-id
1217
+ var RESOLVERS = [{
1218
+ path: [LabelMatchers, VectorSelector],
1219
+ fun: resolveLabelKeysWithEquals
1220
+ }, {
1221
+ path: [PromQL],
1222
+ fun: resolveTopLevel
1223
+ }, {
1224
+ path: [FunctionCallBody],
1225
+ fun: resolveInFunction
1226
+ }, {
1227
+ path: [StringLiteral, UnquotedLabelMatcher],
1228
+ fun: resolveLabelMatcher
1229
+ }, {
1230
+ path: [ERROR_NODE_NAME, BinaryExpr, PromQL],
1231
+ fun: resolveTopLevel
1232
+ }, {
1233
+ path: [ERROR_NODE_NAME, UnquotedLabelMatcher],
1234
+ fun: resolveLabelMatcher
1235
+ }, {
1236
+ path: [ERROR_NODE_NAME, NumberDurationLiteralInDurationContext, MatrixSelector],
1237
+ fun: resolveDurations
1238
+ }, {
1239
+ path: [GroupingLabels],
1240
+ fun: resolveLabelsForGrouping
1241
+ }];
1242
+ var LABEL_OP_MAP = /*#__PURE__*/new Map([[EqlSingle, '='], [EqlRegex, '=~'], [Neq, '!='], [NeqRegex, '!~']]);
1243
+ function getLabelOp(opNode) {
1244
+ var _LABEL_OP_MAP$get;
1245
+ var opChild = opNode.firstChild;
1246
+ if (opChild === null) {
1247
+ return null;
1248
+ }
1249
+ return (_LABEL_OP_MAP$get = LABEL_OP_MAP.get(opChild.type.id)) != null ? _LABEL_OP_MAP$get : null;
1250
+ }
1251
+ function getLabel(labelMatcherNode, text) {
1252
+ if (labelMatcherNode.type.id !== UnquotedLabelMatcher) {
1253
+ return null;
1254
+ }
1255
+ var nameNode = walk(labelMatcherNode, [['firstChild', LabelName]]);
1256
+ if (nameNode === null) {
1257
+ return null;
1258
+ }
1259
+ var opNode = walk(nameNode, [['nextSibling', MatchOp]]);
1260
+ if (opNode === null) {
1261
+ return null;
1262
+ }
1263
+ var op = getLabelOp(opNode);
1264
+ if (op === null) {
1265
+ return null;
1266
+ }
1267
+ var valueNode = walk(labelMatcherNode, [['lastChild', StringLiteral]]);
1268
+ if (valueNode === null) {
1269
+ return null;
1270
+ }
1271
+ var name = getNodeText(nameNode, text);
1272
+ var value = parsePromQLStringLiteral(getNodeText(valueNode, text));
1273
+ return {
1274
+ name: name,
1275
+ value: value,
1276
+ op: op
1277
+ };
1278
+ }
1279
+ function getLabels(labelMatchersNode, text) {
1280
+ if (labelMatchersNode.type.id !== LabelMatchers) {
1281
+ return [];
1282
+ }
1283
+ var labelNodes = labelMatchersNode.getChildren(UnquotedLabelMatcher);
1284
+ return labelNodes.map(function (ln) {
1285
+ return getLabel(ln, text);
1286
+ }).filter(notEmpty);
1287
+ }
1288
+ function getNodeChildren(node) {
1289
+ var child = node.firstChild;
1290
+ var children = [];
1291
+ while (child !== null) {
1292
+ children.push(child);
1293
+ child = child.nextSibling;
1294
+ }
1295
+ return children;
1296
+ }
1297
+ function getNodeInSubtree(node, typeId) {
1298
+ // first we try the current node
1299
+ if (node.type.id === typeId) {
1300
+ return node;
1301
+ }
1302
+ // then we try the children
1303
+ var children = getNodeChildren(node);
1304
+ for (var _iterator2 = _createForOfIteratorHelperLoose(children), _step2; !(_step2 = _iterator2()).done;) {
1305
+ var child = _step2.value;
1306
+ var n = getNodeInSubtree(child, typeId);
1307
+ if (n !== null) {
1308
+ return n;
1309
+ }
1310
+ }
1311
+ return null;
1312
+ }
1313
+ function resolveLabelsForGrouping(node, text, _pos) {
1314
+ var aggrExpNode = walk(node, [['parent', AggregateModifier], ['parent', AggregateExpr]]);
1315
+ if (aggrExpNode === null) {
1316
+ return null;
1317
+ }
1318
+ var bodyNode = aggrExpNode.getChild(FunctionCallBody);
1319
+ if (bodyNode === null) {
1320
+ return null;
1321
+ }
1322
+ var metricIdNode = getNodeInSubtree(bodyNode, Identifier);
1323
+ if (metricIdNode === null) {
1324
+ return null;
1325
+ }
1326
+ var metricName = getNodeText(metricIdNode, text);
1327
+ return {
1328
+ type: 'IN_GROUPING',
1329
+ metricName: metricName,
1330
+ otherLabels: []
1331
+ };
1332
+ }
1333
+ function resolveLabelMatcher(node, text, _pos) {
1334
+ // we can arrive here in two situation. `node` is either:
1335
+ // - a StringNode (like in `{job="^"}`)
1336
+ // - or an error node (like in `{job=^}`)
1337
+ var inStringNode = !node.type.isError;
1338
+ var parent = walk(node, [['parent', UnquotedLabelMatcher]]);
1339
+ if (parent === null) {
1340
+ return null;
1341
+ }
1342
+ var labelNameNode = walk(parent, [['firstChild', LabelName]]);
1343
+ if (labelNameNode === null) {
1344
+ return null;
1345
+ }
1346
+ var labelName = getNodeText(labelNameNode, text);
1347
+ var labelMatchersNode = walk(parent, [['parent', LabelMatchers]]);
1348
+ if (labelMatchersNode === null) {
1349
+ return null;
1350
+ }
1351
+ // now we need to find the other names
1352
+ var allLabels = getLabels(labelMatchersNode, text);
1353
+ // we need to remove "our" label from all-labels, if it is in there
1354
+ var otherLabels = allLabels.filter(function (label) {
1355
+ return label.name !== labelName;
1356
+ });
1357
+ var metricNameNode = walk(labelMatchersNode, [['parent', VectorSelector], ['firstChild', Identifier]]);
1358
+ if (metricNameNode === null) {
1359
+ // we are probably in a situation without a metric name
1360
+ return {
1361
+ type: 'IN_LABEL_SELECTOR_WITH_LABEL_NAME',
1362
+ labelName: labelName,
1363
+ betweenQuotes: inStringNode,
1364
+ otherLabels: otherLabels
1365
+ };
1366
+ }
1367
+ var metricName = getNodeText(metricNameNode, text);
1368
+ return {
1369
+ type: 'IN_LABEL_SELECTOR_WITH_LABEL_NAME',
1370
+ metricName: metricName,
1371
+ labelName: labelName,
1372
+ betweenQuotes: inStringNode,
1373
+ otherLabels: otherLabels
1374
+ };
1375
+ }
1376
+ function resolveTopLevel() {
1377
+ return {
1378
+ type: 'AT_ROOT'
1379
+ };
1380
+ }
1381
+ function resolveInFunction() {
1382
+ return {
1383
+ type: 'IN_FUNCTION'
1384
+ };
1385
+ }
1386
+ function resolveDurations() {
1387
+ return {
1388
+ type: 'IN_DURATION'
1389
+ };
1390
+ }
1391
+ function resolveLabelKeysWithEquals(node, text, pos) {
1392
+ // next false positive:
1393
+ // `something{a="1"^}`
1394
+ var child = walk(node, [['firstChild', UnquotedLabelMatcher]]);
1395
+ if (child !== null) {
1396
+ // means the label-matching part contains at least one label already.
1397
+ //
1398
+ // in this case, we will need to have a `,` character at the end,
1399
+ // to be able to suggest adding the next label.
1400
+ // the area between the end-of-the-child-node and the cursor-pos
1401
+ // must contain a `,` in this case.
1402
+ var textToCheck = text.slice(child.to, pos);
1403
+ if (!textToCheck.includes(',')) {
1404
+ return null;
1405
+ }
1406
+ }
1407
+ var metricNameNode = walk(node, [['parent', VectorSelector], ['firstChild', Identifier]]);
1408
+ var otherLabels = getLabels(node, text);
1409
+ if (metricNameNode === null) {
1410
+ // we are probably in a situation without a metric name.
1411
+ return {
1412
+ type: 'IN_LABEL_SELECTOR_NO_LABEL_NAME',
1413
+ otherLabels: otherLabels
1414
+ };
1415
+ }
1416
+ var metricName = getNodeText(metricNameNode, text);
1417
+ return {
1418
+ type: 'IN_LABEL_SELECTOR_NO_LABEL_NAME',
1419
+ metricName: metricName,
1420
+ otherLabels: otherLabels
1421
+ };
1422
+ }
1423
+ // we find the first error-node in the tree that is at the cursor-position.
1424
+ // NOTE: this might be too slow, might need to optimize it
1425
+ // (ideas: we do not need to go into every subtree, based on from/to)
1426
+ // also, only go to places that are in the sub-tree of the node found
1427
+ // by default by lezer. problem is, `next()` will go upward too,
1428
+ // and we do not want to go higher than our node
1429
+ function getErrorNode(tree, pos) {
1430
+ var cur = tree.cursorAt(pos);
1431
+ while (true) {
1432
+ if (cur.from === pos && cur.to === pos) {
1433
+ var node = cur.node;
1434
+ if (node.type.isError) {
1435
+ return node;
1436
+ }
1437
+ }
1438
+ if (!cur.next()) {
1439
+ break;
1440
+ }
1441
+ }
1442
+ return null;
1443
+ }
1444
+ function getSituation(text, pos) {
1445
+ // there is a special-case when we are at the start of writing text,
1446
+ // so we handle that case first
1447
+ if (text === '') {
1448
+ return {
1449
+ type: 'EMPTY'
1450
+ };
1451
+ }
1452
+ /**
1453
+ PromQL
1454
+ Expr
1455
+ VectorSelector
1456
+ LabelMatchers
1457
+ */
1458
+ var tree = parser.parse(text);
1459
+ // if the tree contains error, it is very probable that
1460
+ // our node is one of those error-nodes.
1461
+ // also, if there are errors, the node lezer finds us,
1462
+ // might not be the best node.
1463
+ // so first we check if there is an error-node at the cursor-position
1464
+ var maybeErrorNode = getErrorNode(tree, pos);
1465
+ var cur = maybeErrorNode != null ? maybeErrorNode.cursor() : tree.cursorAt(pos);
1466
+ var currentNode = cur.node;
1467
+ var ids = [cur.type.id];
1468
+ while (cur.parent()) {
1469
+ ids.push(cur.type.id);
1470
+ }
1471
+ for (var _iterator3 = _createForOfIteratorHelperLoose(RESOLVERS), _step3; !(_step3 = _iterator3()).done;) {
1472
+ var resolver = _step3.value;
1473
+ // i do not use a foreach because i want to stop as soon
1474
+ // as i find something
1475
+ if (isPathMatch(resolver.path, ids)) {
1476
+ return resolver.fun(currentNode, text, pos);
1477
+ }
1478
+ }
1479
+ return null;
1480
+ }
1481
+ function notEmpty(value) {
1482
+ return value !== null && value !== undefined;
1483
+ }
1484
+
1485
+ var metricNamesSearchClient = /*#__PURE__*/new UFuzzy({
1486
+ intraMode: 1
1487
+ });
1488
+ // we order items like: history, functions, metrics
1489
+ function getAllMetricNamesCompletions(dataProvider) {
1490
+ var metricNames = dataProvider.getAllMetricNames();
1491
+ if (metricNames.length > dataProvider.metricNamesSuggestionLimit) {
1492
+ var monacoSettings = dataProvider.monacoSettings;
1493
+ monacoSettings.enableAutocompleteSuggestionsUpdate();
1494
+ if (monacoSettings.inputInRange) {
1495
+ var _metricNamesSearchCli, _metricNamesSearchCli2;
1496
+ metricNames = (_metricNamesSearchCli = (_metricNamesSearchCli2 = metricNamesSearchClient.filter(metricNames, monacoSettings.inputInRange)) == null ? void 0 : _metricNamesSearchCli2.slice(0, dataProvider.metricNamesSuggestionLimit).map(function (idx) {
1497
+ return metricNames[idx];
1498
+ })) != null ? _metricNamesSearchCli : [];
1499
+ } else {
1500
+ metricNames = metricNames.slice(0, dataProvider.metricNamesSuggestionLimit);
1501
+ }
1502
+ }
1503
+ return dataProvider.metricNamesToMetrics(metricNames).map(function (metric) {
1504
+ return {
1505
+ type: 'METRIC_NAME',
1506
+ label: metric.name,
1507
+ insertText: metric.name,
1508
+ detail: metric.name + " : " + metric.type,
1509
+ documentation: metric.help
1510
+ };
1511
+ });
1512
+ }
1513
+ var FUNCTION_COMPLETIONS = /*#__PURE__*/FUNCTIONS.map(function (f) {
1514
+ var _f$insertText;
1515
+ return {
1516
+ type: 'FUNCTION',
1517
+ label: f.label,
1518
+ insertText: (_f$insertText = f.insertText) != null ? _f$insertText : '',
1519
+ detail: f.detail,
1520
+ documentation: f.documentation
1521
+ };
1522
+ });
1523
+ function getAllFunctionsAndMetricNamesCompletions(_x) {
1524
+ return _getAllFunctionsAndMetricNamesCompletions.apply(this, arguments);
1525
+ }
1526
+ function _getAllFunctionsAndMetricNamesCompletions() {
1527
+ _getAllFunctionsAndMetricNamesCompletions = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(dataProvider) {
1528
+ var metricNames;
1529
+ return _regenerator().w(function (_context) {
1530
+ while (1) switch (_context.n) {
1531
+ case 0:
1532
+ metricNames = getAllMetricNamesCompletions(dataProvider);
1533
+ return _context.a(2, [].concat(FUNCTION_COMPLETIONS, metricNames));
1534
+ }
1535
+ }, _callee);
1536
+ }));
1537
+ return _getAllFunctionsAndMetricNamesCompletions.apply(this, arguments);
1538
+ }
1539
+ var DURATION_COMPLETIONS = /*#__PURE__*/['$__interval', '$__range', '$__rate_interval', '1m', '5m', '10m', '30m', '1h', '1d'].map(function (text) {
1540
+ return {
1541
+ type: 'DURATION',
1542
+ label: text,
1543
+ insertText: text
1544
+ };
1545
+ });
1546
+ function getAllHistoryCompletions(_dataProvider) {
1547
+ return [];
1548
+ // function getAllHistoryCompletions(queryHistory: PromHistoryItem[]): Completion[] {
1549
+ // NOTE: the typescript types are wrong. historyItem.query.expr can be undefined
1550
+ // const allHistory = dataProvider.getHistory();
1551
+ // FIXME: find a better history-limit
1552
+ // return allHistory.slice(0, 10).map((expr) => ({
1553
+ // type: 'HISTORY',
1554
+ // label: expr,
1555
+ // insertText: expr,
1556
+ // }));
1557
+ }
1558
+ function getLabelNames(_x2, _x3, _x4) {
1559
+ return _getLabelNames.apply(this, arguments);
1560
+ }
1561
+ function _getLabelNames() {
1562
+ _getLabelNames = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(metric, otherLabels, dataProvider) {
1563
+ var selector, _selector, series, labelNames, _iterator, _step, labelSet, _i, _Object$entries, _Object$entries$_i, key;
1564
+ return _regenerator().w(function (_context2) {
1565
+ while (1) switch (_context2.n) {
1566
+ case 0:
1567
+ if (!(metric === undefined || metric === '')) {
1568
+ _context2.n = 2;
1569
+ break;
1570
+ }
1571
+ selector = makeSelector('', otherLabels);
1572
+ _context2.n = 1;
1573
+ return dataProvider.fetchLabels(selector);
1574
+ case 1:
1575
+ return _context2.a(2, _context2.v);
1576
+ case 2:
1577
+ _selector = makeSelector(metric, otherLabels);
1578
+ _context2.n = 3;
1579
+ return dataProvider.fetchSeries(_selector);
1580
+ case 3:
1581
+ series = _context2.v;
1582
+ labelNames = new Set();
1583
+ _iterator = _createForOfIteratorHelperLoose(series);
1584
+ case 4:
1585
+ if ((_step = _iterator()).done) {
1586
+ _context2.n = 9;
1587
+ break;
1588
+ }
1589
+ labelSet = _step.value;
1590
+ _i = 0, _Object$entries = Object.entries(labelSet);
1591
+ case 5:
1592
+ if (!(_i < _Object$entries.length)) {
1593
+ _context2.n = 8;
1594
+ break;
1595
+ }
1596
+ _Object$entries$_i = _Object$entries[_i], key = _Object$entries$_i[0];
1597
+ if (!(key === '__name__')) {
1598
+ _context2.n = 6;
1599
+ break;
1600
+ }
1601
+ return _context2.a(3, 7);
1602
+ case 6:
1603
+ labelNames.add(key);
1604
+ case 7:
1605
+ _i++;
1606
+ _context2.n = 5;
1607
+ break;
1608
+ case 8:
1609
+ _context2.n = 4;
1610
+ break;
1611
+ case 9:
1612
+ return _context2.a(2, Array.from(labelNames));
1613
+ case 10:
1614
+ return _context2.a(2);
1615
+ }
1616
+ }, _callee2);
1617
+ }));
1618
+ return _getLabelNames.apply(this, arguments);
1619
+ }
1620
+ function getLabelNamesForCompletions(_x5, _x6, _x7, _x8, _x9) {
1621
+ return _getLabelNamesForCompletions.apply(this, arguments);
1622
+ }
1623
+ function _getLabelNamesForCompletions() {
1624
+ _getLabelNamesForCompletions = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(metric, suffix, triggerOnInsert, otherLabels, dataProvider) {
1625
+ var labelNames;
1626
+ return _regenerator().w(function (_context3) {
1627
+ while (1) switch (_context3.n) {
1628
+ case 0:
1629
+ _context3.n = 1;
1630
+ return getLabelNames(metric, otherLabels, dataProvider);
1631
+ case 1:
1632
+ labelNames = _context3.v;
1633
+ return _context3.a(2, labelNames.map(function (text) {
1634
+ return {
1635
+ type: 'LABEL_NAME',
1636
+ label: text,
1637
+ insertText: "" + text + suffix,
1638
+ triggerOnInsert: triggerOnInsert
1639
+ };
1640
+ }));
1641
+ }
1642
+ }, _callee3);
1643
+ }));
1644
+ return _getLabelNamesForCompletions.apply(this, arguments);
1645
+ }
1646
+ function getLabelNamesForSelectorCompletions(_x0, _x1, _x10) {
1647
+ return _getLabelNamesForSelectorCompletions.apply(this, arguments);
1648
+ }
1649
+ function _getLabelNamesForSelectorCompletions() {
1650
+ _getLabelNamesForSelectorCompletions = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(metric, otherLabels, dataProvider) {
1651
+ return _regenerator().w(function (_context4) {
1652
+ while (1) switch (_context4.n) {
1653
+ case 0:
1654
+ return _context4.a(2, getLabelNamesForCompletions(metric, '=', true, otherLabels, dataProvider));
1655
+ }
1656
+ }, _callee4);
1657
+ }));
1658
+ return _getLabelNamesForSelectorCompletions.apply(this, arguments);
1659
+ }
1660
+ function getLabelNamesForByCompletions(_x11, _x12, _x13) {
1661
+ return _getLabelNamesForByCompletions.apply(this, arguments);
1662
+ }
1663
+ function _getLabelNamesForByCompletions() {
1664
+ _getLabelNamesForByCompletions = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(metric, otherLabels, dataProvider) {
1665
+ return _regenerator().w(function (_context5) {
1666
+ while (1) switch (_context5.n) {
1667
+ case 0:
1668
+ return _context5.a(2, getLabelNamesForCompletions(metric, '', false, otherLabels, dataProvider));
1669
+ }
1670
+ }, _callee5);
1671
+ }));
1672
+ return _getLabelNamesForByCompletions.apply(this, arguments);
1673
+ }
1674
+ function getLabelValues(_x14, _x15, _x16, _x17) {
1675
+ return _getLabelValues.apply(this, arguments);
1676
+ }
1677
+ function _getLabelValues() {
1678
+ _getLabelValues = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(metric, labelName, otherLabels, dataProvider) {
1679
+ var selector, _selector2, series, labelValues, _iterator2, _step2, labelSet, _i2, _Object$entries2, _Object$entries2$_i, key, value, variablesNames;
1680
+ return _regenerator().w(function (_context6) {
1681
+ while (1) switch (_context6.n) {
1682
+ case 0:
1683
+ if (!(metric === undefined || metric === '')) {
1684
+ _context6.n = 2;
1685
+ break;
1686
+ }
1687
+ selector = makeSelector('', otherLabels);
1688
+ _context6.n = 1;
1689
+ return dataProvider.fetchLabelValues(labelName, selector);
1690
+ case 1:
1691
+ return _context6.a(2, _context6.v);
1692
+ case 2:
1693
+ _selector2 = makeSelector(metric, otherLabels, labelName);
1694
+ _context6.n = 3;
1695
+ return dataProvider.fetchSeries(_selector2);
1696
+ case 3:
1697
+ series = _context6.v;
1698
+ labelValues = new Set();
1699
+ _iterator2 = _createForOfIteratorHelperLoose(series);
1700
+ case 4:
1701
+ if ((_step2 = _iterator2()).done) {
1702
+ _context6.n = 9;
1703
+ break;
1704
+ }
1705
+ labelSet = _step2.value;
1706
+ _i2 = 0, _Object$entries2 = Object.entries(labelSet);
1707
+ case 5:
1708
+ if (!(_i2 < _Object$entries2.length)) {
1709
+ _context6.n = 8;
1710
+ break;
1711
+ }
1712
+ _Object$entries2$_i = _Object$entries2[_i2], key = _Object$entries2$_i[0], value = _Object$entries2$_i[1];
1713
+ if (!(key === '__name__')) {
1714
+ _context6.n = 6;
1715
+ break;
1716
+ }
1717
+ return _context6.a(3, 7);
1718
+ case 6:
1719
+ if (key === labelName) {
1720
+ labelValues.add(value);
1721
+ }
1722
+ case 7:
1723
+ _i2++;
1724
+ _context6.n = 5;
1725
+ break;
1726
+ case 8:
1727
+ _context6.n = 4;
1728
+ break;
1729
+ case 9:
1730
+ variablesNames = dataProvider.getVariablesNames();
1731
+ return _context6.a(2, variablesNames.concat(Array.from(labelValues)));
1732
+ case 10:
1733
+ return _context6.a(2);
1734
+ }
1735
+ }, _callee6);
1736
+ }));
1737
+ return _getLabelValues.apply(this, arguments);
1738
+ }
1739
+ function getLabelValuesForMetricCompletions(_x18, _x19, _x20, _x21, _x22) {
1740
+ return _getLabelValuesForMetricCompletions.apply(this, arguments);
1741
+ }
1742
+ function _getLabelValuesForMetricCompletions() {
1743
+ _getLabelValuesForMetricCompletions = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(metric, labelName, betweenQuotes, otherLabels, dataProvider) {
1744
+ var values;
1745
+ return _regenerator().w(function (_context7) {
1746
+ while (1) switch (_context7.n) {
1747
+ case 0:
1748
+ _context7.n = 1;
1749
+ return getLabelValues(metric, labelName, otherLabels, dataProvider);
1750
+ case 1:
1751
+ values = _context7.v;
1752
+ return _context7.a(2, values.map(function (text) {
1753
+ return {
1754
+ type: 'LABEL_VALUE',
1755
+ label: text,
1756
+ insertText: betweenQuotes ? text : "\"" + text + "\""
1757
+ };
1758
+ }));
1759
+ }
1760
+ }, _callee7);
1761
+ }));
1762
+ return _getLabelValuesForMetricCompletions.apply(this, arguments);
1763
+ }
1764
+ function getCompletions(situation, dataProvider) {
1765
+ switch (situation.type) {
1766
+ case 'IN_DURATION':
1767
+ return Promise.resolve(DURATION_COMPLETIONS);
1768
+ case 'IN_FUNCTION':
1769
+ return getAllFunctionsAndMetricNamesCompletions(dataProvider);
1770
+ case 'AT_ROOT':
1771
+ {
1772
+ return getAllFunctionsAndMetricNamesCompletions(dataProvider);
1773
+ }
1774
+ case 'EMPTY':
1775
+ {
1776
+ var metricNames = getAllMetricNamesCompletions(dataProvider);
1777
+ var historyCompletions = getAllHistoryCompletions();
1778
+ return Promise.resolve([].concat(historyCompletions, FUNCTION_COMPLETIONS, metricNames));
1779
+ }
1780
+ case 'IN_LABEL_SELECTOR_NO_LABEL_NAME':
1781
+ return getLabelNamesForSelectorCompletions(situation.metricName, situation.otherLabels, dataProvider);
1782
+ case 'IN_GROUPING':
1783
+ return getLabelNamesForByCompletions(situation.metricName, situation.otherLabels, dataProvider);
1784
+ case 'IN_LABEL_SELECTOR_WITH_LABEL_NAME':
1785
+ return getLabelValuesForMetricCompletions(situation.metricName, situation.labelName, situation.betweenQuotes, situation.otherLabels, dataProvider);
1786
+ default:
1787
+ throw new NeverCaseError(situation);
1788
+ }
1789
+ }
1790
+
1791
+ function getMonacoCompletionItemKind(type, monaco) {
1792
+ switch (type) {
1793
+ case 'DURATION':
1794
+ return monaco.languages.CompletionItemKind.Unit;
1795
+ case 'FUNCTION':
1796
+ return monaco.languages.CompletionItemKind.Variable;
1797
+ case 'HISTORY':
1798
+ return monaco.languages.CompletionItemKind.Snippet;
1799
+ case 'LABEL_NAME':
1800
+ return monaco.languages.CompletionItemKind.Enum;
1801
+ case 'LABEL_VALUE':
1802
+ return monaco.languages.CompletionItemKind.EnumMember;
1803
+ case 'METRIC_NAME':
1804
+ return monaco.languages.CompletionItemKind.Constructor;
1805
+ default:
1806
+ throw new NeverCaseError(type);
1807
+ }
1808
+ }
1809
+ function getCompletionProvider(monaco, dataProvider) {
1810
+ var provideCompletionItems = function provideCompletionItems(model, position) {
1811
+ var word = model.getWordAtPosition(position);
1812
+ var range = word != null ? monaco.Range.lift({
1813
+ startLineNumber: position.lineNumber,
1814
+ endLineNumber: position.lineNumber,
1815
+ startColumn: word.startColumn,
1816
+ endColumn: word.endColumn
1817
+ }) : monaco.Range.fromPositions(position);
1818
+ // documentation says `position` will be "adjusted" in `getOffsetAt`
1819
+ // i don't know what that means, to be sure i clone it
1820
+ var positionClone = {
1821
+ column: position.column,
1822
+ lineNumber: position.lineNumber
1823
+ };
1824
+ dataProvider.monacoSettings.setInputInRange(model.getValueInRange(range));
1825
+ // Check to see if the browser supports window.getSelection()
1826
+ if (window.getSelection) {
1827
+ var _window$getSelection;
1828
+ var selectedText = (_window$getSelection = window.getSelection()) == null ? void 0 : _window$getSelection.toString();
1829
+ // If the user has selected text, adjust the cursor position to be at the start of the selection, instead of the end
1830
+ if (selectedText && selectedText.length > 0) {
1831
+ positionClone.column = positionClone.column - selectedText.length;
1832
+ }
1833
+ }
1834
+ var offset = model.getOffsetAt(positionClone);
1835
+ var situation = getSituation(model.getValue(), offset);
1836
+ var completionsPromise = situation != null ? getCompletions(situation, dataProvider) : Promise.resolve([]);
1837
+ return completionsPromise.then(function (items) {
1838
+ // monaco by-default alphabetically orders the items.
1839
+ // to stop it, we use a number-as-string sortkey,
1840
+ // so that monaco keeps the order we use
1841
+ var maxIndexDigits = items.length.toString().length;
1842
+ var suggestions = items.map(function (item, index) {
1843
+ return {
1844
+ kind: getMonacoCompletionItemKind(item.type, monaco),
1845
+ label: item.label,
1846
+ insertText: item.insertText,
1847
+ detail: item.detail,
1848
+ documentation: item.documentation,
1849
+ sortText: index.toString().padStart(maxIndexDigits, '0'),
1850
+ range: range,
1851
+ command: item.triggerOnInsert ? {
1852
+ id: 'editor.action.triggerSuggest',
1853
+ title: ''
1854
+ } : undefined
1855
+ };
1856
+ });
1857
+ return {
1858
+ suggestions: suggestions,
1859
+ incomplete: dataProvider.monacoSettings.suggestionsIncomplete
1860
+ };
1861
+ });
1862
+ };
1863
+ return {
1864
+ triggerCharacters: ['{', ',', '[', '(', '=', '~', ' ', '"'],
1865
+ provideCompletionItems: provideCompletionItems
1866
+ };
1867
+ }
1868
+
1869
+ var ErrorId = 0;
1870
+ function validateQuery(query, interpolatedQuery, queryLines, parser) {
1871
+ if (!query) {
1872
+ return false;
1873
+ }
1874
+ var interpolatedErrors = parseQuery(interpolatedQuery, parser);
1875
+ if (!interpolatedErrors.length) {
1876
+ return false;
1877
+ }
1878
+ var parseErrors = interpolatedErrors;
1879
+ if (query !== interpolatedQuery) {
1880
+ var queryErrors = parseQuery(query, parser);
1881
+ parseErrors = interpolatedErrors.flatMap(function (interpolatedError) {
1882
+ return queryErrors.filter(function (queryError) {
1883
+ return interpolatedError.text === queryError.text;
1884
+ }) || interpolatedError;
1885
+ });
1886
+ }
1887
+ return parseErrors.map(function (parseError) {
1888
+ return findErrorBoundary(query, queryLines, parseError);
1889
+ }).filter(isErrorBoundary);
1890
+ }
1891
+ function parseQuery(query, parser) {
1892
+ var parseErrors = [];
1893
+ var tree = parser.parse(query);
1894
+ tree.iterate({
1895
+ enter: function enter(nodeRef) {
1896
+ if (nodeRef.type.id === ErrorId) {
1897
+ var node = nodeRef.node;
1898
+ parseErrors.push({
1899
+ node: node,
1900
+ text: query.substring(node.from, node.to)
1901
+ });
1902
+ }
1903
+ }
1904
+ });
1905
+ return parseErrors;
1906
+ }
1907
+ function findErrorBoundary(query, queryLines, parseError) {
1908
+ if (queryLines.length === 1) {
1909
+ var isEmptyString = parseError.node.from === parseError.node.to;
1910
+ var errorNode = isEmptyString && parseError.node.parent ? parseError.node.parent : parseError.node;
1911
+ var error = isEmptyString ? query.substring(errorNode.from, errorNode.to) : parseError.text;
1912
+ return {
1913
+ startLineNumber: 1,
1914
+ startColumn: errorNode.from + 1,
1915
+ endLineNumber: 1,
1916
+ endColumn: errorNode.to + 1,
1917
+ error: error
1918
+ };
1919
+ }
1920
+ var startPos = 0,
1921
+ endPos = 0;
1922
+ for (var line = 0; line < queryLines.length; line++) {
1923
+ endPos = startPos + queryLines[line].length;
1924
+ if (parseError.node.from > endPos) {
1925
+ startPos += queryLines[line].length + 1;
1926
+ continue;
1927
+ }
1928
+ return {
1929
+ startLineNumber: line + 1,
1930
+ startColumn: parseError.node.from - startPos + 1,
1931
+ endLineNumber: line + 1,
1932
+ endColumn: parseError.node.to - startPos + 1,
1933
+ error: parseError.text
1934
+ };
1935
+ }
1936
+ return null;
1937
+ }
1938
+ function isErrorBoundary(boundary) {
1939
+ return boundary !== null;
1940
+ }
1941
+
1942
+ var _excluded = ["error"];
1943
+ var PROMQL_LANG_ID = promLanguageDefinition.id;
1944
+ var EDITOR_HEIGHT_OFFSET = 2;
1945
+ var SIZE_MAP = {
1946
+ small: {
1947
+ className: 'ant-input-sm',
1948
+ top: 1,
1949
+ bottom: 1
1950
+ },
1951
+ middle: {
1952
+ className: 'ant-input-md',
1953
+ top: 1,
1954
+ bottom: 1
1955
+ },
1956
+ large: {
1957
+ className: 'ant-input-lg',
1958
+ top: 3,
1959
+ bottom: 2
1960
+ }
1961
+ };
1962
+ var themeMap = {
1963
+ light: 'vs-light',
1964
+ dark: 'vs-dark'
1965
+ };
1966
+ var getStyles = function getStyles(placeholder) {
1967
+ return {
1968
+ placeholder: css({
1969
+ '::after': {
1970
+ content: "'" + placeholder + "'",
1971
+ opacity: 0.6
1972
+ }
1973
+ })
1974
+ };
1975
+ };
1976
+ function PromQLEditor(props) {
1977
+ var id = v4();
1978
+ var _props$size = props.size,
1979
+ size = _props$size === void 0 ? 'middle' : _props$size,
1980
+ _props$theme = props.theme,
1981
+ theme = _props$theme === void 0 ? 'light' : _props$theme,
1982
+ variablesNames = props.variablesNames,
1983
+ value = props.value,
1984
+ placeholder = props.placeholder,
1985
+ interpolateString = props.interpolateString,
1986
+ onChange = props.onChange,
1987
+ onShiftEnter = props.onShiftEnter,
1988
+ onBlur = props.onBlur;
1989
+ var autocompleteDisposeFun = useRef(null);
1990
+ var containerRef = useRef(null);
1991
+ var dataProviderRef = useRef(null);
1992
+ var styles = getStyles(placeholder);
1993
+ useEffect(function () {
1994
+ // 注册 PromQL 语言
1995
+ var aliases = promLanguageDefinition.aliases,
1996
+ extensions = promLanguageDefinition.extensions,
1997
+ mimetypes = promLanguageDefinition.mimetypes;
1998
+ languages.register({
1999
+ id: PROMQL_LANG_ID,
2000
+ aliases: aliases,
2001
+ extensions: extensions,
2002
+ mimetypes: mimetypes
2003
+ });
2004
+ // 设置语法高亮
2005
+ languages.setMonarchTokensProvider(PROMQL_LANG_ID, language);
2006
+ // 设置语言配置
2007
+ languages.setLanguageConfiguration(PROMQL_LANG_ID, languageConfiguration);
2008
+ return function () {
2009
+ autocompleteDisposeFun.current == null || autocompleteDisposeFun.current();
2010
+ };
2011
+ }, []);
2012
+ var handleEditorDidMount = function handleEditorDidMount(editor$1) {
2013
+ var isEditorFocused = editor$1.createContextKey('isEditorFocused' + id, false);
2014
+ // we setup on-blur
2015
+ editor$1.onDidBlurEditorWidget(function () {
2016
+ isEditorFocused.set(false);
2017
+ onBlur == null || onBlur(editor$1.getValue());
2018
+ });
2019
+ editor$1.onDidFocusEditorText(function () {
2020
+ isEditorFocused.set(true);
2021
+ });
2022
+ var dataProvider = new DataProvider({
2023
+ url: props.url,
2024
+ lookbackInterval: props.lookbackInterval,
2025
+ variablesNames: props.variablesNames,
2026
+ request: props.request,
2027
+ httpMethod: props.httpMethod,
2028
+ apiPrefix: props.apiPrefix,
2029
+ httpErrorHandler: props.httpErrorHandler
2030
+ });
2031
+ dataProviderRef.current = dataProvider;
2032
+ dataProvider.start();
2033
+ var completionProvider = getCompletionProvider(monaco, dataProvider);
2034
+ var filteringCompletionProvider = _extends({}, completionProvider, {
2035
+ provideCompletionItems: function provideCompletionItems(model, position, context, token) {
2036
+ var _editor$getModel;
2037
+ if (((_editor$getModel = editor$1.getModel()) == null ? void 0 : _editor$getModel.id) !== model.id) {
2038
+ return {
2039
+ suggestions: []
2040
+ };
2041
+ }
2042
+ return completionProvider.provideCompletionItems(model, position, context, token);
2043
+ }
2044
+ });
2045
+ var _monaco$languages$reg = languages.registerCompletionItemProvider(PROMQL_LANG_ID, filteringCompletionProvider),
2046
+ dispose = _monaco$languages$reg.dispose;
2047
+ autocompleteDisposeFun.current = dispose;
2048
+ var updateElementHeight = function updateElementHeight() {
2049
+ var containerDiv = containerRef.current;
2050
+ if (containerDiv !== null) {
2051
+ var pixelHeight = editor$1.getContentHeight();
2052
+ containerDiv.style.height = pixelHeight + EDITOR_HEIGHT_OFFSET + "px";
2053
+ containerDiv.style.width = '100%';
2054
+ var pixelWidth = containerDiv.clientWidth;
2055
+ editor$1.layout({
2056
+ width: pixelWidth,
2057
+ height: pixelHeight
2058
+ });
2059
+ }
2060
+ };
2061
+ editor$1.onDidContentSizeChange(updateElementHeight);
2062
+ updateElementHeight();
2063
+ // Fixes Monaco capturing the search key binding and displaying a useless search box within the Editor.
2064
+ editor.addKeybindingRule({
2065
+ keybinding: KeyMod.CtrlCmd | KeyCode.KeyF,
2066
+ command: null
2067
+ });
2068
+ // handle: shift + enter
2069
+ editor$1.addCommand(KeyMod.Shift | KeyCode.Enter, function () {
2070
+ console.log(22222);
2071
+ onShiftEnter == null || onShiftEnter(editor$1.getValue());
2072
+ }, 'isEditorFocused' + id);
2073
+ if (placeholder) {
2074
+ var placeholderDecorators = [{
2075
+ range: new Range(1, 1, 1, 1),
2076
+ options: {
2077
+ className: styles.placeholder,
2078
+ isWholeLine: true
2079
+ }
2080
+ }];
2081
+ var decorators = [];
2082
+ var checkDecorators = function checkDecorators() {
2083
+ var model = editor$1.getModel();
2084
+ if (!model) {
2085
+ return;
2086
+ }
2087
+ var newDecorators = model.getValueLength() === 0 ? placeholderDecorators : [];
2088
+ decorators = model.deltaDecorations(decorators, newDecorators);
2089
+ };
2090
+ checkDecorators();
2091
+ editor$1.onDidChangeModelContent(checkDecorators);
2092
+ }
2093
+ editor$1.onDidChangeModelContent(function () {
2094
+ var model = editor$1.getModel();
2095
+ if (model) {
2096
+ var query = model.getValue();
2097
+ var errors = validateQuery(query, interpolateString ? interpolateString(query) : query, model.getLinesContent(), parser) || [];
2098
+ var markers = errors.map(function (_ref) {
2099
+ var error = _ref.error,
2100
+ boundary = _objectWithoutPropertiesLoose(_ref, _excluded);
2101
+ return _extends({
2102
+ message: (error ? "Error parsing \"" + error + "\"" : 'Parse error') + ". The query appears to be incorrect and could fail to be executed.",
2103
+ severity: MarkerSeverity.Error
2104
+ }, boundary);
2105
+ });
2106
+ editor.setModelMarkers(model, 'owner', markers);
2107
+ }
2108
+ });
2109
+ };
2110
+ useEffect(function () {
2111
+ var dataProvider = dataProviderRef.current;
2112
+ if (dataProvider) {
2113
+ dataProvider.setVariablesNames(variablesNames || []);
2114
+ }
2115
+ }, [JSON.stringify(variablesNames)]);
2116
+ return React.createElement("div", {
2117
+ className: 'ant-input' + (size ? " " + SIZE_MAP[size].className : '')
2118
+ }, React.createElement("div", {
2119
+ ref: containerRef
2120
+ }, React.createElement(MonacoEditor, {
2121
+ width: '100%',
2122
+ height: '100%',
2123
+ language: 'promql',
2124
+ theme: themeMap[theme],
2125
+ value: value,
2126
+ onChange: onChange,
2127
+ editorDidMount: handleEditorDidMount,
2128
+ options: {
2129
+ codeLens: false,
2130
+ contextmenu: false,
2131
+ fixedOverflowWidgets: true,
2132
+ folding: false,
2133
+ fontSize: 12,
2134
+ lineDecorationsWidth: 0,
2135
+ lineNumbers: 'off',
2136
+ minimap: {
2137
+ enabled: false
2138
+ },
2139
+ overviewRulerBorder: false,
2140
+ overviewRulerLanes: 0,
2141
+ padding: {
2142
+ top: SIZE_MAP[size].top,
2143
+ bottom: SIZE_MAP[size].bottom
2144
+ },
2145
+ renderLineHighlight: 'none',
2146
+ scrollbar: {
2147
+ vertical: 'hidden',
2148
+ verticalScrollbarSize: 8,
2149
+ horizontal: 'hidden',
2150
+ horizontalScrollbarSize: 0,
2151
+ alwaysConsumeMouseWheel: false
2152
+ },
2153
+ scrollBeyondLastLine: false,
2154
+ suggest: {
2155
+ showWords: false
2156
+ },
2157
+ suggestFontSize: 12,
2158
+ wordWrap: 'on'
2159
+ }
2160
+ })));
2161
+ }
2162
+
2163
+ export { PromQLEditor as PromQLMonacoEditor };
2164
+ //# sourceMappingURL=monaco-editor.esm.js.map