@kusto/monaco-kusto 4.0.4 → 4.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.
@@ -1,1588 +1,1752 @@
1
- var __assign = (this && this.__assign) || function () {
2
- __assign = Object.assign || function(t) {
3
- for (var s, i = 1, n = arguments.length; i < n; i++) {
4
- s = arguments[i];
5
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
- t[p] = s[p];
7
- }
8
- return t;
9
- };
10
- return __assign.apply(this, arguments);
11
- };
12
- /// <reference path="../../node_modules/@kusto/language-service/Kusto.JavaScript.Client.d.ts" />
13
- /// <reference path="../../node_modules/@kusto/language-service-next/Kusto.Language.Bridge.d.ts" />
14
- /// <reference path="../typings/refs.d.ts" />
15
- import * as s from './schema';
16
- // polyfill string endsWith
17
- if (!String.prototype.endsWith) {
18
- String.prototype.endsWith = function (search, this_len) {
19
- if (this_len === undefined || this_len > this.length) {
20
- this_len = this.length;
21
- }
22
- return this.substring(this_len - search.length, this_len) === search;
23
- };
24
- }
25
- // If we're running in a web worker - which doesn't share global context with the main thread -
26
- // we need to manually load dependencies that are not explicit- meaning our non-module dependencies
27
- // generated by Bridge.Net
28
- if (typeof document == 'undefined') {
29
- // monaco will run the worker from vs/base/worker so the relative path needs to be from there (hence going up 2 dirs)
30
- importScripts('../../language/kusto/bridge.min.js');
31
- importScripts('../../language/kusto/kusto.javascript.client.min.js');
32
- importScripts('../../language/kusto/Kusto.Language.Bridge.min.js');
33
- }
34
- import * as ls from './../_deps/vscode-languageserver-types/main';
35
- import * as XRegExp from './../_deps/xregexp/xregexp-all';
36
- var k = Kusto.Data.IntelliSense;
37
- var parsing = Kusto.Language.Parsing;
38
- var k2 = Kusto.Language.Editor;
39
- var sym = Kusto.Language.Symbols;
40
- var GlobalState = Kusto.Language.GlobalState;
41
- import { getCslTypeNameFromClrType, getEntityDataTypeFromCslType } from './schema';
42
- var List = System.Collections.Generic.List$1;
43
- function assertNever(x) {
44
- throw new Error('Unexpected object: ' + x);
45
- }
46
- var ParseProperties = /** @class */ (function () {
47
- function ParseProperties(version, uri, rulesProvider, parseMode) {
48
- this.version = version;
49
- this.uri = uri;
50
- this.rulesProvider = rulesProvider;
51
- this.parseMode = parseMode;
52
- }
53
- ParseProperties.prototype.isParseNeeded = function (document, rulesProvider, parseMode) {
54
- if (document.uri === this.uri &&
55
- (!rulesProvider || rulesProvider === this.rulesProvider) &&
56
- document.version <= this.version &&
57
- parseMode &&
58
- parseMode <= this.parseMode) {
59
- return false;
60
- }
61
- return true;
62
- };
63
- return ParseProperties;
64
- }());
65
- export var TokenKind;
66
- (function (TokenKind) {
67
- TokenKind[TokenKind["TableToken"] = 2] = "TableToken";
68
- TokenKind[TokenKind["TableColumnToken"] = 4] = "TableColumnToken";
69
- TokenKind[TokenKind["OperatorToken"] = 8] = "OperatorToken";
70
- TokenKind[TokenKind["SubOperatorToken"] = 16] = "SubOperatorToken";
71
- TokenKind[TokenKind["CalculatedColumnToken"] = 32] = "CalculatedColumnToken";
72
- TokenKind[TokenKind["StringLiteralToken"] = 64] = "StringLiteralToken";
73
- TokenKind[TokenKind["FunctionNameToken"] = 128] = "FunctionNameToken";
74
- TokenKind[TokenKind["UnknownToken"] = 256] = "UnknownToken";
75
- TokenKind[TokenKind["CommentToken"] = 512] = "CommentToken";
76
- TokenKind[TokenKind["PlainTextToken"] = 1024] = "PlainTextToken";
77
- TokenKind[TokenKind["DataTypeToken"] = 2048] = "DataTypeToken";
78
- TokenKind[TokenKind["ControlCommandToken"] = 4096] = "ControlCommandToken";
79
- TokenKind[TokenKind["CommandPartToken"] = 8192] = "CommandPartToken";
80
- TokenKind[TokenKind["QueryParametersToken"] = 16384] = "QueryParametersToken";
81
- TokenKind[TokenKind["CslCommandToken"] = 32768] = "CslCommandToken";
82
- TokenKind[TokenKind["LetVariablesToken"] = 65536] = "LetVariablesToken";
83
- TokenKind[TokenKind["PluginToken"] = 131072] = "PluginToken";
84
- TokenKind[TokenKind["BracketRangeToken"] = 262144] = "BracketRangeToken";
85
- TokenKind[TokenKind["ClientDirectiveToken"] = 524288] = "ClientDirectiveToken";
86
- })(TokenKind || (TokenKind = {}));
87
- /**
88
- * convert the bridge.net object to a plain javascript object that only contains data.
89
- * @param k2Classifications @kusto/language-service-next bridge.net object
90
- */
91
- function toClassifiedRange(k2Classifications) {
92
- return k2Classifications.map(function (classification) { return ({
93
- start: classification.Start,
94
- end: classification.End,
95
- length: classification.Length,
96
- kind: classification.Kind,
97
- }); });
98
- }
99
- /**
100
- * Kusto Language service translates the kusto object model (transpiled from C# by Bridge.Net)
101
- * to the vscode language server types, which are used by vscode language extensions.
102
- * This should make things easier in the future to provide a vscode extension based on this translation layer.
103
- *
104
- * Further translations, if needed, to support specific editors (Atom, sublime, Etc)
105
- * should be done on top of this API, since it is (at least meant to be) a standard that is supported by multiple editors.
106
- *
107
- * Note1: Currently monaco isn't using this object model so further translation will be necessary on calling modules.
108
- *
109
- * Note2: This file is responsible for interacting with the kusto object model and exposing Microsoft language service types.
110
- * An exception to that rule is tokenization (and syntax highlighting which depends on it) -
111
- * since it's not currently part of the Microsoft language service protocol. Thus tokenize() _does_ 'leak' kusto types to the callers.
112
- */
113
- var KustoLanguageService = /** @class */ (function () {
114
- function KustoLanguageService(schema, languageSettings) {
115
- var _a, _b, _c, _d;
116
- var _this = this;
117
- this._toOptionKind = (_a = {},
118
- _a[k2.CompletionKind.AggregateFunction] = k.OptionKind.FunctionAggregation,
119
- _a[k2.CompletionKind.BuiltInFunction] = k.OptionKind.FunctionServerSide,
120
- _a[k2.CompletionKind.Cluster] = k.OptionKind.Database,
121
- _a[k2.CompletionKind.Column] = k.OptionKind.Column,
122
- _a[k2.CompletionKind.CommandPrefix] = k.OptionKind.None,
123
- _a[k2.CompletionKind.Database] = k.OptionKind.Database,
124
- _a[k2.CompletionKind.DatabaseFunction] = k.OptionKind.FunctionServerSide,
125
- _a[k2.CompletionKind.Example] = k.OptionKind.None,
126
- _a[k2.CompletionKind.Identifier] = k.OptionKind.None,
127
- _a[k2.CompletionKind.Keyword] = k.OptionKind.None,
128
- _a[k2.CompletionKind.LocalFunction] = k.OptionKind.FunctionLocal,
129
- _a[k2.CompletionKind.MaterialiedView] = k.OptionKind.MaterializedView,
130
- _a[k2.CompletionKind.Parameter] = k.OptionKind.Parameter,
131
- _a[k2.CompletionKind.Punctuation] = k.OptionKind.None,
132
- _a[k2.CompletionKind.QueryPrefix] = k.OptionKind.Operator,
133
- _a[k2.CompletionKind.RenderChart] = k.OptionKind.Operator,
134
- _a[k2.CompletionKind.ScalarInfix] = k.OptionKind.None,
135
- _a[k2.CompletionKind.ScalarPrefix] = k.OptionKind.None,
136
- _a[k2.CompletionKind.ScalarType] = k.OptionKind.DataType,
137
- _a[k2.CompletionKind.Syntax] = k.OptionKind.None,
138
- _a[k2.CompletionKind.Table] = k.OptionKind.Table,
139
- _a[k2.CompletionKind.TabularPrefix] = k.OptionKind.None,
140
- _a[k2.CompletionKind.TabularSuffix] = k.OptionKind.None,
141
- _a[k2.CompletionKind.Unknown] = k.OptionKind.None,
142
- _a[k2.CompletionKind.Variable] = k.OptionKind.Parameter,
143
- _a[k2.CompletionKind.Option] = k.OptionKind.Option,
144
- _a);
145
- this.disabledCompletionItemsV2 = {
146
- // render charts
147
- ladderchart: k2.CompletionKind.RenderChart,
148
- pivotchart: k2.CompletionKind.RenderChart,
149
- timeline: k2.CompletionKind.RenderChart,
150
- timepivot: k2.CompletionKind.RenderChart,
151
- '3Dchart': k2.CompletionKind.RenderChart,
152
- list: k2.CompletionKind.RenderChart,
153
- };
154
- this.isIntellisenseV2 = function () {
155
- return _this._languageSettings.useIntellisenseV2 && _this._schema && _this._schema.clusterType === 'Engine';
156
- };
157
- this.disabledCompletionItemsV1 = {
158
- capacity: k.OptionKind.Policy,
159
- callout: k.OptionKind.Policy,
160
- encoding: k.OptionKind.Policy,
161
- batching: k.OptionKind.Policy,
162
- querythrottling: k.OptionKind.Policy,
163
- merge: k.OptionKind.Policy,
164
- querylimit: k.OptionKind.Policy,
165
- rowstore: k.OptionKind.Policy,
166
- streamingingestion: k.OptionKind.Policy,
167
- restricted_view_access: k.OptionKind.Policy,
168
- sharding: k.OptionKind.Policy,
169
- 'restricted-viewers': k.OptionKind.Policy,
170
- attach: k.OptionKind.Command,
171
- purge: k.OptionKind.Command,
172
- };
173
- this._kustoKindtolsKind = (_b = {},
174
- _b[k.OptionKind.None] = ls.CompletionItemKind.Interface,
175
- _b[k.OptionKind.Operator] = ls.CompletionItemKind.Method,
176
- _b[k.OptionKind.Command] = ls.CompletionItemKind.Method,
177
- _b[k.OptionKind.Service] = ls.CompletionItemKind.Class,
178
- _b[k.OptionKind.Policy] = ls.CompletionItemKind.Reference,
179
- _b[k.OptionKind.Database] = ls.CompletionItemKind.Class,
180
- _b[k.OptionKind.Table] = ls.CompletionItemKind.Class,
181
- _b[k.OptionKind.DataType] = ls.CompletionItemKind.Class,
182
- _b[k.OptionKind.Literal] = ls.CompletionItemKind.Property,
183
- _b[k.OptionKind.Parameter] = ls.CompletionItemKind.Variable,
184
- _b[k.OptionKind.IngestionMapping] = ls.CompletionItemKind.Variable,
185
- _b[k.OptionKind.ExpressionFunction] = ls.CompletionItemKind.Variable,
186
- _b[k.OptionKind.Option] = ls.CompletionItemKind.Interface,
187
- _b[k.OptionKind.OptionKind] = ls.CompletionItemKind.Interface,
188
- _b[k.OptionKind.OptionRender] = ls.CompletionItemKind.Interface,
189
- _b[k.OptionKind.Column] = ls.CompletionItemKind.Function,
190
- _b[k.OptionKind.ColumnString] = ls.CompletionItemKind.Field,
191
- _b[k.OptionKind.ColumnNumeric] = ls.CompletionItemKind.Field,
192
- _b[k.OptionKind.ColumnDateTime] = ls.CompletionItemKind.Field,
193
- _b[k.OptionKind.ColumnTimespan] = ls.CompletionItemKind.Field,
194
- _b[k.OptionKind.FunctionServerSide] = ls.CompletionItemKind.Field,
195
- _b[k.OptionKind.FunctionAggregation] = ls.CompletionItemKind.Field,
196
- _b[k.OptionKind.FunctionFilter] = ls.CompletionItemKind.Field,
197
- _b[k.OptionKind.FunctionScalar] = ls.CompletionItemKind.Field,
198
- _b[k.OptionKind.ClientDirective] = ls.CompletionItemKind.Enum,
199
- _b);
200
- this._kustoKindToLsKindV2 = (_c = {},
201
- _c[k2.CompletionKind.AggregateFunction] = ls.CompletionItemKind.Field,
202
- _c[k2.CompletionKind.BuiltInFunction] = ls.CompletionItemKind.Field,
203
- _c[k2.CompletionKind.Cluster] = ls.CompletionItemKind.Class,
204
- _c[k2.CompletionKind.Column] = ls.CompletionItemKind.Function,
205
- _c[k2.CompletionKind.CommandPrefix] = ls.CompletionItemKind.Field,
206
- _c[k2.CompletionKind.Database] = ls.CompletionItemKind.Class,
207
- _c[k2.CompletionKind.DatabaseFunction] = ls.CompletionItemKind.Field,
208
- _c[k2.CompletionKind.Example] = ls.CompletionItemKind.Text,
209
- _c[k2.CompletionKind.Identifier] = ls.CompletionItemKind.Method,
210
- _c[k2.CompletionKind.Keyword] = ls.CompletionItemKind.Method,
211
- _c[k2.CompletionKind.LocalFunction] = ls.CompletionItemKind.Field,
212
- _c[k2.CompletionKind.MaterialiedView] = ls.CompletionItemKind.Class,
213
- _c[k2.CompletionKind.Parameter] = ls.CompletionItemKind.Variable,
214
- _c[k2.CompletionKind.Punctuation] = ls.CompletionItemKind.Interface,
215
- _c[k2.CompletionKind.QueryPrefix] = ls.CompletionItemKind.Function,
216
- _c[k2.CompletionKind.RenderChart] = ls.CompletionItemKind.Method,
217
- _c[k2.CompletionKind.ScalarInfix] = ls.CompletionItemKind.Field,
218
- _c[k2.CompletionKind.ScalarPrefix] = ls.CompletionItemKind.Field,
219
- _c[k2.CompletionKind.ScalarType] = ls.CompletionItemKind.TypeParameter,
220
- _c[k2.CompletionKind.Syntax] = ls.CompletionItemKind.Method,
221
- _c[k2.CompletionKind.Table] = ls.CompletionItemKind.Class,
222
- _c[k2.CompletionKind.TabularPrefix] = ls.CompletionItemKind.Field,
223
- // datatable, externaldata
224
- _c[k2.CompletionKind.TabularSuffix] = ls.CompletionItemKind.Field,
225
- _c[k2.CompletionKind.Unknown] = ls.CompletionItemKind.Interface,
226
- _c[k2.CompletionKind.Variable] = ls.CompletionItemKind.Variable,
227
- _c[k2.CompletionKind.Option] = ls.CompletionItemKind.Text,
228
- _c);
229
- this._tokenKindToClassificationKind = (_d = {},
230
- _d[TokenKind.TableToken] = k2.ClassificationKind.Table,
231
- _d[TokenKind.TableColumnToken] = k2.ClassificationKind.Column,
232
- _d[TokenKind.OperatorToken] = k2.ClassificationKind.QueryOperator,
233
- _d[TokenKind.SubOperatorToken] = k2.ClassificationKind.Function,
234
- _d[TokenKind.CalculatedColumnToken] = k2.ClassificationKind.Column,
235
- _d[TokenKind.StringLiteralToken] = k2.ClassificationKind.Literal,
236
- _d[TokenKind.FunctionNameToken] = k2.ClassificationKind.Function,
237
- _d[TokenKind.UnknownToken] = k2.ClassificationKind.PlainText,
238
- _d[TokenKind.CommentToken] = k2.ClassificationKind.Comment,
239
- _d[TokenKind.PlainTextToken] = k2.ClassificationKind.PlainText,
240
- _d[TokenKind.DataTypeToken] = k2.ClassificationKind.Type,
241
- _d[TokenKind.ControlCommandToken] = k2.ClassificationKind.PlainText,
242
- _d[TokenKind.CommandPartToken] = k2.ClassificationKind.PlainText,
243
- _d[TokenKind.QueryParametersToken] = k2.ClassificationKind.QueryParameter,
244
- _d[TokenKind.CslCommandToken] = k2.ClassificationKind.Keyword,
245
- _d[TokenKind.LetVariablesToken] = k2.ClassificationKind.Identifier,
246
- _d[TokenKind.PluginToken] = k2.ClassificationKind.Function,
247
- _d[TokenKind.BracketRangeToken] = k2.ClassificationKind.Keyword,
248
- _d[TokenKind.ClientDirectiveToken] = k2.ClassificationKind.Keyword,
249
- _d);
250
- this._schemaCache = {};
251
- this._kustoJsSchema = KustoLanguageService.convertToKustoJsSchema(schema);
252
- this._kustoJsSchemaV2 = this.convertToKustoJsSchemaV2(schema);
253
- this._schema = schema;
254
- this.configure(languageSettings);
255
- this._newlineAppendPipePolicy = new Kusto.Data.IntelliSense.ApplyPolicy();
256
- this._newlineAppendPipePolicy.Text = '\n| ';
257
- }
258
- KustoLanguageService.prototype.configure = function (languageSettings) {
259
- this._languageSettings = languageSettings;
260
- // Since we're still reverting to V1 intellisense for control commands, we need to update the rules provider
261
- // (which is a notion of V1 intellisense).
262
- this.createRulesProvider(this._kustoJsSchema, this._schema.clusterType);
263
- };
264
- KustoLanguageService.prototype.doComplete = function (document, position) {
265
- return this.isIntellisenseV2() ? this.doCompleteV2(document, position) : this.doCompleteV1(document, position);
266
- };
267
- KustoLanguageService.prototype.doCompleteV2 = function (document, position) {
268
- var _this = this;
269
- if (!document) {
270
- return Promise.resolve(ls.CompletionList.create([]));
271
- }
272
- var script = this.parseDocumentV2(document);
273
- var cursorOffset = document.offsetAt(position);
274
- var currentcommand = this.getCurrentCommandV2(script, cursorOffset);
275
- var completionItems = currentcommand.Service.GetCompletionItems(cursorOffset);
276
- var disabledItems = this.disabledCompletionItemsV2;
277
- if (this._languageSettings.disabledCompletionItems) {
278
- this._languageSettings.disabledCompletionItems.map(function (item) {
279
- // logic will treat unknown as a '*' wildcard, meaning that if the key is in the object
280
- // the completion item will be suppressed.
281
- disabledItems[item] = k2.CompletionKind.Unknown;
282
- });
283
- }
284
- var items = this.toArray(completionItems.Items)
285
- .filter(function (item) {
286
- return !(item &&
287
- item.MatchText &&
288
- disabledItems[item.MatchText] !== undefined &&
289
- (disabledItems[item.MatchText] === k2.CompletionKind.Unknown ||
290
- disabledItems[item.MatchText] === item.Kind));
291
- })
292
- .map(function (kItem, i) {
293
- var v1CompletionOption = new k.CompletionOption(_this._toOptionKind[kItem.Kind] || k.OptionKind.None, kItem.DisplayText);
294
- var helpTopic = _this.getTopic(v1CompletionOption);
295
- // If we have AfterText it means that the cursor should no be placed at end of suggested text.
296
- // In that case we switch to snippet format and represent the point where the cursor should be as
297
- // as '\$0'
298
- var _a = kItem.AfterText && kItem.AfterText.length > 0
299
- ? {
300
- textToInsert: kItem.EditText + '$0' + kItem.AfterText,
301
- format: ls.InsertTextFormat.Snippet,
302
- }
303
- : {
304
- textToInsert: kItem.EditText,
305
- format: ls.InsertTextFormat.PlainText,
306
- }, textToInsert = _a.textToInsert, format = _a.format;
307
- var lsItem = ls.CompletionItem.create(kItem.DisplayText);
308
- var startPosition = document.positionAt(completionItems.EditStart);
309
- var endPosition = document.positionAt(completionItems.EditStart + completionItems.EditLength);
310
- lsItem.textEdit = ls.TextEdit.replace(ls.Range.create(startPosition, endPosition), textToInsert);
311
- lsItem.sortText = _this.getSortText(i + 1);
312
- lsItem.kind = _this.kustoKindToLsKindV2(kItem.Kind);
313
- lsItem.insertTextFormat = format;
314
- lsItem.detail = helpTopic ? helpTopic.ShortDescription : undefined;
315
- lsItem.documentation = helpTopic
316
- ? { value: helpTopic.LongDescription, kind: ls.MarkupKind.Markdown }
317
- : undefined;
318
- return lsItem;
319
- });
320
- return Promise.resolve(ls.CompletionList.create(items));
321
- };
322
- /**
323
- * when trying to get a topic we need the function name (abs, toLower, ETC).
324
- * The problem is that the 'Value' string also contains the arguments (e.g abs(number)), which means that we are
325
- * not able to correlate the option with its documentation.
326
- * This piece of code tries to strip this hwne getting topic.
327
- * @param completionOption the Completion option
328
- */
329
- KustoLanguageService.prototype.getTopic = function (completionOption) {
330
- if (completionOption.Kind == k.OptionKind.FunctionScalar ||
331
- completionOption.Kind == k.OptionKind.FunctionAggregation) {
332
- // from a value like 'abs(number)' remove the '(number)' so that only 'abs' will remain
333
- var indexOfParen = completionOption.Value.indexOf('(');
334
- if (indexOfParen >= 0) {
335
- completionOption = new k.CompletionOption(completionOption.Kind, completionOption.Value.substring(0, indexOfParen));
336
- }
337
- }
338
- return k.CslDocumentation.Instance.GetTopic(completionOption);
339
- };
340
- KustoLanguageService.prototype.doCompleteV1 = function (document, position) {
341
- var _this = this;
342
- // TODO: fix typing in CslCommandParser to allow rulesProvider to be query only.
343
- var caretAbsolutePosition = document.offsetAt(position);
344
- // find out what's the current command to only parse this one.
345
- this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
346
- var currentCommand = this.getCurrentCommand(document, caretAbsolutePosition);
347
- var commandTextUntilCursor = '';
348
- if (currentCommand) {
349
- var commandStartOffset = currentCommand.AbsoluteStart;
350
- this.parseTextV1(currentCommand.Text, k.ParseMode.TokenizeAllText);
351
- var caretRelativePosition = caretAbsolutePosition - currentCommand.AbsoluteStart;
352
- commandTextUntilCursor = currentCommand.Text.substring(currentCommand.CslExpressionStartPosition, caretRelativePosition);
353
- }
354
- var commandTextWithoutLastWord = this.getCommandWithoutLastWord(commandTextUntilCursor);
355
- var context = this._rulesProvider.AnalyzeCommand$1(commandTextUntilCursor, currentCommand).Context;
356
- var result = { v: null };
357
- this._rulesProvider.TryMatchAnyRule(commandTextWithoutLastWord, result);
358
- var rule = result.v;
359
- if (rule) {
360
- var completionOptions = this.toArray(rule.GetCompletionOptions(context));
361
- // TODO once AppendPipePolicy becomes a public static member of ApplyPolicy in our c# code, and bridge.Net transplies this,
362
- // remove the 'as any' part..
363
- // Also = DefaultApplyPolicy is internal in c# code, so not exposed in d.ts, so we cast it to any.
364
- if (this._languageSettings.newlineAfterPipe &&
365
- rule.DefaultAfterApplyPolicy === Kusto.Data.IntelliSense.ApplyPolicy.AppendPipePolicy) {
366
- rule.DefaultAfterApplyPolicy = this._newlineAppendPipePolicy;
367
- }
368
- var options = completionOptions
369
- .filter(function (option) {
370
- return !(option && option.Value && _this.disabledCompletionItemsV1[option.Value] === option.Kind);
371
- })
372
- .map(function (option, ordinal) {
373
- var _a = _this.getTextToInsert(rule, option), insertText = _a.insertText, insertTextFormat = _a.insertTextFormat;
374
- var helpTopic = k.CslDocumentation.Instance.GetTopic(option);
375
- var item = ls.CompletionItem.create(option.Value);
376
- item.kind = _this.kustoKindToLsKind(option.Kind);
377
- item.insertText = insertText;
378
- item.insertTextFormat = insertTextFormat;
379
- item.sortText = _this.getSortText(ordinal + 1);
380
- item.detail = helpTopic ? helpTopic.ShortDescription : undefined;
381
- item.documentation = helpTopic
382
- ? { value: helpTopic.LongDescription, kind: ls.MarkupKind.Markdown }
383
- : undefined;
384
- return item;
385
- });
386
- return Promise.resolve(ls.CompletionList.create(options));
387
- }
388
- return Promise.resolve(ls.CompletionList.create([]));
389
- };
390
- KustoLanguageService.prototype.doRangeFormat = function (document, range) {
391
- if (!document) {
392
- return Promise.resolve([]);
393
- }
394
- var rangeStartOffset = document.offsetAt(range.start);
395
- var rangeEndOffset = document.offsetAt(range.end);
396
- var commands = this.getFormattedCommandsInDocumentV2(document, rangeStartOffset, rangeEndOffset);
397
- if (!commands.originalRange || commands.formattedCommands.length === 0) {
398
- return Promise.resolve([]);
399
- }
400
- return Promise.resolve([ls.TextEdit.replace(commands.originalRange, commands.formattedCommands.join(''))]);
401
- };
402
- KustoLanguageService.prototype.doDocumentFormat = function (document) {
403
- if (!document) {
404
- return Promise.resolve([]);
405
- }
406
- var startPos = document.positionAt(0);
407
- var endPos = document.positionAt(document.getText().length);
408
- var fullDocRange = ls.Range.create(startPos, endPos);
409
- var formattedDoc = this.getFormattedCommandsInDocumentV2(document).formattedCommands.join('');
410
- return Promise.resolve([ls.TextEdit.replace(fullDocRange, formattedDoc)]);
411
- };
412
- // Method is not triggered, instead doRangeFormat is invoked with the range of the caret's line.
413
- KustoLanguageService.prototype.doCurrentCommandFormat = function (document, caretPosition) {
414
- var offset = document.offsetAt(caretPosition);
415
- var range = this.createRange(document, offset - 1, offset + 1);
416
- return this.doRangeFormat(document, range);
417
- };
418
- KustoLanguageService.prototype.doFolding = function (document) {
419
- if (!document) {
420
- return Promise.resolve([]);
421
- }
422
- return this.getCommandsInDocument(document).then(function (commands) {
423
- return commands.map(function (command) {
424
- // don't count the last empty line as part of the folded range (consider linux, mac, pc newlines)
425
- if (command.text.endsWith('\r\n')) {
426
- command.absoluteEnd -= 2;
427
- }
428
- else if (command.text.endsWith('\r') || command.text.endsWith('\n')) {
429
- --command.absoluteEnd;
430
- }
431
- var startPosition = document.positionAt(command.absoluteStart);
432
- var endPosition = document.positionAt(command.absoluteEnd);
433
- return {
434
- startLine: startPosition.line,
435
- startCharacter: startPosition.character,
436
- endLine: endPosition.line,
437
- endCharacter: endPosition.character,
438
- };
439
- });
440
- });
441
- };
442
- KustoLanguageService.prototype.doValidation = function (document, changeIntervals) {
443
- var _this = this;
444
- // didn't implement validation for v1.
445
- if (!document || !this.isIntellisenseV2()) {
446
- return Promise.resolve([]);
447
- }
448
- var script = this.parseDocumentV2(document);
449
- var blocks = this.toArray(script.Blocks);
450
- if (changeIntervals.length > 0) {
451
- blocks = this.getAffectedBlocks(blocks, changeIntervals);
452
- }
453
- var diagnostics = blocks
454
- .map(function (block) {
455
- var diagnostics = _this.toArray(block.Service.GetDiagnostics());
456
- if (diagnostics) {
457
- return diagnostics;
458
- }
459
- return [];
460
- })
461
- .reduce(function (prev, curr) { return prev.concat(curr); }, []);
462
- var lsDiagnostics = this.toLsDiagnostics(diagnostics, document);
463
- return Promise.resolve(lsDiagnostics);
464
- };
465
- KustoLanguageService.prototype.toLsDiagnostics = function (diagnostics, document) {
466
- return diagnostics
467
- .filter(function (diag) { return diag.HasLocation; })
468
- .map(function (diag) {
469
- var start = document.positionAt(diag.Start);
470
- var end = document.positionAt(diag.Start + diag.Length);
471
- var range = ls.Range.create(start, end);
472
- return ls.Diagnostic.create(range, diag.Message, ls.DiagnosticSeverity.Error);
473
- });
474
- };
475
- /**
476
- * Colorize one or more kusto blocks (a.k.a commands), or just the entire document.
477
- * Supports multi-cursor editing (colorizes blocks on multiple changes).
478
- * @param document The document to colorize
479
- * @param changeIntervals an array containing 0 or more changed intervals. if the array is empty - just colorize the entire row.
480
- * if the array contains a single change - just color the kusto blocks that wraps this change. If multiple changes are provided,
481
- * colorize all blocks that intersect these changes.
482
- * The code will try to only parse once if this is the same command.
483
- */
484
- KustoLanguageService.prototype.doColorization = function (document, changeIntervals) {
485
- var _this = this;
486
- if (!document || !this._languageSettings.useSemanticColorization) {
487
- return Promise.resolve([]);
488
- }
489
- // V1 intellisense
490
- if (!this.isIntellisenseV2()) {
491
- // Handle specific ranges changes (and not the whole doc)
492
- if (changeIntervals.length > 0) {
493
- this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
494
- var affectedCommands = this.toArray(this._parser.Results).filter(function (command) {
495
- // a command is affected if it intersects at least on of changed ranges.
496
- return command // command can be null. we're filtering all nulls in the array.
497
- ? changeIntervals.some(function (_a) {
498
- var changeStart = _a.start, changeEnd = _a.end;
499
- // both intervals intersect if either the start or the end of interval A is inside interval B.
500
- // If we deleted something at the end of a command, the interval will not intersect the current command.
501
- // so we also want consider affected commands commands the end where the interval begins.
502
- // hence the + 1.
503
- return (command.AbsoluteStart >= changeStart && command.AbsoluteStart <= changeEnd) ||
504
- (changeStart >= command.AbsoluteStart && changeStart <= command.AbsoluteEnd + 1);
505
- })
506
- : false;
507
- });
508
- // We're not on any command so don't return any classifications.
509
- // this can happen if we're at the and of the file and deleting empty rows (for example).
510
- if (!affectedCommands || affectedCommands.length === 0) {
511
- return Promise.resolve([
512
- {
513
- classifications: [],
514
- absoluteStart: changeIntervals[0].start,
515
- absoluteEnd: changeIntervals[0].end,
516
- },
517
- ]);
518
- }
519
- var results = affectedCommands.map(function (command) {
520
- _this.parseTextV1(command.Text, k.ParseMode.TokenizeAllText);
521
- var k2Classifications = _this.getClassificationsFromParseResult(command.AbsoluteStart);
522
- var classifications = toClassifiedRange(k2Classifications);
523
- return {
524
- classifications: classifications,
525
- absoluteStart: command.AbsoluteStart,
526
- absoluteEnd: command.AbsoluteEnd,
527
- };
528
- });
529
- return Promise.resolve(results);
530
- }
531
- // Entire document requested
532
- this.parseDocumentV1(document, k.ParseMode.TokenizeAllText);
533
- var classifications_1 = this.getClassificationsFromParseResult();
534
- return Promise.resolve([
535
- {
536
- classifications: toClassifiedRange(classifications_1),
537
- absoluteStart: 0,
538
- absoluteEnd: document.getText().length,
539
- },
540
- ]);
541
- }
542
- // V2 intellisense
543
- var script = this.parseDocumentV2(document);
544
- if (changeIntervals.length > 0) {
545
- var blocks_1 = this.toArray(script.Blocks);
546
- var affectedBlocks = this.getAffectedBlocks(blocks_1, changeIntervals);
547
- var result = affectedBlocks.map(function (block) { return ({
548
- classifications: toClassifiedRange(_this.toArray(block.Service.GetClassifications(block.Start, block.End).Classifications)),
549
- absoluteStart: block.Start,
550
- absoluteEnd: block.End,
551
- }); });
552
- return Promise.resolve(result);
553
- }
554
- // Entire document requested
555
- var blocks = this.toArray(script.Blocks);
556
- var classifications = blocks
557
- .map(function (block) {
558
- return _this.toArray(block.Service.GetClassifications(block.Start, block.Length).Classifications);
559
- })
560
- .reduce(function (prev, curr) { return prev.concat(curr); }, []);
561
- return Promise.resolve([
562
- {
563
- classifications: toClassifiedRange(classifications),
564
- absoluteStart: 0,
565
- absoluteEnd: document.getText().length,
566
- },
567
- ]);
568
- };
569
- KustoLanguageService.prototype.getAffectedBlocks = function (blocks, changeIntervals) {
570
- return blocks.filter(function (block) {
571
- // a command is affected if it intersects at least on of changed ranges.
572
- return block // command can be null. we're filtering all nulls in the array.
573
- ? changeIntervals.some(function (_a) {
574
- var changeStart = _a.start, changeEnd = _a.end;
575
- // both intervals intersect if either the start or the end of interval A is inside interval B.
576
- return (block.Start >= changeStart && block.Start <= changeEnd) ||
577
- (changeStart >= block.Start && changeStart <= block.End + 1);
578
- })
579
- : false;
580
- });
581
- };
582
- KustoLanguageService.prototype.setSchema = function (schema) {
583
- var _this = this;
584
- this._schema = schema;
585
- if (this._languageSettings.useIntellisenseV2) {
586
- var kustoJsSchemaV2 = schema && schema.clusterType === 'Engine' ? this.convertToKustoJsSchemaV2(schema) : null;
587
- this._kustoJsSchemaV2 = kustoJsSchemaV2;
588
- this._script = undefined;
589
- this._parsePropertiesV2 = undefined;
590
- }
591
- // since V2 doesn't support control commands, we're initializing V1 intellisense for both cases and we'll going to use V1 intellisense for contorl commands.
592
- return new Promise(function (resolve, reject) {
593
- var kustoJsSchema = schema ? KustoLanguageService.convertToKustoJsSchema(schema) : undefined;
594
- _this._kustoJsSchema = kustoJsSchema;
595
- _this.createRulesProvider(kustoJsSchema, schema.clusterType);
596
- resolve(undefined);
597
- });
598
- };
599
- KustoLanguageService.prototype.setParameters = function (parameters) {
600
- if (!this._languageSettings.useIntellisenseV2 || this._schema.clusterType !== 'Engine') {
601
- throw new Error('setParameters requires intellisense V2 and Engine cluster');
602
- }
603
- this._schema.globalParameters = parameters;
604
- var symbols = parameters.map(function (param) { return KustoLanguageService.createParameterSymbol(param); });
605
- this._kustoJsSchemaV2 = this._kustoJsSchemaV2.WithParameters(KustoLanguageService.toBridgeList(symbols));
606
- return Promise.resolve(undefined);
607
- };
608
- /**
609
- * A combination of normalizeSchema and setSchema
610
- * @param schema schema json as received from .show schema as json
611
- * @param clusterConnectionString cluster connection string
612
- * @param databaseInContextName name of database in context
613
- */
614
- KustoLanguageService.prototype.setSchemaFromShowSchema = function (schema, clusterConnectionString, databaseInContextName, globalParameters) {
615
- var _this = this;
616
- return this.normalizeSchema(schema, clusterConnectionString, databaseInContextName).then(function (normalized) {
617
- return _this.setSchema(__assign(__assign({}, normalized), { globalParameters: globalParameters }));
618
- });
619
- };
620
- /**
621
- * Converts the result of .show schema as json to a normalized schema used by kusto language service.
622
- * @param schema result of show schema
623
- * @param clusterConnectionString cluster connection string`
624
- * @param databaseInContextName database in context name
625
- */
626
- KustoLanguageService.prototype.normalizeSchema = function (schema, clusterConnectionString, databaseInContextName) {
627
- var databases = Object.keys(schema.Databases)
628
- .map(function (key) { return schema.Databases[key]; })
629
- .map(function (_a) {
630
- var Name = _a.Name, Tables = _a.Tables, Functions = _a.Functions, MinorVersion = _a.MinorVersion, MajorVersion = _a.MajorVersion;
631
- return ({
632
- name: Name,
633
- minorVersion: MinorVersion,
634
- majorVersion: MajorVersion,
635
- tables: Object.keys(Tables)
636
- .map(function (key) { return Tables[key]; })
637
- .map(function (_a) {
638
- var Name = _a.Name, OrderedColumns = _a.OrderedColumns, DocString = _a.DocString, EntityType = _a.EntityType;
639
- return ({
640
- name: Name,
641
- docstring: DocString,
642
- entityType: EntityType,
643
- columns: OrderedColumns.map(function (_a) {
644
- var Name = _a.Name, Type = _a.Type, DocString = _a.DocString, CslType = _a.CslType;
645
- return ({
646
- name: Name,
647
- type: CslType,
648
- docstring: DocString,
649
- });
650
- }),
651
- });
652
- }),
653
- functions: Object.keys(Functions)
654
- .map(function (key) { return Functions[key]; })
655
- .map(function (_a) {
656
- var Name = _a.Name, Body = _a.Body, DocString = _a.DocString, InputParameters = _a.InputParameters;
657
- return ({
658
- name: Name,
659
- body: Body,
660
- docstring: DocString,
661
- inputParameters: InputParameters.map(function (inputParam) { return ({
662
- name: inputParam.Name,
663
- type: inputParam.Type,
664
- cslType: inputParam.CslType,
665
- cslDefaultValue: inputParam.CslDefaultValue,
666
- columns: inputParam.Columns
667
- ? inputParam.Columns.map(function (col) { return ({
668
- name: col.Name,
669
- type: col.Type,
670
- cslType: col.CslType,
671
- }); })
672
- : inputParam.Columns,
673
- }); }),
674
- });
675
- }),
676
- });
677
- });
678
- var result = {
679
- clusterType: 'Engine',
680
- cluster: {
681
- connectionString: clusterConnectionString,
682
- databases: databases,
683
- },
684
- database: databases.filter(function (db) { return db.name === databaseInContextName; })[0],
685
- };
686
- return Promise.resolve(result);
687
- };
688
- KustoLanguageService.prototype.getSchema = function () {
689
- return Promise.resolve(this._schema);
690
- };
691
- KustoLanguageService.prototype.getCommandInContext = function (document, cursorOffset) {
692
- return this.isIntellisenseV2()
693
- ? this.getCommandInContextV2(document, cursorOffset)
694
- : this.getCommandInContextV1(document, cursorOffset);
695
- };
696
- KustoLanguageService.prototype.getCommandAndLocationInContext = function (document, cursorOffset) {
697
- // We are going to remove v1 intellisense. no use to keep parity.
698
- if (!document || !this.isIntellisenseV2()) {
699
- return Promise.resolve(null);
700
- }
701
- var script = this.parseDocumentV2(document);
702
- var block = this.getCurrentCommandV2(script, cursorOffset);
703
- if (!block) {
704
- return Promise.resolve(null);
705
- }
706
- var start = document.positionAt(block.Start);
707
- var end = document.positionAt(block.End);
708
- var location = ls.Location.create(document.uri, ls.Range.create(start, end));
709
- var text = block.Text;
710
- return Promise.resolve({
711
- text: text,
712
- location: location,
713
- });
714
- };
715
- KustoLanguageService.prototype.getCommandInContextV1 = function (document, cursorOffset) {
716
- this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
717
- var command = this.getCurrentCommand(document, cursorOffset);
718
- if (!command) {
719
- return Promise.resolve(null);
720
- }
721
- return Promise.resolve(command.Text);
722
- };
723
- KustoLanguageService.prototype.getCommandInContextV2 = function (document, cursorOffset) {
724
- if (!document) {
725
- return Promise.resolve(null);
726
- }
727
- var script = this.parseDocumentV2(document);
728
- var block = this.getCurrentCommandV2(script, cursorOffset);
729
- if (!block) {
730
- return Promise.resolve(null);
731
- }
732
- // TODO: do we need to do tricks like V1 is doing in this.getCurrentCommand?
733
- return Promise.resolve(block.Text);
734
- };
735
- /**
736
- * Return an array of commands in document. each command contains the range and text.
737
- */
738
- KustoLanguageService.prototype.getCommandsInDocument = function (document) {
739
- if (!document) {
740
- return Promise.resolve([]);
741
- }
742
- return this.isIntellisenseV2()
743
- ? this.getCommandsInDocumentV2(document)
744
- : this.getCommandsInDocumentV1(document);
745
- };
746
- KustoLanguageService.prototype.getCommandsInDocumentV1 = function (document) {
747
- this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
748
- var commands = this.toArray(this._parser.Results);
749
- return Promise.resolve(commands.map(function (_a) {
750
- var AbsoluteStart = _a.AbsoluteStart, AbsoluteEnd = _a.AbsoluteEnd, Text = _a.Text;
751
- return ({
752
- absoluteStart: AbsoluteStart,
753
- absoluteEnd: AbsoluteEnd,
754
- text: Text,
755
- });
756
- }));
757
- };
758
- KustoLanguageService.prototype.toPlacementStyle = function (formatterPlacementStyle) {
759
- if (!formatterPlacementStyle) {
760
- return undefined;
761
- }
762
- switch (formatterPlacementStyle) {
763
- case 'None':
764
- return k2.PlacementStyle.None;
765
- case 'NewLine':
766
- return k2.PlacementStyle.NewLine;
767
- case 'Smart':
768
- return k2.PlacementStyle.Smart;
769
- default:
770
- throw new Error('Unknown PlacementStyle');
771
- }
772
- };
773
- KustoLanguageService.prototype.getFormattedCommandsInDocumentV2 = function (document, rangeStart, rangeEnd) {
774
- var _this = this;
775
- var script = this.parseDocumentV2(document);
776
- var commands = this.toArray(script.Blocks).filter(function (command) {
777
- if (!command.Text || command.Text.trim() == '')
778
- return false;
779
- if (rangeStart == null || rangeEnd == null)
780
- return true;
781
- // calculate command end position without \r\n.
782
- var commandEnd = command.End;
783
- var commandText = command.Text;
784
- for (var i = commandText.length - 1; i >= 0; i--) {
785
- if (commandText[i] != '\r' && commandText[i] != '\n') {
786
- break;
787
- }
788
- else {
789
- commandEnd--;
790
- }
791
- }
792
- if (command.Start > rangeStart && command.Start < rangeEnd)
793
- return true;
794
- if (commandEnd > rangeStart && commandEnd < rangeEnd)
795
- return true;
796
- if (command.Start <= rangeStart && commandEnd >= rangeEnd)
797
- return true;
798
- });
799
- if (commands.length === 0) {
800
- return { formattedCommands: [] };
801
- }
802
- var formattedCommands = commands.map(function (command) {
803
- var _a, _b;
804
- var formatterOptions = _this._languageSettings.formatter;
805
- var formatter = Kusto.Language.Editor.FormattingOptions.Default.WithIndentationSize((_a = formatterOptions === null || formatterOptions === void 0 ? void 0 : formatterOptions.indentationSize) !== null && _a !== void 0 ? _a : 4)
806
- .WithInsertMissingTokens(false)
807
- .WithPipeOperatorStyle((_b = _this.toPlacementStyle(formatterOptions === null || formatterOptions === void 0 ? void 0 : formatterOptions.pipeOperatorStyle)) !== null && _b !== void 0 ? _b : k2.PlacementStyle.Smart)
808
- .WithSemicolonStyle(Kusto.Language.Editor.PlacementStyle.None)
809
- .WithBrackettingStyle(k2.BrackettingStyle.Diagonal);
810
- if (rangeStart == null || rangeEnd == null || (rangeStart === command.Start && rangeEnd === command.End)) {
811
- var result = command.Service.GetFormattedText(formatter);
812
- return result.Text;
813
- }
814
- return command.Service.GetFormattedText(formatter).Text;
815
- });
816
- var originalRange = this.createRange(document, commands[0].Start, commands[commands.length - 1].End);
817
- return { formattedCommands: formattedCommands, originalRange: originalRange };
818
- };
819
- KustoLanguageService.prototype.getCommandsInDocumentV2 = function (document) {
820
- var script = this.parseDocumentV2(document);
821
- var commands = this.toArray(script.Blocks).filter(function (command) { return command.Text.trim() != ''; });
822
- return Promise.resolve(commands.map(function (_a) {
823
- var Start = _a.Start, End = _a.End, Text = _a.Text;
824
- return ({ absoluteStart: Start, absoluteEnd: End, text: Text });
825
- }));
826
- };
827
- KustoLanguageService.prototype.getClientDirective = function (text) {
828
- var outParam = { v: null };
829
- var isClientDirective = k.CslCommandParser.IsClientDirective(text, outParam);
830
- return Promise.resolve({
831
- isClientDirective: isClientDirective,
832
- directiveWithoutLeadingComments: outParam.v,
833
- });
834
- };
835
- KustoLanguageService.prototype.getAdminCommand = function (text) {
836
- var outParam = { v: null };
837
- var isAdminCommand = k.CslCommandParser.IsAdminCommand$1(text, outParam);
838
- return Promise.resolve({
839
- isAdminCommand: isAdminCommand,
840
- adminCommandWithoutLeadingComments: outParam.v,
841
- });
842
- };
843
- KustoLanguageService.prototype.findDefinition = function (document, position) {
844
- if (!document || !this.isIntellisenseV2()) {
845
- return Promise.resolve([]);
846
- }
847
- var script = this.parseDocumentV2(document);
848
- var cursorOffset = document.offsetAt(position);
849
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
850
- if (!currentBlock) {
851
- return Promise.resolve([]);
852
- }
853
- var relatedInfo = currentBlock.Service.GetRelatedElements(document.offsetAt(position));
854
- var relatedElements = this.toArray(relatedInfo.Elements);
855
- var definition = relatedElements[0];
856
- if (!definition) {
857
- return Promise.resolve([]);
858
- }
859
- var start = document.positionAt(definition.Start);
860
- var end = document.positionAt(definition.End);
861
- var range = ls.Range.create(start, end);
862
- var location = ls.Location.create(document.uri, range);
863
- return Promise.resolve([location]);
864
- };
865
- KustoLanguageService.prototype.findReferences = function (document, position) {
866
- if (!document || !this.isIntellisenseV2()) {
867
- return Promise.resolve([]);
868
- }
869
- var script = this.parseDocumentV2(document);
870
- var cursorOffset = document.offsetAt(position);
871
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
872
- if (!currentBlock) {
873
- return Promise.resolve([]);
874
- }
875
- var relatedInfo = currentBlock.Service.GetRelatedElements(document.offsetAt(position));
876
- var relatedElements = this.toArray(relatedInfo.Elements);
877
- if (!relatedElements || relatedElements.length == 0) {
878
- return Promise.resolve([]);
879
- }
880
- var references = relatedElements.map(function (relatedElement) {
881
- var start = document.positionAt(relatedElement.Start);
882
- var end = document.positionAt(relatedElement.End);
883
- var range = ls.Range.create(start, end);
884
- var location = ls.Location.create(document.uri, range);
885
- return location;
886
- });
887
- return Promise.resolve(references);
888
- };
889
- KustoLanguageService.prototype.getQueryParams = function (document, cursorOffset) {
890
- if (!document || !this.isIntellisenseV2()) {
891
- return Promise.resolve([]);
892
- }
893
- var script = this.parseDocumentV2(document);
894
- var parsedAndAnalyzed = this.parseAndAnalyze(document, cursorOffset);
895
- var queryParamStatements = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.QueryParametersStatement));
896
- if (!queryParamStatements || queryParamStatements.length == 0) {
897
- return Promise.resolve([]);
898
- }
899
- var queryParams = [];
900
- queryParamStatements.forEach(function (paramStatement) {
901
- paramStatement.WalkElements(function (el) {
902
- return el.ReferencedSymbol && el.ReferencedSymbol.Type
903
- ? queryParams.push({ name: el.ReferencedSymbol.Name, type: el.ReferencedSymbol.Type.Name })
904
- : undefined;
905
- });
906
- });
907
- return Promise.resolve(queryParams);
908
- };
909
- KustoLanguageService.prototype.getRenderInfo = function (document, cursorOffset) {
910
- var _this = this;
911
- var parsedAndAnalyzed = this.parseAndAnalyze(document, cursorOffset);
912
- if (!parsedAndAnalyzed) {
913
- return Promise.resolve(undefined);
914
- }
915
- var renderStatements = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.RenderOperator));
916
- if (!renderStatements || renderStatements.length === 0) {
917
- return Promise.resolve(undefined);
918
- }
919
- // assuming a single render statement
920
- var renderStatement = renderStatements[0];
921
- // Start and end relative to block start.
922
- var startOffset = renderStatement.TextStart;
923
- var endOffset = renderStatement.End;
924
- var visualization = renderStatement.ChartType.ValueText;
925
- var withClause = renderStatement.WithClause;
926
- if (!withClause) {
927
- var info = {
928
- options: {
929
- visualization: visualization,
930
- },
931
- location: { startOffset: startOffset, endOffset: endOffset },
932
- };
933
- return Promise.resolve(info);
934
- }
935
- var properties = this.toArray(withClause.Properties);
936
- var props = properties.reduce(function (prev, property) {
937
- var name = property.Element$1.Name.SimpleName;
938
- switch (name) {
939
- case 'xcolumn':
940
- var value = property.Element$1.Expression.ReferencedSymbol.Name;
941
- prev[name] = value;
942
- break;
943
- case 'ycolumns':
944
- case 'anomalycolumns':
945
- var nameNodes = _this.toArray(property.Element$1.Expression.Names);
946
- var values = nameNodes.map(function (nameNode) { return nameNode.Element$1.SimpleName; });
947
- prev[name] = values;
948
- break;
949
- case 'ymin':
950
- case 'ymax':
951
- var numericVal = parseFloat(property.Element$1.Expression.ConstantValue);
952
- prev[name] = numericVal;
953
- break;
954
- case 'title':
955
- case 'xtitle':
956
- case 'ytitle':
957
- case 'visualization':
958
- case 'series':
959
- var strVal = property.Element$1.Expression.ConstantValue;
960
- prev[name] = strVal;
961
- break;
962
- case 'xaxis':
963
- case 'yaxis':
964
- var scale = property.Element$1.Expression.ConstantValue;
965
- prev[name] = scale;
966
- break;
967
- case 'legend':
968
- var legend = property.Element$1.Expression.ConstantValue;
969
- prev[name] = legend;
970
- break;
971
- case 'ySplit':
972
- var split = property.Element$1.Expression.ConstantValue;
973
- prev[name] = split;
974
- break;
975
- case 'accumulate':
976
- var accumulate = property.Element$1.Expression.ConstantValue;
977
- prev[name] = accumulate;
978
- break;
979
- case 'kind':
980
- var val = property.Element$1.Expression.ConstantValue;
981
- prev[name] = val;
982
- break;
983
- default:
984
- assertNever(name);
985
- }
986
- return prev;
987
- }, {});
988
- var renderOptions = __assign({ visualization: visualization }, props);
989
- var renderInfo = {
990
- options: renderOptions,
991
- location: { startOffset: startOffset, endOffset: endOffset },
992
- };
993
- return Promise.resolve(renderInfo);
994
- };
995
- KustoLanguageService.prototype.getReferencedGlobalParams = function (document, cursorOffset) {
996
- if (!document || !this.isIntellisenseV2()) {
997
- return Promise.resolve([]);
998
- }
999
- var script = this.parseDocumentV2(document);
1000
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
1001
- if (!currentBlock) {
1002
- return Promise.resolve([]);
1003
- }
1004
- var text = currentBlock.Text;
1005
- var parsedAndAnalyzed = Kusto.Language.KustoCode.ParseAndAnalyze(text, this._kustoJsSchemaV2);
1006
- // We take the ambient parameters
1007
- var ambientParameters = this.toArray(this._kustoJsSchemaV2.Parameters);
1008
- // We take all referenced symbols in the query
1009
- var referencedSymbols = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.Expression))
1010
- .filter(function (expression) { return expression.ReferencedSymbol !== null; })
1011
- .map(function (x) { return x.ReferencedSymbol; });
1012
- // The Intersection between them is the ambient parameters that are used in the query.
1013
- // Note: Ideally we would use Set here (or at least array.Include), but were' compiling down to es2015.
1014
- var intersection = referencedSymbols.filter(function (referencedSymbol) {
1015
- return ambientParameters.filter(function (ambientParameter) { return ambientParameter === referencedSymbol; }).length > 0;
1016
- });
1017
- var result = intersection.map(function (param) { return ({ name: param.Name, type: param.Type.Name }); });
1018
- return Promise.resolve(result);
1019
- };
1020
- KustoLanguageService.prototype.getGlobalParams = function (document) {
1021
- if (!this.isIntellisenseV2()) {
1022
- return Promise.resolve([]);
1023
- }
1024
- var params = this.toArray(this._kustoJsSchemaV2.Parameters);
1025
- var result = params.map(function (param) { return ({ name: param.Name, type: param.Type.Name }); });
1026
- return Promise.resolve(result);
1027
- };
1028
- KustoLanguageService.prototype.doRename = function (document, position, newName) {
1029
- var _a;
1030
- if (!document || !this.isIntellisenseV2()) {
1031
- return Promise.resolve(undefined);
1032
- }
1033
- var script = this.parseDocumentV2(document);
1034
- var cursorOffset = document.offsetAt(position);
1035
- var currentBLock = this.getCurrentCommandV2(script, cursorOffset);
1036
- if (!currentBLock) {
1037
- return Promise.resolve(undefined);
1038
- }
1039
- var relatedInfo = currentBLock.Service.GetRelatedElements(document.offsetAt(position));
1040
- var relatedElements = this.toArray(relatedInfo.Elements);
1041
- var declarations = relatedElements.filter(function (e) { return e.Kind == k2.RelatedElementKind.Declaration; });
1042
- // A declaration must be one of the elements
1043
- if (!declarations || declarations.length == 0) {
1044
- return Promise.resolve(undefined);
1045
- }
1046
- var edits = relatedElements.map(function (edit) {
1047
- var start = document.positionAt(edit.Start);
1048
- var end = document.positionAt(edit.End);
1049
- var range = ls.Range.create(start, end);
1050
- return ls.TextEdit.replace(range, newName);
1051
- });
1052
- // create a workspace edit
1053
- var workspaceEdit = { changes: (_a = {}, _a[document.uri] = edits, _a) };
1054
- return Promise.resolve(workspaceEdit);
1055
- };
1056
- KustoLanguageService.prototype.doHover = function (document, position) {
1057
- if (!document || !this.isIntellisenseV2()) {
1058
- return Promise.resolve(undefined);
1059
- }
1060
- var script = this.parseDocumentV2(document);
1061
- var cursorOffset = document.offsetAt(position);
1062
- var currentBLock = this.getCurrentCommandV2(script, cursorOffset);
1063
- if (!currentBLock) {
1064
- return Promise.resolve(undefined);
1065
- }
1066
- var isSupported = currentBLock.Service.IsFeatureSupported(k2.CodeServiceFeatures.QuickInfo, cursorOffset);
1067
- if (!isSupported) {
1068
- return Promise.resolve(undefined);
1069
- }
1070
- var quickInfo = currentBLock.Service.GetQuickInfo(cursorOffset);
1071
- if (!quickInfo || !quickInfo.Items) {
1072
- return Promise.resolve(undefined);
1073
- }
1074
- var items = this.toArray(quickInfo.Items);
1075
- if (!items) {
1076
- return Promise.resolve(undefined);
1077
- }
1078
- // Errors are already shown in getDiagnostics. we don't want them in doHover.
1079
- items = items.filter(function (item) { return item.Kind !== k2.QuickInfoKind.Error; });
1080
- var itemsText = items.map(function (item) { return item.Text.replace('\n\n', '\n* * *\n'); });
1081
- // separate items by horizontal line.
1082
- var text = itemsText.join('\n* * *\n');
1083
- // Instead of just an empty line between the first line (the signature) and the second line (the description)
1084
- // add an horizontal line (* * * in markdown) between them.
1085
- return Promise.resolve({ contents: text });
1086
- };
1087
- Object.defineProperty(KustoLanguageService, "dummySchema", {
1088
- //#region dummy schema for manual testing
1089
- get: function () {
1090
- var database = {
1091
- majorVersion: 0,
1092
- minorVersion: 0,
1093
- name: 'Kuskus',
1094
- tables: [
1095
- {
1096
- name: 'KustoLogs',
1097
- columns: [
1098
- {
1099
- name: 'Source',
1100
- type: 'string',
1101
- },
1102
- {
1103
- name: 'Timestamp',
1104
- type: 'datetime',
1105
- },
1106
- {
1107
- name: 'Directory',
1108
- type: 'string',
1109
- },
1110
- ],
1111
- docstring: 'A dummy description to test that docstring shows as expected when hovering over a table',
1112
- },
1113
- ],
1114
- functions: [
1115
- {
1116
- name: 'HowBig',
1117
- inputParameters: [
1118
- {
1119
- name: 'T',
1120
- columns: [
1121
- {
1122
- name: 'Timestamp',
1123
- type: 'System.DateTime',
1124
- cslType: 'datetime',
1125
- },
1126
- ],
1127
- },
1128
- ],
1129
- docstring: 'A dummy description to test that docstring shows as expected when hovering over a function',
1130
- body: "{\r\n union \r\n (T | count | project V='Volume', Metric = strcat(Count/1e9, ' Billion records')),\r\n (T | summarize FirstRecord=min(Timestamp)| project V='Volume', Metric = strcat(toint((now()-FirstRecord)/1d), ' Days of data (from: ', format_datetime(FirstRecord, 'yyyy-MM-dd'),')')),\r\n (T | where Timestamp > ago(1h) | count | project V='Velocity', Metric = strcat(Count/1e6, ' Million records / hour')),\r\n (T | summarize Latency=now()-max(Timestamp) | project V='Velocity', Metric = strcat(Latency / 1sec, ' seconds latency')),\r\n (T | take 1 | project V='Variety', Metric=tostring(pack_all()))\r\n | order by V \r\n}",
1131
- },
1132
- {
1133
- name: 'FindCIDPast24h',
1134
- inputParameters: [
1135
- {
1136
- name: 'clientActivityId',
1137
- type: 'System.String',
1138
- cslType: 'string',
1139
- },
1140
- ],
1141
- body: '{ KustoLogs | where Timestamp > now(-1d) | where ClientActivityId == clientActivityId} ',
1142
- },
1143
- ],
1144
- };
1145
- var languageServiceSchema = {
1146
- clusterType: 'Engine',
1147
- cluster: {
1148
- connectionString: 'https://kuskus.kusto.windows.net;fed=true',
1149
- databases: [database],
1150
- },
1151
- database: database,
1152
- };
1153
- return languageServiceSchema;
1154
- },
1155
- enumerable: false,
1156
- configurable: true
1157
- });
1158
- //#endregion
1159
- KustoLanguageService.convertToEntityDataType = function (kustoType) { };
1160
- /**
1161
- * We do not want to expose Bridge.Net generated schema, so we expose a cleaner javascript schema.
1162
- * Here it gets converted to the bridge.Net schema
1163
- * @param schema Language Service schema
1164
- */
1165
- KustoLanguageService.convertToKustoJsSchema = function (schema) {
1166
- switch (schema.clusterType) {
1167
- case 'Engine':
1168
- var currentDatabaseName_1 = schema.database ? schema.database.name : undefined;
1169
- var kCluster = new k.KustoIntelliSenseClusterEntity();
1170
- var kDatabaseInContext_1 = undefined;
1171
- kCluster.ConnectionString = schema.cluster.connectionString;
1172
- var databases_1 = [];
1173
- schema.cluster.databases.forEach(function (database) {
1174
- var kDatabase = new k.KustoIntelliSenseDatabaseEntity();
1175
- kDatabase.Name = database.name;
1176
- var tables = [];
1177
- database.tables.forEach(function (table) {
1178
- var kTable = new k.KustoIntelliSenseTableEntity();
1179
- kTable.Name = table.name;
1180
- var cols = [];
1181
- table.columns.forEach(function (column) {
1182
- var kColumn = new k.KustoIntelliSenseColumnEntity();
1183
- kColumn.Name = column.name;
1184
- kColumn.TypeCode = k.EntityDataType[getEntityDataTypeFromCslType(column.type)];
1185
- cols.push(kColumn);
1186
- });
1187
- kTable.Columns = new Bridge.ArrayEnumerable(cols);
1188
- tables.push(kTable);
1189
- });
1190
- var functions = [];
1191
- database.functions.forEach(function (fn) {
1192
- var kFunction = new k.KustoIntelliSenseFunctionEntity();
1193
- (kFunction.Name = fn.name),
1194
- (kFunction.CallName = s.getCallName(fn)),
1195
- (kFunction.Expression = s.getExpression(fn)),
1196
- functions.push(kFunction);
1197
- });
1198
- kDatabase.Tables = new Bridge.ArrayEnumerable(tables);
1199
- kDatabase.Functions = new Bridge.ArrayEnumerable(functions);
1200
- databases_1.push(kDatabase);
1201
- if (database.name == currentDatabaseName_1) {
1202
- kDatabaseInContext_1 = kDatabase;
1203
- }
1204
- });
1205
- kCluster.Databases = new Bridge.ArrayEnumerable(databases_1);
1206
- var kSchema = new k.KustoIntelliSenseQuerySchema(kCluster, kDatabaseInContext_1);
1207
- return kSchema;
1208
- case 'ClusterManager':
1209
- var accounts = schema.accounts.map(function (account) {
1210
- var kAccount = new k.KustoIntelliSenseAccountEntity();
1211
- kAccount.Name = account;
1212
- return kAccount;
1213
- });
1214
- var services = schema.services.map(function (service) {
1215
- var kService = new k.KustoIntelliSenseServiceEntity();
1216
- kService.Name = service;
1217
- return kService;
1218
- });
1219
- var connectionString = schema.connectionString;
1220
- var result = {
1221
- accounts: accounts,
1222
- services: services,
1223
- connectionString: connectionString,
1224
- };
1225
- return result;
1226
- case 'DataManagement':
1227
- return undefined;
1228
- default:
1229
- return assertNever(schema);
1230
- }
1231
- };
1232
- /**
1233
- * Returns something like '(x: string, y: datetime)'
1234
- * @param params scalar parameters
1235
- */
1236
- KustoLanguageService.scalarParametersToSignature = function (params) {
1237
- var signatureWithoutParens = params.map(function (param) { return param.name + ": " + param.cslType; }).join(', ');
1238
- return "(" + signatureWithoutParens + ")";
1239
- };
1240
- /**
1241
- * Returns something like '(x: string, T: (y: int))'
1242
- * @param params input parameters (tabular or scalar)
1243
- */
1244
- KustoLanguageService.inputParameterToSignature = function (params) {
1245
- var _this = this;
1246
- var signatureWithoutParens = params
1247
- .map(function (param) {
1248
- if (param.columns) {
1249
- var tableSignature = _this.scalarParametersToSignature(param.columns);
1250
- return param.name + ": " + tableSignature;
1251
- }
1252
- else {
1253
- return param.name + ": " + param.cslType;
1254
- }
1255
- })
1256
- .join(', ');
1257
- return "(" + signatureWithoutParens + ")";
1258
- };
1259
- /**
1260
- * converts a function definition to a let statement.
1261
- * @param fn function
1262
- */
1263
- KustoLanguageService.toLetStatement = function (fn) {
1264
- var signature = this.inputParameterToSignature(fn.inputParameters);
1265
- return "let " + fn.name + " = " + signature + " " + fn.body;
1266
- };
1267
- KustoLanguageService.createColumnSymbol = function (col) {
1268
- return new sym.ColumnSymbol(col.name, sym.ScalarTypes.GetSymbol(getCslTypeNameFromClrType(col.type)), col.docstring);
1269
- };
1270
- KustoLanguageService.createParameterSymbol = function (param) {
1271
- var paramSymbol = Kusto.Language.Symbols.ScalarTypes.GetSymbol(getCslTypeNameFromClrType(param.type));
1272
- return new sym.ParameterSymbol(param.name, paramSymbol, null);
1273
- };
1274
- KustoLanguageService.createParameter = function (param) {
1275
- if (!param.columns) {
1276
- var paramSymbol = Kusto.Language.Symbols.ScalarTypes.GetSymbol(getCslTypeNameFromClrType(param.type));
1277
- var expression = param.cslDefaultValue && typeof param.cslDefaultValue === 'string'
1278
- ? parsing.QueryParser.ParseLiteral$1(param.cslDefaultValue)
1279
- : undefined;
1280
- return new sym.Parameter.$ctor3(param.name, paramSymbol, null, null, null, false, null, 1, 1, expression, null);
1281
- }
1282
- if (param.columns.length == 0) {
1283
- return new sym.Parameter.ctor(param.name, sym.ParameterTypeKind.Tabular, sym.ArgumentKind.Expression, null, null, false, null, 1, 1, null, null);
1284
- }
1285
- var argumentType = new sym.TableSymbol.ctor(param.columns.map(function (col) { return KustoLanguageService.createColumnSymbol(col); }));
1286
- return new sym.Parameter.$ctor2(param.name, argumentType);
1287
- };
1288
- KustoLanguageService.convertToDatabaseSymbol = function (db, globalState, addFunctions) {
1289
- var createFunctionSymbol = function (fn) {
1290
- var parameters = fn.inputParameters.map(function (param) {
1291
- return KustoLanguageService.createParameter(param);
1292
- });
1293
- // TODO: handle outputColumns (right now it doesn't seem to be implemented for any function).
1294
- return new sym.FunctionSymbol.$ctor16(fn.name, fn.body, KustoLanguageService.toBridgeList(parameters), fn.docstring);
1295
- };
1296
- var createTableSymbol = function (tbl) {
1297
- var columnSymbols = tbl.columns.map(function (col) { return KustoLanguageService.createColumnSymbol(col); });
1298
- var symbol = new sym.TableSymbol.$ctor3(tbl.name, columnSymbols);
1299
- symbol.Description = tbl.docstring;
1300
- switch (tbl.entityType) {
1301
- case 'MaterializedViewTable':
1302
- symbol = symbol.WithIsMaterializedView(true);
1303
- break;
1304
- case 'ExternalTable':
1305
- symbol = symbol.WithIsExternal(true);
1306
- break;
1307
- default:
1308
- }
1309
- return symbol;
1310
- };
1311
- var createDatabaseSymbol = function (db) {
1312
- var tableSymbols = db.tables ? db.tables.map(function (tbl) { return createTableSymbol(tbl); }) : [];
1313
- var functionSymbols = db.functions ? db.functions.map(function (fun) { return createFunctionSymbol(fun); }) : [];
1314
- return new sym.DatabaseSymbol.ctor(db.name, tableSymbols.concat(functionSymbols));
1315
- };
1316
- var databaseSymbol = createDatabaseSymbol(db);
1317
- return databaseSymbol;
1318
- };
1319
- KustoLanguageService.prototype.convertToKustoJsSchemaV2 = function (schema) {
1320
- var cached = this._schemaCache[schema.cluster.connectionString];
1321
- // create a cache entry for the cluster if non yet exists.
1322
- if (!cached) {
1323
- this._schemaCache[schema.cluster.connectionString] = {};
1324
- cached = this._schemaCache[schema.cluster.connectionString];
1325
- }
1326
- // Remove deleted databases from cache
1327
- var schemaDbLookup = schema.cluster.databases.reduce(function (prev, curr) { return (prev[curr.name] = curr); }, {});
1328
- Object.keys(cached).map(function (dbName) {
1329
- if (!schemaDbLookup[dbName]) {
1330
- delete cached.dbName;
1331
- }
1332
- });
1333
- var globalState = GlobalState.Default;
1334
- var currentDatabaseName = schema.database ? schema.database.name : undefined;
1335
- var databaseInContext = undefined;
1336
- // Update out-of-data databases to cache
1337
- var databases = schema.cluster.databases.map(function (db) {
1338
- var shouldIncludeFunctions = db.name === currentDatabaseName;
1339
- var cachedDb = cached[db.name];
1340
- // This is an older version than we have, or we need to parse functions.
1341
- if (!cachedDb ||
1342
- cachedDb.database.majorVersion < db.majorVersion ||
1343
- (shouldIncludeFunctions && !cachedDb.includesFunctions)) {
1344
- // only add functions for the database in context (it's very time consuming)
1345
- var databaseSymbol_1 = KustoLanguageService.convertToDatabaseSymbol(db, globalState, shouldIncludeFunctions);
1346
- cached[db.name] = { database: db, symbol: databaseSymbol_1, includesFunctions: shouldIncludeFunctions };
1347
- }
1348
- var databaseSymbol = cached[db.name].symbol;
1349
- if (db.name === currentDatabaseName) {
1350
- databaseInContext = databaseSymbol;
1351
- }
1352
- return databaseSymbol;
1353
- });
1354
- // Replace new URL due to polyfill issue in IE
1355
- // const hostname = new URL(schema.cluster.connectionString.split(';')[0]).hostname;
1356
- var hostname = schema.cluster.connectionString.match(/(.*\/\/)?([^\/;]*)/)[2];
1357
- var clusterName = hostname.split('.')[0];
1358
- var clusterSymbol = new sym.ClusterSymbol.ctor(clusterName, databases);
1359
- globalState = globalState.WithCluster(clusterSymbol);
1360
- if (databaseInContext) {
1361
- globalState = globalState.WithDatabase(databaseInContext);
1362
- }
1363
- // Inject global parameters to global scope.
1364
- if (schema.globalParameters) {
1365
- var parameters = schema.globalParameters.map(function (param) {
1366
- return KustoLanguageService.createParameterSymbol(param);
1367
- });
1368
- globalState = globalState.WithParameters(KustoLanguageService.toBridgeList(parameters));
1369
- }
1370
- return globalState;
1371
- };
1372
- KustoLanguageService.prototype.getClassificationsFromParseResult = function (offset) {
1373
- var _this = this;
1374
- if (offset === void 0) { offset = 0; }
1375
- var classifications = this.toArray(this._parser.Results)
1376
- .map(function (command) { return _this.toArray(command.Tokens); })
1377
- .reduce(function (prev, curr) { return prev.concat(curr); }, [])
1378
- .map(function (cslCommandToken) {
1379
- var range = new k2.ClassifiedRange(_this.tokenKindToClassificationKind(cslCommandToken.TokenKind), cslCommandToken.AbsoluteStart + offset, cslCommandToken.Length);
1380
- return range;
1381
- });
1382
- return classifications;
1383
- };
1384
- /**
1385
- * trim trailing newlines from range
1386
- */
1387
- KustoLanguageService.trimTrailingNewlineFromRange = function (textInRange, rangeStartOffset, document, range) {
1388
- var currentIndex = textInRange.length - 1;
1389
- while (textInRange[currentIndex] === '\r' || textInRange[currentIndex] === '\n') {
1390
- --currentIndex;
1391
- }
1392
- var newEndOffset = rangeStartOffset + currentIndex + 1;
1393
- var newEndPosition = document.positionAt(newEndOffset);
1394
- var newRange = ls.Range.create(range.start, newEndPosition);
1395
- return newRange;
1396
- };
1397
- /**
1398
- * Maps numbers to strings, such that if a>b numerically, f(a)>f(b) lexicographically.
1399
- * 1 -> "a", 26 -> "z", 27 -> "za", 28 -> "zb", 52 -> "zz", 53 ->"zza"
1400
- * @param order - The number to be converted to a sorting-string. order should start at 1.
1401
- * @returns A string repenting the order.
1402
- */
1403
- KustoLanguageService.prototype.getSortText = function (order) {
1404
- if (order <= 0) {
1405
- throw new RangeError("order should be a number >= 1. instead got " + order);
1406
- }
1407
- var sortText = '';
1408
- var numCharacters = 26; // "z" - "a" + 1;
1409
- var div = Math.floor(order / numCharacters);
1410
- for (var i = 0; i < div; ++i) {
1411
- sortText += 'z';
1412
- }
1413
- var reminder = order % numCharacters;
1414
- if (reminder > 0) {
1415
- sortText += String.fromCharCode(96 + reminder);
1416
- }
1417
- return sortText;
1418
- };
1419
- /**
1420
- * ParseTextV1 parses the given text with the given parse mode.
1421
- * Additionally - it will make sure not to provide rules provider for non-engine clusters
1422
- * since the only rules provider parse can handle is the engine's. It will try to look for function
1423
- * definitions to colorize and will throw since they're not there.
1424
- * @param text
1425
- * @param parseMode
1426
- */
1427
- KustoLanguageService.prototype.parseTextV1 = function (text, parseMode) {
1428
- this._parser.Parse(this._schema.clusterType === 'Engine' ? this._rulesProvider : null, text, parseMode);
1429
- };
1430
- KustoLanguageService.prototype.parseDocumentV1 = function (document, parseMode) {
1431
- // already parsed a later version, or better parse mode for this uri
1432
- if (this._parsePropertiesV1 &&
1433
- !this._parsePropertiesV1.isParseNeeded(document, this._rulesProvider, parseMode)) {
1434
- return;
1435
- }
1436
- this.parseTextV1(document.getText(), parseMode);
1437
- this._parsePropertiesV1 = new ParseProperties(document.version, document.uri, this._rulesProvider, parseMode);
1438
- };
1439
- KustoLanguageService.prototype.parseDocumentV2 = function (document) {
1440
- if (this._parsePropertiesV2 && !this._parsePropertiesV2.isParseNeeded(document, this._rulesProvider)) {
1441
- return this._script;
1442
- }
1443
- if (!this._script) {
1444
- this._script = k2.CodeScript.From$1(document.getText(), this._kustoJsSchemaV2);
1445
- }
1446
- else {
1447
- this._script = this._script.WithText(document.getText());
1448
- }
1449
- this._parsePropertiesV2 = new ParseProperties(document.version, document.uri);
1450
- return this._script;
1451
- };
1452
- /**
1453
- * Return the CslCommand that wraps the caret location, or undefined if caret is outside any command
1454
- * @param document the document to extract the current command from
1455
- * @param caretAbsolutePosition absolute caret position
1456
- */
1457
- KustoLanguageService.prototype.getCurrentCommand = function (document, caretAbsolutePosition) {
1458
- var commands = this.toArray(this._parser.Results);
1459
- var command = commands.filter(function (command) { return command.AbsoluteStart <= caretAbsolutePosition && command.AbsoluteEnd >= caretAbsolutePosition; })[0];
1460
- // There is an edge case when cursor appears at the end of the command
1461
- // which is not yet considered to be part of the parsed command (therefore: +1 for the AbsoluteEdit property)
1462
- if (!command) {
1463
- command = commands.filter(function (command) {
1464
- return command.AbsoluteStart <= caretAbsolutePosition && command.AbsoluteEnd + 1 >= caretAbsolutePosition;
1465
- })[0];
1466
- // If we have 2 newlines in the end of the text the cursor is _probably_ at the end of the text
1467
- // which this means that we're not actually standing on any command. Thus return null.
1468
- if (!command || command.Text.endsWith('\r\n\r\n')) {
1469
- return null;
1470
- }
1471
- }
1472
- return command;
1473
- };
1474
- KustoLanguageService.prototype.getCurrentCommandV2 = function (script, offset) {
1475
- var block = script.GetBlockAtPosition(offset);
1476
- return block;
1477
- };
1478
- KustoLanguageService.prototype.getTextToInsert = function (rule, option) {
1479
- var beforeApplyInfo = rule.GetBeforeApplyInfo(option.Value);
1480
- var afterApplyInfo = rule.GetAfterApplyInfo(option.Value);
1481
- // this is the basic text to be inserted,
1482
- // but we still need to figure out where the cursor will end up after completion is applied.
1483
- var insertText = beforeApplyInfo.Text || '' + option.Value + afterApplyInfo.Text || '';
1484
- var insertTextFormat = ls.InsertTextFormat.PlainText;
1485
- var snippetFinalTabStop = '$0';
1486
- if (afterApplyInfo.OffsetToken && afterApplyInfo.OffsetPosition) {
1487
- var tokenOffset = insertText.indexOf(afterApplyInfo.OffsetToken);
1488
- if (tokenOffset >= 0) {
1489
- insertText = this.insertToString(insertText, snippetFinalTabStop, tokenOffset - insertText.length + afterApplyInfo.OffsetPosition);
1490
- insertTextFormat = ls.InsertTextFormat.Snippet;
1491
- }
1492
- }
1493
- else if (afterApplyInfo.OffsetPosition) {
1494
- // We only handle negative offsets
1495
- insertText = this.insertToString(insertText, snippetFinalTabStop, afterApplyInfo.OffsetPosition);
1496
- insertTextFormat = ls.InsertTextFormat.Snippet;
1497
- }
1498
- return { insertText: insertText, insertTextFormat: insertTextFormat };
1499
- };
1500
- /**
1501
- * create a new string with stringToInsert inserted at offsetFromEnd in originalString.
1502
- * @param originalString string to insert to
1503
- * @param stringToInsert string to insert
1504
- * @param offsetFromEnd a negative number that will represent offset to the left. 0 means simple concat
1505
- */
1506
- KustoLanguageService.prototype.insertToString = function (originalString, stringToInsert, offsetFromEnd) {
1507
- var index = originalString.length + offsetFromEnd;
1508
- if (offsetFromEnd >= 0 || index < 0) {
1509
- return originalString; // Cannot insert before or after the string
1510
- }
1511
- var before = originalString.substring(0, index);
1512
- var after = originalString.substring(index);
1513
- return before + stringToInsert + after;
1514
- };
1515
- KustoLanguageService.prototype.getCommandWithoutLastWord = function (text) {
1516
- var lastWordRegex = XRegExp('[\\w_]*$', 's');
1517
- return text.replace(lastWordRegex, '');
1518
- };
1519
- KustoLanguageService.prototype.createRulesProvider = function (schema, clusterType) {
1520
- var queryParameters = new (List(String))();
1521
- var availableClusters = new (List(String))();
1522
- this._parser = new k.CslCommandParser();
1523
- if (clusterType == 'Engine') {
1524
- var engineSchema = schema;
1525
- this._rulesProvider =
1526
- this._languageSettings && this._languageSettings.includeControlCommands
1527
- ? new k.CslIntelliSenseRulesProvider.$ctor1(engineSchema.Cluster, engineSchema, queryParameters, availableClusters, null, true, true)
1528
- : new k.CslQueryIntelliSenseRulesProvider.$ctor1(engineSchema.Cluster, engineSchema, queryParameters, availableClusters, null, null, null);
1529
- return;
1530
- }
1531
- if (clusterType === 'DataManagement') {
1532
- this._rulesProvider = new k.DataManagerIntelliSenseRulesProvider(null);
1533
- return;
1534
- }
1535
- // This is a cluster manger
1536
- var _a = schema, accounts = _a.accounts, services = _a.services, connectionString = _a.connectionString;
1537
- new k.KustoIntelliSenseAccountEntity();
1538
- new k.KustoIntelliSenseServiceEntity();
1539
- this._rulesProvider = new k.ClusterManagerIntelliSenseRulesProvider.$ctor1(new Bridge.ArrayEnumerable(accounts), new Bridge.ArrayEnumerable(services), connectionString);
1540
- };
1541
- KustoLanguageService.prototype.kustoKindToLsKind = function (kustoKind) {
1542
- var res = this._kustoKindtolsKind[kustoKind];
1543
- return res ? res : ls.CompletionItemKind.Variable;
1544
- };
1545
- KustoLanguageService.prototype.kustoKindToLsKindV2 = function (kustoKind) {
1546
- var res = this._kustoKindToLsKindV2[kustoKind];
1547
- return res ? res : ls.CompletionItemKind.Variable;
1548
- };
1549
- KustoLanguageService.prototype.createRange = function (document, start, end) {
1550
- return ls.Range.create(document.positionAt(start), document.positionAt(end));
1551
- };
1552
- KustoLanguageService.prototype.toArray = function (bridgeList) {
1553
- return Bridge.toArray(bridgeList);
1554
- };
1555
- KustoLanguageService.toBridgeList = function (array) {
1556
- // copied from bridge.js from the implementation of Enumerable.prototype.toList
1557
- return new (System.Collections.Generic.List$1(System.Object).$ctor1)(array);
1558
- };
1559
- KustoLanguageService.prototype.tokenKindToClassificationKind = function (token) {
1560
- var conversion = this._tokenKindToClassificationKind[token];
1561
- return conversion || k2.ClassificationKind.PlainText;
1562
- };
1563
- KustoLanguageService.prototype.parseAndAnalyze = function (document, cursorOffset) {
1564
- if (!document || !this.isIntellisenseV2()) {
1565
- return undefined;
1566
- }
1567
- var script = this.parseDocumentV2(document);
1568
- var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
1569
- if (!currentBlock) {
1570
- return undefined;
1571
- }
1572
- var text = currentBlock.Text;
1573
- var parsedAndAnalyzed = Kusto.Language.KustoCode.ParseAndAnalyze(text, this._kustoJsSchemaV2);
1574
- return parsedAndAnalyzed;
1575
- };
1576
- return KustoLanguageService;
1577
- }());
1578
- var languageService = new KustoLanguageService(KustoLanguageService.dummySchema, {
1579
- includeControlCommands: true,
1580
- useIntellisenseV2: true,
1581
- useSemanticColorization: true,
1582
- });
1583
- /**
1584
- * Obtain an instance of the kusto language service.
1585
- */
1586
- export function getKustoLanguageService() {
1587
- return languageService;
1588
- }
1
+ var __assign = (this && this.__assign) || function () {
2
+ __assign = Object.assign || function(t) {
3
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
4
+ s = arguments[i];
5
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
+ t[p] = s[p];
7
+ }
8
+ return t;
9
+ };
10
+ return __assign.apply(this, arguments);
11
+ };
12
+ /// <reference path="../../node_modules/@kusto/language-service/Kusto.JavaScript.Client.d.ts" />
13
+ /// <reference path="../../node_modules/@kusto/language-service-next/Kusto.Language.Bridge.d.ts" />
14
+ /// <reference path="../typings/refs.d.ts" />
15
+ import * as s from './schema';
16
+ // polyfill string endsWith
17
+ if (!String.prototype.endsWith) {
18
+ String.prototype.endsWith = function (search, this_len) {
19
+ if (this_len === undefined || this_len > this.length) {
20
+ this_len = this.length;
21
+ }
22
+ return this.substring(this_len - search.length, this_len) === search;
23
+ };
24
+ }
25
+ // If we're running in a web worker - which doesn't share global context with the main thread -
26
+ // we need to manually load dependencies that are not explicit- meaning our non-module dependencies
27
+ // generated by Bridge.Net
28
+ if (typeof document == 'undefined') {
29
+ // monaco will run the worker from vs/base/worker so the relative path needs to be from there (hence going up 2 dirs)
30
+ importScripts('../../language/kusto/bridge.min.js');
31
+ importScripts('../../language/kusto/kusto.javascript.client.min.js');
32
+ importScripts('../../language/kusto/Kusto.Language.Bridge.min.js');
33
+ }
34
+ import * as ls from '../_deps/vscode-languageserver-types/main';
35
+ import * as XRegExp from '../_deps/xregexp/xregexp-all';
36
+ var k = Kusto.Data.IntelliSense;
37
+ var parsing = Kusto.Language.Parsing;
38
+ var k2 = Kusto.Language.Editor;
39
+ var sym = Kusto.Language.Symbols;
40
+ var GlobalState = Kusto.Language.GlobalState;
41
+ import { getCslTypeNameFromClrType, getEntityDataTypeFromCslType } from './schema';
42
+ var List = System.Collections.Generic.List$1;
43
+ function assertNever(x) {
44
+ throw new Error('Unexpected object: ' + x);
45
+ }
46
+ var ParseProperties = /** @class */ (function () {
47
+ function ParseProperties(version, uri, rulesProvider, parseMode) {
48
+ this.version = version;
49
+ this.uri = uri;
50
+ this.rulesProvider = rulesProvider;
51
+ this.parseMode = parseMode;
52
+ }
53
+ ParseProperties.prototype.isParseNeeded = function (document, rulesProvider, parseMode) {
54
+ if (document.uri === this.uri &&
55
+ (!rulesProvider || rulesProvider === this.rulesProvider) &&
56
+ document.version <= this.version &&
57
+ parseMode &&
58
+ parseMode <= this.parseMode) {
59
+ return false;
60
+ }
61
+ return true;
62
+ };
63
+ return ParseProperties;
64
+ }());
65
+ export var TokenKind;
66
+ (function (TokenKind) {
67
+ TokenKind[TokenKind["TableToken"] = 2] = "TableToken";
68
+ TokenKind[TokenKind["TableColumnToken"] = 4] = "TableColumnToken";
69
+ TokenKind[TokenKind["OperatorToken"] = 8] = "OperatorToken";
70
+ TokenKind[TokenKind["SubOperatorToken"] = 16] = "SubOperatorToken";
71
+ TokenKind[TokenKind["CalculatedColumnToken"] = 32] = "CalculatedColumnToken";
72
+ TokenKind[TokenKind["StringLiteralToken"] = 64] = "StringLiteralToken";
73
+ TokenKind[TokenKind["FunctionNameToken"] = 128] = "FunctionNameToken";
74
+ TokenKind[TokenKind["UnknownToken"] = 256] = "UnknownToken";
75
+ TokenKind[TokenKind["CommentToken"] = 512] = "CommentToken";
76
+ TokenKind[TokenKind["PlainTextToken"] = 1024] = "PlainTextToken";
77
+ TokenKind[TokenKind["DataTypeToken"] = 2048] = "DataTypeToken";
78
+ TokenKind[TokenKind["ControlCommandToken"] = 4096] = "ControlCommandToken";
79
+ TokenKind[TokenKind["CommandPartToken"] = 8192] = "CommandPartToken";
80
+ TokenKind[TokenKind["QueryParametersToken"] = 16384] = "QueryParametersToken";
81
+ TokenKind[TokenKind["CslCommandToken"] = 32768] = "CslCommandToken";
82
+ TokenKind[TokenKind["LetVariablesToken"] = 65536] = "LetVariablesToken";
83
+ TokenKind[TokenKind["PluginToken"] = 131072] = "PluginToken";
84
+ TokenKind[TokenKind["BracketRangeToken"] = 262144] = "BracketRangeToken";
85
+ TokenKind[TokenKind["ClientDirectiveToken"] = 524288] = "ClientDirectiveToken";
86
+ })(TokenKind || (TokenKind = {}));
87
+ /**
88
+ * convert the bridge.net object to a plain javascript object that only contains data.
89
+ * @param k2Classifications @kusto/language-service-next bridge.net object
90
+ */
91
+ function toClassifiedRange(k2Classifications) {
92
+ return k2Classifications.map(function (classification) { return ({
93
+ start: classification.Start,
94
+ end: classification.End,
95
+ length: classification.Length,
96
+ kind: classification.Kind,
97
+ }); });
98
+ }
99
+ ;
100
+ /**
101
+ * Kusto Language service translates the kusto object model (transpiled from C# by Bridge.Net)
102
+ * to the vscode language server types, which are used by vscode language extensions.
103
+ * This should make things easier in the future to provide a vscode extension based on this translation layer.
104
+ *
105
+ * Further translations, if needed, to support specific editors (Atom, sublime, Etc)
106
+ * should be done on top of this API, since it is (at least meant to be) a standard that is supported by multiple editors.
107
+ *
108
+ * Note1: Currently monaco isn't using this object model so further translation will be necessary on calling modules.
109
+ *
110
+ * Note2: This file is responsible for interacting with the kusto object model and exposing Microsoft language service types.
111
+ * An exception to that rule is tokenization (and syntax highlighting which depends on it) -
112
+ * since it's not currently part of the Microsoft language service protocol. Thus tokenize() _does_ 'leak' kusto types to the callers.
113
+ */
114
+ var KustoLanguageService = /** @class */ (function () {
115
+ function KustoLanguageService(schema, languageSettings) {
116
+ var _a, _b, _c, _d;
117
+ var _this = this;
118
+ this._toOptionKind = (_a = {},
119
+ _a[k2.CompletionKind.AggregateFunction] = k.OptionKind.FunctionAggregation,
120
+ _a[k2.CompletionKind.BuiltInFunction] = k.OptionKind.FunctionServerSide,
121
+ _a[k2.CompletionKind.Cluster] = k.OptionKind.Database,
122
+ _a[k2.CompletionKind.Column] = k.OptionKind.Column,
123
+ _a[k2.CompletionKind.CommandPrefix] = k.OptionKind.None,
124
+ _a[k2.CompletionKind.Database] = k.OptionKind.Database,
125
+ _a[k2.CompletionKind.DatabaseFunction] = k.OptionKind.FunctionServerSide,
126
+ _a[k2.CompletionKind.Example] = k.OptionKind.None,
127
+ _a[k2.CompletionKind.Identifier] = k.OptionKind.None,
128
+ _a[k2.CompletionKind.Keyword] = k.OptionKind.None,
129
+ _a[k2.CompletionKind.LocalFunction] = k.OptionKind.FunctionLocal,
130
+ _a[k2.CompletionKind.MaterialiedView] = k.OptionKind.MaterializedView,
131
+ _a[k2.CompletionKind.Parameter] = k.OptionKind.Parameter,
132
+ _a[k2.CompletionKind.Punctuation] = k.OptionKind.None,
133
+ _a[k2.CompletionKind.QueryPrefix] = k.OptionKind.Operator,
134
+ _a[k2.CompletionKind.RenderChart] = k.OptionKind.Operator,
135
+ _a[k2.CompletionKind.ScalarInfix] = k.OptionKind.None,
136
+ _a[k2.CompletionKind.ScalarPrefix] = k.OptionKind.None,
137
+ _a[k2.CompletionKind.ScalarType] = k.OptionKind.DataType,
138
+ _a[k2.CompletionKind.Syntax] = k.OptionKind.None,
139
+ _a[k2.CompletionKind.Table] = k.OptionKind.Table,
140
+ _a[k2.CompletionKind.TabularPrefix] = k.OptionKind.None,
141
+ _a[k2.CompletionKind.TabularSuffix] = k.OptionKind.None,
142
+ _a[k2.CompletionKind.Unknown] = k.OptionKind.None,
143
+ _a[k2.CompletionKind.Variable] = k.OptionKind.Parameter,
144
+ _a[k2.CompletionKind.Option] = k.OptionKind.Option,
145
+ _a);
146
+ this.disabledCompletionItemsV2 = {
147
+ // render charts
148
+ ladderchart: k2.CompletionKind.RenderChart,
149
+ pivotchart: k2.CompletionKind.RenderChart,
150
+ timeline: k2.CompletionKind.RenderChart,
151
+ timepivot: k2.CompletionKind.RenderChart,
152
+ '3Dchart': k2.CompletionKind.RenderChart,
153
+ list: k2.CompletionKind.RenderChart,
154
+ };
155
+ this.isIntellisenseV2 = function () {
156
+ return _this._languageSettings.useIntellisenseV2 && _this._schema && _this._schema.clusterType === 'Engine';
157
+ };
158
+ this.disabledCompletionItemsV1 = {
159
+ capacity: k.OptionKind.Policy,
160
+ callout: k.OptionKind.Policy,
161
+ encoding: k.OptionKind.Policy,
162
+ batching: k.OptionKind.Policy,
163
+ querythrottling: k.OptionKind.Policy,
164
+ merge: k.OptionKind.Policy,
165
+ querylimit: k.OptionKind.Policy,
166
+ rowstore: k.OptionKind.Policy,
167
+ streamingingestion: k.OptionKind.Policy,
168
+ restricted_view_access: k.OptionKind.Policy,
169
+ sharding: k.OptionKind.Policy,
170
+ 'restricted-viewers': k.OptionKind.Policy,
171
+ attach: k.OptionKind.Command,
172
+ purge: k.OptionKind.Command,
173
+ };
174
+ this._kustoKindtolsKind = (_b = {},
175
+ _b[k.OptionKind.None] = ls.CompletionItemKind.Interface,
176
+ _b[k.OptionKind.Operator] = ls.CompletionItemKind.Method,
177
+ _b[k.OptionKind.Command] = ls.CompletionItemKind.Method,
178
+ _b[k.OptionKind.Service] = ls.CompletionItemKind.Class,
179
+ _b[k.OptionKind.Policy] = ls.CompletionItemKind.Reference,
180
+ _b[k.OptionKind.Database] = ls.CompletionItemKind.Class,
181
+ _b[k.OptionKind.Table] = ls.CompletionItemKind.Class,
182
+ _b[k.OptionKind.DataType] = ls.CompletionItemKind.Class,
183
+ _b[k.OptionKind.Literal] = ls.CompletionItemKind.Property,
184
+ _b[k.OptionKind.Parameter] = ls.CompletionItemKind.Variable,
185
+ _b[k.OptionKind.IngestionMapping] = ls.CompletionItemKind.Variable,
186
+ _b[k.OptionKind.ExpressionFunction] = ls.CompletionItemKind.Variable,
187
+ _b[k.OptionKind.Option] = ls.CompletionItemKind.Interface,
188
+ _b[k.OptionKind.OptionKind] = ls.CompletionItemKind.Interface,
189
+ _b[k.OptionKind.OptionRender] = ls.CompletionItemKind.Interface,
190
+ _b[k.OptionKind.Column] = ls.CompletionItemKind.Function,
191
+ _b[k.OptionKind.ColumnString] = ls.CompletionItemKind.Field,
192
+ _b[k.OptionKind.ColumnNumeric] = ls.CompletionItemKind.Field,
193
+ _b[k.OptionKind.ColumnDateTime] = ls.CompletionItemKind.Field,
194
+ _b[k.OptionKind.ColumnTimespan] = ls.CompletionItemKind.Field,
195
+ _b[k.OptionKind.FunctionServerSide] = ls.CompletionItemKind.Field,
196
+ _b[k.OptionKind.FunctionAggregation] = ls.CompletionItemKind.Field,
197
+ _b[k.OptionKind.FunctionFilter] = ls.CompletionItemKind.Field,
198
+ _b[k.OptionKind.FunctionScalar] = ls.CompletionItemKind.Field,
199
+ _b[k.OptionKind.ClientDirective] = ls.CompletionItemKind.Enum,
200
+ _b);
201
+ this._kustoKindToLsKindV2 = (_c = {},
202
+ _c[k2.CompletionKind.AggregateFunction] = ls.CompletionItemKind.Field,
203
+ _c[k2.CompletionKind.BuiltInFunction] = ls.CompletionItemKind.Field,
204
+ _c[k2.CompletionKind.Cluster] = ls.CompletionItemKind.Class,
205
+ _c[k2.CompletionKind.Column] = ls.CompletionItemKind.Function,
206
+ _c[k2.CompletionKind.CommandPrefix] = ls.CompletionItemKind.Field,
207
+ _c[k2.CompletionKind.Database] = ls.CompletionItemKind.Class,
208
+ _c[k2.CompletionKind.DatabaseFunction] = ls.CompletionItemKind.Field,
209
+ _c[k2.CompletionKind.Example] = ls.CompletionItemKind.Text,
210
+ _c[k2.CompletionKind.Identifier] = ls.CompletionItemKind.Method,
211
+ _c[k2.CompletionKind.Keyword] = ls.CompletionItemKind.Method,
212
+ _c[k2.CompletionKind.LocalFunction] = ls.CompletionItemKind.Field,
213
+ _c[k2.CompletionKind.MaterialiedView] = ls.CompletionItemKind.Class,
214
+ _c[k2.CompletionKind.Parameter] = ls.CompletionItemKind.Variable,
215
+ _c[k2.CompletionKind.Punctuation] = ls.CompletionItemKind.Interface,
216
+ _c[k2.CompletionKind.QueryPrefix] = ls.CompletionItemKind.Function,
217
+ _c[k2.CompletionKind.RenderChart] = ls.CompletionItemKind.Method,
218
+ _c[k2.CompletionKind.ScalarInfix] = ls.CompletionItemKind.Field,
219
+ _c[k2.CompletionKind.ScalarPrefix] = ls.CompletionItemKind.Field,
220
+ _c[k2.CompletionKind.ScalarType] = ls.CompletionItemKind.TypeParameter,
221
+ _c[k2.CompletionKind.Syntax] = ls.CompletionItemKind.Method,
222
+ _c[k2.CompletionKind.Table] = ls.CompletionItemKind.Class,
223
+ _c[k2.CompletionKind.TabularPrefix] = ls.CompletionItemKind.Field,
224
+ // datatable, externaldata
225
+ _c[k2.CompletionKind.TabularSuffix] = ls.CompletionItemKind.Field,
226
+ _c[k2.CompletionKind.Unknown] = ls.CompletionItemKind.Interface,
227
+ _c[k2.CompletionKind.Variable] = ls.CompletionItemKind.Variable,
228
+ _c[k2.CompletionKind.Option] = ls.CompletionItemKind.Text,
229
+ _c);
230
+ this._tokenKindToClassificationKind = (_d = {},
231
+ _d[TokenKind.TableToken] = k2.ClassificationKind.Table,
232
+ _d[TokenKind.TableColumnToken] = k2.ClassificationKind.Column,
233
+ _d[TokenKind.OperatorToken] = k2.ClassificationKind.QueryOperator,
234
+ _d[TokenKind.SubOperatorToken] = k2.ClassificationKind.Function,
235
+ _d[TokenKind.CalculatedColumnToken] = k2.ClassificationKind.Column,
236
+ _d[TokenKind.StringLiteralToken] = k2.ClassificationKind.Literal,
237
+ _d[TokenKind.FunctionNameToken] = k2.ClassificationKind.Function,
238
+ _d[TokenKind.UnknownToken] = k2.ClassificationKind.PlainText,
239
+ _d[TokenKind.CommentToken] = k2.ClassificationKind.Comment,
240
+ _d[TokenKind.PlainTextToken] = k2.ClassificationKind.PlainText,
241
+ _d[TokenKind.DataTypeToken] = k2.ClassificationKind.Type,
242
+ _d[TokenKind.ControlCommandToken] = k2.ClassificationKind.PlainText,
243
+ _d[TokenKind.CommandPartToken] = k2.ClassificationKind.PlainText,
244
+ _d[TokenKind.QueryParametersToken] = k2.ClassificationKind.QueryParameter,
245
+ _d[TokenKind.CslCommandToken] = k2.ClassificationKind.Keyword,
246
+ _d[TokenKind.LetVariablesToken] = k2.ClassificationKind.Identifier,
247
+ _d[TokenKind.PluginToken] = k2.ClassificationKind.Function,
248
+ _d[TokenKind.BracketRangeToken] = k2.ClassificationKind.Keyword,
249
+ _d[TokenKind.ClientDirectiveToken] = k2.ClassificationKind.Keyword,
250
+ _d);
251
+ this._schemaCache = {};
252
+ this._kustoJsSchema = KustoLanguageService.convertToKustoJsSchema(schema);
253
+ this.__kustoJsSchemaV2 = this.convertToKustoJsSchemaV2(schema);
254
+ this._schema = schema;
255
+ this._clustersSetInGlobalState = new Set();
256
+ this._nonEmptyDatabaseSetInGlobalState = new Set(); // used to remove clusters that are already in the global state
257
+ this.configure(languageSettings);
258
+ this._newlineAppendPipePolicy = new Kusto.Data.IntelliSense.ApplyPolicy();
259
+ this._newlineAppendPipePolicy.Text = '\n| ';
260
+ }
261
+ KustoLanguageService.prototype.createDatabaseUniqueName = function (clusterName, databaseName) {
262
+ return clusterName + "_" + databaseName;
263
+ };
264
+ Object.defineProperty(KustoLanguageService.prototype, "_kustoJsSchemaV2", {
265
+ /**
266
+ * A getter for __kustoJsSchemaV2
267
+ */
268
+ get: function () {
269
+ return this.__kustoJsSchemaV2;
270
+ },
271
+ /**
272
+ * A setter for _kustoJsSchemaV2. After a schema (global state) is set, create 2 sets of cluster and database names.
273
+ */
274
+ set: function (globalState) {
275
+ this.__kustoJsSchemaV2 = globalState;
276
+ this._clustersSetInGlobalState.clear();
277
+ this._nonEmptyDatabaseSetInGlobalState.clear();
278
+ // create 2 Sets with cluster names and database names based on the updated Global State.
279
+ for (var i = 0; i < globalState.Clusters.Count; i++) {
280
+ var clusterSymbol = this._kustoJsSchemaV2.Clusters.getItem(i);
281
+ this._clustersSetInGlobalState.add(clusterSymbol.Name);
282
+ for (var i2 = 0; i2 < clusterSymbol.Databases.Count; i2++) {
283
+ var databaseSymbol = clusterSymbol.Databases.getItem(i2);
284
+ if (databaseSymbol.Tables.Count > 0) { // only include database with tables
285
+ this._nonEmptyDatabaseSetInGlobalState.add(this.createDatabaseUniqueName(clusterSymbol.Name, databaseSymbol.Name));
286
+ }
287
+ }
288
+ }
289
+ },
290
+ enumerable: false,
291
+ configurable: true
292
+ });
293
+ KustoLanguageService.prototype.configure = function (languageSettings) {
294
+ this._languageSettings = languageSettings;
295
+ // Since we're still reverting to V1 intellisense for control commands, we need to update the rules provider
296
+ // (which is a notion of V1 intellisense).
297
+ this.createRulesProvider(this._kustoJsSchema, this._schema.clusterType);
298
+ };
299
+ KustoLanguageService.prototype.doComplete = function (document, position) {
300
+ return this.isIntellisenseV2() ? this.doCompleteV2(document, position) : this.doCompleteV1(document, position);
301
+ };
302
+ /**
303
+ * important: Only use during development to test Global State.
304
+ * Prints clusters, databases and tables that are currently in the GlobalState.
305
+ */
306
+ KustoLanguageService.prototype.debugGlobalState = function (globals) {
307
+ // iterate over clusters
308
+ console.log("globals.Clusters.Count: " + globals.Clusters.Count);
309
+ for (var i = 0; i < globals.Clusters.Count; i++) {
310
+ var cluster = globals.Clusters.getItem(i);
311
+ console.log("cluster: " + cluster.Name);
312
+ // iterate over databases
313
+ console.log("cluster.Databases.Count: " + cluster.Databases.Count);
314
+ for (var i2 = 0; i2 < cluster.Databases.Count; i2++) {
315
+ var database = cluster.Databases.getItem(i2);
316
+ console.log("cluster.database: [" + cluster.Name + "].[" + database.Name + "]");
317
+ // iterate over tables
318
+ console.log("cluster.Databases.Tables.Count: " + database.Tables.Count);
319
+ for (var i3 = 0; i3 < database.Tables.Count; i3++) {
320
+ var table = database.Tables.getItem(i3);
321
+ console.log("cluster.database.table: [" + cluster.Name + "].[" + database.Name + "].[" + table.Name + "]");
322
+ }
323
+ }
324
+ }
325
+ };
326
+ KustoLanguageService.prototype.doCompleteV2 = function (document, position) {
327
+ var _this = this;
328
+ if (!document) {
329
+ return Promise.resolve(ls.CompletionList.create([]));
330
+ }
331
+ var script = this.parseDocumentV2(document);
332
+ // print cluster/database/tables from CodeScript.Globals
333
+ // this.debugGlobalState(script.Globals);
334
+ // get current command
335
+ var cursorOffset = document.offsetAt(position);
336
+ var currentCommand = script.GetBlockAtPosition(cursorOffset);
337
+ // get completion items
338
+ var completionItems = currentCommand.Service.GetCompletionItems(cursorOffset);
339
+ var disabledItems = this.disabledCompletionItemsV2;
340
+ if (this._languageSettings.disabledCompletionItems) {
341
+ this._languageSettings.disabledCompletionItems.map(function (item) {
342
+ // logic will treat unknown as a '*' wildcard, meaning that if the key is in the object
343
+ // the completion item will be suppressed.
344
+ disabledItems[item] = k2.CompletionKind.Unknown;
345
+ });
346
+ }
347
+ var items = this.toArray(completionItems.Items)
348
+ .filter(function (item) {
349
+ return !(item &&
350
+ item.MatchText &&
351
+ disabledItems[item.MatchText] !== undefined &&
352
+ (disabledItems[item.MatchText] === k2.CompletionKind.Unknown ||
353
+ disabledItems[item.MatchText] === item.Kind));
354
+ })
355
+ .map(function (kItem, i) {
356
+ var v1CompletionOption = new k.CompletionOption(_this._toOptionKind[kItem.Kind] || k.OptionKind.None, kItem.DisplayText);
357
+ var helpTopic = _this.getTopic(v1CompletionOption);
358
+ // If we have AfterText it means that the cursor should no be placed at end of suggested text.
359
+ // In that case we switch to snippet format and represent the point where the cursor should be as
360
+ // as '\$0'
361
+ var _a = kItem.AfterText && kItem.AfterText.length > 0
362
+ ? {
363
+ textToInsert: kItem.EditText + '$0' + kItem.AfterText,
364
+ format: ls.InsertTextFormat.Snippet,
365
+ }
366
+ : {
367
+ textToInsert: kItem.EditText,
368
+ format: ls.InsertTextFormat.PlainText,
369
+ }, textToInsert = _a.textToInsert, format = _a.format;
370
+ var lsItem = ls.CompletionItem.create(kItem.DisplayText);
371
+ var startPosition = document.positionAt(completionItems.EditStart);
372
+ var endPosition = document.positionAt(completionItems.EditStart + completionItems.EditLength);
373
+ lsItem.textEdit = ls.TextEdit.replace(ls.Range.create(startPosition, endPosition), textToInsert);
374
+ lsItem.sortText = _this.getSortText(i + 1);
375
+ lsItem.kind = _this.kustoKindToLsKindV2(kItem.Kind);
376
+ lsItem.insertTextFormat = format;
377
+ lsItem.detail = helpTopic ? helpTopic.ShortDescription : undefined;
378
+ lsItem.documentation = helpTopic
379
+ ? { value: helpTopic.LongDescription, kind: ls.MarkupKind.Markdown }
380
+ : undefined;
381
+ return lsItem;
382
+ });
383
+ return Promise.resolve(ls.CompletionList.create(items));
384
+ };
385
+ /**
386
+ * when trying to get a topic we need the function name (abs, toLower, ETC).
387
+ * The problem is that the 'Value' string also contains the arguments (e.g abs(number)), which means that we are
388
+ * not able to correlate the option with its documentation.
389
+ * This piece of code tries to strip this hwne getting topic.
390
+ * @param completionOption the Completion option
391
+ */
392
+ KustoLanguageService.prototype.getTopic = function (completionOption) {
393
+ if (completionOption.Kind == k.OptionKind.FunctionScalar ||
394
+ completionOption.Kind == k.OptionKind.FunctionAggregation) {
395
+ // from a value like 'abs(number)' remove the '(number)' so that only 'abs' will remain
396
+ var indexOfParen = completionOption.Value.indexOf('(');
397
+ if (indexOfParen >= 0) {
398
+ completionOption = new k.CompletionOption(completionOption.Kind, completionOption.Value.substring(0, indexOfParen));
399
+ }
400
+ }
401
+ return k.CslDocumentation.Instance.GetTopic(completionOption);
402
+ };
403
+ KustoLanguageService.prototype.doCompleteV1 = function (document, position) {
404
+ var _this = this;
405
+ // TODO: fix typing in CslCommandParser to allow rulesProvider to be query only.
406
+ var caretAbsolutePosition = document.offsetAt(position);
407
+ // find out what's the current command to only parse this one.
408
+ this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
409
+ var currentCommand = this.getCurrentCommand(document, caretAbsolutePosition);
410
+ var commandTextUntilCursor = '';
411
+ if (currentCommand) {
412
+ var commandStartOffset = currentCommand.AbsoluteStart;
413
+ this.parseTextV1(currentCommand.Text, k.ParseMode.TokenizeAllText);
414
+ var caretRelativePosition = caretAbsolutePosition - currentCommand.AbsoluteStart;
415
+ commandTextUntilCursor = currentCommand.Text.substring(currentCommand.CslExpressionStartPosition, caretRelativePosition);
416
+ }
417
+ var commandTextWithoutLastWord = this.getCommandWithoutLastWord(commandTextUntilCursor);
418
+ var context = this._rulesProvider.AnalyzeCommand$1(commandTextUntilCursor, currentCommand).Context;
419
+ var result = { v: null };
420
+ this._rulesProvider.TryMatchAnyRule(commandTextWithoutLastWord, result);
421
+ var rule = result.v;
422
+ if (rule) {
423
+ var completionOptions = this.toArray(rule.GetCompletionOptions(context));
424
+ // TODO once AppendPipePolicy becomes a public static member of ApplyPolicy in our c# code, and bridge.Net transplies this,
425
+ // remove the 'as any' part..
426
+ // Also = DefaultApplyPolicy is internal in c# code, so not exposed in d.ts, so we cast it to any.
427
+ if (this._languageSettings.newlineAfterPipe &&
428
+ rule.DefaultAfterApplyPolicy === Kusto.Data.IntelliSense.ApplyPolicy.AppendPipePolicy) {
429
+ rule.DefaultAfterApplyPolicy = this._newlineAppendPipePolicy;
430
+ }
431
+ var options = completionOptions
432
+ .filter(function (option) {
433
+ return !(option && option.Value && _this.disabledCompletionItemsV1[option.Value] === option.Kind);
434
+ })
435
+ .map(function (option, ordinal) {
436
+ var _a = _this.getTextToInsert(rule, option), insertText = _a.insertText, insertTextFormat = _a.insertTextFormat;
437
+ var helpTopic = k.CslDocumentation.Instance.GetTopic(option);
438
+ var item = ls.CompletionItem.create(option.Value);
439
+ item.kind = _this.kustoKindToLsKind(option.Kind);
440
+ item.insertText = insertText;
441
+ item.insertTextFormat = insertTextFormat;
442
+ item.sortText = _this.getSortText(ordinal + 1);
443
+ item.detail = helpTopic ? helpTopic.ShortDescription : undefined;
444
+ item.documentation = helpTopic
445
+ ? { value: helpTopic.LongDescription, kind: ls.MarkupKind.Markdown }
446
+ : undefined;
447
+ return item;
448
+ });
449
+ return Promise.resolve(ls.CompletionList.create(options));
450
+ }
451
+ return Promise.resolve(ls.CompletionList.create([]));
452
+ };
453
+ KustoLanguageService.prototype.doRangeFormat = function (document, range) {
454
+ if (!document) {
455
+ return Promise.resolve([]);
456
+ }
457
+ var rangeStartOffset = document.offsetAt(range.start);
458
+ var rangeEndOffset = document.offsetAt(range.end);
459
+ var commands = this.getFormattedCommandsInDocumentV2(document, rangeStartOffset, rangeEndOffset);
460
+ if (!commands.originalRange || commands.formattedCommands.length === 0) {
461
+ return Promise.resolve([]);
462
+ }
463
+ return Promise.resolve([ls.TextEdit.replace(commands.originalRange, commands.formattedCommands.join(''))]);
464
+ };
465
+ KustoLanguageService.prototype.doDocumentFormat = function (document) {
466
+ if (!document) {
467
+ return Promise.resolve([]);
468
+ }
469
+ var startPos = document.positionAt(0);
470
+ var endPos = document.positionAt(document.getText().length);
471
+ var fullDocRange = ls.Range.create(startPos, endPos);
472
+ var formattedDoc = this.getFormattedCommandsInDocumentV2(document).formattedCommands.join('');
473
+ return Promise.resolve([ls.TextEdit.replace(fullDocRange, formattedDoc)]);
474
+ };
475
+ // Method is not triggered, instead doRangeFormat is invoked with the range of the caret's line.
476
+ KustoLanguageService.prototype.doCurrentCommandFormat = function (document, caretPosition) {
477
+ var offset = document.offsetAt(caretPosition);
478
+ var range = this.createRange(document, offset - 1, offset + 1);
479
+ return this.doRangeFormat(document, range);
480
+ };
481
+ KustoLanguageService.prototype.doFolding = function (document) {
482
+ if (!document) {
483
+ return Promise.resolve([]);
484
+ }
485
+ return this.getCommandsInDocument(document).then(function (commands) {
486
+ return commands.map(function (command) {
487
+ // don't count the last empty line as part of the folded range (consider linux, mac, pc newlines)
488
+ if (command.text.endsWith('\r\n')) {
489
+ command.absoluteEnd -= 2;
490
+ }
491
+ else if (command.text.endsWith('\r') || command.text.endsWith('\n')) {
492
+ --command.absoluteEnd;
493
+ }
494
+ var startPosition = document.positionAt(command.absoluteStart);
495
+ var endPosition = document.positionAt(command.absoluteEnd);
496
+ return {
497
+ startLine: startPosition.line,
498
+ startCharacter: startPosition.character,
499
+ endLine: endPosition.line,
500
+ endCharacter: endPosition.character,
501
+ };
502
+ });
503
+ });
504
+ };
505
+ KustoLanguageService.prototype.getClusterReferences = function (document, cursorOffset) {
506
+ var _a;
507
+ var script = this.parseDocumentV2(document);
508
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
509
+ var clusterReferences = (_a = currentBlock === null || currentBlock === void 0 ? void 0 : currentBlock.Service) === null || _a === void 0 ? void 0 : _a.GetClusterReferences();
510
+ if (!clusterReferences) {
511
+ return Promise.resolve([]);
512
+ }
513
+ var newClustersReferences = [];
514
+ var newClustersReferencesSet = new Set(); // used to remove duplicates
515
+ // Keep only unique clusters that aren't already exist in the Global State
516
+ for (var i = 0; i < clusterReferences.Count; i++) {
517
+ var clusterReference = clusterReferences.getItem(i);
518
+ var clusterHostName = Kusto.Language.KustoFacts.GetHostName(clusterReference.Cluster);
519
+ // ignore duplicates
520
+ if (newClustersReferencesSet.has(clusterHostName)) {
521
+ continue;
522
+ }
523
+ newClustersReferencesSet.add(clusterHostName);
524
+ // ignore references that are already in the GlobalState.
525
+ if (!this._clustersSetInGlobalState.has(clusterHostName)) {
526
+ newClustersReferences.push({ clusterName: clusterHostName });
527
+ }
528
+ }
529
+ return Promise.resolve(newClustersReferences);
530
+ };
531
+ KustoLanguageService.prototype.getDatabaseReferences = function (document, cursorOffset) {
532
+ var _a;
533
+ var script = this.parseDocumentV2(document);
534
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
535
+ var databasesReferences = (_a = currentBlock === null || currentBlock === void 0 ? void 0 : currentBlock.Service) === null || _a === void 0 ? void 0 : _a.GetDatabaseReferences();
536
+ if (!databasesReferences) {
537
+ return Promise.resolve([]);
538
+ }
539
+ var newDatabasesReferences = [];
540
+ var newDatabasesReferencesSet = new Set();
541
+ for (var i1 = 0; i1 < databasesReferences.Count; i1++) {
542
+ var databaseReference = databasesReferences.getItem(i1);
543
+ var clusterHostName = Kusto.Language.KustoFacts.GetHostName(databaseReference.Cluster);
544
+ // ignore duplicates
545
+ var databaseReferenceUniqueId = this.createDatabaseUniqueName(clusterHostName, databaseReference.Database);
546
+ if (newDatabasesReferencesSet.has(databaseReferenceUniqueId)) {
547
+ continue;
548
+ }
549
+ newDatabasesReferencesSet.add(databaseReferenceUniqueId);
550
+ // ignore references that are already in the GlobalState.
551
+ var foundInGlobalState = this._nonEmptyDatabaseSetInGlobalState.has(databaseReferenceUniqueId);
552
+ if (!foundInGlobalState) {
553
+ newDatabasesReferences.push({
554
+ databaseName: databaseReference.Database,
555
+ clusterName: databaseReference.Cluster
556
+ });
557
+ }
558
+ }
559
+ return Promise.resolve(newDatabasesReferences);
560
+ };
561
+ KustoLanguageService.prototype.doValidation = function (document, changeIntervals) {
562
+ var _this = this;
563
+ // didn't implement validation for v1.
564
+ if (!document || !this.isIntellisenseV2()) {
565
+ return Promise.resolve([]);
566
+ }
567
+ var script = this.parseDocumentV2(document);
568
+ var blocks = this.toArray(script.Blocks);
569
+ if (changeIntervals.length > 0) {
570
+ blocks = this.getAffectedBlocks(blocks, changeIntervals);
571
+ }
572
+ var diagnostics = blocks
573
+ .map(function (block) {
574
+ var diagnostics = _this.toArray(block.Service.GetDiagnostics());
575
+ if (diagnostics) {
576
+ return diagnostics;
577
+ }
578
+ return [];
579
+ })
580
+ .reduce(function (prev, curr) { return prev.concat(curr); }, []);
581
+ var lsDiagnostics = this.toLsDiagnostics(diagnostics, document);
582
+ return Promise.resolve(lsDiagnostics);
583
+ };
584
+ KustoLanguageService.prototype.toLsDiagnostics = function (diagnostics, document) {
585
+ return diagnostics
586
+ .filter(function (diag) { return diag.HasLocation; })
587
+ .map(function (diag) {
588
+ var start = document.positionAt(diag.Start);
589
+ var end = document.positionAt(diag.Start + diag.Length);
590
+ var range = ls.Range.create(start, end);
591
+ return ls.Diagnostic.create(range, diag.Message, ls.DiagnosticSeverity.Error);
592
+ });
593
+ };
594
+ /**
595
+ * Colorize one or more kusto blocks (a.k.a commands), or just the entire document.
596
+ * Supports multi-cursor editing (colorizes blocks on multiple changes).
597
+ * @param document The document to colorize
598
+ * @param changeIntervals an array containing 0 or more changed intervals. if the array is empty - just colorize the entire row.
599
+ * if the array contains a single change - just color the kusto blocks that wraps this change. If multiple changes are provided,
600
+ * colorize all blocks that intersect these changes.
601
+ * The code will try to only parse once if this is the same command.
602
+ */
603
+ KustoLanguageService.prototype.doColorization = function (document, changeIntervals) {
604
+ var _this = this;
605
+ if (!document || !this._languageSettings.useSemanticColorization) {
606
+ return Promise.resolve([]);
607
+ }
608
+ // V1 intellisense
609
+ if (!this.isIntellisenseV2()) {
610
+ // Handle specific ranges changes (and not the whole doc)
611
+ if (changeIntervals.length > 0) {
612
+ this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
613
+ var affectedCommands = this.toArray(this._parser.Results).filter(function (command) {
614
+ // a command is affected if it intersects at least on of changed ranges.
615
+ return command // command can be null. we're filtering all nulls in the array.
616
+ ? changeIntervals.some(function (_a) {
617
+ var changeStart = _a.start, changeEnd = _a.end;
618
+ // both intervals intersect if either the start or the end of interval A is inside interval B.
619
+ // If we deleted something at the end of a command, the interval will not intersect the current command.
620
+ // so we also want consider affected commands commands the end where the interval begins.
621
+ // hence the + 1.
622
+ return (command.AbsoluteStart >= changeStart && command.AbsoluteStart <= changeEnd) ||
623
+ (changeStart >= command.AbsoluteStart && changeStart <= command.AbsoluteEnd + 1);
624
+ })
625
+ : false;
626
+ });
627
+ // We're not on any command so don't return any classifications.
628
+ // this can happen if we're at the and of the file and deleting empty rows (for example).
629
+ if (!affectedCommands || affectedCommands.length === 0) {
630
+ return Promise.resolve([
631
+ {
632
+ classifications: [],
633
+ absoluteStart: changeIntervals[0].start,
634
+ absoluteEnd: changeIntervals[0].end,
635
+ },
636
+ ]);
637
+ }
638
+ var results = affectedCommands.map(function (command) {
639
+ _this.parseTextV1(command.Text, k.ParseMode.TokenizeAllText);
640
+ var k2Classifications = _this.getClassificationsFromParseResult(command.AbsoluteStart);
641
+ var classifications = toClassifiedRange(k2Classifications);
642
+ return {
643
+ classifications: classifications,
644
+ absoluteStart: command.AbsoluteStart,
645
+ absoluteEnd: command.AbsoluteEnd,
646
+ };
647
+ });
648
+ return Promise.resolve(results);
649
+ }
650
+ // Entire document requested
651
+ this.parseDocumentV1(document, k.ParseMode.TokenizeAllText);
652
+ var classifications_1 = this.getClassificationsFromParseResult();
653
+ return Promise.resolve([
654
+ {
655
+ classifications: toClassifiedRange(classifications_1),
656
+ absoluteStart: 0,
657
+ absoluteEnd: document.getText().length,
658
+ },
659
+ ]);
660
+ }
661
+ // V2 intellisense
662
+ var script = this.parseDocumentV2(document);
663
+ if (changeIntervals.length > 0) {
664
+ var blocks_1 = this.toArray(script.Blocks);
665
+ var affectedBlocks = this.getAffectedBlocks(blocks_1, changeIntervals);
666
+ var result = affectedBlocks.map(function (block) { return ({
667
+ classifications: toClassifiedRange(_this.toArray(block.Service.GetClassifications(block.Start, block.End).Classifications)),
668
+ absoluteStart: block.Start,
669
+ absoluteEnd: block.End,
670
+ }); });
671
+ return Promise.resolve(result);
672
+ }
673
+ // Entire document requested
674
+ var blocks = this.toArray(script.Blocks);
675
+ var classifications = blocks
676
+ .map(function (block) {
677
+ return _this.toArray(block.Service.GetClassifications(block.Start, block.Length).Classifications);
678
+ })
679
+ .reduce(function (prev, curr) { return prev.concat(curr); }, []);
680
+ return Promise.resolve([
681
+ {
682
+ classifications: toClassifiedRange(classifications),
683
+ absoluteStart: 0,
684
+ absoluteEnd: document.getText().length,
685
+ },
686
+ ]);
687
+ };
688
+ KustoLanguageService.prototype.getAffectedBlocks = function (blocks, changeIntervals) {
689
+ return blocks.filter(function (block) {
690
+ // a command is affected if it intersects at least on of changed ranges.
691
+ return block // command can be null. we're filtering all nulls in the array.
692
+ ? changeIntervals.some(function (_a) {
693
+ var changeStart = _a.start, changeEnd = _a.end;
694
+ // both intervals intersect if either the start or the end of interval A is inside interval B.
695
+ return (block.Start >= changeStart && block.Start <= changeEnd) ||
696
+ (changeStart >= block.Start && changeStart <= block.End + 1);
697
+ })
698
+ : false;
699
+ });
700
+ };
701
+ KustoLanguageService.prototype.addClusterToSchema = function (document, clusterName, databaseNames) {
702
+ var clusterNameOnly = Kusto.Language.KustoFacts.GetHostName(clusterName);
703
+ var cluster = this._kustoJsSchemaV2.GetCluster$1(clusterNameOnly);
704
+ if (cluster) {
705
+ // add databases that are not already in the cluster.
706
+ databaseNames
707
+ .filter(function (databaseName) { return !cluster.GetDatabase(databaseName); })
708
+ .map(function (databaseName) {
709
+ var symbol = new sym.DatabaseSymbol.$ctor1(databaseName, undefined, false);
710
+ cluster = cluster.AddDatabase(symbol);
711
+ });
712
+ }
713
+ if (!cluster) {
714
+ var databaseSymbols = databaseNames
715
+ .map(function (databaseName) {
716
+ var symbol = new sym.DatabaseSymbol.$ctor1(databaseName, undefined, false);
717
+ return symbol;
718
+ });
719
+ var databaseSymbolsList = KustoLanguageService.toBridgeList(databaseSymbols);
720
+ cluster = new sym.ClusterSymbol.$ctor1(clusterNameOnly, databaseSymbolsList, false);
721
+ }
722
+ this._kustoJsSchemaV2 = this._kustoJsSchemaV2.AddOrReplaceCluster(cluster);
723
+ this._script = k2.CodeScript.From$1(document.getText(), this._kustoJsSchemaV2);
724
+ return Promise.resolve();
725
+ };
726
+ KustoLanguageService.prototype.addDatabaseToSchema = function (document, clusterName, databaseSchema) {
727
+ var clusterHostName = Kusto.Language.KustoFacts.GetHostName(clusterName);
728
+ var cluster = this._kustoJsSchemaV2.GetCluster$1(clusterHostName);
729
+ if (!cluster) {
730
+ cluster = new sym.ClusterSymbol.$ctor1(clusterHostName, null, false);
731
+ }
732
+ var databaseSymbol = KustoLanguageService.convertToDatabaseSymbol(databaseSchema);
733
+ cluster = cluster.AddOrUpdateDatabase(databaseSymbol);
734
+ this._kustoJsSchemaV2 = this._kustoJsSchemaV2.AddOrReplaceCluster(cluster);
735
+ this._script = k2.CodeScript.From$1(document.getText(), this._kustoJsSchemaV2);
736
+ return Promise.resolve();
737
+ };
738
+ KustoLanguageService.prototype.setSchema = function (schema) {
739
+ var _this = this;
740
+ this._schema = schema;
741
+ if (this._languageSettings.useIntellisenseV2) {
742
+ var kustoJsSchemaV2 = schema && schema.clusterType === 'Engine' ? this.convertToKustoJsSchemaV2(schema) : null;
743
+ this._kustoJsSchemaV2 = kustoJsSchemaV2;
744
+ this._script = undefined;
745
+ this._parsePropertiesV2 = undefined;
746
+ }
747
+ // since V2 doesn't support control commands, we're initializing V1 intellisense for both cases and we'll going to use V1 intellisense for contorl commands.
748
+ return new Promise(function (resolve, reject) {
749
+ var kustoJsSchema = schema ? KustoLanguageService.convertToKustoJsSchema(schema) : undefined;
750
+ _this._kustoJsSchema = kustoJsSchema;
751
+ _this.createRulesProvider(kustoJsSchema, schema.clusterType);
752
+ resolve(undefined);
753
+ });
754
+ };
755
+ KustoLanguageService.prototype.setParameters = function (parameters) {
756
+ if (!this._languageSettings.useIntellisenseV2 || this._schema.clusterType !== 'Engine') {
757
+ throw new Error('setParameters requires intellisense V2 and Engine cluster');
758
+ }
759
+ this._schema.globalParameters = parameters;
760
+ var symbols = parameters.map(function (param) { return KustoLanguageService.createParameterSymbol(param); });
761
+ this._kustoJsSchemaV2 = this._kustoJsSchemaV2.WithParameters(KustoLanguageService.toBridgeList(symbols));
762
+ return Promise.resolve(undefined);
763
+ };
764
+ /**
765
+ * A combination of normalizeSchema and setSchema
766
+ * @param schema schema json as received from .show schema as json
767
+ * @param clusterConnectionString cluster connection string
768
+ * @param databaseInContextName name of database in context
769
+ */
770
+ KustoLanguageService.prototype.setSchemaFromShowSchema = function (schema, clusterConnectionString, databaseInContextName, globalParameters) {
771
+ var _this = this;
772
+ return this.normalizeSchema(schema, clusterConnectionString, databaseInContextName).then(function (normalized) {
773
+ return _this.setSchema(__assign(__assign({}, normalized), { globalParameters: globalParameters }));
774
+ });
775
+ };
776
+ /**
777
+ * Converts the result of .show schema as json to a normalized schema used by kusto language service.
778
+ * @param schema result of show schema
779
+ * @param clusterConnectionString cluster connection string`
780
+ * @param databaseInContextName database in context name
781
+ */
782
+ KustoLanguageService.prototype.normalizeSchema = function (schema, clusterConnectionString, databaseInContextName) {
783
+ var databases = Object.keys(schema.Databases)
784
+ .map(function (key) { return schema.Databases[key]; })
785
+ .map(function (_a) {
786
+ var Name = _a.Name, Tables = _a.Tables, ExternalTables = _a.ExternalTables, MaterializedViews = _a.MaterializedViews, Functions = _a.Functions, MinorVersion = _a.MinorVersion, MajorVersion = _a.MajorVersion;
787
+ return ({
788
+ name: Name,
789
+ minorVersion: MinorVersion,
790
+ majorVersion: MajorVersion,
791
+ tables: [].concat.apply([], [[Tables, 'Table'], [MaterializedViews, 'MaterializedView'], [ExternalTables, 'ExternalTable']]
792
+ .filter(function (_a) {
793
+ var tableContainer = _a[0];
794
+ return tableContainer;
795
+ })
796
+ .map(function (_a) {
797
+ var tableContainer = _a[0], tableEntity = _a[1];
798
+ return Object
799
+ .values(tableContainer)
800
+ .map(function (_a) {
801
+ var Name = _a.Name, OrderedColumns = _a.OrderedColumns, DocString = _a.DocString;
802
+ return ({
803
+ name: Name,
804
+ docstring: DocString,
805
+ entityType: tableEntity,
806
+ columns: OrderedColumns.map(function (_a) {
807
+ var Name = _a.Name, Type = _a.Type, DocString = _a.DocString, CslType = _a.CslType;
808
+ return ({
809
+ name: Name,
810
+ type: CslType,
811
+ docstring: DocString,
812
+ });
813
+ }),
814
+ });
815
+ });
816
+ })),
817
+ functions: Object.keys(Functions)
818
+ .map(function (key) { return Functions[key]; })
819
+ .map(function (_a) {
820
+ var Name = _a.Name, Body = _a.Body, DocString = _a.DocString, InputParameters = _a.InputParameters;
821
+ return ({
822
+ name: Name,
823
+ body: Body,
824
+ docstring: DocString,
825
+ inputParameters: InputParameters.map(function (inputParam) { return ({
826
+ name: inputParam.Name,
827
+ type: inputParam.Type,
828
+ cslType: inputParam.CslType,
829
+ cslDefaultValue: inputParam.CslDefaultValue,
830
+ columns: inputParam.Columns
831
+ ? inputParam.Columns.map(function (col) { return ({
832
+ name: col.Name,
833
+ type: col.Type,
834
+ cslType: col.CslType,
835
+ }); })
836
+ : inputParam.Columns,
837
+ }); }),
838
+ });
839
+ }),
840
+ });
841
+ });
842
+ var result = {
843
+ clusterType: 'Engine',
844
+ cluster: {
845
+ connectionString: clusterConnectionString,
846
+ databases: databases,
847
+ },
848
+ database: databases.filter(function (db) { return db.name === databaseInContextName; })[0],
849
+ };
850
+ return Promise.resolve(result);
851
+ };
852
+ KustoLanguageService.prototype.getSchema = function () {
853
+ return Promise.resolve(this._schema);
854
+ };
855
+ KustoLanguageService.prototype.getCommandInContext = function (document, cursorOffset) {
856
+ return this.isIntellisenseV2()
857
+ ? this.getCommandInContextV2(document, cursorOffset)
858
+ : this.getCommandInContextV1(document, cursorOffset);
859
+ };
860
+ KustoLanguageService.prototype.getCommandAndLocationInContext = function (document, cursorOffset) {
861
+ // We are going to remove v1 intellisense. no use to keep parity.
862
+ if (!document || !this.isIntellisenseV2()) {
863
+ return Promise.resolve(null);
864
+ }
865
+ var script = this.parseDocumentV2(document);
866
+ var block = this.getCurrentCommandV2(script, cursorOffset);
867
+ if (!block) {
868
+ return Promise.resolve(null);
869
+ }
870
+ var start = document.positionAt(block.Start);
871
+ var end = document.positionAt(block.End);
872
+ var location = ls.Location.create(document.uri, ls.Range.create(start, end));
873
+ var text = block.Text;
874
+ return Promise.resolve({
875
+ text: text,
876
+ location: location,
877
+ });
878
+ };
879
+ KustoLanguageService.prototype.getCommandInContextV1 = function (document, cursorOffset) {
880
+ this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
881
+ var command = this.getCurrentCommand(document, cursorOffset);
882
+ if (!command) {
883
+ return Promise.resolve(null);
884
+ }
885
+ return Promise.resolve(command.Text);
886
+ };
887
+ KustoLanguageService.prototype.getCommandInContextV2 = function (document, cursorOffset) {
888
+ if (!document) {
889
+ return Promise.resolve(null);
890
+ }
891
+ var script = this.parseDocumentV2(document);
892
+ var block = this.getCurrentCommandV2(script, cursorOffset);
893
+ if (!block) {
894
+ return Promise.resolve(null);
895
+ }
896
+ // TODO: do we need to do tricks like V1 is doing in this.getCurrentCommand?
897
+ return Promise.resolve(block.Text);
898
+ };
899
+ /**
900
+ * Return an array of commands in document. each command contains the range and text.
901
+ */
902
+ KustoLanguageService.prototype.getCommandsInDocument = function (document) {
903
+ if (!document) {
904
+ return Promise.resolve([]);
905
+ }
906
+ return this.isIntellisenseV2()
907
+ ? this.getCommandsInDocumentV2(document)
908
+ : this.getCommandsInDocumentV1(document);
909
+ };
910
+ KustoLanguageService.prototype.getCommandsInDocumentV1 = function (document) {
911
+ this.parseDocumentV1(document, k.ParseMode.CommandTokensOnly);
912
+ var commands = this.toArray(this._parser.Results);
913
+ return Promise.resolve(commands.map(function (_a) {
914
+ var AbsoluteStart = _a.AbsoluteStart, AbsoluteEnd = _a.AbsoluteEnd, Text = _a.Text;
915
+ return ({
916
+ absoluteStart: AbsoluteStart,
917
+ absoluteEnd: AbsoluteEnd,
918
+ text: Text,
919
+ });
920
+ }));
921
+ };
922
+ KustoLanguageService.prototype.toPlacementStyle = function (formatterPlacementStyle) {
923
+ if (!formatterPlacementStyle) {
924
+ return undefined;
925
+ }
926
+ switch (formatterPlacementStyle) {
927
+ case 'None':
928
+ return k2.PlacementStyle.None;
929
+ case 'NewLine':
930
+ return k2.PlacementStyle.NewLine;
931
+ case 'Smart':
932
+ return k2.PlacementStyle.Smart;
933
+ default:
934
+ throw new Error('Unknown PlacementStyle');
935
+ }
936
+ };
937
+ KustoLanguageService.prototype.getFormattedCommandsInDocumentV2 = function (document, rangeStart, rangeEnd) {
938
+ var _this = this;
939
+ var script = this.parseDocumentV2(document);
940
+ var commands = this.toArray(script.Blocks).filter(function (command) {
941
+ if (!command.Text || command.Text.trim() == '')
942
+ return false;
943
+ if (rangeStart == null || rangeEnd == null)
944
+ return true;
945
+ // calculate command end position without \r\n.
946
+ var commandEnd = command.End;
947
+ var commandText = command.Text;
948
+ for (var i = commandText.length - 1; i >= 0; i--) {
949
+ if (commandText[i] != '\r' && commandText[i] != '\n') {
950
+ break;
951
+ }
952
+ else {
953
+ commandEnd--;
954
+ }
955
+ }
956
+ if (command.Start > rangeStart && command.Start < rangeEnd)
957
+ return true;
958
+ if (commandEnd > rangeStart && commandEnd < rangeEnd)
959
+ return true;
960
+ if (command.Start <= rangeStart && commandEnd >= rangeEnd)
961
+ return true;
962
+ });
963
+ if (commands.length === 0) {
964
+ return { formattedCommands: [] };
965
+ }
966
+ var formattedCommands = commands.map(function (command) {
967
+ var _a, _b;
968
+ var formatterOptions = _this._languageSettings.formatter;
969
+ var formatter = Kusto.Language.Editor.FormattingOptions.Default.WithIndentationSize((_a = formatterOptions === null || formatterOptions === void 0 ? void 0 : formatterOptions.indentationSize) !== null && _a !== void 0 ? _a : 4)
970
+ .WithInsertMissingTokens(false)
971
+ .WithPipeOperatorStyle((_b = _this.toPlacementStyle(formatterOptions === null || formatterOptions === void 0 ? void 0 : formatterOptions.pipeOperatorStyle)) !== null && _b !== void 0 ? _b : k2.PlacementStyle.Smart)
972
+ .WithSemicolonStyle(Kusto.Language.Editor.PlacementStyle.None)
973
+ .WithBrackettingStyle(k2.BrackettingStyle.Diagonal);
974
+ if (rangeStart == null || rangeEnd == null || (rangeStart === command.Start && rangeEnd === command.End)) {
975
+ var result = command.Service.GetFormattedText(formatter);
976
+ return result.Text;
977
+ }
978
+ return command.Service.GetFormattedText(formatter).Text;
979
+ });
980
+ var originalRange = this.createRange(document, commands[0].Start, commands[commands.length - 1].End);
981
+ return { formattedCommands: formattedCommands, originalRange: originalRange };
982
+ };
983
+ KustoLanguageService.prototype.getCommandsInDocumentV2 = function (document) {
984
+ var script = this.parseDocumentV2(document);
985
+ var commands = this.toArray(script.Blocks).filter(function (command) { return command.Text.trim() != ''; });
986
+ return Promise.resolve(commands.map(function (_a) {
987
+ var Start = _a.Start, End = _a.End, Text = _a.Text;
988
+ return ({ absoluteStart: Start, absoluteEnd: End, text: Text });
989
+ }));
990
+ };
991
+ KustoLanguageService.prototype.getClientDirective = function (text) {
992
+ var outParam = { v: null };
993
+ var isClientDirective = k.CslCommandParser.IsClientDirective(text, outParam);
994
+ return Promise.resolve({
995
+ isClientDirective: isClientDirective,
996
+ directiveWithoutLeadingComments: outParam.v,
997
+ });
998
+ };
999
+ KustoLanguageService.prototype.getAdminCommand = function (text) {
1000
+ var outParam = { v: null };
1001
+ var isAdminCommand = k.CslCommandParser.IsAdminCommand$1(text, outParam);
1002
+ return Promise.resolve({
1003
+ isAdminCommand: isAdminCommand,
1004
+ adminCommandWithoutLeadingComments: outParam.v,
1005
+ });
1006
+ };
1007
+ KustoLanguageService.prototype.findDefinition = function (document, position) {
1008
+ if (!document || !this.isIntellisenseV2()) {
1009
+ return Promise.resolve([]);
1010
+ }
1011
+ var script = this.parseDocumentV2(document);
1012
+ var cursorOffset = document.offsetAt(position);
1013
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
1014
+ if (!currentBlock) {
1015
+ return Promise.resolve([]);
1016
+ }
1017
+ var relatedInfo = currentBlock.Service.GetRelatedElements(document.offsetAt(position));
1018
+ var relatedElements = this.toArray(relatedInfo.Elements);
1019
+ var definition = relatedElements[0];
1020
+ if (!definition) {
1021
+ return Promise.resolve([]);
1022
+ }
1023
+ var start = document.positionAt(definition.Start);
1024
+ var end = document.positionAt(definition.End);
1025
+ var range = ls.Range.create(start, end);
1026
+ var location = ls.Location.create(document.uri, range);
1027
+ return Promise.resolve([location]);
1028
+ };
1029
+ KustoLanguageService.prototype.findReferences = function (document, position) {
1030
+ if (!document || !this.isIntellisenseV2()) {
1031
+ return Promise.resolve([]);
1032
+ }
1033
+ var script = this.parseDocumentV2(document);
1034
+ var cursorOffset = document.offsetAt(position);
1035
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
1036
+ if (!currentBlock) {
1037
+ return Promise.resolve([]);
1038
+ }
1039
+ var relatedInfo = currentBlock.Service.GetRelatedElements(document.offsetAt(position));
1040
+ var relatedElements = this.toArray(relatedInfo.Elements);
1041
+ if (!relatedElements || relatedElements.length == 0) {
1042
+ return Promise.resolve([]);
1043
+ }
1044
+ var references = relatedElements.map(function (relatedElement) {
1045
+ var start = document.positionAt(relatedElement.Start);
1046
+ var end = document.positionAt(relatedElement.End);
1047
+ var range = ls.Range.create(start, end);
1048
+ var location = ls.Location.create(document.uri, range);
1049
+ return location;
1050
+ });
1051
+ return Promise.resolve(references);
1052
+ };
1053
+ KustoLanguageService.prototype.getQueryParams = function (document, cursorOffset) {
1054
+ if (!document || !this.isIntellisenseV2()) {
1055
+ return Promise.resolve([]);
1056
+ }
1057
+ var script = this.parseDocumentV2(document);
1058
+ var parsedAndAnalyzed = this.parseAndAnalyze(document, cursorOffset);
1059
+ var queryParamStatements = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.QueryParametersStatement));
1060
+ if (!queryParamStatements || queryParamStatements.length == 0) {
1061
+ return Promise.resolve([]);
1062
+ }
1063
+ var queryParams = [];
1064
+ queryParamStatements.forEach(function (paramStatement) {
1065
+ paramStatement.WalkElements(function (el) {
1066
+ return el.ReferencedSymbol && el.ReferencedSymbol.Type
1067
+ ? queryParams.push({ name: el.ReferencedSymbol.Name, type: el.ReferencedSymbol.Type.Name })
1068
+ : undefined;
1069
+ });
1070
+ });
1071
+ return Promise.resolve(queryParams);
1072
+ };
1073
+ KustoLanguageService.prototype.getRenderInfo = function (document, cursorOffset) {
1074
+ var _this = this;
1075
+ var parsedAndAnalyzed = this.parseAndAnalyze(document, cursorOffset);
1076
+ if (!parsedAndAnalyzed) {
1077
+ return Promise.resolve(undefined);
1078
+ }
1079
+ var renderStatements = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.RenderOperator));
1080
+ if (!renderStatements || renderStatements.length === 0) {
1081
+ return Promise.resolve(undefined);
1082
+ }
1083
+ // assuming a single render statement
1084
+ var renderStatement = renderStatements[0];
1085
+ // Start and end relative to block start.
1086
+ var startOffset = renderStatement.TextStart;
1087
+ var endOffset = renderStatement.End;
1088
+ var visualization = renderStatement.ChartType.ValueText;
1089
+ var withClause = renderStatement.WithClause;
1090
+ if (!withClause) {
1091
+ var info = {
1092
+ options: {
1093
+ visualization: visualization,
1094
+ },
1095
+ location: { startOffset: startOffset, endOffset: endOffset },
1096
+ };
1097
+ return Promise.resolve(info);
1098
+ }
1099
+ var properties = this.toArray(withClause.Properties);
1100
+ var props = properties.reduce(function (prev, property) {
1101
+ var name = property.Element$1.Name.SimpleName;
1102
+ switch (name) {
1103
+ case 'xcolumn':
1104
+ var value = property.Element$1.Expression.ReferencedSymbol.Name;
1105
+ prev[name] = value;
1106
+ break;
1107
+ case 'ycolumns':
1108
+ case 'anomalycolumns':
1109
+ var nameNodes = _this.toArray(property.Element$1.Expression.Names);
1110
+ var values = nameNodes.map(function (nameNode) { return nameNode.Element$1.SimpleName; });
1111
+ prev[name] = values;
1112
+ break;
1113
+ case 'ymin':
1114
+ case 'ymax':
1115
+ var numericVal = parseFloat(property.Element$1.Expression.ConstantValue);
1116
+ prev[name] = numericVal;
1117
+ break;
1118
+ case 'title':
1119
+ case 'xtitle':
1120
+ case 'ytitle':
1121
+ case 'visualization':
1122
+ case 'series':
1123
+ var strVal = property.Element$1.Expression.ConstantValue;
1124
+ prev[name] = strVal;
1125
+ break;
1126
+ case 'xaxis':
1127
+ case 'yaxis':
1128
+ var scale = property.Element$1.Expression.ConstantValue;
1129
+ prev[name] = scale;
1130
+ break;
1131
+ case 'legend':
1132
+ var legend = property.Element$1.Expression.ConstantValue;
1133
+ prev[name] = legend;
1134
+ break;
1135
+ case 'ySplit':
1136
+ var split = property.Element$1.Expression.ConstantValue;
1137
+ prev[name] = split;
1138
+ break;
1139
+ case 'accumulate':
1140
+ var accumulate = property.Element$1.Expression.ConstantValue;
1141
+ prev[name] = accumulate;
1142
+ break;
1143
+ case 'kind':
1144
+ var val = property.Element$1.Expression.ConstantValue;
1145
+ prev[name] = val;
1146
+ break;
1147
+ default:
1148
+ assertNever(name);
1149
+ }
1150
+ return prev;
1151
+ }, {});
1152
+ var renderOptions = __assign({ visualization: visualization }, props);
1153
+ var renderInfo = {
1154
+ options: renderOptions,
1155
+ location: { startOffset: startOffset, endOffset: endOffset },
1156
+ };
1157
+ return Promise.resolve(renderInfo);
1158
+ };
1159
+ KustoLanguageService.prototype.getReferencedGlobalParams = function (document, cursorOffset) {
1160
+ if (!document || !this.isIntellisenseV2()) {
1161
+ return Promise.resolve([]);
1162
+ }
1163
+ var script = this.parseDocumentV2(document);
1164
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
1165
+ if (!currentBlock) {
1166
+ return Promise.resolve([]);
1167
+ }
1168
+ var text = currentBlock.Text;
1169
+ var parsedAndAnalyzed = Kusto.Language.KustoCode.ParseAndAnalyze(text, this._kustoJsSchemaV2);
1170
+ // We take the ambient parameters
1171
+ var ambientParameters = this.toArray(this._kustoJsSchemaV2.Parameters);
1172
+ // We take all referenced symbols in the query
1173
+ var referencedSymbols = this.toArray(parsedAndAnalyzed.Syntax.GetDescendants(Kusto.Language.Syntax.Expression))
1174
+ .filter(function (expression) { return expression.ReferencedSymbol !== null; })
1175
+ .map(function (x) { return x.ReferencedSymbol; });
1176
+ // The Intersection between them is the ambient parameters that are used in the query.
1177
+ // Note: Ideally we would use Set here (or at least array.Include), but were' compiling down to es2015.
1178
+ var intersection = referencedSymbols.filter(function (referencedSymbol) {
1179
+ return ambientParameters.filter(function (ambientParameter) { return ambientParameter === referencedSymbol; }).length > 0;
1180
+ });
1181
+ var result = intersection.map(function (param) { return ({ name: param.Name, type: param.Type.Name }); });
1182
+ return Promise.resolve(result);
1183
+ };
1184
+ KustoLanguageService.prototype.getGlobalParams = function (document) {
1185
+ if (!this.isIntellisenseV2()) {
1186
+ return Promise.resolve([]);
1187
+ }
1188
+ var params = this.toArray(this._kustoJsSchemaV2.Parameters);
1189
+ var result = params.map(function (param) { return ({ name: param.Name, type: param.Type.Name }); });
1190
+ return Promise.resolve(result);
1191
+ };
1192
+ KustoLanguageService.prototype.doRename = function (document, position, newName) {
1193
+ var _a;
1194
+ if (!document || !this.isIntellisenseV2()) {
1195
+ return Promise.resolve(undefined);
1196
+ }
1197
+ var script = this.parseDocumentV2(document);
1198
+ var cursorOffset = document.offsetAt(position);
1199
+ var currentBLock = this.getCurrentCommandV2(script, cursorOffset);
1200
+ if (!currentBLock) {
1201
+ return Promise.resolve(undefined);
1202
+ }
1203
+ var relatedInfo = currentBLock.Service.GetRelatedElements(document.offsetAt(position));
1204
+ var relatedElements = this.toArray(relatedInfo.Elements);
1205
+ var declarations = relatedElements.filter(function (e) { return e.Kind == k2.RelatedElementKind.Declaration; });
1206
+ // A declaration must be one of the elements
1207
+ if (!declarations || declarations.length == 0) {
1208
+ return Promise.resolve(undefined);
1209
+ }
1210
+ var edits = relatedElements.map(function (edit) {
1211
+ var start = document.positionAt(edit.Start);
1212
+ var end = document.positionAt(edit.End);
1213
+ var range = ls.Range.create(start, end);
1214
+ return ls.TextEdit.replace(range, newName);
1215
+ });
1216
+ // create a workspace edit
1217
+ var workspaceEdit = { changes: (_a = {}, _a[document.uri] = edits, _a) };
1218
+ return Promise.resolve(workspaceEdit);
1219
+ };
1220
+ KustoLanguageService.prototype.doHover = function (document, position) {
1221
+ if (!document || !this.isIntellisenseV2()) {
1222
+ return Promise.resolve(undefined);
1223
+ }
1224
+ var script = this.parseDocumentV2(document);
1225
+ var cursorOffset = document.offsetAt(position);
1226
+ var currentBLock = this.getCurrentCommandV2(script, cursorOffset);
1227
+ if (!currentBLock) {
1228
+ return Promise.resolve(undefined);
1229
+ }
1230
+ var isSupported = currentBLock.Service.IsFeatureSupported(k2.CodeServiceFeatures.QuickInfo, cursorOffset);
1231
+ if (!isSupported) {
1232
+ return Promise.resolve(undefined);
1233
+ }
1234
+ var quickInfo = currentBLock.Service.GetQuickInfo(cursorOffset);
1235
+ if (!quickInfo || !quickInfo.Items) {
1236
+ return Promise.resolve(undefined);
1237
+ }
1238
+ var items = this.toArray(quickInfo.Items);
1239
+ if (!items) {
1240
+ return Promise.resolve(undefined);
1241
+ }
1242
+ // Errors are already shown in getDiagnostics. we don't want them in doHover.
1243
+ items = items.filter(function (item) { return item.Kind !== k2.QuickInfoKind.Error; });
1244
+ var itemsText = items.map(function (item) { return item.Text.replace('\n\n', '\n* * *\n'); });
1245
+ // separate items by horizontal line.
1246
+ var text = itemsText.join('\n* * *\n');
1247
+ // Instead of just an empty line between the first line (the signature) and the second line (the description)
1248
+ // add an horizontal line (* * * in markdown) between them.
1249
+ return Promise.resolve({ contents: text });
1250
+ };
1251
+ Object.defineProperty(KustoLanguageService, "dummySchema", {
1252
+ //#region dummy schema for manual testing
1253
+ get: function () {
1254
+ var database = {
1255
+ majorVersion: 0,
1256
+ minorVersion: 0,
1257
+ name: 'Kuskus',
1258
+ tables: [
1259
+ {
1260
+ name: 'KustoLogs',
1261
+ columns: [
1262
+ {
1263
+ name: 'Source',
1264
+ type: 'string',
1265
+ },
1266
+ {
1267
+ name: 'Timestamp',
1268
+ type: 'datetime',
1269
+ },
1270
+ {
1271
+ name: 'Directory',
1272
+ type: 'string',
1273
+ },
1274
+ ],
1275
+ docstring: 'A dummy description to test that docstring shows as expected when hovering over a table',
1276
+ },
1277
+ ],
1278
+ functions: [
1279
+ {
1280
+ name: 'HowBig',
1281
+ inputParameters: [
1282
+ {
1283
+ name: 'T',
1284
+ columns: [
1285
+ {
1286
+ name: 'Timestamp',
1287
+ type: 'System.DateTime',
1288
+ cslType: 'datetime',
1289
+ },
1290
+ ],
1291
+ },
1292
+ ],
1293
+ docstring: 'A dummy description to test that docstring shows as expected when hovering over a function',
1294
+ body: "{\r\n union \r\n (T | count | project V='Volume', Metric = strcat(Count/1e9, ' Billion records')),\r\n (T | summarize FirstRecord=min(Timestamp)| project V='Volume', Metric = strcat(toint((now()-FirstRecord)/1d), ' Days of data (from: ', format_datetime(FirstRecord, 'yyyy-MM-dd'),')')),\r\n (T | where Timestamp > ago(1h) | count | project V='Velocity', Metric = strcat(Count/1e6, ' Million records / hour')),\r\n (T | summarize Latency=now()-max(Timestamp) | project V='Velocity', Metric = strcat(Latency / 1sec, ' seconds latency')),\r\n (T | take 1 | project V='Variety', Metric=tostring(pack_all()))\r\n | order by V \r\n}",
1295
+ },
1296
+ {
1297
+ name: 'FindCIDPast24h',
1298
+ inputParameters: [
1299
+ {
1300
+ name: 'clientActivityId',
1301
+ type: 'System.String',
1302
+ cslType: 'string',
1303
+ },
1304
+ ],
1305
+ body: '{ KustoLogs | where Timestamp > now(-1d) | where ClientActivityId == clientActivityId} ',
1306
+ },
1307
+ ],
1308
+ };
1309
+ var languageServiceSchema = {
1310
+ clusterType: 'Engine',
1311
+ cluster: {
1312
+ connectionString: 'https://kuskus.kusto.windows.net;fed=true',
1313
+ databases: [database],
1314
+ },
1315
+ database: database,
1316
+ };
1317
+ return languageServiceSchema;
1318
+ },
1319
+ enumerable: false,
1320
+ configurable: true
1321
+ });
1322
+ //#endregion
1323
+ KustoLanguageService.convertToEntityDataType = function (kustoType) { };
1324
+ /**
1325
+ * We do not want to expose Bridge.Net generated schema, so we expose a cleaner javascript schema.
1326
+ * Here it gets converted to the bridge.Net schema
1327
+ * @param schema Language Service schema
1328
+ */
1329
+ KustoLanguageService.convertToKustoJsSchema = function (schema) {
1330
+ switch (schema.clusterType) {
1331
+ case 'Engine':
1332
+ var currentDatabaseName_1 = schema.database ? schema.database.name : undefined;
1333
+ var kCluster = new k.KustoIntelliSenseClusterEntity();
1334
+ var kDatabaseInContext_1 = undefined;
1335
+ kCluster.ConnectionString = schema.cluster.connectionString;
1336
+ var databases_1 = [];
1337
+ schema.cluster.databases.forEach(function (database) {
1338
+ var kDatabase = new k.KustoIntelliSenseDatabaseEntity();
1339
+ kDatabase.Name = database.name;
1340
+ var tables = [];
1341
+ database.tables.forEach(function (table) {
1342
+ var kTable = new k.KustoIntelliSenseTableEntity();
1343
+ kTable.Name = table.name;
1344
+ var cols = [];
1345
+ table.columns.forEach(function (column) {
1346
+ var kColumn = new k.KustoIntelliSenseColumnEntity();
1347
+ kColumn.Name = column.name;
1348
+ kColumn.TypeCode = k.EntityDataType[getEntityDataTypeFromCslType(column.type)];
1349
+ cols.push(kColumn);
1350
+ });
1351
+ kTable.Columns = new Bridge.ArrayEnumerable(cols);
1352
+ tables.push(kTable);
1353
+ });
1354
+ var functions = [];
1355
+ database.functions.forEach(function (fn) {
1356
+ var kFunction = new k.KustoIntelliSenseFunctionEntity();
1357
+ (kFunction.Name = fn.name),
1358
+ (kFunction.CallName = s.getCallName(fn)),
1359
+ (kFunction.Expression = s.getExpression(fn)),
1360
+ functions.push(kFunction);
1361
+ });
1362
+ kDatabase.Tables = new Bridge.ArrayEnumerable(tables);
1363
+ kDatabase.Functions = new Bridge.ArrayEnumerable(functions);
1364
+ databases_1.push(kDatabase);
1365
+ if (database.name == currentDatabaseName_1) {
1366
+ kDatabaseInContext_1 = kDatabase;
1367
+ }
1368
+ });
1369
+ kCluster.Databases = new Bridge.ArrayEnumerable(databases_1);
1370
+ var kSchema = new k.KustoIntelliSenseQuerySchema(kCluster, kDatabaseInContext_1);
1371
+ return kSchema;
1372
+ case 'ClusterManager':
1373
+ var accounts = schema.accounts.map(function (account) {
1374
+ var kAccount = new k.KustoIntelliSenseAccountEntity();
1375
+ kAccount.Name = account;
1376
+ return kAccount;
1377
+ });
1378
+ var services = schema.services.map(function (service) {
1379
+ var kService = new k.KustoIntelliSenseServiceEntity();
1380
+ kService.Name = service;
1381
+ return kService;
1382
+ });
1383
+ var connectionString = schema.connectionString;
1384
+ var result = {
1385
+ accounts: accounts,
1386
+ services: services,
1387
+ connectionString: connectionString,
1388
+ };
1389
+ return result;
1390
+ case 'DataManagement':
1391
+ return undefined;
1392
+ default:
1393
+ return assertNever(schema);
1394
+ }
1395
+ };
1396
+ /**
1397
+ * Returns something like '(x: string, y: datetime)'
1398
+ * @param params scalar parameters
1399
+ */
1400
+ KustoLanguageService.scalarParametersToSignature = function (params) {
1401
+ var signatureWithoutParens = params.map(function (param) { return param.name + ": " + param.cslType; }).join(', ');
1402
+ return "(" + signatureWithoutParens + ")";
1403
+ };
1404
+ /**
1405
+ * Returns something like '(x: string, T: (y: int))'
1406
+ * @param params input parameters (tabular or scalar)
1407
+ */
1408
+ KustoLanguageService.inputParameterToSignature = function (params) {
1409
+ var _this = this;
1410
+ var signatureWithoutParens = params
1411
+ .map(function (param) {
1412
+ if (param.columns) {
1413
+ var tableSignature = _this.scalarParametersToSignature(param.columns);
1414
+ return param.name + ": " + tableSignature;
1415
+ }
1416
+ else {
1417
+ return param.name + ": " + param.cslType;
1418
+ }
1419
+ })
1420
+ .join(', ');
1421
+ return "(" + signatureWithoutParens + ")";
1422
+ };
1423
+ /**
1424
+ * converts a function definition to a let statement.
1425
+ * @param fn function
1426
+ */
1427
+ KustoLanguageService.toLetStatement = function (fn) {
1428
+ var signature = this.inputParameterToSignature(fn.inputParameters);
1429
+ return "let " + fn.name + " = " + signature + " " + fn.body;
1430
+ };
1431
+ KustoLanguageService.createColumnSymbol = function (col) {
1432
+ return new sym.ColumnSymbol(col.name, sym.ScalarTypes.GetSymbol(getCslTypeNameFromClrType(col.type)), col.docstring);
1433
+ };
1434
+ KustoLanguageService.createParameterSymbol = function (param) {
1435
+ var paramSymbol = Kusto.Language.Symbols.ScalarTypes.GetSymbol(getCslTypeNameFromClrType(param.type));
1436
+ return new sym.ParameterSymbol(param.name, paramSymbol, null);
1437
+ };
1438
+ KustoLanguageService.createParameter = function (param) {
1439
+ if (!param.columns) {
1440
+ var paramSymbol = Kusto.Language.Symbols.ScalarTypes.GetSymbol(getCslTypeNameFromClrType(param.type));
1441
+ var expression = param.cslDefaultValue && typeof param.cslDefaultValue === 'string'
1442
+ ? parsing.QueryParser.ParseLiteral$1(param.cslDefaultValue)
1443
+ : undefined;
1444
+ return new sym.Parameter.$ctor3(param.name, paramSymbol, null, null, null, false, null, 1, 1, expression, null);
1445
+ }
1446
+ if (param.columns.length == 0) {
1447
+ return new sym.Parameter.ctor(param.name, sym.ParameterTypeKind.Tabular, sym.ArgumentKind.Expression, null, null, false, null, 1, 1, null, null);
1448
+ }
1449
+ var argumentType = new sym.TableSymbol.ctor(param.columns.map(function (col) { return KustoLanguageService.createColumnSymbol(col); }));
1450
+ return new sym.Parameter.$ctor2(param.name, argumentType);
1451
+ };
1452
+ KustoLanguageService.convertToDatabaseSymbol = function (db) {
1453
+ var createFunctionSymbol = function (fn) {
1454
+ var parameters = fn.inputParameters.map(function (param) {
1455
+ return KustoLanguageService.createParameter(param);
1456
+ });
1457
+ // TODO: handle outputColumns (right now it doesn't seem to be implemented for any function).
1458
+ return new sym.FunctionSymbol.$ctor16(fn.name, fn.body, KustoLanguageService.toBridgeList(parameters), fn.docstring);
1459
+ };
1460
+ var createTableSymbol = function (tbl) {
1461
+ var columnSymbols = tbl.columns.map(function (col) { return KustoLanguageService.createColumnSymbol(col); });
1462
+ var symbol = new sym.TableSymbol.$ctor3(tbl.name, columnSymbols);
1463
+ symbol.Description = tbl.docstring;
1464
+ switch (tbl.entityType) {
1465
+ case 'MaterializedViewTable':
1466
+ symbol = symbol.WithIsMaterializedView(true);
1467
+ break;
1468
+ case 'ExternalTable':
1469
+ symbol = symbol.WithIsExternal(true);
1470
+ break;
1471
+ default:
1472
+ }
1473
+ return symbol;
1474
+ };
1475
+ var createDatabaseSymbol = function (db) {
1476
+ var tableSymbols = db.tables ? db.tables.map(function (tbl) { return createTableSymbol(tbl); }) : [];
1477
+ var functionSymbols = db.functions ? db.functions.map(function (fun) { return createFunctionSymbol(fun); }) : [];
1478
+ return new sym.DatabaseSymbol.ctor(db.name, tableSymbols.concat(functionSymbols));
1479
+ };
1480
+ var databaseSymbol = createDatabaseSymbol(db);
1481
+ return databaseSymbol;
1482
+ };
1483
+ KustoLanguageService.prototype.convertToKustoJsSchemaV2 = function (schema) {
1484
+ var cached = this._schemaCache[schema.cluster.connectionString];
1485
+ // create a cache entry for the cluster if non yet exists.
1486
+ if (!cached) {
1487
+ this._schemaCache[schema.cluster.connectionString] = {};
1488
+ cached = this._schemaCache[schema.cluster.connectionString];
1489
+ }
1490
+ // Remove deleted databases from cache
1491
+ var schemaDbLookup = schema.cluster.databases.reduce(function (prev, curr) { return (prev[curr.name] = curr); }, {});
1492
+ Object.keys(cached).map(function (dbName) {
1493
+ if (!schemaDbLookup[dbName]) {
1494
+ delete cached.dbName;
1495
+ }
1496
+ });
1497
+ var globalState = GlobalState.Default;
1498
+ var currentDatabaseName = schema.database ? schema.database.name : undefined;
1499
+ var databaseInContext = undefined;
1500
+ // Update out-of-data databases to cache
1501
+ var databases = schema.cluster.databases.map(function (db) {
1502
+ var shouldIncludeFunctions = db.name === currentDatabaseName;
1503
+ var cachedDb = cached[db.name];
1504
+ // This is an older version than we have, or we need to parse functions.
1505
+ if (!cachedDb ||
1506
+ cachedDb.database.majorVersion < db.majorVersion ||
1507
+ (shouldIncludeFunctions && !cachedDb.includesFunctions)) {
1508
+ // only add functions for the database in context (it's very time consuming)
1509
+ var databaseSymbol_1 = KustoLanguageService.convertToDatabaseSymbol(db);
1510
+ cached[db.name] = { database: db, symbol: databaseSymbol_1, includesFunctions: shouldIncludeFunctions };
1511
+ }
1512
+ var databaseSymbol = cached[db.name].symbol;
1513
+ if (db.name === currentDatabaseName) {
1514
+ databaseInContext = databaseSymbol;
1515
+ }
1516
+ return databaseSymbol;
1517
+ });
1518
+ // Replace new URL due to polyfill issue in IE
1519
+ // const hostname = new URL(schema.cluster.connectionString.split(';')[0]).hostname;
1520
+ var hostname = schema.cluster.connectionString.match(/(.*\/\/)?([^\/;]*)/)[2];
1521
+ var clusterName = hostname.split('.')[0];
1522
+ var clusterSymbol = new sym.ClusterSymbol.ctor(clusterName, databases);
1523
+ globalState = globalState.WithCluster(clusterSymbol);
1524
+ if (databaseInContext) {
1525
+ globalState = globalState.WithDatabase(databaseInContext);
1526
+ }
1527
+ // Inject global parameters to global scope.
1528
+ if (schema.globalParameters) {
1529
+ var parameters = schema.globalParameters.map(function (param) {
1530
+ return KustoLanguageService.createParameterSymbol(param);
1531
+ });
1532
+ globalState = globalState.WithParameters(KustoLanguageService.toBridgeList(parameters));
1533
+ }
1534
+ return globalState;
1535
+ };
1536
+ KustoLanguageService.prototype.getClassificationsFromParseResult = function (offset) {
1537
+ var _this = this;
1538
+ if (offset === void 0) { offset = 0; }
1539
+ var classifications = this.toArray(this._parser.Results)
1540
+ .map(function (command) { return _this.toArray(command.Tokens); })
1541
+ .reduce(function (prev, curr) { return prev.concat(curr); }, [])
1542
+ .map(function (cslCommandToken) {
1543
+ var range = new k2.ClassifiedRange(_this.tokenKindToClassificationKind(cslCommandToken.TokenKind), cslCommandToken.AbsoluteStart + offset, cslCommandToken.Length);
1544
+ return range;
1545
+ });
1546
+ return classifications;
1547
+ };
1548
+ /**
1549
+ * trim trailing newlines from range
1550
+ */
1551
+ KustoLanguageService.trimTrailingNewlineFromRange = function (textInRange, rangeStartOffset, document, range) {
1552
+ var currentIndex = textInRange.length - 1;
1553
+ while (textInRange[currentIndex] === '\r' || textInRange[currentIndex] === '\n') {
1554
+ --currentIndex;
1555
+ }
1556
+ var newEndOffset = rangeStartOffset + currentIndex + 1;
1557
+ var newEndPosition = document.positionAt(newEndOffset);
1558
+ var newRange = ls.Range.create(range.start, newEndPosition);
1559
+ return newRange;
1560
+ };
1561
+ /**
1562
+ * Maps numbers to strings, such that if a>b numerically, f(a)>f(b) lexicographically.
1563
+ * 1 -> "a", 26 -> "z", 27 -> "za", 28 -> "zb", 52 -> "zz", 53 ->"zza"
1564
+ * @param order - The number to be converted to a sorting-string. order should start at 1.
1565
+ * @returns A string repenting the order.
1566
+ */
1567
+ KustoLanguageService.prototype.getSortText = function (order) {
1568
+ if (order <= 0) {
1569
+ throw new RangeError("order should be a number >= 1. instead got " + order);
1570
+ }
1571
+ var sortText = '';
1572
+ var numCharacters = 26; // "z" - "a" + 1;
1573
+ var div = Math.floor(order / numCharacters);
1574
+ for (var i = 0; i < div; ++i) {
1575
+ sortText += 'z';
1576
+ }
1577
+ var reminder = order % numCharacters;
1578
+ if (reminder > 0) {
1579
+ sortText += String.fromCharCode(96 + reminder);
1580
+ }
1581
+ return sortText;
1582
+ };
1583
+ /**
1584
+ * ParseTextV1 parses the given text with the given parse mode.
1585
+ * Additionally - it will make sure not to provide rules provider for non-engine clusters
1586
+ * since the only rules provider parse can handle is the engine's. It will try to look for function
1587
+ * definitions to colorize and will throw since they're not there.
1588
+ * @param text
1589
+ * @param parseMode
1590
+ */
1591
+ KustoLanguageService.prototype.parseTextV1 = function (text, parseMode) {
1592
+ this._parser.Parse(this._schema.clusterType === 'Engine' ? this._rulesProvider : null, text, parseMode);
1593
+ };
1594
+ KustoLanguageService.prototype.parseDocumentV1 = function (document, parseMode) {
1595
+ // already parsed a later version, or better parse mode for this uri
1596
+ if (this._parsePropertiesV1 &&
1597
+ !this._parsePropertiesV1.isParseNeeded(document, this._rulesProvider, parseMode)) {
1598
+ return;
1599
+ }
1600
+ this.parseTextV1(document.getText(), parseMode);
1601
+ this._parsePropertiesV1 = new ParseProperties(document.version, document.uri, this._rulesProvider, parseMode);
1602
+ };
1603
+ KustoLanguageService.prototype.parseDocumentV2 = function (document) {
1604
+ if (this._parsePropertiesV2 && !this._parsePropertiesV2.isParseNeeded(document, this._rulesProvider)) {
1605
+ return this._script;
1606
+ }
1607
+ if (!this._script) {
1608
+ this._script = k2.CodeScript.From$1(document.getText(), this._kustoJsSchemaV2);
1609
+ }
1610
+ else {
1611
+ this._script = this._script.WithText(document.getText());
1612
+ }
1613
+ this._parsePropertiesV2 = new ParseProperties(document.version, document.uri);
1614
+ return this._script;
1615
+ };
1616
+ /**
1617
+ * Return the CslCommand that wraps the caret location, or undefined if caret is outside any command
1618
+ * @param document the document to extract the current command from
1619
+ * @param caretAbsolutePosition absolute caret position
1620
+ */
1621
+ KustoLanguageService.prototype.getCurrentCommand = function (document, caretAbsolutePosition) {
1622
+ var commands = this.toArray(this._parser.Results);
1623
+ var command = commands.filter(function (command) { return command.AbsoluteStart <= caretAbsolutePosition && command.AbsoluteEnd >= caretAbsolutePosition; })[0];
1624
+ // There is an edge case when cursor appears at the end of the command
1625
+ // which is not yet considered to be part of the parsed command (therefore: +1 for the AbsoluteEdit property)
1626
+ if (!command) {
1627
+ command = commands.filter(function (command) {
1628
+ return command.AbsoluteStart <= caretAbsolutePosition && command.AbsoluteEnd + 1 >= caretAbsolutePosition;
1629
+ })[0];
1630
+ // If we have 2 newlines in the end of the text the cursor is _probably_ at the end of the text
1631
+ // which this means that we're not actually standing on any command. Thus return null.
1632
+ if (!command || command.Text.endsWith('\r\n\r\n')) {
1633
+ return null;
1634
+ }
1635
+ }
1636
+ return command;
1637
+ };
1638
+ KustoLanguageService.prototype.getCurrentCommandV2 = function (script, offset) {
1639
+ var block = script.GetBlockAtPosition(offset);
1640
+ return block;
1641
+ };
1642
+ KustoLanguageService.prototype.getTextToInsert = function (rule, option) {
1643
+ var beforeApplyInfo = rule.GetBeforeApplyInfo(option.Value);
1644
+ var afterApplyInfo = rule.GetAfterApplyInfo(option.Value);
1645
+ // this is the basic text to be inserted,
1646
+ // but we still need to figure out where the cursor will end up after completion is applied.
1647
+ var insertText = beforeApplyInfo.Text || '' + option.Value + afterApplyInfo.Text || '';
1648
+ var insertTextFormat = ls.InsertTextFormat.PlainText;
1649
+ var snippetFinalTabStop = '$0';
1650
+ if (afterApplyInfo.OffsetToken && afterApplyInfo.OffsetPosition) {
1651
+ var tokenOffset = insertText.indexOf(afterApplyInfo.OffsetToken);
1652
+ if (tokenOffset >= 0) {
1653
+ insertText = this.insertToString(insertText, snippetFinalTabStop, tokenOffset - insertText.length + afterApplyInfo.OffsetPosition);
1654
+ insertTextFormat = ls.InsertTextFormat.Snippet;
1655
+ }
1656
+ }
1657
+ else if (afterApplyInfo.OffsetPosition) {
1658
+ // We only handle negative offsets
1659
+ insertText = this.insertToString(insertText, snippetFinalTabStop, afterApplyInfo.OffsetPosition);
1660
+ insertTextFormat = ls.InsertTextFormat.Snippet;
1661
+ }
1662
+ return { insertText: insertText, insertTextFormat: insertTextFormat };
1663
+ };
1664
+ /**
1665
+ * create a new string with stringToInsert inserted at offsetFromEnd in originalString.
1666
+ * @param originalString string to insert to
1667
+ * @param stringToInsert string to insert
1668
+ * @param offsetFromEnd a negative number that will represent offset to the left. 0 means simple concat
1669
+ */
1670
+ KustoLanguageService.prototype.insertToString = function (originalString, stringToInsert, offsetFromEnd) {
1671
+ var index = originalString.length + offsetFromEnd;
1672
+ if (offsetFromEnd >= 0 || index < 0) {
1673
+ return originalString; // Cannot insert before or after the string
1674
+ }
1675
+ var before = originalString.substring(0, index);
1676
+ var after = originalString.substring(index);
1677
+ return before + stringToInsert + after;
1678
+ };
1679
+ KustoLanguageService.prototype.getCommandWithoutLastWord = function (text) {
1680
+ var lastWordRegex = XRegExp('[\\w_]*$', 's');
1681
+ return text.replace(lastWordRegex, '');
1682
+ };
1683
+ KustoLanguageService.prototype.createRulesProvider = function (schema, clusterType) {
1684
+ var queryParameters = new (List(String))();
1685
+ var availableClusters = new (List(String))();
1686
+ this._parser = new k.CslCommandParser();
1687
+ if (clusterType == 'Engine') {
1688
+ var engineSchema = schema;
1689
+ this._rulesProvider =
1690
+ this._languageSettings && this._languageSettings.includeControlCommands
1691
+ ? new k.CslIntelliSenseRulesProvider.$ctor1(engineSchema.Cluster, engineSchema, queryParameters, availableClusters, null, true, true)
1692
+ : new k.CslQueryIntelliSenseRulesProvider.$ctor1(engineSchema.Cluster, engineSchema, queryParameters, availableClusters, null, null, null);
1693
+ return;
1694
+ }
1695
+ if (clusterType === 'DataManagement') {
1696
+ this._rulesProvider = new k.DataManagerIntelliSenseRulesProvider(null);
1697
+ return;
1698
+ }
1699
+ // This is a cluster manger
1700
+ var _a = schema, accounts = _a.accounts, services = _a.services, connectionString = _a.connectionString;
1701
+ new k.KustoIntelliSenseAccountEntity();
1702
+ new k.KustoIntelliSenseServiceEntity();
1703
+ this._rulesProvider = new k.ClusterManagerIntelliSenseRulesProvider.$ctor1(new Bridge.ArrayEnumerable(accounts), new Bridge.ArrayEnumerable(services), connectionString);
1704
+ };
1705
+ KustoLanguageService.prototype.kustoKindToLsKind = function (kustoKind) {
1706
+ var res = this._kustoKindtolsKind[kustoKind];
1707
+ return res ? res : ls.CompletionItemKind.Variable;
1708
+ };
1709
+ KustoLanguageService.prototype.kustoKindToLsKindV2 = function (kustoKind) {
1710
+ var res = this._kustoKindToLsKindV2[kustoKind];
1711
+ return res ? res : ls.CompletionItemKind.Variable;
1712
+ };
1713
+ KustoLanguageService.prototype.createRange = function (document, start, end) {
1714
+ return ls.Range.create(document.positionAt(start), document.positionAt(end));
1715
+ };
1716
+ KustoLanguageService.prototype.toArray = function (bridgeList) {
1717
+ return Bridge.toArray(bridgeList);
1718
+ };
1719
+ KustoLanguageService.toBridgeList = function (array) {
1720
+ // copied from bridge.js from the implementation of Enumerable.prototype.toList
1721
+ return new (System.Collections.Generic.List$1(System.Object).$ctor1)(array);
1722
+ };
1723
+ KustoLanguageService.prototype.tokenKindToClassificationKind = function (token) {
1724
+ var conversion = this._tokenKindToClassificationKind[token];
1725
+ return conversion || k2.ClassificationKind.PlainText;
1726
+ };
1727
+ KustoLanguageService.prototype.parseAndAnalyze = function (document, cursorOffset) {
1728
+ if (!document || !this.isIntellisenseV2()) {
1729
+ return undefined;
1730
+ }
1731
+ var script = this.parseDocumentV2(document);
1732
+ var currentBlock = this.getCurrentCommandV2(script, cursorOffset);
1733
+ if (!currentBlock) {
1734
+ return undefined;
1735
+ }
1736
+ var text = currentBlock.Text;
1737
+ var parsedAndAnalyzed = Kusto.Language.KustoCode.ParseAndAnalyze(text, this._kustoJsSchemaV2);
1738
+ return parsedAndAnalyzed;
1739
+ };
1740
+ return KustoLanguageService;
1741
+ }());
1742
+ var languageService = new KustoLanguageService(KustoLanguageService.dummySchema, {
1743
+ includeControlCommands: true,
1744
+ useIntellisenseV2: true,
1745
+ useSemanticColorization: true,
1746
+ });
1747
+ /**
1748
+ * Obtain an instance of the kusto language service.
1749
+ */
1750
+ export function getKustoLanguageService() {
1751
+ return languageService;
1752
+ }