plugin-elastic-report 0.1.1 → 0.7.0

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.
Files changed (60) hide show
  1. package/ai/skills/elastic-report/SKILLS.md +5 -3
  2. package/dist/client/357.0dd385384cab5dbf.js +10 -0
  3. package/dist/client/index.js +1 -1
  4. package/dist/client-v2/851.142c93fc6d666b28.js +10 -0
  5. package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
  6. package/dist/client-v2/877.f4095a3dbcadf98f.js +10 -0
  7. package/dist/client-v2/index.js +1 -1
  8. package/dist/externalVersion.js +3 -2
  9. package/dist/locale/en-US.json +100 -1
  10. package/dist/locale/vi-VN.json +100 -1
  11. package/dist/locale/zh-CN.json +100 -1
  12. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  13. package/dist/server/acl-guard.js +97 -25
  14. package/dist/server/collections/es-report-data-views.js +6 -0
  15. package/dist/server/collections/es-reports.js +6 -0
  16. package/dist/server/mcp/ElasticReportToolCatalog.js +232 -10
  17. package/dist/server/plugin.js +153 -19
  18. package/dist/server/services/ElasticReportService.js +125 -11
  19. package/dist/server/services/ElasticsearchConnectionService.js +274 -34
  20. package/dist/server/services/ReportExportService.js +243 -0
  21. package/dist/server/services/ReportQueryCompiler.js +532 -91
  22. package/dist/server/workflow/ElasticReportQueryInstruction.js +123 -0
  23. package/dist/shared/constants.js +17 -2
  24. package/package.json +3 -2
  25. package/src/client/index.tsx +16 -1
  26. package/src/client/workflow-instructions.tsx +44 -0
  27. package/src/client-v2/__tests__/elastic-report.test.tsx +519 -39
  28. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
  29. package/src/client-v2/api.ts +96 -0
  30. package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
  31. package/src/client-v2/components/ElasticBasicCharts.tsx +345 -92
  32. package/src/client-v2/components/ElasticFilterBar.tsx +372 -0
  33. package/src/client-v2/components/ElasticKqlInput.tsx +421 -0
  34. package/src/client-v2/components/ElasticReportBlock.tsx +157 -11
  35. package/src/client-v2/components/ElasticReportRenderer.tsx +621 -71
  36. package/src/client-v2/components/ReportSelect.tsx +39 -26
  37. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
  38. package/src/client-v2/models/ElasticReportBlockModel.tsx +36 -3
  39. package/src/client-v2/pages/ElasticReportManager.tsx +432 -26
  40. package/src/client-v2/plugin.tsx +20 -0
  41. package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
  42. package/src/client-v2/workflow/instructions.tsx +149 -0
  43. package/src/locale/en-US.json +100 -1
  44. package/src/locale/vi-VN.json +100 -1
  45. package/src/locale/zh-CN.json +100 -1
  46. package/src/server/__tests__/query-compiler.test.ts +390 -1
  47. package/src/server/__tests__/report-mcp-acl.integration.test.ts +271 -3
  48. package/src/server/acl-guard.ts +119 -28
  49. package/src/server/collections/es-report-data-views.ts +6 -0
  50. package/src/server/collections/es-reports.ts +6 -0
  51. package/src/server/mcp/ElasticReportToolCatalog.ts +255 -9
  52. package/src/server/plugin.ts +189 -21
  53. package/src/server/services/ElasticReportService.ts +165 -5
  54. package/src/server/services/ElasticsearchConnectionService.ts +375 -48
  55. package/src/server/services/ReportExportService.ts +282 -0
  56. package/src/server/services/ReportQueryCompiler.ts +629 -94
  57. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
  58. package/src/shared/constants.ts +7 -0
  59. package/src/shared/types.ts +98 -1
  60. package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
@@ -0,0 +1,861 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import type { EsFieldCapability, FieldTopValueBucket, ReportRowHit } from '../../shared/types';
11
+
12
+ export type KqlContextStage = 'field' | 'operator' | 'value' | 'connector' | 'group_connector';
13
+
14
+ export type KqlSuggestionCategory = 'free_text' | 'field' | 'operator' | 'value' | 'connector';
15
+
16
+ export interface KqlCursorContext {
17
+ stage: KqlContextStage;
18
+ replaceStart: number;
19
+ replaceEnd: number;
20
+ field?: string;
21
+ fieldMeta?: EsFieldCapability;
22
+ operator?: ':' | '>=' | '<=' | '>' | '<';
23
+ partial: string;
24
+ insideFieldGroup: boolean;
25
+ openExprParens: number;
26
+ needsLeadingAnd?: boolean;
27
+ }
28
+
29
+ export interface KqlSuggestionItem {
30
+ key: string;
31
+ category: KqlSuggestionCategory;
32
+ /** Full resulting query string if this suggestion is selected */
33
+ nextQuery: string;
34
+ /** Cursor index in `nextQuery` after insertion */
35
+ nextCursor: number;
36
+ /** Primary token displayed on the left of the option row */
37
+ displayToken: string;
38
+ /** Plain-language explanation or field type / count shown on the right */
39
+ description: string;
40
+ /** Short badge text (e.g. field type or hit count) */
41
+ badge?: string;
42
+ /** Keep autocomplete popup open after selecting so user can continue building step-by-step */
43
+ keepOpen: boolean;
44
+ /** Submit search immediately when user clicks this explicit free-text run action */
45
+ submitImmediately?: boolean;
46
+ }
47
+
48
+ const NUMERIC_ES_TYPES = new Set([
49
+ 'long',
50
+ 'integer',
51
+ 'short',
52
+ 'byte',
53
+ 'double',
54
+ 'float',
55
+ 'half_float',
56
+ 'scaled_float',
57
+ 'unsigned_long',
58
+ ]);
59
+
60
+ const DATE_ES_TYPES = new Set(['date', 'date_nanos']);
61
+
62
+ export function isNumericEsField(field?: EsFieldCapability): boolean {
63
+ return Boolean(field && NUMERIC_ES_TYPES.has(field.type));
64
+ }
65
+
66
+ export function isDateEsField(field?: EsFieldCapability): boolean {
67
+ return Boolean(field && DATE_ES_TYPES.has(field.type));
68
+ }
69
+
70
+ export function canFetchFieldTopValues(field?: EsFieldCapability): boolean {
71
+ if (!field) return true;
72
+ if (DATE_ES_TYPES.has(field.type)) return false;
73
+ return field.aggregatable || Boolean(field.keywordSubfield);
74
+ }
75
+
76
+ export function escapeKqlQuotedString(raw: string): string {
77
+ return raw.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
78
+ }
79
+
80
+ export function formatKqlValueLiteral(raw: string, fieldMeta?: EsFieldCapability): string {
81
+ const trimmed = raw.trim();
82
+ if (!trimmed) return '""';
83
+ if (fieldMeta?.type === 'boolean' && (trimmed === 'true' || trimmed === 'false')) {
84
+ return trimmed;
85
+ }
86
+ if (isNumericEsField(fieldMeta) && /^-?\d+(?:\.\d+)?$/.test(trimmed)) {
87
+ return trimmed;
88
+ }
89
+ if (!fieldMeta && /^-?\d+(?:\.\d+)?$/.test(trimmed)) {
90
+ return trimmed;
91
+ }
92
+ return `"${escapeKqlQuotedString(raw)}"`;
93
+ }
94
+
95
+ interface ParenScope {
96
+ kind: 'field_group' | 'expr_group';
97
+ field?: string;
98
+ openIndex: number;
99
+ }
100
+
101
+ interface ScanState {
102
+ inQuotes: boolean;
103
+ quoteChar: '"' | "'" | '';
104
+ quoteOpenIndex: number;
105
+ parenStack: ParenScope[];
106
+ /** Start index of current clause after the latest top-level (within current paren scope) boolean connector or `(` */
107
+ clauseStart: number;
108
+ }
109
+
110
+ function scanBeforeCursor(before: string): ScanState {
111
+ let inQuotes = false;
112
+ let quoteChar: '"' | "'" | '' = '';
113
+ let quoteOpenIndex = -1;
114
+ const parenStack: ParenScope[] = [];
115
+ let clauseStart = 0;
116
+
117
+ for (let i = 0; i < before.length; i++) {
118
+ const ch = before[i];
119
+ if (inQuotes) {
120
+ if (ch === '\\') {
121
+ i++;
122
+ continue;
123
+ }
124
+ if (ch === quoteChar) {
125
+ inQuotes = false;
126
+ quoteChar = '';
127
+ quoteOpenIndex = -1;
128
+ }
129
+ continue;
130
+ }
131
+
132
+ if (ch === '"' || ch === "'") {
133
+ inQuotes = true;
134
+ quoteChar = ch;
135
+ quoteOpenIndex = i;
136
+ continue;
137
+ }
138
+
139
+ if (ch === '(') {
140
+ const prefixSlice = before.slice(clauseStart, i);
141
+ const fieldColonMatch = prefixSlice.match(/^\s*([A-Za-z0-9_@.-]+)\s*:\s*$/);
142
+ if (fieldColonMatch) {
143
+ parenStack.push({ kind: 'field_group', field: fieldColonMatch[1], openIndex: i });
144
+ } else {
145
+ parenStack.push({ kind: 'expr_group', openIndex: i });
146
+ }
147
+ clauseStart = i + 1;
148
+ continue;
149
+ }
150
+
151
+ if (ch === ')') {
152
+ const popped = parenStack.pop();
153
+ if (popped?.kind === 'field_group') {
154
+ // Keep clauseStart before `field: (...)` so the completed field group is recognized as a finished clause
155
+ const beforeGroup = before.slice(0, popped.openIndex);
156
+ const colonMatch = beforeGroup.match(/([A-Za-z0-9_@.-]+)\s*:\s*$/);
157
+ clauseStart = colonMatch && colonMatch.index !== undefined ? colonMatch.index : popped.openIndex;
158
+ }
159
+ continue;
160
+ }
161
+
162
+ // Detect boolean connectors (`AND`, `OR`, `NOT`) with word boundaries inside the active scope
163
+ const prevBoundary = i === 0 || /[\s(]/.test(before[i - 1]);
164
+ if (prevBoundary) {
165
+ const rest = before.slice(i);
166
+ const connectorMatch = rest.match(/^(AND\s+NOT|AND|OR|NOT)(?=[\s(])/i);
167
+ if (connectorMatch) {
168
+ const kw = connectorMatch[1];
169
+ i += kw.length - 1;
170
+ clauseStart = i + 1;
171
+ }
172
+ }
173
+ }
174
+
175
+ return {
176
+ inQuotes,
177
+ quoteChar,
178
+ quoteOpenIndex,
179
+ parenStack,
180
+ clauseStart,
181
+ };
182
+ }
183
+
184
+ function findFieldMeta(fieldName: string, fields: EsFieldCapability[]): EsFieldCapability | undefined {
185
+ const exact = fields.find((f) => f.name === fieldName);
186
+ if (exact) return exact;
187
+ const lower = fieldName.toLowerCase();
188
+ return fields.find((f) => f.name.toLowerCase() === lower);
189
+ }
190
+
191
+ function splitCompletedSingleValueAndRest(rhs: string): {
192
+ completedValue: string;
193
+ trailingWhitespace: boolean;
194
+ trailingWord: string;
195
+ trailingWordOffsetInRhs: number;
196
+ } | null {
197
+ const leadMatch = rhs.match(/^\s*/);
198
+ const offset0 = leadMatch ? leadMatch[0].length : 0;
199
+ const trimmedStart = rhs.slice(offset0);
200
+ if (!trimmedStart) return null;
201
+
202
+ // Quoted value: "..." or '...'
203
+ if (trimmedStart.startsWith('"') || trimmedStart.startsWith("'")) {
204
+ const q = trimmedStart[0];
205
+ let i = 1;
206
+ while (i < trimmedStart.length) {
207
+ if (trimmedStart[i] === '\\') {
208
+ i += 2;
209
+ continue;
210
+ }
211
+ if (trimmedStart[i] === q) {
212
+ const completedValue = trimmedStart.slice(0, i + 1);
213
+ const afterQuote = trimmedStart.slice(i + 1);
214
+ const wsMatch = afterQuote.match(/^(\s*)(.*)$/);
215
+ const ws = wsMatch ? wsMatch[1] : '';
216
+ const rest = wsMatch ? wsMatch[2] : '';
217
+ return {
218
+ completedValue,
219
+ trailingWhitespace: ws.length > 0 || rest.length === 0,
220
+ trailingWord: rest,
221
+ trailingWordOffsetInRhs: offset0 + i + 1 + ws.length,
222
+ };
223
+ }
224
+ i++;
225
+ }
226
+ return null;
227
+ }
228
+
229
+ // Balanced parenthesized group: (...)
230
+ if (trimmedStart.startsWith('(')) {
231
+ let depth = 0;
232
+ let inQ = false;
233
+ let qChar = '';
234
+ for (let i = 0; i < trimmedStart.length; i++) {
235
+ const c = trimmedStart[i];
236
+ if (inQ) {
237
+ if (c === '\\') {
238
+ i++;
239
+ continue;
240
+ }
241
+ if (c === qChar) inQ = false;
242
+ continue;
243
+ }
244
+ if (c === '"' || c === "'") {
245
+ inQ = true;
246
+ qChar = c;
247
+ continue;
248
+ }
249
+ if (c === '(') depth++;
250
+ if (c === ')') {
251
+ depth--;
252
+ if (depth === 0) {
253
+ const completedValue = trimmedStart.slice(0, i + 1);
254
+ const afterParen = trimmedStart.slice(i + 1);
255
+ const wsMatch = afterParen.match(/^(\s*)(.*)$/);
256
+ const ws = wsMatch ? wsMatch[1] : '';
257
+ const rest = wsMatch ? wsMatch[2] : '';
258
+ return {
259
+ completedValue,
260
+ trailingWhitespace: ws.length > 0 || rest.length === 0,
261
+ trailingWord: rest,
262
+ trailingWordOffsetInRhs: offset0 + i + 1 + ws.length,
263
+ };
264
+ }
265
+ }
266
+ }
267
+ return null;
268
+ }
269
+
270
+ // Unquoted token followed by whitespace
271
+ const tokenMatch = trimmedStart.match(/^(\S+)(\s+)(.*)$/);
272
+ if (tokenMatch) {
273
+ const [, completedValue, ws, rest] = tokenMatch;
274
+ return {
275
+ completedValue,
276
+ trailingWhitespace: true,
277
+ trailingWord: rest,
278
+ trailingWordOffsetInRhs: offset0 + completedValue.length + ws.length,
279
+ };
280
+ }
281
+
282
+ return null;
283
+ }
284
+
285
+ export function analyzeKqlCursorContext(
286
+ input: string,
287
+ cursorPos: number = input.length,
288
+ fields: EsFieldCapability[] = [],
289
+ ): KqlCursorContext {
290
+ const clampedCursor = Math.max(0, Math.min(input.length, cursorPos));
291
+ const before = input.slice(0, clampedCursor);
292
+ const after = input.slice(clampedCursor);
293
+ const scan = scanBeforeCursor(before);
294
+ const topParen = scan.parenStack[scan.parenStack.length - 1];
295
+ const openExprParens = scan.parenStack.filter((p) => p.kind === 'expr_group').length;
296
+
297
+ // Consume adjacent closing quote when user edits inside an existing quoted literal
298
+ const computeReplaceEnd = (isQuotedToken: boolean): number => {
299
+ if (isQuotedToken && scan.inQuotes && scan.quoteChar && after.startsWith(scan.quoteChar)) {
300
+ return clampedCursor + 1;
301
+ }
302
+ return clampedCursor;
303
+ };
304
+
305
+ // 1. Inside `field: (...)` value group
306
+ if (topParen?.kind === 'field_group' && topParen.field) {
307
+ const fieldMeta = findFieldMeta(topParen.field, fields);
308
+ const clause = before.slice(scan.clauseStart);
309
+ const leadWs = clause.match(/^\s*/)?.[0].length ?? 0;
310
+ const trimmedClause = clause.slice(leadWs);
311
+
312
+ if (!scan.inQuotes) {
313
+ const completed = splitCompletedSingleValueAndRest(clause);
314
+ if (completed && completed.trailingWhitespace) {
315
+ return {
316
+ stage: 'group_connector',
317
+ replaceStart: scan.clauseStart + completed.trailingWordOffsetInRhs,
318
+ replaceEnd: clampedCursor,
319
+ field: fieldMeta?.name ?? topParen.field,
320
+ fieldMeta,
321
+ partial: completed.trailingWord,
322
+ insideFieldGroup: true,
323
+ openExprParens,
324
+ };
325
+ }
326
+ }
327
+
328
+ const inlineOpMatch = !scan.inQuotes ? trimmedClause.match(/^(>=|<=|>|<)\s*(.*)$/) : null;
329
+ if (inlineOpMatch) {
330
+ const [, rawOp, rhsVal] = inlineOpMatch;
331
+ const opLen = trimmedClause.length - rhsVal.length;
332
+ const rawPartial = rhsVal.replace(/^['"]/, '');
333
+ return {
334
+ stage: 'value',
335
+ replaceStart: scan.clauseStart + leadWs + opLen,
336
+ replaceEnd: computeReplaceEnd(rhsVal.startsWith('"') || rhsVal.startsWith("'")),
337
+ field: fieldMeta?.name ?? topParen.field,
338
+ fieldMeta,
339
+ operator: rawOp as '>=' | '<=' | '>' | '<',
340
+ partial: rawPartial,
341
+ insideFieldGroup: true,
342
+ openExprParens,
343
+ };
344
+ }
345
+
346
+ const rawPartial = trimmedClause.replace(/^['"]/, '');
347
+ return {
348
+ stage: 'value',
349
+ replaceStart: scan.clauseStart + leadWs,
350
+ replaceEnd: computeReplaceEnd(trimmedClause.startsWith('"') || trimmedClause.startsWith("'")),
351
+ field: fieldMeta?.name ?? topParen.field,
352
+ fieldMeta,
353
+ operator: ':',
354
+ partial: rawPartial,
355
+ insideFieldGroup: true,
356
+ openExprParens,
357
+ };
358
+ }
359
+
360
+ // 2. Normal top-level or `(expr)` scope
361
+ const clause = before.slice(scan.clauseStart);
362
+ const leadWs = clause.match(/^\s*/)?.[0].length ?? 0;
363
+ const clauseStartTrimmed = scan.clauseStart + leadWs;
364
+ const trimmedClause = clause.slice(leadWs);
365
+
366
+ if (!trimmedClause) {
367
+ return {
368
+ stage: 'field',
369
+ replaceStart: clampedCursor,
370
+ replaceEnd: clampedCursor,
371
+ partial: '',
372
+ insideFieldGroup: false,
373
+ openExprParens,
374
+ };
375
+ }
376
+
377
+ // Check if user typed `<knownField> >` or `<knownField> <` without trailing space yet (could want `>=` or `<=`)
378
+ if (!scan.inQuotes) {
379
+ const partialOpMatch = trimmedClause.match(/^([A-Za-z0-9_@.-]+)\s+([><=!]+)$/);
380
+ if (partialOpMatch) {
381
+ const [, rawField, partialOp] = partialOpMatch;
382
+ const fieldMeta = findFieldMeta(rawField, fields);
383
+ if (fieldMeta && (partialOp === '>' || partialOp === '<' || partialOp === '!')) {
384
+ return {
385
+ stage: 'operator',
386
+ replaceStart: clauseStartTrimmed,
387
+ replaceEnd: clampedCursor,
388
+ field: fieldMeta.name,
389
+ fieldMeta,
390
+ partial: partialOp,
391
+ insideFieldGroup: false,
392
+ openExprParens,
393
+ };
394
+ }
395
+ }
396
+ }
397
+
398
+ // Check `field (: | >= | <= | > | <) rhs`
399
+ const fieldOpMatch = trimmedClause.match(/^([A-Za-z0-9_@.-]+)(\s*(:|>=|<=|>|<))(.*)$/);
400
+ if (fieldOpMatch) {
401
+ const [, rawField, opSegment, rawOp, rhs] = fieldOpMatch;
402
+ const fieldMeta = findFieldMeta(rawField, fields);
403
+ const rhsOffsetInInput = clauseStartTrimmed + rawField.length + opSegment.length;
404
+
405
+ if (!scan.inQuotes) {
406
+ const completed = splitCompletedSingleValueAndRest(rhs);
407
+ if (completed && completed.trailingWhitespace) {
408
+ const connectorStart = rhsOffsetInInput + completed.trailingWordOffsetInRhs;
409
+ const trailingWord = completed.trailingWord;
410
+ const matchesConnectorPrefix =
411
+ !trailingWord ||
412
+ 'AND'.startsWith(trailingWord.toUpperCase()) ||
413
+ 'OR'.startsWith(trailingWord.toUpperCase()) ||
414
+ 'NOT'.startsWith(trailingWord.toUpperCase());
415
+ return {
416
+ stage: 'connector',
417
+ replaceStart: connectorStart,
418
+ replaceEnd: clampedCursor,
419
+ partial: trailingWord,
420
+ insideFieldGroup: false,
421
+ openExprParens,
422
+ needsLeadingAnd: Boolean(trailingWord && !matchesConnectorPrefix),
423
+ };
424
+ }
425
+ }
426
+
427
+ const rhsLeadWs = rhs.match(/^\s*/)?.[0].length ?? 0;
428
+ const rhsTrimmed = rhs.slice(rhsLeadWs);
429
+ const rawPartial = rhsTrimmed.replace(/^['"]/, '');
430
+
431
+ return {
432
+ stage: 'value',
433
+ replaceStart: rhsLeadWs > 0 ? rhsOffsetInInput + rhsLeadWs : rhsOffsetInInput,
434
+ replaceEnd: computeReplaceEnd(rhsTrimmed.startsWith('"') || rhsTrimmed.startsWith("'")),
435
+ field: fieldMeta?.name ?? rawField,
436
+ fieldMeta,
437
+ operator: rawOp as ':' | '>=' | '<=' | '>' | '<',
438
+ partial: rawPartial,
439
+ insideFieldGroup: false,
440
+ openExprParens,
441
+ };
442
+ }
443
+
444
+ // Single word followed by whitespace: either `<knownField> ` -> operator stage, or `<freeTextWord> ` -> connector stage
445
+ if (!scan.inQuotes) {
446
+ const singleWordWithSpace = trimmedClause.match(/^([A-Za-z0-9_@.-]+)\s+$/);
447
+ if (singleWordWithSpace) {
448
+ const word = singleWordWithSpace[1];
449
+ const fieldMeta = findFieldMeta(word, fields);
450
+ if (fieldMeta) {
451
+ return {
452
+ stage: 'operator',
453
+ replaceStart: clauseStartTrimmed,
454
+ replaceEnd: clampedCursor,
455
+ field: fieldMeta.name,
456
+ fieldMeta,
457
+ partial: '',
458
+ insideFieldGroup: false,
459
+ openExprParens,
460
+ };
461
+ }
462
+ return {
463
+ stage: 'connector',
464
+ replaceStart: clampedCursor,
465
+ replaceEnd: clampedCursor,
466
+ partial: '',
467
+ insideFieldGroup: false,
468
+ openExprParens,
469
+ };
470
+ }
471
+
472
+ // Multiple free-text tokens: suggest connectors when ending with whitespace or connector prefix
473
+ if (/\s/.test(trimmedClause)) {
474
+ const trailingSpace = /\s$/.test(trimmedClause);
475
+ if (trailingSpace) {
476
+ return {
477
+ stage: 'connector',
478
+ replaceStart: clampedCursor,
479
+ replaceEnd: clampedCursor,
480
+ partial: '',
481
+ insideFieldGroup: false,
482
+ openExprParens,
483
+ };
484
+ }
485
+ const lastSpaceIdx = before.lastIndexOf(' ');
486
+ const lastWord = before.slice(lastSpaceIdx + 1);
487
+ return {
488
+ stage: 'connector',
489
+ replaceStart: lastSpaceIdx + 1,
490
+ replaceEnd: clampedCursor,
491
+ partial: lastWord,
492
+ insideFieldGroup: false,
493
+ openExprParens,
494
+ needsLeadingAnd:
495
+ Boolean(lastWord) &&
496
+ !'AND'.startsWith(lastWord.toUpperCase()) &&
497
+ !'OR'.startsWith(lastWord.toUpperCase()) &&
498
+ !'NOT'.startsWith(lastWord.toUpperCase()),
499
+ };
500
+ }
501
+ }
502
+
503
+ // Single partial token at start of clause: `<partialFieldOrFreeText>`
504
+ return {
505
+ stage: 'field',
506
+ replaceStart: clauseStartTrimmed,
507
+ replaceEnd: clampedCursor,
508
+ partial: trimmedClause.replace(/^['"]/, ''),
509
+ insideFieldGroup: false,
510
+ openExprParens,
511
+ };
512
+ }
513
+
514
+ function spliceSuggestion(
515
+ fullInput: string,
516
+ replaceStart: number,
517
+ replaceEnd: number,
518
+ insertion: string,
519
+ ): { nextQuery: string; nextCursor: number } {
520
+ const rawPrefix = fullInput.slice(0, replaceStart);
521
+ const prefix = insertion.startsWith(')') ? rawPrefix.replace(/\s+$/, '') : rawPrefix;
522
+ const suffix = fullInput.slice(replaceEnd);
523
+ const needsLeadingSpace =
524
+ prefix.length > 0 && !/[\s(]$/.test(prefix) && !insertion.startsWith(' ') && !insertion.startsWith(')');
525
+ const normalizedInsert = needsLeadingSpace ? ` ${insertion}` : insertion;
526
+ const trimmedSuffix = normalizedInsert.endsWith(' ') && suffix.startsWith(' ') ? suffix.slice(1) : suffix;
527
+ const nextQuery = `${prefix}${normalizedInsert}${trimmedSuffix}`;
528
+ return {
529
+ nextQuery,
530
+ nextCursor: prefix.length + normalizedInsert.length,
531
+ };
532
+ }
533
+
534
+ function extractSampleValuesFromRows(field: string, rows: ReportRowHit[] | undefined): string[] {
535
+ if (!rows || rows.length === 0) return [];
536
+ const seen = new Set<string>();
537
+ const parts = field.replace(/\.keyword$/, '').split('.');
538
+
539
+ for (const row of rows) {
540
+ let cur: unknown = row.source;
541
+ for (const p of parts) {
542
+ if (cur && typeof cur === 'object' && !Array.isArray(cur) && p in (cur as Record<string, unknown>)) {
543
+ cur = (cur as Record<string, unknown>)[p];
544
+ } else {
545
+ cur = undefined;
546
+ break;
547
+ }
548
+ }
549
+ if (typeof cur === 'string' || typeof cur === 'number' || typeof cur === 'boolean') {
550
+ const str = String(cur).trim();
551
+ if (str && str.length <= 80 && !seen.has(str)) {
552
+ seen.add(str);
553
+ if (seen.size >= 10) break;
554
+ }
555
+ }
556
+ }
557
+ return Array.from(seen);
558
+ }
559
+
560
+ export interface BuildKqlSuggestionsParams {
561
+ input: string;
562
+ cursorPos?: number;
563
+ fields: EsFieldCapability[];
564
+ topValueBuckets?: FieldTopValueBucket[];
565
+ sampleRows?: ReportRowHit[];
566
+ t: (key: string) => string;
567
+ }
568
+
569
+ export function buildKqlSuggestions({
570
+ input,
571
+ cursorPos = input.length,
572
+ fields,
573
+ topValueBuckets = [],
574
+ sampleRows,
575
+ t,
576
+ }: BuildKqlSuggestionsParams): {
577
+ context: KqlCursorContext;
578
+ items: KqlSuggestionItem[];
579
+ } {
580
+ const ctx = analyzeKqlCursorContext(input, cursorPos, fields);
581
+ const items: KqlSuggestionItem[] = [];
582
+ const lowerPartial = ctx.partial.toLowerCase();
583
+
584
+ const buildFieldItem = (f: EsFieldCapability, prefixConnector = ''): KqlSuggestionItem => {
585
+ const isRangeCapable = isNumericEsField(f) || isDateEsField(f);
586
+ const insertion = `${prefixConnector}${f.name}${isRangeCapable ? ' ' : ': '}`;
587
+ const { nextQuery, nextCursor } = spliceSuggestion(input, ctx.replaceStart, ctx.replaceEnd, insertion);
588
+ return {
589
+ key: `field:${prefixConnector}${f.name}`,
590
+ category: 'field',
591
+ nextQuery,
592
+ nextCursor,
593
+ displayToken: `${prefixConnector}${f.name}`,
594
+ description: isRangeCapable ? t('Choose comparison (=, >=, <=...)') : t('Filter by field value'),
595
+ badge: f.type,
596
+ keepOpen: true,
597
+ };
598
+ };
599
+
600
+ const buildOperatorItems = (
601
+ fieldName: string,
602
+ fieldMeta?: EsFieldCapability,
603
+ filterOpPrefix = '',
604
+ ): KqlSuggestionItem[] => {
605
+ const isRangeCapable = !fieldMeta || isNumericEsField(fieldMeta) || isDateEsField(fieldMeta);
606
+ const rawOps: Array<{ suffix: string; token: string; desc: string; keepOpen: boolean }> = isRangeCapable
607
+ ? [
608
+ { suffix: ': ', token: `${fieldName}: `, desc: t('Equals (=)'), keepOpen: true },
609
+ { suffix: ' >= ', token: `${fieldName} >= `, desc: t('Greater than or equal (>=)'), keepOpen: true },
610
+ { suffix: ' <= ', token: `${fieldName} <= `, desc: t('Less than or equal (<=)'), keepOpen: true },
611
+ { suffix: ' > ', token: `${fieldName} > `, desc: t('Greater than (>)'), keepOpen: true },
612
+ { suffix: ' < ', token: `${fieldName} < `, desc: t('Less than (<)'), keepOpen: true },
613
+ { suffix: ': (', token: `${fieldName}: (`, desc: t('Match multiple values (OR)'), keepOpen: true },
614
+ { suffix: ': * ', token: `${fieldName}: *`, desc: t('Has any value (exists)'), keepOpen: true },
615
+ ]
616
+ : [
617
+ { suffix: ': ', token: `${fieldName}: `, desc: t('Equals or contains (: )'), keepOpen: true },
618
+ { suffix: ': (', token: `${fieldName}: (`, desc: t('Match multiple values (OR)'), keepOpen: true },
619
+ { suffix: ': * ', token: `${fieldName}: *`, desc: t('Has any value (exists)'), keepOpen: true },
620
+ ];
621
+
622
+ return rawOps
623
+ .filter((op) => {
624
+ if (!filterOpPrefix) return true;
625
+ if (filterOpPrefix === '!') return false;
626
+ return op.suffix.trimStart().startsWith(filterOpPrefix);
627
+ })
628
+ .map((op) => {
629
+ const insertion = `${fieldName}${op.suffix}`;
630
+ const { nextQuery, nextCursor } = spliceSuggestion(input, ctx.replaceStart, ctx.replaceEnd, insertion);
631
+ return {
632
+ key: `op:${fieldName}:${op.suffix.trim()}`,
633
+ category: 'operator',
634
+ nextQuery,
635
+ nextCursor,
636
+ displayToken: op.token.trimEnd(),
637
+ description: op.desc,
638
+ keepOpen: op.keepOpen,
639
+ };
640
+ });
641
+ };
642
+
643
+ const getFilteredFields = (query: string): EsFieldCapability[] => {
644
+ const showSubfields = query.includes('.');
645
+ const candidates = fields.filter((f) => f.searchable !== false && (showSubfields || !f.isSubfield));
646
+ if (!query) {
647
+ return candidates.slice(0, 20);
648
+ }
649
+ const q = query.toLowerCase();
650
+ const starts: EsFieldCapability[] = [];
651
+ const contains: EsFieldCapability[] = [];
652
+ for (const f of candidates) {
653
+ const lowerName = f.name.toLowerCase();
654
+ if (lowerName.startsWith(q)) {
655
+ starts.push(f);
656
+ } else if (lowerName.includes(q)) {
657
+ contains.push(f);
658
+ }
659
+ }
660
+ return [...starts, ...contains].slice(0, 15);
661
+ };
662
+
663
+ // Stage 1: Field suggestions (+ exact-match operator shortcuts + free-text fallback)
664
+ if (ctx.stage === 'field') {
665
+ const exactField = ctx.partial ? findFieldMeta(ctx.partial, fields) : undefined;
666
+ if (exactField) {
667
+ items.push(...buildOperatorItems(exactField.name, exactField));
668
+ }
669
+
670
+ for (const f of getFilteredFields(ctx.partial)) {
671
+ if (exactField && f.name === exactField.name) continue;
672
+ items.push(buildFieldItem(f));
673
+ }
674
+
675
+ if (!lowerPartial || 'not'.startsWith(lowerPartial)) {
676
+ const beforePrefix = input.slice(0, ctx.replaceStart).trimEnd();
677
+ if (!/\bNOT$/i.test(beforePrefix)) {
678
+ const { nextQuery, nextCursor } = spliceSuggestion(input, ctx.replaceStart, ctx.replaceEnd, 'NOT ');
679
+ items.push({
680
+ key: 'conn:NOT',
681
+ category: 'connector',
682
+ nextQuery,
683
+ nextCursor,
684
+ displayToken: 'NOT',
685
+ description: t('Exclude matching records'),
686
+ badge: 'logic',
687
+ keepOpen: true,
688
+ });
689
+ }
690
+ }
691
+
692
+ if (ctx.partial.trim().length >= 2 && ctx.replaceStart === 0 && ctx.replaceEnd === input.length) {
693
+ items.push({
694
+ key: `freetext:${ctx.partial}`,
695
+ category: 'free_text',
696
+ nextQuery: input,
697
+ nextCursor: input.length,
698
+ displayToken: `"${ctx.partial}"`,
699
+ description: t('Search text across all fields (Press Enter)'),
700
+ badge: 'text',
701
+ keepOpen: false,
702
+ submitImmediately: true,
703
+ });
704
+ }
705
+
706
+ return { context: ctx, items };
707
+ }
708
+
709
+ // Stage 2: Operator suggestions after `<field> `
710
+ if (ctx.stage === 'operator' && ctx.field) {
711
+ items.push(...buildOperatorItems(ctx.field, ctx.fieldMeta, ctx.partial));
712
+ if (!ctx.partial) {
713
+ for (const conn of [
714
+ { token: 'AND ', label: 'AND', desc: t('Combine another condition (both match)') },
715
+ { token: 'OR ', label: 'OR', desc: t('Match either condition') },
716
+ ]) {
717
+ const { nextQuery, nextCursor } = spliceSuggestion(input, cursorPos, cursorPos, conn.token);
718
+ items.push({
719
+ key: `op-conn:${conn.label}`,
720
+ category: 'connector',
721
+ nextQuery,
722
+ nextCursor,
723
+ displayToken: conn.label,
724
+ description: conn.desc,
725
+ badge: 'logic',
726
+ keepOpen: true,
727
+ });
728
+ }
729
+ }
730
+ return { context: ctx, items };
731
+ }
732
+
733
+ // Stage 3: Value suggestions after `field: ` / `field >= ` / `field: (`
734
+ if (ctx.stage === 'value' && ctx.field) {
735
+ const seenLiterals = new Set<string>();
736
+
737
+ const pushValueOption = (rawVal: string, desc: string, badge?: string, rawInsertionOverride?: string) => {
738
+ if (lowerPartial && !rawVal.toLowerCase().includes(lowerPartial)) {
739
+ return;
740
+ }
741
+ const literal = rawInsertionOverride ?? `${formatKqlValueLiteral(rawVal, ctx.fieldMeta)} `;
742
+ if (seenLiterals.has(literal)) return;
743
+ seenLiterals.add(literal);
744
+
745
+ const { nextQuery, nextCursor } = spliceSuggestion(input, ctx.replaceStart, ctx.replaceEnd, literal);
746
+ items.push({
747
+ key: `val:${ctx.field}:${literal.trim()}`,
748
+ category: 'value',
749
+ nextQuery,
750
+ nextCursor,
751
+ displayToken: literal.trimEnd(),
752
+ description: desc,
753
+ badge,
754
+ keepOpen: true,
755
+ });
756
+ };
757
+
758
+ // Boolean literals
759
+ if (ctx.fieldMeta?.type === 'boolean') {
760
+ pushValueOption('true', t('Boolean true'), 'boolean');
761
+ pushValueOption('false', t('Boolean false'), 'boolean');
762
+ }
763
+
764
+ // Relative time literals for date fields
765
+ if (isDateEsField(ctx.fieldMeta)) {
766
+ pushValueOption('now-15m', t('Last 15 minutes'), 'date', '"now-15m" ');
767
+ pushValueOption('now-1h', t('Last 1 hour'), 'date', '"now-1h" ');
768
+ pushValueOption('now-24h', t('Last 24 hours'), 'date', '"now-24h" ');
769
+ pushValueOption('now-7d', t('Last 7 days'), 'date', '"now-7d" ');
770
+ }
771
+
772
+ // Real top values from Elasticsearch
773
+ for (const bucket of topValueBuckets) {
774
+ if (!bucket.value) continue;
775
+ pushValueOption(bucket.value, t('Suggested value from data'), `${bucket.count}`);
776
+ }
777
+
778
+ // Sample values from loaded table rows as instant fallback
779
+ for (const sampleVal of extractSampleValuesFromRows(ctx.field, sampleRows)) {
780
+ pushValueOption(sampleVal, t('Sample value from loaded rows'));
781
+ }
782
+
783
+ // Special KQL helpers (`*` exists and `(` multi-value group) when operator is `:` outside a group
784
+ if (ctx.operator === ':' && !ctx.insideFieldGroup) {
785
+ if (!lowerPartial || '*'.startsWith(lowerPartial)) {
786
+ pushValueOption('*', t('Has any value (exists)'), 'KQL', '* ');
787
+ }
788
+ if (!lowerPartial) {
789
+ const { nextQuery, nextCursor } = spliceSuggestion(input, ctx.replaceStart, ctx.replaceEnd, '(');
790
+ items.push({
791
+ key: `val:${ctx.field}:group`,
792
+ category: 'operator',
793
+ nextQuery,
794
+ nextCursor,
795
+ displayToken: '(',
796
+ description: t('Match multiple values (OR)'),
797
+ badge: 'group',
798
+ keepOpen: true,
799
+ });
800
+ }
801
+ }
802
+
803
+ return { context: ctx, items };
804
+ }
805
+
806
+ // Stage 4: Inside `field: ("a" ` -> suggest closing `)` or `OR `
807
+ if (ctx.stage === 'group_connector') {
808
+ const groupConnectors = [
809
+ { insert: ') ', label: ')', desc: t('Finish value group') },
810
+ { insert: 'OR ', label: 'OR', desc: t('Add another value to group') },
811
+ { insert: 'AND NOT ', label: 'AND NOT', desc: t('Exclude value in group') },
812
+ ];
813
+ for (const gc of groupConnectors) {
814
+ if (lowerPartial && !gc.label.toLowerCase().startsWith(lowerPartial)) continue;
815
+ const { nextQuery, nextCursor } = spliceSuggestion(input, ctx.replaceStart, ctx.replaceEnd, gc.insert);
816
+ items.push({
817
+ key: `gconn:${gc.label}`,
818
+ category: 'connector',
819
+ nextQuery,
820
+ nextCursor,
821
+ displayToken: gc.label,
822
+ description: gc.desc,
823
+ badge: 'group',
824
+ keepOpen: true,
825
+ });
826
+ }
827
+ return { context: ctx, items };
828
+ }
829
+
830
+ // Stage 5: Connector stage after a completed clause (`status >= 500 `)
831
+ const connectors = [
832
+ { insert: 'AND ', label: 'AND', desc: t('Combine another condition (both match)') },
833
+ { insert: 'OR ', label: 'OR', desc: t('Match either condition') },
834
+ { insert: 'AND NOT ', label: 'AND NOT', desc: t('Exclude next condition') },
835
+ ...(ctx.openExprParens > 0 ? [{ insert: ') ', label: ')', desc: t('Close condition group') }] : []),
836
+ ];
837
+
838
+ for (const conn of connectors) {
839
+ if (lowerPartial && !conn.label.toLowerCase().startsWith(lowerPartial)) continue;
840
+ const { nextQuery, nextCursor } = spliceSuggestion(input, ctx.replaceStart, ctx.replaceEnd, conn.insert);
841
+ items.push({
842
+ key: `conn:${conn.label}`,
843
+ category: 'connector',
844
+ nextQuery,
845
+ nextCursor,
846
+ displayToken: conn.label,
847
+ description: conn.desc,
848
+ badge: 'logic',
849
+ keepOpen: true,
850
+ });
851
+ }
852
+
853
+ // Auto-insert `AND ` when user starts typing a new field name directly after a completed clause
854
+ if (ctx.needsLeadingAnd && ctx.partial) {
855
+ for (const f of getFilteredFields(ctx.partial)) {
856
+ items.push(buildFieldItem(f, 'AND '));
857
+ }
858
+ }
859
+
860
+ return { context: ctx, items };
861
+ }