plugin-elastic-report 0.7.0 → 0.9.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 (70) hide show
  1. package/client-v2.d.ts +2 -2
  2. package/client-v2.js +1 -1
  3. package/client.d.ts +2 -2
  4. package/client.js +1 -1
  5. package/{ai → dist/ai}/skills/elastic-report/SKILLS.md +52 -34
  6. package/dist/client-v2/851.35e416bfb3fb565f.js +10 -0
  7. package/dist/client-v2/877.81b10beb7b7f4bd7.js +10 -0
  8. package/dist/client-v2/index.js +1 -1
  9. package/dist/externalVersion.js +2 -1
  10. package/dist/locale/en-US.json +213 -198
  11. package/dist/locale/vi-VN.json +213 -198
  12. package/dist/locale/zh-CN.json +213 -198
  13. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  14. package/dist/server/mcp/ElasticReportToolCatalog.js +6 -4
  15. package/dist/server/plugin.js +4 -4
  16. package/dist/server/report-block-tools.js +340 -0
  17. package/dist/server/services/ElasticReportService.js +12 -6
  18. package/dist/shared/constants.js +9 -0
  19. package/package.json +2 -3
  20. package/server.d.ts +2 -2
  21. package/server.js +1 -1
  22. package/src/ai/skills/elastic-report/SKILLS.md +52 -0
  23. package/src/client/index.tsx +34 -34
  24. package/src/client/workflow-instructions.tsx +44 -44
  25. package/src/client-v2/__tests__/elastic-report.test.tsx +879 -791
  26. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -178
  27. package/src/client-v2/api.ts +320 -320
  28. package/src/client-v2/bus/DashboardFilterBus.ts +212 -212
  29. package/src/client-v2/components/ElasticBasicCharts.tsx +652 -652
  30. package/src/client-v2/components/ElasticFilterBar.tsx +372 -372
  31. package/src/client-v2/components/ElasticKqlInput.tsx +421 -421
  32. package/src/client-v2/components/ElasticReportBlock.tsx +306 -306
  33. package/src/client-v2/components/ElasticReportRenderer.tsx +1257 -1257
  34. package/src/client-v2/components/HighlightText.tsx +50 -50
  35. package/src/client-v2/components/ReportSelect.tsx +85 -85
  36. package/src/client-v2/index.tsx +14 -14
  37. package/src/client-v2/locale.ts +23 -23
  38. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -115
  39. package/src/client-v2/models/ElasticReportBlockModel.tsx +118 -118
  40. package/src/client-v2/pages/ElasticReportManager.tsx +1453 -1453
  41. package/src/client-v2/plugin.tsx +107 -72
  42. package/src/client-v2/report-destination.tsx +126 -0
  43. package/src/client-v2/utils/kqlAutocomplete.ts +861 -861
  44. package/src/client-v2/workflow/instructions.tsx +149 -149
  45. package/src/index.ts +11 -11
  46. package/src/locale/en-US.json +213 -198
  47. package/src/locale/vi-VN.json +213 -198
  48. package/src/locale/zh-CN.json +213 -198
  49. package/src/server/__tests__/ai-blocks.integration.test.ts +292 -0
  50. package/src/server/__tests__/query-compiler.test.ts +620 -620
  51. package/src/server/__tests__/report-mcp-acl.integration.test.ts +645 -645
  52. package/src/server/acl-guard.ts +194 -194
  53. package/src/server/collections/es-report-data-views.ts +64 -64
  54. package/src/server/collections/es-reports.ts +80 -80
  55. package/src/server/index.ts +15 -15
  56. package/src/server/mcp/ElasticReportMcpServer.ts +391 -391
  57. package/src/server/mcp/ElasticReportToolCatalog.ts +667 -663
  58. package/src/server/plugin.ts +599 -599
  59. package/src/server/report-block-tools.ts +400 -0
  60. package/src/server/services/ElasticReportService.ts +494 -486
  61. package/src/server/services/ElasticsearchConnectionService.ts +728 -728
  62. package/src/server/services/ReportExportService.ts +282 -282
  63. package/src/server/services/ReportQueryCompiler.ts +1552 -1552
  64. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -124
  65. package/src/shared/constants.ts +39 -36
  66. package/src/shared/types.ts +272 -272
  67. package/dist/client-v2/851.142c93fc6d666b28.js +0 -10
  68. package/dist/client-v2/877.f4095a3dbcadf98f.js +0 -10
  69. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv +0 -15
  70. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv.cmd +0 -7
@@ -1,1552 +1,1552 @@
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 {
11
- DEFAULT_PAGE_SIZE,
12
- HIGHLIGHT_POST_TAG,
13
- HIGHLIGHT_PRE_TAG,
14
- MAX_RESULT_WINDOW,
15
- MAX_SPLIT_SERIES,
16
- MAX_TERMS_BUCKETS,
17
- MAX_UI_PAGE_SIZE,
18
- } from '../../shared/constants';
19
- import type {
20
- BucketAggType,
21
- CalendarIntervalOption,
22
- ChartStackMode,
23
- EsFieldCapability,
24
- FieldFormatType,
25
- FilterOperator,
26
- ID,
27
- MetricAggType,
28
- RecordContextBinding,
29
- ReportExecutionResult,
30
- ReportFilterItem,
31
- ReportHistogramBucket,
32
- ReportRowHit,
33
- ReportRuntimeOverrides,
34
- ReportSeriesPoint,
35
- ReportShardStats,
36
- ReportSortItem,
37
- ReportSpec,
38
- ReportSubSeriesPoint,
39
- ReportTimeRange,
40
- ReportVisualizationType,
41
- ScalarFilterValue,
42
- TimeRangePreset,
43
- } from '../../shared/types';
44
-
45
- export class KqlSyntaxError extends Error {
46
- public readonly status = 400;
47
-
48
- constructor(message: string) {
49
- super(message);
50
- this.name = 'KqlSyntaxError';
51
- }
52
- }
53
-
54
- const VALID_VISUALIZATIONS: ReadonlySet<ReportVisualizationType> = new Set([
55
- 'table',
56
- 'bar',
57
- 'line',
58
- 'area',
59
- 'pie',
60
- 'metric',
61
- ]);
62
-
63
- const VALID_OPERATORS: ReadonlySet<FilterOperator> = new Set([
64
- 'eq',
65
- 'ne',
66
- 'in',
67
- 'not_in',
68
- 'gt',
69
- 'gte',
70
- 'lt',
71
- 'lte',
72
- 'between',
73
- 'contains',
74
- 'exists',
75
- 'not_exists',
76
- ]);
77
-
78
- const VALID_PRESETS: ReadonlySet<TimeRangePreset> = new Set([
79
- 'last_15m',
80
- 'last_1h',
81
- 'last_24h',
82
- 'last_7d',
83
- 'last_30d',
84
- 'last_90d',
85
- 'all',
86
- 'custom',
87
- ]);
88
-
89
- const VALID_METRICS: ReadonlySet<MetricAggType> = new Set([
90
- 'count',
91
- 'sum',
92
- 'avg',
93
- 'min',
94
- 'max',
95
- 'cardinality',
96
- 'p50',
97
- 'p95',
98
- 'p99',
99
- ]);
100
- const VALID_STACK_MODES: ReadonlySet<ChartStackMode> = new Set(['none', 'stacked', 'percent']);
101
- const VALID_FIELD_FORMATS: ReadonlySet<FieldFormatType> = new Set([
102
- 'auto',
103
- 'duration_ms',
104
- 'bytes',
105
- 'percent',
106
- 'number',
107
- 'status_badge',
108
- 'url',
109
- ]);
110
- const VALID_BUCKETS: ReadonlySet<BucketAggType> = new Set(['date_histogram', 'terms']);
111
- const VALID_INTERVALS: ReadonlySet<CalendarIntervalOption> = new Set([
112
- 'auto',
113
- '1m',
114
- '5m',
115
- '15m',
116
- '1h',
117
- '1d',
118
- '1w',
119
- '1M',
120
- ]);
121
-
122
- // Elasticsearch calendar_interval only accepts single calendar units; multi-unit durations require fixed_interval.
123
- const CALENDAR_UNIT_INTERVALS: ReadonlySet<CalendarIntervalOption> = new Set(['1m', '1h', '1d', '1w', '1M']);
124
-
125
- const PRESET_TO_ES_EXPR: Record<Exclude<TimeRangePreset, 'all' | 'custom'>, string> = {
126
- last_15m: 'now-15m',
127
- last_1h: 'now-1h',
128
- last_24h: 'now-24h',
129
- last_7d: 'now-7d',
130
- last_30d: 'now-30d',
131
- last_90d: 'now-90d',
132
- };
133
-
134
- const PRESET_TO_PREV_ES_EXPR: Record<Exclude<TimeRangePreset, 'all' | 'custom'>, { gte: string; lt: string }> = {
135
- last_15m: { gte: 'now-30m', lt: 'now-15m' },
136
- last_1h: { gte: 'now-2h', lt: 'now-1h' },
137
- last_24h: { gte: 'now-48h', lt: 'now-24h' },
138
- last_7d: { gte: 'now-14d', lt: 'now-7d' },
139
- last_30d: { gte: 'now-60d', lt: 'now-30d' },
140
- last_90d: { gte: 'now-180d', lt: 'now-90d' },
141
- };
142
-
143
- export function sanitizeTimeZone(raw?: unknown): string | undefined {
144
- if (typeof raw !== 'string' || !raw.trim()) return undefined;
145
- const candidate = raw.trim();
146
- try {
147
- Intl.DateTimeFormat(undefined, { timeZone: candidate });
148
- return candidate;
149
- } catch {
150
- return undefined;
151
- }
152
- }
153
-
154
- function isRecord(value: unknown): value is Record<string, unknown> {
155
- return typeof value === 'object' && value !== null && !Array.isArray(value);
156
- }
157
-
158
- function clamp(num: number, min: number, max: number): number {
159
- if (!Number.isFinite(num)) return min;
160
- return Math.max(min, Math.min(max, Math.trunc(num)));
161
- }
162
-
163
- function toScalarValue(raw: unknown): ScalarFilterValue | undefined {
164
- if (typeof raw === 'string') return raw;
165
- if (typeof raw === 'number' && Number.isFinite(raw)) return raw;
166
- if (typeof raw === 'boolean') return raw;
167
- return undefined;
168
- }
169
-
170
- function coerceLiteral(raw: string, fieldMeta?: EsFieldCapability): ScalarFilterValue {
171
- const trimmed = raw.trim();
172
- if (fieldMeta) {
173
- if (fieldMeta.type === 'boolean') {
174
- if (trimmed.toLowerCase() === 'true') return true;
175
- if (trimmed.toLowerCase() === 'false') return false;
176
- }
177
- if (
178
- ['long', 'integer', 'short', 'byte', 'double', 'float', 'half_float', 'scaled_float'].includes(fieldMeta.type)
179
- ) {
180
- const parsed = Number(trimmed);
181
- if (Number.isFinite(parsed)) return parsed;
182
- }
183
- }
184
- if (trimmed.toLowerCase() === 'true') return true;
185
- if (trimmed.toLowerCase() === 'false') return false;
186
- if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
187
- const parsed = Number(trimmed);
188
- if (Number.isFinite(parsed)) return parsed;
189
- }
190
- return trimmed;
191
- }
192
-
193
- export function buildFieldCapabilityMap(fields?: EsFieldCapability[] | null): Map<string, EsFieldCapability> {
194
- const map = new Map<string, EsFieldCapability>();
195
- if (!Array.isArray(fields)) return map;
196
- for (const field of fields) {
197
- if (field && typeof field.name === 'string' && field.name.trim()) {
198
- map.set(field.name.trim(), field);
199
- }
200
- }
201
- return map;
202
- }
203
-
204
- export function resolveAggregatableField(fieldName: string, fieldMap: Map<string, EsFieldCapability>): string {
205
- const clean = fieldName.trim();
206
- const meta = fieldMap.get(clean);
207
- if (!meta) return clean;
208
- if (meta.aggregatable) return clean;
209
- if (meta.keywordSubfield) return meta.keywordSubfield;
210
- const candidate = `${clean}.keyword`;
211
- if (fieldMap.get(candidate)?.aggregatable) return candidate;
212
- return clean;
213
- }
214
-
215
- function resolveUnmappedSortType(fieldName: string, fieldMap: Map<string, EsFieldCapability>): string | undefined {
216
- const meta = fieldMap.get(fieldName);
217
- if (!meta) return undefined;
218
- switch (meta.type) {
219
- case 'date':
220
- case 'date_nanos':
221
- return 'date';
222
- case 'long':
223
- case 'integer':
224
- case 'short':
225
- case 'byte':
226
- return 'long';
227
- case 'double':
228
- case 'float':
229
- case 'half_float':
230
- case 'scaled_float':
231
- return 'double';
232
- case 'boolean':
233
- return 'boolean';
234
- case 'keyword':
235
- case 'constant_keyword':
236
- case 'wildcard':
237
- return 'keyword';
238
- default:
239
- return undefined;
240
- }
241
- }
242
-
243
- export function normalizeReportFilters(raw: unknown): ReportFilterItem[] {
244
- if (!Array.isArray(raw)) return [];
245
- const items: ReportFilterItem[] = [];
246
- for (const entry of raw) {
247
- if (!isRecord(entry)) continue;
248
- const field = typeof entry.field === 'string' ? entry.field.trim() : '';
249
- const operator = typeof entry.operator === 'string' ? (entry.operator as FilterOperator) : 'eq';
250
- if (!field || !VALID_OPERATORS.has(operator)) continue;
251
-
252
- let value: ScalarFilterValue | ScalarFilterValue[] | undefined;
253
- if (Array.isArray(entry.value)) {
254
- const arr = entry.value.map(toScalarValue).filter((v): v is ScalarFilterValue => v !== undefined);
255
- value = arr;
256
- } else if (typeof entry.value === 'string' && (operator === 'in' || operator === 'not_in')) {
257
- value = entry.value
258
- .split(',')
259
- .map((part) => part.trim())
260
- .filter(Boolean);
261
- } else {
262
- value = toScalarValue(entry.value);
263
- }
264
-
265
- const valueTo = toScalarValue(entry.valueTo);
266
- items.push({
267
- ...(typeof entry.id === 'string' && entry.id ? { id: entry.id } : {}),
268
- field,
269
- operator,
270
- ...(value !== undefined ? { value } : {}),
271
- ...(valueTo !== undefined ? { valueTo } : {}),
272
- enabled: entry.enabled !== false,
273
- });
274
- }
275
- return items;
276
- }
277
-
278
- export function normalizeReportSort(raw: unknown): ReportSortItem[] {
279
- if (!Array.isArray(raw)) return [];
280
- const items: ReportSortItem[] = [];
281
- for (const entry of raw) {
282
- if (typeof entry === 'string' && entry.trim()) {
283
- const trimmed = entry.trim();
284
- if (trimmed.startsWith('-')) {
285
- items.push({ field: trimmed.slice(1), order: 'desc' });
286
- } else {
287
- items.push({ field: trimmed, order: 'asc' });
288
- }
289
- continue;
290
- }
291
- if (!isRecord(entry)) continue;
292
- const field = typeof entry.field === 'string' ? entry.field.trim() : '';
293
- if (!field) continue;
294
- const order = entry.order === 'asc' ? 'asc' : 'desc';
295
- items.push({ field, order });
296
- }
297
- return items;
298
- }
299
-
300
- export function normalizeTimeRange(raw: unknown): ReportTimeRange | undefined {
301
- if (!isRecord(raw)) return undefined;
302
- const preset =
303
- typeof raw.preset === 'string' && VALID_PRESETS.has(raw.preset as TimeRangePreset)
304
- ? (raw.preset as TimeRangePreset)
305
- : 'last_24h';
306
- const from = typeof raw.from === 'string' && raw.from.trim() ? raw.from.trim() : undefined;
307
- const to = typeof raw.to === 'string' && raw.to.trim() ? raw.to.trim() : undefined;
308
- const timeZone = sanitizeTimeZone(raw.timeZone);
309
- return {
310
- preset,
311
- ...(from ? { from } : {}),
312
- ...(to ? { to } : {}),
313
- ...(timeZone ? { timeZone } : {}),
314
- };
315
- }
316
-
317
- function normalizeFieldFormats(raw: unknown): Record<string, FieldFormatType> | undefined {
318
- if (!isRecord(raw)) return undefined;
319
- const out: Record<string, FieldFormatType> = {};
320
- for (const [k, v] of Object.entries(raw)) {
321
- const fieldName = k.trim();
322
- if (fieldName && typeof v === 'string' && VALID_FIELD_FORMATS.has(v as FieldFormatType) && v !== 'auto') {
323
- out[fieldName] = v as FieldFormatType;
324
- }
325
- }
326
- return Object.keys(out).length > 0 ? out : undefined;
327
- }
328
-
329
- function normalizeContextBindings(raw: unknown): RecordContextBinding[] | undefined {
330
- if (!Array.isArray(raw)) return undefined;
331
- const out: RecordContextBinding[] = [];
332
- for (const item of raw) {
333
- if (!isRecord(item)) continue;
334
- const esField = typeof item.esField === 'string' ? item.esField.trim() : '';
335
- const recordFieldPath = typeof item.recordFieldPath === 'string' ? item.recordFieldPath.trim() : '';
336
- if (esField && recordFieldPath) {
337
- out.push({ esField, recordFieldPath });
338
- }
339
- }
340
- return out.length > 0 ? out : undefined;
341
- }
342
-
343
- export interface ServerUserTokenContext {
344
- userId?: ID;
345
- username?: string;
346
- email?: string;
347
- role?: string;
348
- }
349
-
350
- function resolveTokenScalar(val: ScalarFilterValue, userCtx: ServerUserTokenContext): ScalarFilterValue {
351
- if (typeof val !== 'string') return val;
352
- const trimmed = val.trim();
353
- const tokenMatch = trimmed.match(/^\{\{\s*\$(user\.(?:id|username|email)|role)\s*\}\}$/);
354
- if (!tokenMatch) return val;
355
- const tokenName = tokenMatch[1];
356
- let resolved: ScalarFilterValue | undefined;
357
- if (
358
- tokenName === 'user.id' &&
359
- userCtx.userId !== undefined &&
360
- userCtx.userId !== null &&
361
- String(userCtx.userId) !== ''
362
- ) {
363
- resolved = userCtx.userId;
364
- } else if (tokenName === 'user.username' && userCtx.username?.trim()) {
365
- resolved = userCtx.username.trim();
366
- } else if (tokenName === 'user.email' && userCtx.email?.trim()) {
367
- resolved = userCtx.email.trim();
368
- } else if (tokenName === 'role' && userCtx.role?.trim()) {
369
- resolved = userCtx.role.trim();
370
- }
371
- if (resolved === undefined) {
372
- const err = new Error(
373
- `Permission denied: missing authenticated value for locked filter token "$${tokenName}"`,
374
- ) as Error & {
375
- status?: number;
376
- };
377
- err.status = 403;
378
- throw err;
379
- }
380
- return resolved;
381
- }
382
-
383
- export function resolveServerLockedFilters(
384
- lockedFilters: ReportFilterItem[] | undefined,
385
- userCtx?: ServerUserTokenContext,
386
- ): ReportFilterItem[] {
387
- if (!lockedFilters || lockedFilters.length === 0) return [];
388
- const ctx = userCtx ?? {};
389
- return lockedFilters.map((item) => {
390
- const nextVal = Array.isArray(item.value)
391
- ? item.value.map((v) => resolveTokenScalar(v, ctx))
392
- : item.value !== undefined
393
- ? resolveTokenScalar(item.value, ctx)
394
- : undefined;
395
- const nextValTo = item.valueTo !== undefined ? resolveTokenScalar(item.valueTo, ctx) : undefined;
396
- return {
397
- ...item,
398
- ...(nextVal !== undefined ? { value: nextVal } : {}),
399
- ...(nextValTo !== undefined ? { valueTo: nextValTo } : {}),
400
- enabled: true,
401
- };
402
- });
403
- }
404
-
405
- export function normalizeReportSpec(raw: unknown, fallbackVisualization?: unknown): ReportSpec {
406
- const obj = isRecord(raw) ? raw : {};
407
- const visCandidate = typeof obj.visualization === 'string' ? obj.visualization : fallbackVisualization;
408
- const visualization: ReportVisualizationType =
409
- typeof visCandidate === 'string' && VALID_VISUALIZATIONS.has(visCandidate as ReportVisualizationType)
410
- ? (visCandidate as ReportVisualizationType)
411
- : 'table';
412
-
413
- const query = typeof obj.query === 'string' ? obj.query.trim() : '';
414
- const queryMode = obj.queryMode === 'simple' ? 'simple' : 'kql';
415
- const filters = normalizeReportFilters(obj.filters);
416
- const lockedFilters = normalizeReportFilters(obj.lockedFilters).map((item) => ({
417
- ...item,
418
- enabled: true,
419
- }));
420
- const sort = normalizeReportSort(obj.sort);
421
- const timeRange = normalizeTimeRange(obj.timeRange);
422
- const columns = Array.isArray(obj.columns)
423
- ? obj.columns
424
- .filter((col): col is string => typeof col === 'string' && col.trim().length > 0)
425
- .map((col) => col.trim())
426
- : [];
427
- const fieldFormats = normalizeFieldFormats(obj.fieldFormats);
428
- const contextBindings = normalizeContextBindings(obj.contextBindings);
429
- const pageSize = clamp(typeof obj.pageSize === 'number' ? obj.pageSize : DEFAULT_PAGE_SIZE, 1, MAX_UI_PAGE_SIZE);
430
-
431
- const rawChart = isRecord(obj.chart) ? obj.chart : {};
432
- const metricType: MetricAggType =
433
- typeof rawChart.metricType === 'string' && VALID_METRICS.has(rawChart.metricType as MetricAggType)
434
- ? (rawChart.metricType as MetricAggType)
435
- : 'count';
436
- const bucketType: BucketAggType | undefined =
437
- typeof rawChart.bucketType === 'string' && VALID_BUCKETS.has(rawChart.bucketType as BucketAggType)
438
- ? (rawChart.bucketType as BucketAggType)
439
- : undefined;
440
- const calendarInterval: CalendarIntervalOption =
441
- typeof rawChart.calendarInterval === 'string' &&
442
- VALID_INTERVALS.has(rawChart.calendarInterval as CalendarIntervalOption)
443
- ? (rawChart.calendarInterval as CalendarIntervalOption)
444
- : 'auto';
445
- const stackMode: ChartStackMode =
446
- typeof rawChart.stackMode === 'string' && VALID_STACK_MODES.has(rawChart.stackMode as ChartStackMode)
447
- ? (rawChart.stackMode as ChartStackMode)
448
- : 'none';
449
-
450
- return {
451
- query,
452
- queryMode,
453
- filters,
454
- lockedFilters,
455
- sort,
456
- ...(timeRange ? { timeRange } : {}),
457
- columns,
458
- ...(fieldFormats ? { fieldFormats } : {}),
459
- ...(contextBindings ? { contextBindings } : {}),
460
- pageSize,
461
- visualization,
462
- chart: {
463
- ...(bucketType ? { bucketType } : {}),
464
- ...(typeof rawChart.bucketField === 'string' && rawChart.bucketField.trim()
465
- ? { bucketField: rawChart.bucketField.trim() }
466
- : {}),
467
- calendarInterval,
468
- topN: clamp(typeof rawChart.topN === 'number' ? rawChart.topN : 10, 1, MAX_TERMS_BUCKETS),
469
- metricType,
470
- ...(typeof rawChart.metricField === 'string' && rawChart.metricField.trim()
471
- ? { metricField: rawChart.metricField.trim() }
472
- : {}),
473
- ...(typeof rawChart.metricLabel === 'string' && rawChart.metricLabel.trim()
474
- ? { metricLabel: rawChart.metricLabel.trim() }
475
- : {}),
476
- showHistogram: rawChart.showHistogram !== false,
477
- ...(typeof rawChart.splitSeriesField === 'string' && rawChart.splitSeriesField.trim()
478
- ? { splitSeriesField: rawChart.splitSeriesField.trim() }
479
- : {}),
480
- ...(typeof rawChart.splitSeriesTopN === 'number'
481
- ? { splitSeriesTopN: clamp(rawChart.splitSeriesTopN, 1, MAX_SPLIT_SERIES) }
482
- : {}),
483
- ...(stackMode !== 'none' ? { stackMode } : {}),
484
- ...(rawChart.comparePreviousPeriod === true ? { comparePreviousPeriod: true } : {}),
485
- },
486
- allowInteractiveControls: obj.allowInteractiveControls !== false,
487
- allowExport: obj.allowExport !== false,
488
- };
489
- }
490
-
491
- function assertBalancedKqlDelimiters(input: string): void {
492
- let inQuotes = false;
493
- let quoteChar = '';
494
- const openParenPositions: number[] = [];
495
-
496
- for (let i = 0; i < input.length; i++) {
497
- const ch = input[i];
498
- if (inQuotes) {
499
- if (ch === '\\') {
500
- i++;
501
- continue;
502
- }
503
- if (ch === quoteChar) {
504
- inQuotes = false;
505
- }
506
- continue;
507
- }
508
- if (ch === '"' || ch === "'") {
509
- inQuotes = true;
510
- quoteChar = ch;
511
- continue;
512
- }
513
- if (ch === '(') {
514
- openParenPositions.push(i);
515
- continue;
516
- }
517
- if (ch === ')') {
518
- const openIdx = openParenPositions.pop();
519
- if (openIdx === undefined) {
520
- throw new KqlSyntaxError('Invalid KQL syntax: unexpected closing parenthesis ")"');
521
- }
522
- if (!input.slice(openIdx + 1, i).trim()) {
523
- throw new KqlSyntaxError('Invalid KQL syntax: empty parentheses "()"');
524
- }
525
- }
526
- }
527
-
528
- if (inQuotes) {
529
- throw new KqlSyntaxError('Invalid KQL syntax: unclosed quotation mark');
530
- }
531
- if (openParenPositions.length > 0) {
532
- throw new KqlSyntaxError('Invalid KQL syntax: unclosed parenthesis "("');
533
- }
534
- }
535
-
536
- /**
537
- * Split a KQL expression on top-level boolean connectors (`AND` / `OR`) while
538
- * respecting quoted strings and nested parentheses.
539
- */
540
- function splitTopLevelBoolean(input: string, keyword: 'AND' | 'OR'): string[] {
541
- const parts: string[] = [];
542
- let depth = 0;
543
- let inQuotes = false;
544
- let quoteChar = '';
545
- let lastIdx = 0;
546
- let splitFound = false;
547
-
548
- for (let i = 0; i < input.length; i++) {
549
- const ch = input[i];
550
- if (inQuotes) {
551
- if (ch === '\\') {
552
- i++;
553
- continue;
554
- }
555
- if (ch === quoteChar) {
556
- inQuotes = false;
557
- }
558
- continue;
559
- }
560
- if (ch === '"' || ch === "'") {
561
- inQuotes = true;
562
- quoteChar = ch;
563
- continue;
564
- }
565
- if (ch === '(') {
566
- depth++;
567
- continue;
568
- }
569
- if (ch === ')') {
570
- depth = Math.max(0, depth - 1);
571
- continue;
572
- }
573
- if (depth === 0) {
574
- const prevBoundary = i === 0 || /[\s)]/.test(input[i - 1]);
575
- const slice = input.slice(i, i + keyword.length);
576
- const nextChar = input[i + keyword.length];
577
- const nextBoundary = nextChar === undefined || /[\s(]/.test(nextChar);
578
- if (prevBoundary && nextBoundary && slice.toUpperCase() === keyword) {
579
- splitFound = true;
580
- parts.push(input.slice(lastIdx, i).trim());
581
- i += keyword.length - 1;
582
- lastIdx = i + 1;
583
- }
584
- }
585
- }
586
- parts.push(input.slice(lastIdx).trim());
587
- if (splitFound && parts.some((part) => !part)) {
588
- throw new KqlSyntaxError(`Invalid KQL syntax: missing operand around "${keyword}"`);
589
- }
590
- return parts.filter(Boolean);
591
- }
592
-
593
- function hasBalancedOuterParens(expr: string): boolean {
594
- if (!expr.startsWith('(') || !expr.endsWith(')')) return false;
595
- let depth = 0;
596
- let inQuotes = false;
597
- let quoteChar = '';
598
- for (let i = 0; i < expr.length; i++) {
599
- const ch = expr[i];
600
- if (inQuotes) {
601
- if (ch === '\\') {
602
- i++;
603
- continue;
604
- }
605
- if (ch === quoteChar) inQuotes = false;
606
- continue;
607
- }
608
- if (ch === '"' || ch === "'") {
609
- inQuotes = true;
610
- quoteChar = ch;
611
- continue;
612
- }
613
- if (ch === '(') depth++;
614
- if (ch === ')') {
615
- depth--;
616
- if (depth === 0 && i < expr.length - 1) return false;
617
- }
618
- }
619
- return depth === 0;
620
- }
621
-
622
- function unquote(raw: string): { value: string; wasQuoted: boolean } {
623
- const trimmed = raw.trim();
624
- if (
625
- (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2) ||
626
- (trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2)
627
- ) {
628
- return {
629
- value: trimmed.slice(1, -1).replace(/\\(["'\\])/g, '$1'),
630
- wasQuoted: true,
631
- };
632
- }
633
- return { value: trimmed, wasQuoted: false };
634
- }
635
-
636
- function compileSingleFieldValue(
637
- rawField: string,
638
- rawVal: string,
639
- fieldMap: Map<string, EsFieldCapability>,
640
- ): Record<string, unknown> {
641
- const trimmed = rawVal.trim();
642
- if (!trimmed) {
643
- throw new KqlSyntaxError(`Invalid KQL syntax: missing value for field "${rawField}"`);
644
- }
645
-
646
- const inlineRangeMatch = trimmed.match(/^(>=|<=|>|<)\s*(.+)$/);
647
- if (inlineRangeMatch) {
648
- const [, op, rangeRhs] = inlineRangeMatch;
649
- const { value } = unquote(rangeRhs);
650
- if (!value) {
651
- throw new KqlSyntaxError(`Invalid KQL syntax: missing range bound for field "${rawField}"`);
652
- }
653
- const coerced = coerceLiteral(value, fieldMap.get(rawField));
654
- const opKey = op === '>=' ? 'gte' : op === '<=' ? 'lte' : op === '>' ? 'gt' : 'lt';
655
- return { range: { [rawField]: { [opKey]: coerced } } };
656
- }
657
-
658
- const { value, wasQuoted } = unquote(trimmed);
659
- if (!wasQuoted) {
660
- if (/^[[{].*[\]}]$/.test(value)) {
661
- throw new KqlSyntaxError('Lucene range brackets [a TO b] are not valid KQL; use >= and <= instead');
662
- }
663
- if (/^\/.*\/$/.test(value)) {
664
- throw new KqlSyntaxError('Regular expressions /.../ are not valid KQL; use * or ? wildcards instead');
665
- }
666
- if (value.includes('(') || value.includes(')')) {
667
- throw new KqlSyntaxError(`Unsupported KQL field value syntax near "${value}"`);
668
- }
669
- if (value.includes(':')) {
670
- throw new KqlSyntaxError(`Unexpected ":" in unquoted KQL value "${value}"; wrap values containing ":" in quotes`);
671
- }
672
- if (value === '*') {
673
- return { exists: { field: rawField } };
674
- }
675
- }
676
-
677
- const fieldMeta = fieldMap.get(rawField);
678
- if (!wasQuoted && (value.includes('*') || value.includes('?'))) {
679
- const wildcardField = resolveAggregatableField(rawField, fieldMap);
680
- return {
681
- wildcard: {
682
- [wildcardField]: {
683
- value,
684
- case_insensitive: true,
685
- },
686
- },
687
- };
688
- }
689
-
690
- if (wasQuoted) {
691
- if (fieldMeta?.type === 'keyword' || fieldMeta?.type === 'constant_keyword') {
692
- return { term: { [rawField]: value } };
693
- }
694
- return { match_phrase: { [rawField]: value } };
695
- }
696
-
697
- const coerced = coerceLiteral(value, fieldMeta);
698
- if (typeof coerced === 'number' || typeof coerced === 'boolean') {
699
- return { term: { [rawField]: coerced } };
700
- }
701
- if (fieldMeta?.type === 'keyword' || fieldMeta?.type === 'constant_keyword') {
702
- return { term: { [rawField]: coerced } };
703
- }
704
- return { match_phrase: { [rawField]: String(coerced) } };
705
- }
706
-
707
- function compileFieldGroupClause(
708
- fieldName: string,
709
- groupBody: string,
710
- fieldMap: Map<string, EsFieldCapability>,
711
- ): Record<string, unknown> {
712
- const expr = groupBody.trim();
713
- if (!expr) {
714
- throw new KqlSyntaxError(`Invalid KQL syntax: empty value group for field "${fieldName}"`);
715
- }
716
- if (/^NOT$/i.test(expr)) {
717
- throw new KqlSyntaxError(`Invalid KQL syntax: incomplete "NOT" inside "${fieldName}: (...)"`);
718
- }
719
-
720
- if (hasBalancedOuterParens(expr)) {
721
- return compileFieldGroupClause(fieldName, expr.slice(1, -1), fieldMap);
722
- }
723
-
724
- const orParts = splitTopLevelBoolean(expr, 'OR');
725
- if (orParts.length > 1) {
726
- const should = orParts.map((part) => compileFieldGroupClause(fieldName, part, fieldMap));
727
- return should.length === 1 ? should[0] : { bool: { should, minimum_should_match: 1 } };
728
- }
729
-
730
- const andParts = splitTopLevelBoolean(expr, 'AND');
731
- if (andParts.length > 1) {
732
- const must = andParts.map((part) => compileFieldGroupClause(fieldName, part, fieldMap));
733
- return must.length === 1 ? must[0] : { bool: { must } };
734
- }
735
-
736
- if (/^NOT\s+/i.test(expr)) {
737
- const inner = compileFieldGroupClause(fieldName, expr.replace(/^NOT\s+/i, ''), fieldMap);
738
- return { bool: { must_not: [inner] } };
739
- }
740
-
741
- return compileSingleFieldValue(fieldName, expr, fieldMap);
742
- }
743
-
744
- function compileKqlAst(exprInput: string, fieldMap: Map<string, EsFieldCapability>): Record<string, unknown> | null {
745
- const expr = exprInput.trim();
746
- if (!expr) return null;
747
- if (/^NOT$/i.test(expr)) {
748
- throw new KqlSyntaxError('Invalid KQL syntax: incomplete "NOT" operator');
749
- }
750
-
751
- if (hasBalancedOuterParens(expr)) {
752
- return compileKqlAst(expr.slice(1, -1), fieldMap);
753
- }
754
-
755
- const orParts = splitTopLevelBoolean(expr, 'OR');
756
- if (orParts.length > 1) {
757
- const should = orParts
758
- .map((part) => compileKqlAst(part, fieldMap))
759
- .filter((item): item is Record<string, unknown> => item !== null);
760
- if (should.length === 0) return null;
761
- if (should.length === 1) return should[0];
762
- return { bool: { should, minimum_should_match: 1 } };
763
- }
764
-
765
- const andParts = splitTopLevelBoolean(expr, 'AND');
766
- if (andParts.length > 1) {
767
- const must = andParts
768
- .map((part) => compileKqlAst(part, fieldMap))
769
- .filter((item): item is Record<string, unknown> => item !== null);
770
- if (must.length === 0) return null;
771
- if (must.length === 1) return must[0];
772
- return { bool: { must } };
773
- }
774
-
775
- if (/^NOT\s+/i.test(expr)) {
776
- const rest = expr.replace(/^NOT\s+/i, '').trim();
777
- if (!rest) {
778
- throw new KqlSyntaxError('Invalid KQL syntax: incomplete "NOT" operator');
779
- }
780
- const inner = compileKqlAst(rest, fieldMap);
781
- return inner ? { bool: { must_not: [inner] } } : null;
782
- }
783
-
784
- if (/^[A-Za-z0-9_@.-]+\s*(:|>=|<=|>|<)\s*$/.test(expr)) {
785
- throw new KqlSyntaxError('Invalid KQL syntax: missing value after field operator');
786
- }
787
-
788
- // Range expression: field >= value, field > value, field <= value, field < value
789
- const rangeMatch = expr.match(/^([A-Za-z0-9_@.-]+)\s*(>=|<=|>|<)\s*(.+)$/);
790
- if (rangeMatch) {
791
- const [, rawField, op, rawVal] = rangeMatch;
792
- return compileSingleFieldValue(rawField, `${op} ${rawVal}`, fieldMap);
793
- }
794
-
795
- // Field-value or field-group expression: field : value OR field : (a OR b)
796
- const colonMatch = expr.match(/^([A-Za-z0-9_@.-]+)\s*:\s*(.+)$/);
797
- if (colonMatch) {
798
- const [, rawField, rawVal] = colonMatch;
799
- const rhs = rawVal.trim();
800
- if (hasBalancedOuterParens(rhs)) {
801
- return compileFieldGroupClause(rawField, rhs.slice(1, -1), fieldMap);
802
- }
803
- return compileSingleFieldValue(rawField, rhs, fieldMap);
804
- }
805
-
806
- if (!unquote(expr).wasQuoted && (/^[[{].*[\]}]$/.test(expr) || /^\/.*\/$/.test(expr))) {
807
- throw new KqlSyntaxError(`Unsupported KQL expression "${expr}"`);
808
- }
809
-
810
- return {
811
- simple_query_string: {
812
- query: expr,
813
- default_operator: 'and',
814
- lenient: true,
815
- },
816
- };
817
- }
818
-
819
- /**
820
- * Compile a KQL-compatible search string into universal Elasticsearch Query DSL
821
- * so queries run reliably across ES 7.x, 8.x, 9.x, and OpenSearch.
822
- */
823
- export function compileKqlToQueryDsl(
824
- rawQuery: string,
825
- fieldMap: Map<string, EsFieldCapability> = new Map(),
826
- ): Record<string, unknown> | null {
827
- const expr = rawQuery.trim();
828
- if (!expr) return null;
829
- assertBalancedKqlDelimiters(expr);
830
- return compileKqlAst(expr, fieldMap);
831
- }
832
-
833
- export function compileFilterItem(
834
- item: ReportFilterItem,
835
- fieldMap: Map<string, EsFieldCapability>,
836
- ): { clause: Record<string, unknown>; negated: boolean } | null {
837
- if (item.enabled === false || !item.field.trim()) return null;
838
- const field = item.field.trim();
839
- const fieldMeta = fieldMap.get(field);
840
- const keywordField = resolveAggregatableField(field, fieldMap);
841
-
842
- switch (item.operator) {
843
- case 'exists':
844
- return { clause: { exists: { field } }, negated: false };
845
- case 'not_exists':
846
- return { clause: { exists: { field } }, negated: true };
847
- case 'eq':
848
- case 'ne': {
849
- if (item.value === undefined || Array.isArray(item.value)) return null;
850
- const val = typeof item.value === 'string' ? coerceLiteral(item.value, fieldMeta) : item.value;
851
- const useTerm = typeof val !== 'string' || fieldMeta?.aggregatable === true || keywordField !== field;
852
- const clause = useTerm ? { term: { [keywordField]: val } } : { match_phrase: { [field]: val } };
853
- return { clause, negated: item.operator === 'ne' };
854
- }
855
- case 'in':
856
- case 'not_in': {
857
- const values = Array.isArray(item.value) ? item.value : item.value !== undefined ? [item.value] : [];
858
- if (values.length === 0) return null;
859
- const normalized = values.map((v) => (typeof v === 'string' ? coerceLiteral(v, fieldMeta) : v));
860
- return {
861
- clause: { terms: { [keywordField]: normalized } },
862
- negated: item.operator === 'not_in',
863
- };
864
- }
865
- case 'gt':
866
- case 'gte':
867
- case 'lt':
868
- case 'lte': {
869
- if (item.value === undefined || Array.isArray(item.value)) return null;
870
- const val = typeof item.value === 'string' ? coerceLiteral(item.value, fieldMeta) : item.value;
871
- return {
872
- clause: { range: { [field]: { [item.operator]: val } } },
873
- negated: false,
874
- };
875
- }
876
- case 'between': {
877
- const rangeBody: Record<string, ScalarFilterValue> = {};
878
- if (item.value !== undefined && !Array.isArray(item.value)) {
879
- rangeBody.gte = typeof item.value === 'string' ? coerceLiteral(item.value, fieldMeta) : item.value;
880
- }
881
- if (item.valueTo !== undefined) {
882
- rangeBody.lte = typeof item.valueTo === 'string' ? coerceLiteral(item.valueTo, fieldMeta) : item.valueTo;
883
- }
884
- if (Object.keys(rangeBody).length === 0) return null;
885
- return {
886
- clause: { range: { [field]: rangeBody } },
887
- negated: false,
888
- };
889
- }
890
- case 'contains': {
891
- if (item.value === undefined || Array.isArray(item.value)) return null;
892
- const rawText = String(item.value).trim();
893
- if (!rawText) return null;
894
- if (fieldMeta && !fieldMeta.aggregatable && !fieldMeta.keywordSubfield) {
895
- return { clause: { match_phrase: { [field]: rawText } }, negated: false };
896
- }
897
- const escaped = rawText.replace(/([*?\\])/g, '\\$1');
898
- return {
899
- clause: {
900
- wildcard: {
901
- [keywordField]: {
902
- value: `*${escaped}*`,
903
- case_insensitive: true,
904
- },
905
- },
906
- },
907
- negated: false,
908
- };
909
- }
910
- default:
911
- return null;
912
- }
913
- }
914
-
915
- export function compileTimeRange(
916
- timeRange: ReportTimeRange | undefined,
917
- timeField: string | null | undefined,
918
- fallbackTimeZone?: string,
919
- ): Record<string, unknown> | null {
920
- const cleanField = typeof timeField === 'string' ? timeField.trim() : '';
921
- if (!cleanField || !timeRange || timeRange.preset === 'all') return null;
922
-
923
- const tz = sanitizeTimeZone(timeRange.timeZone ?? fallbackTimeZone);
924
-
925
- if (timeRange.preset === 'custom') {
926
- const bounds: Record<string, string> = {};
927
- if (timeRange.from) bounds.gte = timeRange.from;
928
- if (timeRange.to) bounds.lte = timeRange.to;
929
- if (Object.keys(bounds).length === 0) return null;
930
- if (tz) bounds.time_zone = tz;
931
- return { range: { [cleanField]: bounds } };
932
- }
933
-
934
- const expr = PRESET_TO_ES_EXPR[timeRange.preset];
935
- if (!expr) return null;
936
- return {
937
- range: {
938
- [cleanField]: {
939
- gte: expr,
940
- lte: 'now',
941
- ...(tz ? { time_zone: tz } : {}),
942
- },
943
- },
944
- };
945
- }
946
-
947
- export function compilePreviousTimeRange(
948
- timeRange: ReportTimeRange | undefined,
949
- timeField: string | null | undefined,
950
- fallbackTimeZone?: string,
951
- ): Record<string, unknown> | null {
952
- const cleanField = typeof timeField === 'string' ? timeField.trim() : '';
953
- if (!cleanField || !timeRange || timeRange.preset === 'all') return null;
954
- const tz = sanitizeTimeZone(timeRange.timeZone ?? fallbackTimeZone);
955
-
956
- if (timeRange.preset === 'custom') {
957
- const fromMs = timeRange.from ? Date.parse(timeRange.from) : NaN;
958
- const toMs = timeRange.to ? Date.parse(timeRange.to) : NaN;
959
- if (!Number.isFinite(fromMs) || !Number.isFinite(toMs) || toMs <= fromMs) {
960
- return null;
961
- }
962
- const duration = toMs - fromMs;
963
- return {
964
- range: {
965
- [cleanField]: {
966
- gte: new Date(fromMs - duration).toISOString(),
967
- lt: new Date(fromMs).toISOString(),
968
- ...(tz ? { time_zone: tz } : {}),
969
- },
970
- },
971
- };
972
- }
973
-
974
- const prev = PRESET_TO_PREV_ES_EXPR[timeRange.preset];
975
- if (!prev) return null;
976
- return {
977
- range: {
978
- [cleanField]: {
979
- gte: prev.gte,
980
- lt: prev.lt,
981
- ...(tz ? { time_zone: tz } : {}),
982
- },
983
- },
984
- };
985
- }
986
-
987
- function buildMetricAggDefinition(
988
- metricType: MetricAggType,
989
- metricField: string | undefined,
990
- fieldMap: Map<string, EsFieldCapability>,
991
- ): Record<string, unknown> | undefined {
992
- if (metricType === 'count' || !metricField?.trim()) return undefined;
993
- const targetField = resolveAggregatableField(metricField, fieldMap);
994
- if (metricType === 'p50' || metricType === 'p95' || metricType === 'p99') {
995
- const pct = metricType === 'p50' ? 50 : metricType === 'p95' ? 95 : 99;
996
- return {
997
- percentiles: {
998
- field: targetField,
999
- percents: [pct],
1000
- },
1001
- };
1002
- }
1003
- return {
1004
- [metricType]: {
1005
- field: targetField,
1006
- },
1007
- };
1008
- }
1009
-
1010
- function extractMetricValue(aggNode: unknown, metricType: MetricAggType, fallbackCount: number): number | null {
1011
- if (metricType === 'count') {
1012
- return fallbackCount;
1013
- }
1014
- if (!isRecord(aggNode)) return null;
1015
- if (metricType === 'p50' || metricType === 'p95' || metricType === 'p99') {
1016
- const values = isRecord(aggNode.values) ? aggNode.values : undefined;
1017
- if (!values) return null;
1018
- const exactKey = metricType === 'p50' ? '50.0' : metricType === 'p95' ? '95.0' : '99.0';
1019
- const shortKey = metricType === 'p50' ? '50' : metricType === 'p95' ? '95' : '99';
1020
- const raw = values[exactKey] ?? values[shortKey];
1021
- return typeof raw === 'number' && Number.isFinite(raw) ? Number(raw.toFixed(4)) : null;
1022
- }
1023
- return typeof aggNode.value === 'number' && Number.isFinite(aggNode.value) ? Number(aggNode.value.toFixed(4)) : null;
1024
- }
1025
-
1026
- export interface CompileSearchOptions {
1027
- spec: ReportSpec;
1028
- overrides?: ReportRuntimeOverrides;
1029
- timeField?: string | null;
1030
- fields?: EsFieldCapability[] | null;
1031
- maxRowsCap?: number;
1032
- userContext?: ServerUserTokenContext;
1033
- usePit?: boolean;
1034
- }
1035
-
1036
- export function mergeSpecWithOverrides(
1037
- spec: ReportSpec,
1038
- overrides?: ReportRuntimeOverrides,
1039
- ): {
1040
- effectiveSpec: ReportSpec;
1041
- extraRuntimeFilters: ReportFilterItem[];
1042
- effectiveTimeZone?: string;
1043
- page: number;
1044
- pageSize: number;
1045
- searchAfter?: Array<string | number | boolean | null>;
1046
- } {
1047
- if (!overrides) {
1048
- return {
1049
- effectiveSpec: spec,
1050
- extraRuntimeFilters: [],
1051
- effectiveTimeZone: sanitizeTimeZone(spec.timeRange?.timeZone),
1052
- page: 1,
1053
- pageSize: spec.pageSize ?? DEFAULT_PAGE_SIZE,
1054
- };
1055
- }
1056
-
1057
- const effectiveTimeRange =
1058
- overrides.timeRange !== undefined ? normalizeTimeRange(overrides.timeRange) : spec.timeRange;
1059
- const effectiveTimeZone = sanitizeTimeZone(
1060
- overrides.timeZone ?? effectiveTimeRange?.timeZone ?? spec.timeRange?.timeZone,
1061
- );
1062
-
1063
- const effectiveSpec: ReportSpec = {
1064
- ...spec,
1065
- query: overrides.query !== undefined ? overrides.query.trim() : spec.query,
1066
- filters: overrides.filters !== undefined ? normalizeReportFilters(overrides.filters) : spec.filters,
1067
- // Security invariant: lockedFilters are server-owned and can never be replaced or cleared by runtime overrides.
1068
- lockedFilters: spec.lockedFilters,
1069
- sort: overrides.sort !== undefined ? normalizeReportSort(overrides.sort) : spec.sort,
1070
- timeRange: effectiveTimeRange,
1071
- };
1072
-
1073
- const extraRuntimeFilters: ReportFilterItem[] = [
1074
- ...normalizeReportFilters(overrides.sharedFilters),
1075
- ...normalizeReportFilters(overrides.contextFilters),
1076
- ];
1077
-
1078
- const page = clamp(typeof overrides.page === 'number' ? overrides.page : 1, 1, 10000);
1079
- const pageSize = clamp(
1080
- typeof overrides.pageSize === 'number' ? overrides.pageSize : spec.pageSize ?? DEFAULT_PAGE_SIZE,
1081
- 1,
1082
- MAX_UI_PAGE_SIZE,
1083
- );
1084
- const searchAfter =
1085
- Array.isArray(overrides.searchAfter) && overrides.searchAfter.length > 0 ? overrides.searchAfter : undefined;
1086
-
1087
- return {
1088
- effectiveSpec,
1089
- extraRuntimeFilters,
1090
- ...(effectiveTimeZone ? { effectiveTimeZone } : {}),
1091
- page,
1092
- pageSize,
1093
- ...(searchAfter ? { searchAfter } : {}),
1094
- };
1095
- }
1096
-
1097
- export function compileSearchRequest(options: CompileSearchOptions): {
1098
- body: Record<string, unknown>;
1099
- effectiveSpec: ReportSpec;
1100
- } {
1101
- const fieldMap = buildFieldCapabilityMap(options.fields);
1102
- const { effectiveSpec, extraRuntimeFilters, effectiveTimeZone, page, pageSize, searchAfter } = mergeSpecWithOverrides(
1103
- options.spec,
1104
- options.overrides,
1105
- );
1106
- const maxCap = options.maxRowsCap ? clamp(options.maxRowsCap, 1, MAX_UI_PAGE_SIZE) : MAX_UI_PAGE_SIZE;
1107
- const effectivePageSize = Math.min(pageSize, maxCap);
1108
- const timeField = options.timeField?.trim() || null;
1109
-
1110
- const must: Array<Record<string, unknown>> = [];
1111
- const filter: Array<Record<string, unknown>> = [];
1112
- const mustNot: Array<Record<string, unknown>> = [];
1113
-
1114
- if (effectiveSpec.query && effectiveSpec.query.trim()) {
1115
- if (effectiveSpec.queryMode === 'simple') {
1116
- must.push({
1117
- simple_query_string: {
1118
- query: effectiveSpec.query.trim(),
1119
- default_operator: 'and',
1120
- lenient: true,
1121
- },
1122
- });
1123
- } else {
1124
- const parsedQuery = compileKqlToQueryDsl(effectiveSpec.query, fieldMap);
1125
- if (parsedQuery) {
1126
- must.push(parsedQuery);
1127
- }
1128
- }
1129
- }
1130
-
1131
- const resolvedLockedFilters = resolveServerLockedFilters(effectiveSpec.lockedFilters, options.userContext);
1132
- const combinedFilters: ReportFilterItem[] = [
1133
- ...resolvedLockedFilters,
1134
- ...extraRuntimeFilters,
1135
- ...(effectiveSpec.filters ?? []),
1136
- ];
1137
- for (const item of combinedFilters) {
1138
- const compiled = compileFilterItem(item, fieldMap);
1139
- if (!compiled) continue;
1140
- if (compiled.negated) {
1141
- mustNot.push(compiled.clause);
1142
- } else {
1143
- filter.push(compiled.clause);
1144
- }
1145
- }
1146
-
1147
- const currentTimeClause = compileTimeRange(effectiveSpec.timeRange, timeField, effectiveTimeZone);
1148
- const previousTimeClause =
1149
- effectiveSpec.visualization === 'metric' && effectiveSpec.chart?.comparePreviousPeriod === true
1150
- ? compilePreviousTimeRange(effectiveSpec.timeRange, timeField, effectiveTimeZone)
1151
- : null;
1152
- const useDualPeriodMetric = Boolean(currentTimeClause && previousTimeClause);
1153
-
1154
- if (currentTimeClause && !useDualPeriodMetric) {
1155
- filter.push(currentTimeClause);
1156
- }
1157
-
1158
- let queryDsl: Record<string, unknown>;
1159
- if (must.length === 0 && filter.length === 0 && mustNot.length === 0) {
1160
- queryDsl = { match_all: {} };
1161
- } else {
1162
- queryDsl = {
1163
- bool: {
1164
- ...(must.length > 0 ? { must } : {}),
1165
- ...(filter.length > 0 ? { filter } : {}),
1166
- ...(mustNot.length > 0 ? { must_not: mustNot } : {}),
1167
- },
1168
- };
1169
- }
1170
-
1171
- const body: Record<string, unknown> = {
1172
- query: queryDsl,
1173
- track_total_hits: effectiveSpec.visualization === 'metric' ? true : MAX_RESULT_WINDOW,
1174
- };
1175
-
1176
- // Build sort clauses
1177
- const requestedSorts =
1178
- effectiveSpec.sort && effectiveSpec.sort.length > 0
1179
- ? effectiveSpec.sort
1180
- : timeField
1181
- ? [{ field: timeField, order: 'desc' as const }]
1182
- : [];
1183
-
1184
- if (effectiveSpec.visualization === 'table') {
1185
- body.size = effectivePageSize;
1186
-
1187
- if (requestedSorts.length > 0) {
1188
- const sortClauses: Array<Record<string, unknown>> = requestedSorts.map((sortItem) => {
1189
- const targetField = resolveAggregatableField(sortItem.field, fieldMap);
1190
- const unmappedType = resolveUnmappedSortType(targetField, fieldMap);
1191
- return {
1192
- [targetField]: {
1193
- order: sortItem.order,
1194
- ...(unmappedType ? { unmapped_type: unmappedType } : {}),
1195
- },
1196
- };
1197
- });
1198
- const hasTieBreaker = requestedSorts.some(
1199
- (s) => s.field === '_id' || s.field === '_shard_doc' || s.field === '_doc',
1200
- );
1201
- const legacyCursorMatchesUserSortOnly =
1202
- searchAfter !== undefined && searchAfter.length === requestedSorts.length && !hasTieBreaker;
1203
- if (!hasTieBreaker && !legacyCursorMatchesUserSortOnly) {
1204
- const tieBreakerField = options.usePit ? '_shard_doc' : '_doc';
1205
- sortClauses.push({ [tieBreakerField]: { order: 'asc' } });
1206
- }
1207
- body.sort = sortClauses;
1208
- }
1209
-
1210
- if (searchAfter && body.sort) {
1211
- body.search_after = searchAfter;
1212
- } else {
1213
- const rawFrom = (page - 1) * effectivePageSize;
1214
- body.from = Math.min(rawFrom, Math.max(0, MAX_RESULT_WINDOW - effectivePageSize));
1215
- }
1216
-
1217
- if (effectiveSpec.columns && effectiveSpec.columns.length > 0) {
1218
- const sourceFields = new Set(effectiveSpec.columns);
1219
- if (timeField) sourceFields.add(timeField);
1220
- body._source = Array.from(sourceFields);
1221
- }
1222
-
1223
- if (effectiveSpec.query && effectiveSpec.query.trim()) {
1224
- body.highlight = {
1225
- pre_tags: [HIGHLIGHT_PRE_TAG],
1226
- post_tags: [HIGHLIGHT_POST_TAG],
1227
- fields: { '*': {} },
1228
- fragment_size: 160,
1229
- number_of_fragments: 2,
1230
- };
1231
- }
1232
-
1233
- if (timeField && effectiveSpec.chart?.showHistogram !== false) {
1234
- body.aggs = {
1235
- es_time_histogram: {
1236
- auto_date_histogram: {
1237
- field: timeField,
1238
- buckets: 24,
1239
- ...(effectiveTimeZone ? { time_zone: effectiveTimeZone } : {}),
1240
- },
1241
- },
1242
- };
1243
- }
1244
- } else if (effectiveSpec.visualization === 'metric') {
1245
- body.size = 0;
1246
- const metricType = effectiveSpec.chart?.metricType ?? 'count';
1247
- const metricDef = buildMetricAggDefinition(metricType, effectiveSpec.chart?.metricField, fieldMap);
1248
-
1249
- if (useDualPeriodMetric && currentTimeClause && previousTimeClause) {
1250
- body.aggs = {
1251
- es_current_window: {
1252
- filter: currentTimeClause,
1253
- ...(metricDef ? { aggs: { es_metric: metricDef } } : {}),
1254
- },
1255
- es_previous_window: {
1256
- filter: previousTimeClause,
1257
- ...(metricDef ? { aggs: { es_metric: metricDef } } : {}),
1258
- },
1259
- };
1260
- } else if (metricDef) {
1261
- body.aggs = {
1262
- es_metric: metricDef,
1263
- };
1264
- }
1265
- } else {
1266
- // Chart visualizations: bar, line, area, pie
1267
- body.size = 0;
1268
- const chartCfg = effectiveSpec.chart ?? {};
1269
- const defaultBucketType: BucketAggType =
1270
- timeField && (effectiveSpec.visualization === 'line' || effectiveSpec.visualization === 'area')
1271
- ? 'date_histogram'
1272
- : chartCfg.bucketType ?? (timeField ? 'date_histogram' : 'terms');
1273
-
1274
- const rawBucketField =
1275
- chartCfg.bucketField?.trim() ||
1276
- (defaultBucketType === 'date_histogram' ? timeField : '') ||
1277
- Array.from(fieldMap.values()).find((f) => f.aggregatable)?.name ||
1278
- '_index';
1279
-
1280
- const bucketField = resolveAggregatableField(rawBucketField, fieldMap);
1281
- const metricType = chartCfg.metricType ?? 'count';
1282
- const metricDef = buildMetricAggDefinition(metricType, chartCfg.metricField, fieldMap);
1283
- const canOrderByMetric = Boolean(metricDef) && metricType !== 'p50' && metricType !== 'p95' && metricType !== 'p99';
1284
-
1285
- const rawSplitField = chartCfg.splitSeriesField?.trim();
1286
- const splitField = rawSplitField ? resolveAggregatableField(rawSplitField, fieldMap) : undefined;
1287
- const splitTopN = clamp(chartCfg.splitSeriesTopN ?? 5, 1, MAX_SPLIT_SERIES);
1288
-
1289
- const bucketChildAggs: Record<string, unknown> = {};
1290
- if (metricDef) {
1291
- bucketChildAggs.es_metric = metricDef;
1292
- }
1293
- if (splitField) {
1294
- bucketChildAggs.es_split = {
1295
- terms: {
1296
- field: splitField,
1297
- size: splitTopN,
1298
- ...(canOrderByMetric ? { order: { es_metric: 'desc' } } : {}),
1299
- },
1300
- ...(metricDef ? { aggs: { es_metric: metricDef } } : {}),
1301
- };
1302
- }
1303
- const hasChildAggs = Object.keys(bucketChildAggs).length > 0;
1304
-
1305
- if (defaultBucketType === 'date_histogram') {
1306
- const interval = chartCfg.calendarInterval ?? 'auto';
1307
- const intervalKey =
1308
- interval !== 'auto' && CALENDAR_UNIT_INTERVALS.has(interval) ? 'calendar_interval' : 'fixed_interval';
1309
- const bucketAgg =
1310
- interval === 'auto'
1311
- ? {
1312
- auto_date_histogram: {
1313
- field: bucketField,
1314
- buckets: 24,
1315
- ...(effectiveTimeZone ? { time_zone: effectiveTimeZone } : {}),
1316
- },
1317
- }
1318
- : {
1319
- date_histogram: {
1320
- field: bucketField,
1321
- [intervalKey]: interval,
1322
- min_doc_count: 0,
1323
- ...(effectiveTimeZone ? { time_zone: effectiveTimeZone } : {}),
1324
- },
1325
- };
1326
- body.aggs = {
1327
- es_buckets: {
1328
- ...bucketAgg,
1329
- ...(hasChildAggs ? { aggs: bucketChildAggs } : {}),
1330
- },
1331
- };
1332
- } else {
1333
- const topN = clamp(chartCfg.topN ?? 10, 1, MAX_TERMS_BUCKETS);
1334
- body.aggs = {
1335
- es_buckets: {
1336
- terms: {
1337
- field: bucketField,
1338
- size: topN,
1339
- ...(canOrderByMetric ? { order: { es_metric: 'desc' } } : {}),
1340
- },
1341
- ...(hasChildAggs ? { aggs: bucketChildAggs } : {}),
1342
- },
1343
- };
1344
- }
1345
- }
1346
-
1347
- return { body, effectiveSpec };
1348
- }
1349
-
1350
- function deriveColumns(
1351
- rows: ReportRowHit[],
1352
- configuredColumns: string[] | undefined,
1353
- timeField?: string | null,
1354
- ): string[] {
1355
- if (configuredColumns && configuredColumns.length > 0) {
1356
- return configuredColumns;
1357
- }
1358
- const seen = new Set<string>();
1359
- if (timeField && rows.some((r) => timeField in r.source)) {
1360
- seen.add(timeField);
1361
- }
1362
- for (const row of rows) {
1363
- for (const key of Object.keys(row.source)) {
1364
- if (seen.size >= 8) break;
1365
- seen.add(key);
1366
- }
1367
- if (seen.size >= 8) break;
1368
- }
1369
- return Array.from(seen);
1370
- }
1371
-
1372
- function buildDefaultMetricLabel(spec: ReportSpec): string {
1373
- if (spec.chart?.metricLabel) return spec.chart.metricLabel;
1374
- const metricType = spec.chart?.metricType ?? 'count';
1375
- if (metricType === 'count') return 'Count';
1376
- const field = spec.chart?.metricField ?? '';
1377
- return field ? `${metricType.toUpperCase()}(${field})` : metricType.toUpperCase();
1378
- }
1379
-
1380
- export function parseSearchResponse(
1381
- rawResponse: unknown,
1382
- compiledDsl: Record<string, unknown>,
1383
- spec: ReportSpec,
1384
- timeField?: string | null,
1385
- ): ReportExecutionResult {
1386
- const res = isRecord(rawResponse) ? rawResponse : {};
1387
- const tookMs = typeof res.took === 'number' ? res.took : 0;
1388
- const timedOut = res.timed_out === true;
1389
- const shards: ReportShardStats | undefined = isRecord(res._shards)
1390
- ? {
1391
- total: typeof res._shards.total === 'number' ? res._shards.total : 0,
1392
- successful: typeof res._shards.successful === 'number' ? res._shards.successful : 0,
1393
- skipped: typeof res._shards.skipped === 'number' ? res._shards.skipped : 0,
1394
- failed: typeof res._shards.failed === 'number' ? res._shards.failed : 0,
1395
- }
1396
- : undefined;
1397
- const warnings: string[] = [];
1398
- if (timedOut) {
1399
- warnings.push('Elasticsearch query timed out; displayed results may be incomplete.');
1400
- }
1401
- if (shards && shards.failed > 0) {
1402
- warnings.push(`Partial results: ${shards.failed} of ${shards.total} Elasticsearch shards failed.`);
1403
- }
1404
-
1405
- const hitsContainer = isRecord(res.hits) ? res.hits : {};
1406
- const rawTotal = hitsContainer.total;
1407
- let total = 0;
1408
- let totalRelation: 'eq' | 'gte' = 'eq';
1409
- if (typeof rawTotal === 'number') {
1410
- total = rawTotal;
1411
- } else if (isRecord(rawTotal)) {
1412
- total = typeof rawTotal.value === 'number' ? rawTotal.value : 0;
1413
- totalRelation = rawTotal.relation === 'gte' ? 'gte' : 'eq';
1414
- }
1415
-
1416
- const rawHits = Array.isArray(hitsContainer.hits) ? hitsContainer.hits : [];
1417
- const rows: ReportRowHit[] = rawHits.filter(isRecord).map((hit) => {
1418
- const source = isRecord(hit._source) ? hit._source : {};
1419
- let highlights: Record<string, string[]> | undefined;
1420
- if (isRecord(hit.highlight)) {
1421
- highlights = {};
1422
- for (const [hKey, hVal] of Object.entries(hit.highlight)) {
1423
- if (Array.isArray(hVal)) {
1424
- highlights[hKey] = hVal.filter((v): v is string => typeof v === 'string');
1425
- }
1426
- }
1427
- }
1428
- const sortArr = Array.isArray(hit.sort)
1429
- ? hit.sort.map((s) =>
1430
- typeof s === 'string' || typeof s === 'number' || typeof s === 'boolean' || s === null ? s : String(s),
1431
- )
1432
- : undefined;
1433
- return {
1434
- _id: typeof hit._id === 'string' ? hit._id : String(hit._id ?? ''),
1435
- _index: typeof hit._index === 'string' ? hit._index : String(hit._index ?? ''),
1436
- _score: typeof hit._score === 'number' ? hit._score : null,
1437
- ...(sortArr ? { _sort: sortArr } : {}),
1438
- source,
1439
- ...(highlights ? { highlights } : {}),
1440
- };
1441
- });
1442
-
1443
- const lastRow = rows.length > 0 ? rows[rows.length - 1] : undefined;
1444
- const nextSearchAfter = lastRow?._sort && lastRow._sort.length > 0 ? lastRow._sort : undefined;
1445
- const columns = deriveColumns(rows, spec.columns, timeField);
1446
-
1447
- const aggs = isRecord(res.aggregations) ? res.aggregations : {};
1448
- const histogram: ReportHistogramBucket[] = [];
1449
- if (isRecord(aggs.es_time_histogram) && Array.isArray(aggs.es_time_histogram.buckets)) {
1450
- for (const bucket of aggs.es_time_histogram.buckets) {
1451
- if (!isRecord(bucket)) continue;
1452
- const key = typeof bucket.key_as_string === 'string' ? bucket.key_as_string : String(bucket.key ?? '');
1453
- histogram.push({
1454
- key,
1455
- ...(typeof bucket.key === 'number' ? { timestamp: bucket.key } : {}),
1456
- count: typeof bucket.doc_count === 'number' ? bucket.doc_count : 0,
1457
- });
1458
- }
1459
- }
1460
-
1461
- const metricType = spec.chart?.metricType ?? 'count';
1462
- const series: ReportSeriesPoint[] = [];
1463
- const seenSeriesKeys = new Set<string>();
1464
- if (isRecord(aggs.es_buckets) && Array.isArray(aggs.es_buckets.buckets)) {
1465
- for (const bucket of aggs.es_buckets.buckets) {
1466
- if (!isRecord(bucket)) continue;
1467
- const label = typeof bucket.key_as_string === 'string' ? bucket.key_as_string : String(bucket.key ?? '');
1468
- const docCount = typeof bucket.doc_count === 'number' ? bucket.doc_count : 0;
1469
- const extracted = extractMetricValue(bucket.es_metric, metricType, docCount);
1470
- const metricVal = extracted ?? docCount;
1471
-
1472
- let breakdown: ReportSubSeriesPoint[] | undefined;
1473
- if (isRecord(bucket.es_split) && Array.isArray(bucket.es_split.buckets)) {
1474
- breakdown = [];
1475
- for (const sub of bucket.es_split.buckets) {
1476
- if (!isRecord(sub)) continue;
1477
- const sKey = typeof sub.key_as_string === 'string' ? sub.key_as_string : String(sub.key ?? '');
1478
- const sCount = typeof sub.doc_count === 'number' ? sub.doc_count : 0;
1479
- const sVal = extractMetricValue(sub.es_metric, metricType, sCount) ?? sCount;
1480
- seenSeriesKeys.add(sKey);
1481
- breakdown.push({
1482
- seriesKey: sKey,
1483
- value: sVal,
1484
- count: sCount,
1485
- });
1486
- }
1487
- }
1488
-
1489
- series.push({
1490
- key: String(bucket.key ?? label),
1491
- label,
1492
- value: metricVal,
1493
- count: docCount,
1494
- ...(breakdown ? { breakdown } : {}),
1495
- });
1496
- }
1497
- }
1498
-
1499
- let metricValue: number | null = null;
1500
- let previousMetricValue: number | null | undefined;
1501
- let deltaPercent: number | null | undefined;
1502
-
1503
- if (spec.visualization === 'metric') {
1504
- if (isRecord(aggs.es_current_window) && isRecord(aggs.es_previous_window)) {
1505
- const curCount = typeof aggs.es_current_window.doc_count === 'number' ? aggs.es_current_window.doc_count : 0;
1506
- const prevCount = typeof aggs.es_previous_window.doc_count === 'number' ? aggs.es_previous_window.doc_count : 0;
1507
- total = curCount;
1508
- totalRelation = 'eq';
1509
- metricValue =
1510
- metricType === 'count' || !spec.chart?.metricField
1511
- ? curCount
1512
- : extractMetricValue(aggs.es_current_window.es_metric, metricType, curCount);
1513
- previousMetricValue =
1514
- metricType === 'count' || !spec.chart?.metricField
1515
- ? prevCount
1516
- : extractMetricValue(aggs.es_previous_window.es_metric, metricType, prevCount);
1517
- if (metricValue !== null && previousMetricValue !== null && previousMetricValue !== 0) {
1518
- deltaPercent = Number((((metricValue - previousMetricValue) / Math.abs(previousMetricValue)) * 100).toFixed(2));
1519
- } else {
1520
- deltaPercent = null;
1521
- }
1522
- } else if (metricType === 'count' || !spec.chart?.metricField) {
1523
- metricValue = total;
1524
- } else {
1525
- metricValue = extractMetricValue(aggs.es_metric, metricType, total);
1526
- }
1527
- }
1528
-
1529
- const responsePitId = typeof res.pit_id === 'string' && res.pit_id ? res.pit_id : undefined;
1530
-
1531
- return {
1532
- total,
1533
- totalRelation,
1534
- tookMs,
1535
- ...(timedOut ? { timedOut: true } : {}),
1536
- ...(shards ? { shards } : {}),
1537
- ...(warnings.length > 0 ? { warnings } : {}),
1538
- visualization: spec.visualization,
1539
- rows,
1540
- columns,
1541
- ...(nextSearchAfter ? { nextSearchAfter } : {}),
1542
- ...(responsePitId ? { pitId: responsePitId } : {}),
1543
- series,
1544
- ...(seenSeriesKeys.size > 0 ? { seriesKeys: Array.from(seenSeriesKeys) } : {}),
1545
- histogram,
1546
- metricValue,
1547
- ...(previousMetricValue !== undefined ? { previousMetricValue } : {}),
1548
- ...(deltaPercent !== undefined ? { deltaPercent } : {}),
1549
- metricLabel: buildDefaultMetricLabel(spec),
1550
- compiledDsl,
1551
- };
1552
- }
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 {
11
+ DEFAULT_PAGE_SIZE,
12
+ HIGHLIGHT_POST_TAG,
13
+ HIGHLIGHT_PRE_TAG,
14
+ MAX_RESULT_WINDOW,
15
+ MAX_SPLIT_SERIES,
16
+ MAX_TERMS_BUCKETS,
17
+ MAX_UI_PAGE_SIZE,
18
+ } from '../../shared/constants';
19
+ import type {
20
+ BucketAggType,
21
+ CalendarIntervalOption,
22
+ ChartStackMode,
23
+ EsFieldCapability,
24
+ FieldFormatType,
25
+ FilterOperator,
26
+ ID,
27
+ MetricAggType,
28
+ RecordContextBinding,
29
+ ReportExecutionResult,
30
+ ReportFilterItem,
31
+ ReportHistogramBucket,
32
+ ReportRowHit,
33
+ ReportRuntimeOverrides,
34
+ ReportSeriesPoint,
35
+ ReportShardStats,
36
+ ReportSortItem,
37
+ ReportSpec,
38
+ ReportSubSeriesPoint,
39
+ ReportTimeRange,
40
+ ReportVisualizationType,
41
+ ScalarFilterValue,
42
+ TimeRangePreset,
43
+ } from '../../shared/types';
44
+
45
+ export class KqlSyntaxError extends Error {
46
+ public readonly status = 400;
47
+
48
+ constructor(message: string) {
49
+ super(message);
50
+ this.name = 'KqlSyntaxError';
51
+ }
52
+ }
53
+
54
+ const VALID_VISUALIZATIONS: ReadonlySet<ReportVisualizationType> = new Set([
55
+ 'table',
56
+ 'bar',
57
+ 'line',
58
+ 'area',
59
+ 'pie',
60
+ 'metric',
61
+ ]);
62
+
63
+ const VALID_OPERATORS: ReadonlySet<FilterOperator> = new Set([
64
+ 'eq',
65
+ 'ne',
66
+ 'in',
67
+ 'not_in',
68
+ 'gt',
69
+ 'gte',
70
+ 'lt',
71
+ 'lte',
72
+ 'between',
73
+ 'contains',
74
+ 'exists',
75
+ 'not_exists',
76
+ ]);
77
+
78
+ const VALID_PRESETS: ReadonlySet<TimeRangePreset> = new Set([
79
+ 'last_15m',
80
+ 'last_1h',
81
+ 'last_24h',
82
+ 'last_7d',
83
+ 'last_30d',
84
+ 'last_90d',
85
+ 'all',
86
+ 'custom',
87
+ ]);
88
+
89
+ const VALID_METRICS: ReadonlySet<MetricAggType> = new Set([
90
+ 'count',
91
+ 'sum',
92
+ 'avg',
93
+ 'min',
94
+ 'max',
95
+ 'cardinality',
96
+ 'p50',
97
+ 'p95',
98
+ 'p99',
99
+ ]);
100
+ const VALID_STACK_MODES: ReadonlySet<ChartStackMode> = new Set(['none', 'stacked', 'percent']);
101
+ const VALID_FIELD_FORMATS: ReadonlySet<FieldFormatType> = new Set([
102
+ 'auto',
103
+ 'duration_ms',
104
+ 'bytes',
105
+ 'percent',
106
+ 'number',
107
+ 'status_badge',
108
+ 'url',
109
+ ]);
110
+ const VALID_BUCKETS: ReadonlySet<BucketAggType> = new Set(['date_histogram', 'terms']);
111
+ const VALID_INTERVALS: ReadonlySet<CalendarIntervalOption> = new Set([
112
+ 'auto',
113
+ '1m',
114
+ '5m',
115
+ '15m',
116
+ '1h',
117
+ '1d',
118
+ '1w',
119
+ '1M',
120
+ ]);
121
+
122
+ // Elasticsearch calendar_interval only accepts single calendar units; multi-unit durations require fixed_interval.
123
+ const CALENDAR_UNIT_INTERVALS: ReadonlySet<CalendarIntervalOption> = new Set(['1m', '1h', '1d', '1w', '1M']);
124
+
125
+ const PRESET_TO_ES_EXPR: Record<Exclude<TimeRangePreset, 'all' | 'custom'>, string> = {
126
+ last_15m: 'now-15m',
127
+ last_1h: 'now-1h',
128
+ last_24h: 'now-24h',
129
+ last_7d: 'now-7d',
130
+ last_30d: 'now-30d',
131
+ last_90d: 'now-90d',
132
+ };
133
+
134
+ const PRESET_TO_PREV_ES_EXPR: Record<Exclude<TimeRangePreset, 'all' | 'custom'>, { gte: string; lt: string }> = {
135
+ last_15m: { gte: 'now-30m', lt: 'now-15m' },
136
+ last_1h: { gte: 'now-2h', lt: 'now-1h' },
137
+ last_24h: { gte: 'now-48h', lt: 'now-24h' },
138
+ last_7d: { gte: 'now-14d', lt: 'now-7d' },
139
+ last_30d: { gte: 'now-60d', lt: 'now-30d' },
140
+ last_90d: { gte: 'now-180d', lt: 'now-90d' },
141
+ };
142
+
143
+ export function sanitizeTimeZone(raw?: unknown): string | undefined {
144
+ if (typeof raw !== 'string' || !raw.trim()) return undefined;
145
+ const candidate = raw.trim();
146
+ try {
147
+ Intl.DateTimeFormat(undefined, { timeZone: candidate });
148
+ return candidate;
149
+ } catch {
150
+ return undefined;
151
+ }
152
+ }
153
+
154
+ function isRecord(value: unknown): value is Record<string, unknown> {
155
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
156
+ }
157
+
158
+ function clamp(num: number, min: number, max: number): number {
159
+ if (!Number.isFinite(num)) return min;
160
+ return Math.max(min, Math.min(max, Math.trunc(num)));
161
+ }
162
+
163
+ function toScalarValue(raw: unknown): ScalarFilterValue | undefined {
164
+ if (typeof raw === 'string') return raw;
165
+ if (typeof raw === 'number' && Number.isFinite(raw)) return raw;
166
+ if (typeof raw === 'boolean') return raw;
167
+ return undefined;
168
+ }
169
+
170
+ function coerceLiteral(raw: string, fieldMeta?: EsFieldCapability): ScalarFilterValue {
171
+ const trimmed = raw.trim();
172
+ if (fieldMeta) {
173
+ if (fieldMeta.type === 'boolean') {
174
+ if (trimmed.toLowerCase() === 'true') return true;
175
+ if (trimmed.toLowerCase() === 'false') return false;
176
+ }
177
+ if (
178
+ ['long', 'integer', 'short', 'byte', 'double', 'float', 'half_float', 'scaled_float'].includes(fieldMeta.type)
179
+ ) {
180
+ const parsed = Number(trimmed);
181
+ if (Number.isFinite(parsed)) return parsed;
182
+ }
183
+ }
184
+ if (trimmed.toLowerCase() === 'true') return true;
185
+ if (trimmed.toLowerCase() === 'false') return false;
186
+ if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
187
+ const parsed = Number(trimmed);
188
+ if (Number.isFinite(parsed)) return parsed;
189
+ }
190
+ return trimmed;
191
+ }
192
+
193
+ export function buildFieldCapabilityMap(fields?: EsFieldCapability[] | null): Map<string, EsFieldCapability> {
194
+ const map = new Map<string, EsFieldCapability>();
195
+ if (!Array.isArray(fields)) return map;
196
+ for (const field of fields) {
197
+ if (field && typeof field.name === 'string' && field.name.trim()) {
198
+ map.set(field.name.trim(), field);
199
+ }
200
+ }
201
+ return map;
202
+ }
203
+
204
+ export function resolveAggregatableField(fieldName: string, fieldMap: Map<string, EsFieldCapability>): string {
205
+ const clean = fieldName.trim();
206
+ const meta = fieldMap.get(clean);
207
+ if (!meta) return clean;
208
+ if (meta.aggregatable) return clean;
209
+ if (meta.keywordSubfield) return meta.keywordSubfield;
210
+ const candidate = `${clean}.keyword`;
211
+ if (fieldMap.get(candidate)?.aggregatable) return candidate;
212
+ return clean;
213
+ }
214
+
215
+ function resolveUnmappedSortType(fieldName: string, fieldMap: Map<string, EsFieldCapability>): string | undefined {
216
+ const meta = fieldMap.get(fieldName);
217
+ if (!meta) return undefined;
218
+ switch (meta.type) {
219
+ case 'date':
220
+ case 'date_nanos':
221
+ return 'date';
222
+ case 'long':
223
+ case 'integer':
224
+ case 'short':
225
+ case 'byte':
226
+ return 'long';
227
+ case 'double':
228
+ case 'float':
229
+ case 'half_float':
230
+ case 'scaled_float':
231
+ return 'double';
232
+ case 'boolean':
233
+ return 'boolean';
234
+ case 'keyword':
235
+ case 'constant_keyword':
236
+ case 'wildcard':
237
+ return 'keyword';
238
+ default:
239
+ return undefined;
240
+ }
241
+ }
242
+
243
+ export function normalizeReportFilters(raw: unknown): ReportFilterItem[] {
244
+ if (!Array.isArray(raw)) return [];
245
+ const items: ReportFilterItem[] = [];
246
+ for (const entry of raw) {
247
+ if (!isRecord(entry)) continue;
248
+ const field = typeof entry.field === 'string' ? entry.field.trim() : '';
249
+ const operator = typeof entry.operator === 'string' ? (entry.operator as FilterOperator) : 'eq';
250
+ if (!field || !VALID_OPERATORS.has(operator)) continue;
251
+
252
+ let value: ScalarFilterValue | ScalarFilterValue[] | undefined;
253
+ if (Array.isArray(entry.value)) {
254
+ const arr = entry.value.map(toScalarValue).filter((v): v is ScalarFilterValue => v !== undefined);
255
+ value = arr;
256
+ } else if (typeof entry.value === 'string' && (operator === 'in' || operator === 'not_in')) {
257
+ value = entry.value
258
+ .split(',')
259
+ .map((part) => part.trim())
260
+ .filter(Boolean);
261
+ } else {
262
+ value = toScalarValue(entry.value);
263
+ }
264
+
265
+ const valueTo = toScalarValue(entry.valueTo);
266
+ items.push({
267
+ ...(typeof entry.id === 'string' && entry.id ? { id: entry.id } : {}),
268
+ field,
269
+ operator,
270
+ ...(value !== undefined ? { value } : {}),
271
+ ...(valueTo !== undefined ? { valueTo } : {}),
272
+ enabled: entry.enabled !== false,
273
+ });
274
+ }
275
+ return items;
276
+ }
277
+
278
+ export function normalizeReportSort(raw: unknown): ReportSortItem[] {
279
+ if (!Array.isArray(raw)) return [];
280
+ const items: ReportSortItem[] = [];
281
+ for (const entry of raw) {
282
+ if (typeof entry === 'string' && entry.trim()) {
283
+ const trimmed = entry.trim();
284
+ if (trimmed.startsWith('-')) {
285
+ items.push({ field: trimmed.slice(1), order: 'desc' });
286
+ } else {
287
+ items.push({ field: trimmed, order: 'asc' });
288
+ }
289
+ continue;
290
+ }
291
+ if (!isRecord(entry)) continue;
292
+ const field = typeof entry.field === 'string' ? entry.field.trim() : '';
293
+ if (!field) continue;
294
+ const order = entry.order === 'asc' ? 'asc' : 'desc';
295
+ items.push({ field, order });
296
+ }
297
+ return items;
298
+ }
299
+
300
+ export function normalizeTimeRange(raw: unknown): ReportTimeRange | undefined {
301
+ if (!isRecord(raw)) return undefined;
302
+ const preset =
303
+ typeof raw.preset === 'string' && VALID_PRESETS.has(raw.preset as TimeRangePreset)
304
+ ? (raw.preset as TimeRangePreset)
305
+ : 'last_24h';
306
+ const from = typeof raw.from === 'string' && raw.from.trim() ? raw.from.trim() : undefined;
307
+ const to = typeof raw.to === 'string' && raw.to.trim() ? raw.to.trim() : undefined;
308
+ const timeZone = sanitizeTimeZone(raw.timeZone);
309
+ return {
310
+ preset,
311
+ ...(from ? { from } : {}),
312
+ ...(to ? { to } : {}),
313
+ ...(timeZone ? { timeZone } : {}),
314
+ };
315
+ }
316
+
317
+ function normalizeFieldFormats(raw: unknown): Record<string, FieldFormatType> | undefined {
318
+ if (!isRecord(raw)) return undefined;
319
+ const out: Record<string, FieldFormatType> = {};
320
+ for (const [k, v] of Object.entries(raw)) {
321
+ const fieldName = k.trim();
322
+ if (fieldName && typeof v === 'string' && VALID_FIELD_FORMATS.has(v as FieldFormatType) && v !== 'auto') {
323
+ out[fieldName] = v as FieldFormatType;
324
+ }
325
+ }
326
+ return Object.keys(out).length > 0 ? out : undefined;
327
+ }
328
+
329
+ function normalizeContextBindings(raw: unknown): RecordContextBinding[] | undefined {
330
+ if (!Array.isArray(raw)) return undefined;
331
+ const out: RecordContextBinding[] = [];
332
+ for (const item of raw) {
333
+ if (!isRecord(item)) continue;
334
+ const esField = typeof item.esField === 'string' ? item.esField.trim() : '';
335
+ const recordFieldPath = typeof item.recordFieldPath === 'string' ? item.recordFieldPath.trim() : '';
336
+ if (esField && recordFieldPath) {
337
+ out.push({ esField, recordFieldPath });
338
+ }
339
+ }
340
+ return out.length > 0 ? out : undefined;
341
+ }
342
+
343
+ export interface ServerUserTokenContext {
344
+ userId?: ID;
345
+ username?: string;
346
+ email?: string;
347
+ role?: string;
348
+ }
349
+
350
+ function resolveTokenScalar(val: ScalarFilterValue, userCtx: ServerUserTokenContext): ScalarFilterValue {
351
+ if (typeof val !== 'string') return val;
352
+ const trimmed = val.trim();
353
+ const tokenMatch = trimmed.match(/^\{\{\s*\$(user\.(?:id|username|email)|role)\s*\}\}$/);
354
+ if (!tokenMatch) return val;
355
+ const tokenName = tokenMatch[1];
356
+ let resolved: ScalarFilterValue | undefined;
357
+ if (
358
+ tokenName === 'user.id' &&
359
+ userCtx.userId !== undefined &&
360
+ userCtx.userId !== null &&
361
+ String(userCtx.userId) !== ''
362
+ ) {
363
+ resolved = userCtx.userId;
364
+ } else if (tokenName === 'user.username' && userCtx.username?.trim()) {
365
+ resolved = userCtx.username.trim();
366
+ } else if (tokenName === 'user.email' && userCtx.email?.trim()) {
367
+ resolved = userCtx.email.trim();
368
+ } else if (tokenName === 'role' && userCtx.role?.trim()) {
369
+ resolved = userCtx.role.trim();
370
+ }
371
+ if (resolved === undefined) {
372
+ const err = new Error(
373
+ `Permission denied: missing authenticated value for locked filter token "$${tokenName}"`,
374
+ ) as Error & {
375
+ status?: number;
376
+ };
377
+ err.status = 403;
378
+ throw err;
379
+ }
380
+ return resolved;
381
+ }
382
+
383
+ export function resolveServerLockedFilters(
384
+ lockedFilters: ReportFilterItem[] | undefined,
385
+ userCtx?: ServerUserTokenContext,
386
+ ): ReportFilterItem[] {
387
+ if (!lockedFilters || lockedFilters.length === 0) return [];
388
+ const ctx = userCtx ?? {};
389
+ return lockedFilters.map((item) => {
390
+ const nextVal = Array.isArray(item.value)
391
+ ? item.value.map((v) => resolveTokenScalar(v, ctx))
392
+ : item.value !== undefined
393
+ ? resolveTokenScalar(item.value, ctx)
394
+ : undefined;
395
+ const nextValTo = item.valueTo !== undefined ? resolveTokenScalar(item.valueTo, ctx) : undefined;
396
+ return {
397
+ ...item,
398
+ ...(nextVal !== undefined ? { value: nextVal } : {}),
399
+ ...(nextValTo !== undefined ? { valueTo: nextValTo } : {}),
400
+ enabled: true,
401
+ };
402
+ });
403
+ }
404
+
405
+ export function normalizeReportSpec(raw: unknown, fallbackVisualization?: unknown): ReportSpec {
406
+ const obj = isRecord(raw) ? raw : {};
407
+ const visCandidate = typeof obj.visualization === 'string' ? obj.visualization : fallbackVisualization;
408
+ const visualization: ReportVisualizationType =
409
+ typeof visCandidate === 'string' && VALID_VISUALIZATIONS.has(visCandidate as ReportVisualizationType)
410
+ ? (visCandidate as ReportVisualizationType)
411
+ : 'table';
412
+
413
+ const query = typeof obj.query === 'string' ? obj.query.trim() : '';
414
+ const queryMode = obj.queryMode === 'simple' ? 'simple' : 'kql';
415
+ const filters = normalizeReportFilters(obj.filters);
416
+ const lockedFilters = normalizeReportFilters(obj.lockedFilters).map((item) => ({
417
+ ...item,
418
+ enabled: true,
419
+ }));
420
+ const sort = normalizeReportSort(obj.sort);
421
+ const timeRange = normalizeTimeRange(obj.timeRange);
422
+ const columns = Array.isArray(obj.columns)
423
+ ? obj.columns
424
+ .filter((col): col is string => typeof col === 'string' && col.trim().length > 0)
425
+ .map((col) => col.trim())
426
+ : [];
427
+ const fieldFormats = normalizeFieldFormats(obj.fieldFormats);
428
+ const contextBindings = normalizeContextBindings(obj.contextBindings);
429
+ const pageSize = clamp(typeof obj.pageSize === 'number' ? obj.pageSize : DEFAULT_PAGE_SIZE, 1, MAX_UI_PAGE_SIZE);
430
+
431
+ const rawChart = isRecord(obj.chart) ? obj.chart : {};
432
+ const metricType: MetricAggType =
433
+ typeof rawChart.metricType === 'string' && VALID_METRICS.has(rawChart.metricType as MetricAggType)
434
+ ? (rawChart.metricType as MetricAggType)
435
+ : 'count';
436
+ const bucketType: BucketAggType | undefined =
437
+ typeof rawChart.bucketType === 'string' && VALID_BUCKETS.has(rawChart.bucketType as BucketAggType)
438
+ ? (rawChart.bucketType as BucketAggType)
439
+ : undefined;
440
+ const calendarInterval: CalendarIntervalOption =
441
+ typeof rawChart.calendarInterval === 'string' &&
442
+ VALID_INTERVALS.has(rawChart.calendarInterval as CalendarIntervalOption)
443
+ ? (rawChart.calendarInterval as CalendarIntervalOption)
444
+ : 'auto';
445
+ const stackMode: ChartStackMode =
446
+ typeof rawChart.stackMode === 'string' && VALID_STACK_MODES.has(rawChart.stackMode as ChartStackMode)
447
+ ? (rawChart.stackMode as ChartStackMode)
448
+ : 'none';
449
+
450
+ return {
451
+ query,
452
+ queryMode,
453
+ filters,
454
+ lockedFilters,
455
+ sort,
456
+ ...(timeRange ? { timeRange } : {}),
457
+ columns,
458
+ ...(fieldFormats ? { fieldFormats } : {}),
459
+ ...(contextBindings ? { contextBindings } : {}),
460
+ pageSize,
461
+ visualization,
462
+ chart: {
463
+ ...(bucketType ? { bucketType } : {}),
464
+ ...(typeof rawChart.bucketField === 'string' && rawChart.bucketField.trim()
465
+ ? { bucketField: rawChart.bucketField.trim() }
466
+ : {}),
467
+ calendarInterval,
468
+ topN: clamp(typeof rawChart.topN === 'number' ? rawChart.topN : 10, 1, MAX_TERMS_BUCKETS),
469
+ metricType,
470
+ ...(typeof rawChart.metricField === 'string' && rawChart.metricField.trim()
471
+ ? { metricField: rawChart.metricField.trim() }
472
+ : {}),
473
+ ...(typeof rawChart.metricLabel === 'string' && rawChart.metricLabel.trim()
474
+ ? { metricLabel: rawChart.metricLabel.trim() }
475
+ : {}),
476
+ showHistogram: rawChart.showHistogram !== false,
477
+ ...(typeof rawChart.splitSeriesField === 'string' && rawChart.splitSeriesField.trim()
478
+ ? { splitSeriesField: rawChart.splitSeriesField.trim() }
479
+ : {}),
480
+ ...(typeof rawChart.splitSeriesTopN === 'number'
481
+ ? { splitSeriesTopN: clamp(rawChart.splitSeriesTopN, 1, MAX_SPLIT_SERIES) }
482
+ : {}),
483
+ ...(stackMode !== 'none' ? { stackMode } : {}),
484
+ ...(rawChart.comparePreviousPeriod === true ? { comparePreviousPeriod: true } : {}),
485
+ },
486
+ allowInteractiveControls: obj.allowInteractiveControls !== false,
487
+ allowExport: obj.allowExport !== false,
488
+ };
489
+ }
490
+
491
+ function assertBalancedKqlDelimiters(input: string): void {
492
+ let inQuotes = false;
493
+ let quoteChar = '';
494
+ const openParenPositions: number[] = [];
495
+
496
+ for (let i = 0; i < input.length; i++) {
497
+ const ch = input[i];
498
+ if (inQuotes) {
499
+ if (ch === '\\') {
500
+ i++;
501
+ continue;
502
+ }
503
+ if (ch === quoteChar) {
504
+ inQuotes = false;
505
+ }
506
+ continue;
507
+ }
508
+ if (ch === '"' || ch === "'") {
509
+ inQuotes = true;
510
+ quoteChar = ch;
511
+ continue;
512
+ }
513
+ if (ch === '(') {
514
+ openParenPositions.push(i);
515
+ continue;
516
+ }
517
+ if (ch === ')') {
518
+ const openIdx = openParenPositions.pop();
519
+ if (openIdx === undefined) {
520
+ throw new KqlSyntaxError('Invalid KQL syntax: unexpected closing parenthesis ")"');
521
+ }
522
+ if (!input.slice(openIdx + 1, i).trim()) {
523
+ throw new KqlSyntaxError('Invalid KQL syntax: empty parentheses "()"');
524
+ }
525
+ }
526
+ }
527
+
528
+ if (inQuotes) {
529
+ throw new KqlSyntaxError('Invalid KQL syntax: unclosed quotation mark');
530
+ }
531
+ if (openParenPositions.length > 0) {
532
+ throw new KqlSyntaxError('Invalid KQL syntax: unclosed parenthesis "("');
533
+ }
534
+ }
535
+
536
+ /**
537
+ * Split a KQL expression on top-level boolean connectors (`AND` / `OR`) while
538
+ * respecting quoted strings and nested parentheses.
539
+ */
540
+ function splitTopLevelBoolean(input: string, keyword: 'AND' | 'OR'): string[] {
541
+ const parts: string[] = [];
542
+ let depth = 0;
543
+ let inQuotes = false;
544
+ let quoteChar = '';
545
+ let lastIdx = 0;
546
+ let splitFound = false;
547
+
548
+ for (let i = 0; i < input.length; i++) {
549
+ const ch = input[i];
550
+ if (inQuotes) {
551
+ if (ch === '\\') {
552
+ i++;
553
+ continue;
554
+ }
555
+ if (ch === quoteChar) {
556
+ inQuotes = false;
557
+ }
558
+ continue;
559
+ }
560
+ if (ch === '"' || ch === "'") {
561
+ inQuotes = true;
562
+ quoteChar = ch;
563
+ continue;
564
+ }
565
+ if (ch === '(') {
566
+ depth++;
567
+ continue;
568
+ }
569
+ if (ch === ')') {
570
+ depth = Math.max(0, depth - 1);
571
+ continue;
572
+ }
573
+ if (depth === 0) {
574
+ const prevBoundary = i === 0 || /[\s)]/.test(input[i - 1]);
575
+ const slice = input.slice(i, i + keyword.length);
576
+ const nextChar = input[i + keyword.length];
577
+ const nextBoundary = nextChar === undefined || /[\s(]/.test(nextChar);
578
+ if (prevBoundary && nextBoundary && slice.toUpperCase() === keyword) {
579
+ splitFound = true;
580
+ parts.push(input.slice(lastIdx, i).trim());
581
+ i += keyword.length - 1;
582
+ lastIdx = i + 1;
583
+ }
584
+ }
585
+ }
586
+ parts.push(input.slice(lastIdx).trim());
587
+ if (splitFound && parts.some((part) => !part)) {
588
+ throw new KqlSyntaxError(`Invalid KQL syntax: missing operand around "${keyword}"`);
589
+ }
590
+ return parts.filter(Boolean);
591
+ }
592
+
593
+ function hasBalancedOuterParens(expr: string): boolean {
594
+ if (!expr.startsWith('(') || !expr.endsWith(')')) return false;
595
+ let depth = 0;
596
+ let inQuotes = false;
597
+ let quoteChar = '';
598
+ for (let i = 0; i < expr.length; i++) {
599
+ const ch = expr[i];
600
+ if (inQuotes) {
601
+ if (ch === '\\') {
602
+ i++;
603
+ continue;
604
+ }
605
+ if (ch === quoteChar) inQuotes = false;
606
+ continue;
607
+ }
608
+ if (ch === '"' || ch === "'") {
609
+ inQuotes = true;
610
+ quoteChar = ch;
611
+ continue;
612
+ }
613
+ if (ch === '(') depth++;
614
+ if (ch === ')') {
615
+ depth--;
616
+ if (depth === 0 && i < expr.length - 1) return false;
617
+ }
618
+ }
619
+ return depth === 0;
620
+ }
621
+
622
+ function unquote(raw: string): { value: string; wasQuoted: boolean } {
623
+ const trimmed = raw.trim();
624
+ if (
625
+ (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2) ||
626
+ (trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2)
627
+ ) {
628
+ return {
629
+ value: trimmed.slice(1, -1).replace(/\\(["'\\])/g, '$1'),
630
+ wasQuoted: true,
631
+ };
632
+ }
633
+ return { value: trimmed, wasQuoted: false };
634
+ }
635
+
636
+ function compileSingleFieldValue(
637
+ rawField: string,
638
+ rawVal: string,
639
+ fieldMap: Map<string, EsFieldCapability>,
640
+ ): Record<string, unknown> {
641
+ const trimmed = rawVal.trim();
642
+ if (!trimmed) {
643
+ throw new KqlSyntaxError(`Invalid KQL syntax: missing value for field "${rawField}"`);
644
+ }
645
+
646
+ const inlineRangeMatch = trimmed.match(/^(>=|<=|>|<)\s*(.+)$/);
647
+ if (inlineRangeMatch) {
648
+ const [, op, rangeRhs] = inlineRangeMatch;
649
+ const { value } = unquote(rangeRhs);
650
+ if (!value) {
651
+ throw new KqlSyntaxError(`Invalid KQL syntax: missing range bound for field "${rawField}"`);
652
+ }
653
+ const coerced = coerceLiteral(value, fieldMap.get(rawField));
654
+ const opKey = op === '>=' ? 'gte' : op === '<=' ? 'lte' : op === '>' ? 'gt' : 'lt';
655
+ return { range: { [rawField]: { [opKey]: coerced } } };
656
+ }
657
+
658
+ const { value, wasQuoted } = unquote(trimmed);
659
+ if (!wasQuoted) {
660
+ if (/^[[{].*[\]}]$/.test(value)) {
661
+ throw new KqlSyntaxError('Lucene range brackets [a TO b] are not valid KQL; use >= and <= instead');
662
+ }
663
+ if (/^\/.*\/$/.test(value)) {
664
+ throw new KqlSyntaxError('Regular expressions /.../ are not valid KQL; use * or ? wildcards instead');
665
+ }
666
+ if (value.includes('(') || value.includes(')')) {
667
+ throw new KqlSyntaxError(`Unsupported KQL field value syntax near "${value}"`);
668
+ }
669
+ if (value.includes(':')) {
670
+ throw new KqlSyntaxError(`Unexpected ":" in unquoted KQL value "${value}"; wrap values containing ":" in quotes`);
671
+ }
672
+ if (value === '*') {
673
+ return { exists: { field: rawField } };
674
+ }
675
+ }
676
+
677
+ const fieldMeta = fieldMap.get(rawField);
678
+ if (!wasQuoted && (value.includes('*') || value.includes('?'))) {
679
+ const wildcardField = resolveAggregatableField(rawField, fieldMap);
680
+ return {
681
+ wildcard: {
682
+ [wildcardField]: {
683
+ value,
684
+ case_insensitive: true,
685
+ },
686
+ },
687
+ };
688
+ }
689
+
690
+ if (wasQuoted) {
691
+ if (fieldMeta?.type === 'keyword' || fieldMeta?.type === 'constant_keyword') {
692
+ return { term: { [rawField]: value } };
693
+ }
694
+ return { match_phrase: { [rawField]: value } };
695
+ }
696
+
697
+ const coerced = coerceLiteral(value, fieldMeta);
698
+ if (typeof coerced === 'number' || typeof coerced === 'boolean') {
699
+ return { term: { [rawField]: coerced } };
700
+ }
701
+ if (fieldMeta?.type === 'keyword' || fieldMeta?.type === 'constant_keyword') {
702
+ return { term: { [rawField]: coerced } };
703
+ }
704
+ return { match_phrase: { [rawField]: String(coerced) } };
705
+ }
706
+
707
+ function compileFieldGroupClause(
708
+ fieldName: string,
709
+ groupBody: string,
710
+ fieldMap: Map<string, EsFieldCapability>,
711
+ ): Record<string, unknown> {
712
+ const expr = groupBody.trim();
713
+ if (!expr) {
714
+ throw new KqlSyntaxError(`Invalid KQL syntax: empty value group for field "${fieldName}"`);
715
+ }
716
+ if (/^NOT$/i.test(expr)) {
717
+ throw new KqlSyntaxError(`Invalid KQL syntax: incomplete "NOT" inside "${fieldName}: (...)"`);
718
+ }
719
+
720
+ if (hasBalancedOuterParens(expr)) {
721
+ return compileFieldGroupClause(fieldName, expr.slice(1, -1), fieldMap);
722
+ }
723
+
724
+ const orParts = splitTopLevelBoolean(expr, 'OR');
725
+ if (orParts.length > 1) {
726
+ const should = orParts.map((part) => compileFieldGroupClause(fieldName, part, fieldMap));
727
+ return should.length === 1 ? should[0] : { bool: { should, minimum_should_match: 1 } };
728
+ }
729
+
730
+ const andParts = splitTopLevelBoolean(expr, 'AND');
731
+ if (andParts.length > 1) {
732
+ const must = andParts.map((part) => compileFieldGroupClause(fieldName, part, fieldMap));
733
+ return must.length === 1 ? must[0] : { bool: { must } };
734
+ }
735
+
736
+ if (/^NOT\s+/i.test(expr)) {
737
+ const inner = compileFieldGroupClause(fieldName, expr.replace(/^NOT\s+/i, ''), fieldMap);
738
+ return { bool: { must_not: [inner] } };
739
+ }
740
+
741
+ return compileSingleFieldValue(fieldName, expr, fieldMap);
742
+ }
743
+
744
+ function compileKqlAst(exprInput: string, fieldMap: Map<string, EsFieldCapability>): Record<string, unknown> | null {
745
+ const expr = exprInput.trim();
746
+ if (!expr) return null;
747
+ if (/^NOT$/i.test(expr)) {
748
+ throw new KqlSyntaxError('Invalid KQL syntax: incomplete "NOT" operator');
749
+ }
750
+
751
+ if (hasBalancedOuterParens(expr)) {
752
+ return compileKqlAst(expr.slice(1, -1), fieldMap);
753
+ }
754
+
755
+ const orParts = splitTopLevelBoolean(expr, 'OR');
756
+ if (orParts.length > 1) {
757
+ const should = orParts
758
+ .map((part) => compileKqlAst(part, fieldMap))
759
+ .filter((item): item is Record<string, unknown> => item !== null);
760
+ if (should.length === 0) return null;
761
+ if (should.length === 1) return should[0];
762
+ return { bool: { should, minimum_should_match: 1 } };
763
+ }
764
+
765
+ const andParts = splitTopLevelBoolean(expr, 'AND');
766
+ if (andParts.length > 1) {
767
+ const must = andParts
768
+ .map((part) => compileKqlAst(part, fieldMap))
769
+ .filter((item): item is Record<string, unknown> => item !== null);
770
+ if (must.length === 0) return null;
771
+ if (must.length === 1) return must[0];
772
+ return { bool: { must } };
773
+ }
774
+
775
+ if (/^NOT\s+/i.test(expr)) {
776
+ const rest = expr.replace(/^NOT\s+/i, '').trim();
777
+ if (!rest) {
778
+ throw new KqlSyntaxError('Invalid KQL syntax: incomplete "NOT" operator');
779
+ }
780
+ const inner = compileKqlAst(rest, fieldMap);
781
+ return inner ? { bool: { must_not: [inner] } } : null;
782
+ }
783
+
784
+ if (/^[A-Za-z0-9_@.-]+\s*(:|>=|<=|>|<)\s*$/.test(expr)) {
785
+ throw new KqlSyntaxError('Invalid KQL syntax: missing value after field operator');
786
+ }
787
+
788
+ // Range expression: field >= value, field > value, field <= value, field < value
789
+ const rangeMatch = expr.match(/^([A-Za-z0-9_@.-]+)\s*(>=|<=|>|<)\s*(.+)$/);
790
+ if (rangeMatch) {
791
+ const [, rawField, op, rawVal] = rangeMatch;
792
+ return compileSingleFieldValue(rawField, `${op} ${rawVal}`, fieldMap);
793
+ }
794
+
795
+ // Field-value or field-group expression: field : value OR field : (a OR b)
796
+ const colonMatch = expr.match(/^([A-Za-z0-9_@.-]+)\s*:\s*(.+)$/);
797
+ if (colonMatch) {
798
+ const [, rawField, rawVal] = colonMatch;
799
+ const rhs = rawVal.trim();
800
+ if (hasBalancedOuterParens(rhs)) {
801
+ return compileFieldGroupClause(rawField, rhs.slice(1, -1), fieldMap);
802
+ }
803
+ return compileSingleFieldValue(rawField, rhs, fieldMap);
804
+ }
805
+
806
+ if (!unquote(expr).wasQuoted && (/^[[{].*[\]}]$/.test(expr) || /^\/.*\/$/.test(expr))) {
807
+ throw new KqlSyntaxError(`Unsupported KQL expression "${expr}"`);
808
+ }
809
+
810
+ return {
811
+ simple_query_string: {
812
+ query: expr,
813
+ default_operator: 'and',
814
+ lenient: true,
815
+ },
816
+ };
817
+ }
818
+
819
+ /**
820
+ * Compile a KQL-compatible search string into universal Elasticsearch Query DSL
821
+ * so queries run reliably across ES 7.x, 8.x, 9.x, and OpenSearch.
822
+ */
823
+ export function compileKqlToQueryDsl(
824
+ rawQuery: string,
825
+ fieldMap: Map<string, EsFieldCapability> = new Map(),
826
+ ): Record<string, unknown> | null {
827
+ const expr = rawQuery.trim();
828
+ if (!expr) return null;
829
+ assertBalancedKqlDelimiters(expr);
830
+ return compileKqlAst(expr, fieldMap);
831
+ }
832
+
833
+ export function compileFilterItem(
834
+ item: ReportFilterItem,
835
+ fieldMap: Map<string, EsFieldCapability>,
836
+ ): { clause: Record<string, unknown>; negated: boolean } | null {
837
+ if (item.enabled === false || !item.field.trim()) return null;
838
+ const field = item.field.trim();
839
+ const fieldMeta = fieldMap.get(field);
840
+ const keywordField = resolveAggregatableField(field, fieldMap);
841
+
842
+ switch (item.operator) {
843
+ case 'exists':
844
+ return { clause: { exists: { field } }, negated: false };
845
+ case 'not_exists':
846
+ return { clause: { exists: { field } }, negated: true };
847
+ case 'eq':
848
+ case 'ne': {
849
+ if (item.value === undefined || Array.isArray(item.value)) return null;
850
+ const val = typeof item.value === 'string' ? coerceLiteral(item.value, fieldMeta) : item.value;
851
+ const useTerm = typeof val !== 'string' || fieldMeta?.aggregatable === true || keywordField !== field;
852
+ const clause = useTerm ? { term: { [keywordField]: val } } : { match_phrase: { [field]: val } };
853
+ return { clause, negated: item.operator === 'ne' };
854
+ }
855
+ case 'in':
856
+ case 'not_in': {
857
+ const values = Array.isArray(item.value) ? item.value : item.value !== undefined ? [item.value] : [];
858
+ if (values.length === 0) return null;
859
+ const normalized = values.map((v) => (typeof v === 'string' ? coerceLiteral(v, fieldMeta) : v));
860
+ return {
861
+ clause: { terms: { [keywordField]: normalized } },
862
+ negated: item.operator === 'not_in',
863
+ };
864
+ }
865
+ case 'gt':
866
+ case 'gte':
867
+ case 'lt':
868
+ case 'lte': {
869
+ if (item.value === undefined || Array.isArray(item.value)) return null;
870
+ const val = typeof item.value === 'string' ? coerceLiteral(item.value, fieldMeta) : item.value;
871
+ return {
872
+ clause: { range: { [field]: { [item.operator]: val } } },
873
+ negated: false,
874
+ };
875
+ }
876
+ case 'between': {
877
+ const rangeBody: Record<string, ScalarFilterValue> = {};
878
+ if (item.value !== undefined && !Array.isArray(item.value)) {
879
+ rangeBody.gte = typeof item.value === 'string' ? coerceLiteral(item.value, fieldMeta) : item.value;
880
+ }
881
+ if (item.valueTo !== undefined) {
882
+ rangeBody.lte = typeof item.valueTo === 'string' ? coerceLiteral(item.valueTo, fieldMeta) : item.valueTo;
883
+ }
884
+ if (Object.keys(rangeBody).length === 0) return null;
885
+ return {
886
+ clause: { range: { [field]: rangeBody } },
887
+ negated: false,
888
+ };
889
+ }
890
+ case 'contains': {
891
+ if (item.value === undefined || Array.isArray(item.value)) return null;
892
+ const rawText = String(item.value).trim();
893
+ if (!rawText) return null;
894
+ if (fieldMeta && !fieldMeta.aggregatable && !fieldMeta.keywordSubfield) {
895
+ return { clause: { match_phrase: { [field]: rawText } }, negated: false };
896
+ }
897
+ const escaped = rawText.replace(/([*?\\])/g, '\\$1');
898
+ return {
899
+ clause: {
900
+ wildcard: {
901
+ [keywordField]: {
902
+ value: `*${escaped}*`,
903
+ case_insensitive: true,
904
+ },
905
+ },
906
+ },
907
+ negated: false,
908
+ };
909
+ }
910
+ default:
911
+ return null;
912
+ }
913
+ }
914
+
915
+ export function compileTimeRange(
916
+ timeRange: ReportTimeRange | undefined,
917
+ timeField: string | null | undefined,
918
+ fallbackTimeZone?: string,
919
+ ): Record<string, unknown> | null {
920
+ const cleanField = typeof timeField === 'string' ? timeField.trim() : '';
921
+ if (!cleanField || !timeRange || timeRange.preset === 'all') return null;
922
+
923
+ const tz = sanitizeTimeZone(timeRange.timeZone ?? fallbackTimeZone);
924
+
925
+ if (timeRange.preset === 'custom') {
926
+ const bounds: Record<string, string> = {};
927
+ if (timeRange.from) bounds.gte = timeRange.from;
928
+ if (timeRange.to) bounds.lte = timeRange.to;
929
+ if (Object.keys(bounds).length === 0) return null;
930
+ if (tz) bounds.time_zone = tz;
931
+ return { range: { [cleanField]: bounds } };
932
+ }
933
+
934
+ const expr = PRESET_TO_ES_EXPR[timeRange.preset];
935
+ if (!expr) return null;
936
+ return {
937
+ range: {
938
+ [cleanField]: {
939
+ gte: expr,
940
+ lte: 'now',
941
+ ...(tz ? { time_zone: tz } : {}),
942
+ },
943
+ },
944
+ };
945
+ }
946
+
947
+ export function compilePreviousTimeRange(
948
+ timeRange: ReportTimeRange | undefined,
949
+ timeField: string | null | undefined,
950
+ fallbackTimeZone?: string,
951
+ ): Record<string, unknown> | null {
952
+ const cleanField = typeof timeField === 'string' ? timeField.trim() : '';
953
+ if (!cleanField || !timeRange || timeRange.preset === 'all') return null;
954
+ const tz = sanitizeTimeZone(timeRange.timeZone ?? fallbackTimeZone);
955
+
956
+ if (timeRange.preset === 'custom') {
957
+ const fromMs = timeRange.from ? Date.parse(timeRange.from) : NaN;
958
+ const toMs = timeRange.to ? Date.parse(timeRange.to) : NaN;
959
+ if (!Number.isFinite(fromMs) || !Number.isFinite(toMs) || toMs <= fromMs) {
960
+ return null;
961
+ }
962
+ const duration = toMs - fromMs;
963
+ return {
964
+ range: {
965
+ [cleanField]: {
966
+ gte: new Date(fromMs - duration).toISOString(),
967
+ lt: new Date(fromMs).toISOString(),
968
+ ...(tz ? { time_zone: tz } : {}),
969
+ },
970
+ },
971
+ };
972
+ }
973
+
974
+ const prev = PRESET_TO_PREV_ES_EXPR[timeRange.preset];
975
+ if (!prev) return null;
976
+ return {
977
+ range: {
978
+ [cleanField]: {
979
+ gte: prev.gte,
980
+ lt: prev.lt,
981
+ ...(tz ? { time_zone: tz } : {}),
982
+ },
983
+ },
984
+ };
985
+ }
986
+
987
+ function buildMetricAggDefinition(
988
+ metricType: MetricAggType,
989
+ metricField: string | undefined,
990
+ fieldMap: Map<string, EsFieldCapability>,
991
+ ): Record<string, unknown> | undefined {
992
+ if (metricType === 'count' || !metricField?.trim()) return undefined;
993
+ const targetField = resolveAggregatableField(metricField, fieldMap);
994
+ if (metricType === 'p50' || metricType === 'p95' || metricType === 'p99') {
995
+ const pct = metricType === 'p50' ? 50 : metricType === 'p95' ? 95 : 99;
996
+ return {
997
+ percentiles: {
998
+ field: targetField,
999
+ percents: [pct],
1000
+ },
1001
+ };
1002
+ }
1003
+ return {
1004
+ [metricType]: {
1005
+ field: targetField,
1006
+ },
1007
+ };
1008
+ }
1009
+
1010
+ function extractMetricValue(aggNode: unknown, metricType: MetricAggType, fallbackCount: number): number | null {
1011
+ if (metricType === 'count') {
1012
+ return fallbackCount;
1013
+ }
1014
+ if (!isRecord(aggNode)) return null;
1015
+ if (metricType === 'p50' || metricType === 'p95' || metricType === 'p99') {
1016
+ const values = isRecord(aggNode.values) ? aggNode.values : undefined;
1017
+ if (!values) return null;
1018
+ const exactKey = metricType === 'p50' ? '50.0' : metricType === 'p95' ? '95.0' : '99.0';
1019
+ const shortKey = metricType === 'p50' ? '50' : metricType === 'p95' ? '95' : '99';
1020
+ const raw = values[exactKey] ?? values[shortKey];
1021
+ return typeof raw === 'number' && Number.isFinite(raw) ? Number(raw.toFixed(4)) : null;
1022
+ }
1023
+ return typeof aggNode.value === 'number' && Number.isFinite(aggNode.value) ? Number(aggNode.value.toFixed(4)) : null;
1024
+ }
1025
+
1026
+ export interface CompileSearchOptions {
1027
+ spec: ReportSpec;
1028
+ overrides?: ReportRuntimeOverrides;
1029
+ timeField?: string | null;
1030
+ fields?: EsFieldCapability[] | null;
1031
+ maxRowsCap?: number;
1032
+ userContext?: ServerUserTokenContext;
1033
+ usePit?: boolean;
1034
+ }
1035
+
1036
+ export function mergeSpecWithOverrides(
1037
+ spec: ReportSpec,
1038
+ overrides?: ReportRuntimeOverrides,
1039
+ ): {
1040
+ effectiveSpec: ReportSpec;
1041
+ extraRuntimeFilters: ReportFilterItem[];
1042
+ effectiveTimeZone?: string;
1043
+ page: number;
1044
+ pageSize: number;
1045
+ searchAfter?: Array<string | number | boolean | null>;
1046
+ } {
1047
+ if (!overrides) {
1048
+ return {
1049
+ effectiveSpec: spec,
1050
+ extraRuntimeFilters: [],
1051
+ effectiveTimeZone: sanitizeTimeZone(spec.timeRange?.timeZone),
1052
+ page: 1,
1053
+ pageSize: spec.pageSize ?? DEFAULT_PAGE_SIZE,
1054
+ };
1055
+ }
1056
+
1057
+ const effectiveTimeRange =
1058
+ overrides.timeRange !== undefined ? normalizeTimeRange(overrides.timeRange) : spec.timeRange;
1059
+ const effectiveTimeZone = sanitizeTimeZone(
1060
+ overrides.timeZone ?? effectiveTimeRange?.timeZone ?? spec.timeRange?.timeZone,
1061
+ );
1062
+
1063
+ const effectiveSpec: ReportSpec = {
1064
+ ...spec,
1065
+ query: overrides.query !== undefined ? overrides.query.trim() : spec.query,
1066
+ filters: overrides.filters !== undefined ? normalizeReportFilters(overrides.filters) : spec.filters,
1067
+ // Security invariant: lockedFilters are server-owned and can never be replaced or cleared by runtime overrides.
1068
+ lockedFilters: spec.lockedFilters,
1069
+ sort: overrides.sort !== undefined ? normalizeReportSort(overrides.sort) : spec.sort,
1070
+ timeRange: effectiveTimeRange,
1071
+ };
1072
+
1073
+ const extraRuntimeFilters: ReportFilterItem[] = [
1074
+ ...normalizeReportFilters(overrides.sharedFilters),
1075
+ ...normalizeReportFilters(overrides.contextFilters),
1076
+ ];
1077
+
1078
+ const page = clamp(typeof overrides.page === 'number' ? overrides.page : 1, 1, 10000);
1079
+ const pageSize = clamp(
1080
+ typeof overrides.pageSize === 'number' ? overrides.pageSize : spec.pageSize ?? DEFAULT_PAGE_SIZE,
1081
+ 1,
1082
+ MAX_UI_PAGE_SIZE,
1083
+ );
1084
+ const searchAfter =
1085
+ Array.isArray(overrides.searchAfter) && overrides.searchAfter.length > 0 ? overrides.searchAfter : undefined;
1086
+
1087
+ return {
1088
+ effectiveSpec,
1089
+ extraRuntimeFilters,
1090
+ ...(effectiveTimeZone ? { effectiveTimeZone } : {}),
1091
+ page,
1092
+ pageSize,
1093
+ ...(searchAfter ? { searchAfter } : {}),
1094
+ };
1095
+ }
1096
+
1097
+ export function compileSearchRequest(options: CompileSearchOptions): {
1098
+ body: Record<string, unknown>;
1099
+ effectiveSpec: ReportSpec;
1100
+ } {
1101
+ const fieldMap = buildFieldCapabilityMap(options.fields);
1102
+ const { effectiveSpec, extraRuntimeFilters, effectiveTimeZone, page, pageSize, searchAfter } = mergeSpecWithOverrides(
1103
+ options.spec,
1104
+ options.overrides,
1105
+ );
1106
+ const maxCap = options.maxRowsCap ? clamp(options.maxRowsCap, 1, MAX_UI_PAGE_SIZE) : MAX_UI_PAGE_SIZE;
1107
+ const effectivePageSize = Math.min(pageSize, maxCap);
1108
+ const timeField = options.timeField?.trim() || null;
1109
+
1110
+ const must: Array<Record<string, unknown>> = [];
1111
+ const filter: Array<Record<string, unknown>> = [];
1112
+ const mustNot: Array<Record<string, unknown>> = [];
1113
+
1114
+ if (effectiveSpec.query && effectiveSpec.query.trim()) {
1115
+ if (effectiveSpec.queryMode === 'simple') {
1116
+ must.push({
1117
+ simple_query_string: {
1118
+ query: effectiveSpec.query.trim(),
1119
+ default_operator: 'and',
1120
+ lenient: true,
1121
+ },
1122
+ });
1123
+ } else {
1124
+ const parsedQuery = compileKqlToQueryDsl(effectiveSpec.query, fieldMap);
1125
+ if (parsedQuery) {
1126
+ must.push(parsedQuery);
1127
+ }
1128
+ }
1129
+ }
1130
+
1131
+ const resolvedLockedFilters = resolveServerLockedFilters(effectiveSpec.lockedFilters, options.userContext);
1132
+ const combinedFilters: ReportFilterItem[] = [
1133
+ ...resolvedLockedFilters,
1134
+ ...extraRuntimeFilters,
1135
+ ...(effectiveSpec.filters ?? []),
1136
+ ];
1137
+ for (const item of combinedFilters) {
1138
+ const compiled = compileFilterItem(item, fieldMap);
1139
+ if (!compiled) continue;
1140
+ if (compiled.negated) {
1141
+ mustNot.push(compiled.clause);
1142
+ } else {
1143
+ filter.push(compiled.clause);
1144
+ }
1145
+ }
1146
+
1147
+ const currentTimeClause = compileTimeRange(effectiveSpec.timeRange, timeField, effectiveTimeZone);
1148
+ const previousTimeClause =
1149
+ effectiveSpec.visualization === 'metric' && effectiveSpec.chart?.comparePreviousPeriod === true
1150
+ ? compilePreviousTimeRange(effectiveSpec.timeRange, timeField, effectiveTimeZone)
1151
+ : null;
1152
+ const useDualPeriodMetric = Boolean(currentTimeClause && previousTimeClause);
1153
+
1154
+ if (currentTimeClause && !useDualPeriodMetric) {
1155
+ filter.push(currentTimeClause);
1156
+ }
1157
+
1158
+ let queryDsl: Record<string, unknown>;
1159
+ if (must.length === 0 && filter.length === 0 && mustNot.length === 0) {
1160
+ queryDsl = { match_all: {} };
1161
+ } else {
1162
+ queryDsl = {
1163
+ bool: {
1164
+ ...(must.length > 0 ? { must } : {}),
1165
+ ...(filter.length > 0 ? { filter } : {}),
1166
+ ...(mustNot.length > 0 ? { must_not: mustNot } : {}),
1167
+ },
1168
+ };
1169
+ }
1170
+
1171
+ const body: Record<string, unknown> = {
1172
+ query: queryDsl,
1173
+ track_total_hits: effectiveSpec.visualization === 'metric' ? true : MAX_RESULT_WINDOW,
1174
+ };
1175
+
1176
+ // Build sort clauses
1177
+ const requestedSorts =
1178
+ effectiveSpec.sort && effectiveSpec.sort.length > 0
1179
+ ? effectiveSpec.sort
1180
+ : timeField
1181
+ ? [{ field: timeField, order: 'desc' as const }]
1182
+ : [];
1183
+
1184
+ if (effectiveSpec.visualization === 'table') {
1185
+ body.size = effectivePageSize;
1186
+
1187
+ if (requestedSorts.length > 0) {
1188
+ const sortClauses: Array<Record<string, unknown>> = requestedSorts.map((sortItem) => {
1189
+ const targetField = resolveAggregatableField(sortItem.field, fieldMap);
1190
+ const unmappedType = resolveUnmappedSortType(targetField, fieldMap);
1191
+ return {
1192
+ [targetField]: {
1193
+ order: sortItem.order,
1194
+ ...(unmappedType ? { unmapped_type: unmappedType } : {}),
1195
+ },
1196
+ };
1197
+ });
1198
+ const hasTieBreaker = requestedSorts.some(
1199
+ (s) => s.field === '_id' || s.field === '_shard_doc' || s.field === '_doc',
1200
+ );
1201
+ const legacyCursorMatchesUserSortOnly =
1202
+ searchAfter !== undefined && searchAfter.length === requestedSorts.length && !hasTieBreaker;
1203
+ if (!hasTieBreaker && !legacyCursorMatchesUserSortOnly) {
1204
+ const tieBreakerField = options.usePit ? '_shard_doc' : '_doc';
1205
+ sortClauses.push({ [tieBreakerField]: { order: 'asc' } });
1206
+ }
1207
+ body.sort = sortClauses;
1208
+ }
1209
+
1210
+ if (searchAfter && body.sort) {
1211
+ body.search_after = searchAfter;
1212
+ } else {
1213
+ const rawFrom = (page - 1) * effectivePageSize;
1214
+ body.from = Math.min(rawFrom, Math.max(0, MAX_RESULT_WINDOW - effectivePageSize));
1215
+ }
1216
+
1217
+ if (effectiveSpec.columns && effectiveSpec.columns.length > 0) {
1218
+ const sourceFields = new Set(effectiveSpec.columns);
1219
+ if (timeField) sourceFields.add(timeField);
1220
+ body._source = Array.from(sourceFields);
1221
+ }
1222
+
1223
+ if (effectiveSpec.query && effectiveSpec.query.trim()) {
1224
+ body.highlight = {
1225
+ pre_tags: [HIGHLIGHT_PRE_TAG],
1226
+ post_tags: [HIGHLIGHT_POST_TAG],
1227
+ fields: { '*': {} },
1228
+ fragment_size: 160,
1229
+ number_of_fragments: 2,
1230
+ };
1231
+ }
1232
+
1233
+ if (timeField && effectiveSpec.chart?.showHistogram !== false) {
1234
+ body.aggs = {
1235
+ es_time_histogram: {
1236
+ auto_date_histogram: {
1237
+ field: timeField,
1238
+ buckets: 24,
1239
+ ...(effectiveTimeZone ? { time_zone: effectiveTimeZone } : {}),
1240
+ },
1241
+ },
1242
+ };
1243
+ }
1244
+ } else if (effectiveSpec.visualization === 'metric') {
1245
+ body.size = 0;
1246
+ const metricType = effectiveSpec.chart?.metricType ?? 'count';
1247
+ const metricDef = buildMetricAggDefinition(metricType, effectiveSpec.chart?.metricField, fieldMap);
1248
+
1249
+ if (useDualPeriodMetric && currentTimeClause && previousTimeClause) {
1250
+ body.aggs = {
1251
+ es_current_window: {
1252
+ filter: currentTimeClause,
1253
+ ...(metricDef ? { aggs: { es_metric: metricDef } } : {}),
1254
+ },
1255
+ es_previous_window: {
1256
+ filter: previousTimeClause,
1257
+ ...(metricDef ? { aggs: { es_metric: metricDef } } : {}),
1258
+ },
1259
+ };
1260
+ } else if (metricDef) {
1261
+ body.aggs = {
1262
+ es_metric: metricDef,
1263
+ };
1264
+ }
1265
+ } else {
1266
+ // Chart visualizations: bar, line, area, pie
1267
+ body.size = 0;
1268
+ const chartCfg = effectiveSpec.chart ?? {};
1269
+ const defaultBucketType: BucketAggType =
1270
+ timeField && (effectiveSpec.visualization === 'line' || effectiveSpec.visualization === 'area')
1271
+ ? 'date_histogram'
1272
+ : chartCfg.bucketType ?? (timeField ? 'date_histogram' : 'terms');
1273
+
1274
+ const rawBucketField =
1275
+ chartCfg.bucketField?.trim() ||
1276
+ (defaultBucketType === 'date_histogram' ? timeField : '') ||
1277
+ Array.from(fieldMap.values()).find((f) => f.aggregatable)?.name ||
1278
+ '_index';
1279
+
1280
+ const bucketField = resolveAggregatableField(rawBucketField, fieldMap);
1281
+ const metricType = chartCfg.metricType ?? 'count';
1282
+ const metricDef = buildMetricAggDefinition(metricType, chartCfg.metricField, fieldMap);
1283
+ const canOrderByMetric = Boolean(metricDef) && metricType !== 'p50' && metricType !== 'p95' && metricType !== 'p99';
1284
+
1285
+ const rawSplitField = chartCfg.splitSeriesField?.trim();
1286
+ const splitField = rawSplitField ? resolveAggregatableField(rawSplitField, fieldMap) : undefined;
1287
+ const splitTopN = clamp(chartCfg.splitSeriesTopN ?? 5, 1, MAX_SPLIT_SERIES);
1288
+
1289
+ const bucketChildAggs: Record<string, unknown> = {};
1290
+ if (metricDef) {
1291
+ bucketChildAggs.es_metric = metricDef;
1292
+ }
1293
+ if (splitField) {
1294
+ bucketChildAggs.es_split = {
1295
+ terms: {
1296
+ field: splitField,
1297
+ size: splitTopN,
1298
+ ...(canOrderByMetric ? { order: { es_metric: 'desc' } } : {}),
1299
+ },
1300
+ ...(metricDef ? { aggs: { es_metric: metricDef } } : {}),
1301
+ };
1302
+ }
1303
+ const hasChildAggs = Object.keys(bucketChildAggs).length > 0;
1304
+
1305
+ if (defaultBucketType === 'date_histogram') {
1306
+ const interval = chartCfg.calendarInterval ?? 'auto';
1307
+ const intervalKey =
1308
+ interval !== 'auto' && CALENDAR_UNIT_INTERVALS.has(interval) ? 'calendar_interval' : 'fixed_interval';
1309
+ const bucketAgg =
1310
+ interval === 'auto'
1311
+ ? {
1312
+ auto_date_histogram: {
1313
+ field: bucketField,
1314
+ buckets: 24,
1315
+ ...(effectiveTimeZone ? { time_zone: effectiveTimeZone } : {}),
1316
+ },
1317
+ }
1318
+ : {
1319
+ date_histogram: {
1320
+ field: bucketField,
1321
+ [intervalKey]: interval,
1322
+ min_doc_count: 0,
1323
+ ...(effectiveTimeZone ? { time_zone: effectiveTimeZone } : {}),
1324
+ },
1325
+ };
1326
+ body.aggs = {
1327
+ es_buckets: {
1328
+ ...bucketAgg,
1329
+ ...(hasChildAggs ? { aggs: bucketChildAggs } : {}),
1330
+ },
1331
+ };
1332
+ } else {
1333
+ const topN = clamp(chartCfg.topN ?? 10, 1, MAX_TERMS_BUCKETS);
1334
+ body.aggs = {
1335
+ es_buckets: {
1336
+ terms: {
1337
+ field: bucketField,
1338
+ size: topN,
1339
+ ...(canOrderByMetric ? { order: { es_metric: 'desc' } } : {}),
1340
+ },
1341
+ ...(hasChildAggs ? { aggs: bucketChildAggs } : {}),
1342
+ },
1343
+ };
1344
+ }
1345
+ }
1346
+
1347
+ return { body, effectiveSpec };
1348
+ }
1349
+
1350
+ function deriveColumns(
1351
+ rows: ReportRowHit[],
1352
+ configuredColumns: string[] | undefined,
1353
+ timeField?: string | null,
1354
+ ): string[] {
1355
+ if (configuredColumns && configuredColumns.length > 0) {
1356
+ return configuredColumns;
1357
+ }
1358
+ const seen = new Set<string>();
1359
+ if (timeField && rows.some((r) => timeField in r.source)) {
1360
+ seen.add(timeField);
1361
+ }
1362
+ for (const row of rows) {
1363
+ for (const key of Object.keys(row.source)) {
1364
+ if (seen.size >= 8) break;
1365
+ seen.add(key);
1366
+ }
1367
+ if (seen.size >= 8) break;
1368
+ }
1369
+ return Array.from(seen);
1370
+ }
1371
+
1372
+ function buildDefaultMetricLabel(spec: ReportSpec): string {
1373
+ if (spec.chart?.metricLabel) return spec.chart.metricLabel;
1374
+ const metricType = spec.chart?.metricType ?? 'count';
1375
+ if (metricType === 'count') return 'Count';
1376
+ const field = spec.chart?.metricField ?? '';
1377
+ return field ? `${metricType.toUpperCase()}(${field})` : metricType.toUpperCase();
1378
+ }
1379
+
1380
+ export function parseSearchResponse(
1381
+ rawResponse: unknown,
1382
+ compiledDsl: Record<string, unknown>,
1383
+ spec: ReportSpec,
1384
+ timeField?: string | null,
1385
+ ): ReportExecutionResult {
1386
+ const res = isRecord(rawResponse) ? rawResponse : {};
1387
+ const tookMs = typeof res.took === 'number' ? res.took : 0;
1388
+ const timedOut = res.timed_out === true;
1389
+ const shards: ReportShardStats | undefined = isRecord(res._shards)
1390
+ ? {
1391
+ total: typeof res._shards.total === 'number' ? res._shards.total : 0,
1392
+ successful: typeof res._shards.successful === 'number' ? res._shards.successful : 0,
1393
+ skipped: typeof res._shards.skipped === 'number' ? res._shards.skipped : 0,
1394
+ failed: typeof res._shards.failed === 'number' ? res._shards.failed : 0,
1395
+ }
1396
+ : undefined;
1397
+ const warnings: string[] = [];
1398
+ if (timedOut) {
1399
+ warnings.push('Elasticsearch query timed out; displayed results may be incomplete.');
1400
+ }
1401
+ if (shards && shards.failed > 0) {
1402
+ warnings.push(`Partial results: ${shards.failed} of ${shards.total} Elasticsearch shards failed.`);
1403
+ }
1404
+
1405
+ const hitsContainer = isRecord(res.hits) ? res.hits : {};
1406
+ const rawTotal = hitsContainer.total;
1407
+ let total = 0;
1408
+ let totalRelation: 'eq' | 'gte' = 'eq';
1409
+ if (typeof rawTotal === 'number') {
1410
+ total = rawTotal;
1411
+ } else if (isRecord(rawTotal)) {
1412
+ total = typeof rawTotal.value === 'number' ? rawTotal.value : 0;
1413
+ totalRelation = rawTotal.relation === 'gte' ? 'gte' : 'eq';
1414
+ }
1415
+
1416
+ const rawHits = Array.isArray(hitsContainer.hits) ? hitsContainer.hits : [];
1417
+ const rows: ReportRowHit[] = rawHits.filter(isRecord).map((hit) => {
1418
+ const source = isRecord(hit._source) ? hit._source : {};
1419
+ let highlights: Record<string, string[]> | undefined;
1420
+ if (isRecord(hit.highlight)) {
1421
+ highlights = {};
1422
+ for (const [hKey, hVal] of Object.entries(hit.highlight)) {
1423
+ if (Array.isArray(hVal)) {
1424
+ highlights[hKey] = hVal.filter((v): v is string => typeof v === 'string');
1425
+ }
1426
+ }
1427
+ }
1428
+ const sortArr = Array.isArray(hit.sort)
1429
+ ? hit.sort.map((s) =>
1430
+ typeof s === 'string' || typeof s === 'number' || typeof s === 'boolean' || s === null ? s : String(s),
1431
+ )
1432
+ : undefined;
1433
+ return {
1434
+ _id: typeof hit._id === 'string' ? hit._id : String(hit._id ?? ''),
1435
+ _index: typeof hit._index === 'string' ? hit._index : String(hit._index ?? ''),
1436
+ _score: typeof hit._score === 'number' ? hit._score : null,
1437
+ ...(sortArr ? { _sort: sortArr } : {}),
1438
+ source,
1439
+ ...(highlights ? { highlights } : {}),
1440
+ };
1441
+ });
1442
+
1443
+ const lastRow = rows.length > 0 ? rows[rows.length - 1] : undefined;
1444
+ const nextSearchAfter = lastRow?._sort && lastRow._sort.length > 0 ? lastRow._sort : undefined;
1445
+ const columns = deriveColumns(rows, spec.columns, timeField);
1446
+
1447
+ const aggs = isRecord(res.aggregations) ? res.aggregations : {};
1448
+ const histogram: ReportHistogramBucket[] = [];
1449
+ if (isRecord(aggs.es_time_histogram) && Array.isArray(aggs.es_time_histogram.buckets)) {
1450
+ for (const bucket of aggs.es_time_histogram.buckets) {
1451
+ if (!isRecord(bucket)) continue;
1452
+ const key = typeof bucket.key_as_string === 'string' ? bucket.key_as_string : String(bucket.key ?? '');
1453
+ histogram.push({
1454
+ key,
1455
+ ...(typeof bucket.key === 'number' ? { timestamp: bucket.key } : {}),
1456
+ count: typeof bucket.doc_count === 'number' ? bucket.doc_count : 0,
1457
+ });
1458
+ }
1459
+ }
1460
+
1461
+ const metricType = spec.chart?.metricType ?? 'count';
1462
+ const series: ReportSeriesPoint[] = [];
1463
+ const seenSeriesKeys = new Set<string>();
1464
+ if (isRecord(aggs.es_buckets) && Array.isArray(aggs.es_buckets.buckets)) {
1465
+ for (const bucket of aggs.es_buckets.buckets) {
1466
+ if (!isRecord(bucket)) continue;
1467
+ const label = typeof bucket.key_as_string === 'string' ? bucket.key_as_string : String(bucket.key ?? '');
1468
+ const docCount = typeof bucket.doc_count === 'number' ? bucket.doc_count : 0;
1469
+ const extracted = extractMetricValue(bucket.es_metric, metricType, docCount);
1470
+ const metricVal = extracted ?? docCount;
1471
+
1472
+ let breakdown: ReportSubSeriesPoint[] | undefined;
1473
+ if (isRecord(bucket.es_split) && Array.isArray(bucket.es_split.buckets)) {
1474
+ breakdown = [];
1475
+ for (const sub of bucket.es_split.buckets) {
1476
+ if (!isRecord(sub)) continue;
1477
+ const sKey = typeof sub.key_as_string === 'string' ? sub.key_as_string : String(sub.key ?? '');
1478
+ const sCount = typeof sub.doc_count === 'number' ? sub.doc_count : 0;
1479
+ const sVal = extractMetricValue(sub.es_metric, metricType, sCount) ?? sCount;
1480
+ seenSeriesKeys.add(sKey);
1481
+ breakdown.push({
1482
+ seriesKey: sKey,
1483
+ value: sVal,
1484
+ count: sCount,
1485
+ });
1486
+ }
1487
+ }
1488
+
1489
+ series.push({
1490
+ key: String(bucket.key ?? label),
1491
+ label,
1492
+ value: metricVal,
1493
+ count: docCount,
1494
+ ...(breakdown ? { breakdown } : {}),
1495
+ });
1496
+ }
1497
+ }
1498
+
1499
+ let metricValue: number | null = null;
1500
+ let previousMetricValue: number | null | undefined;
1501
+ let deltaPercent: number | null | undefined;
1502
+
1503
+ if (spec.visualization === 'metric') {
1504
+ if (isRecord(aggs.es_current_window) && isRecord(aggs.es_previous_window)) {
1505
+ const curCount = typeof aggs.es_current_window.doc_count === 'number' ? aggs.es_current_window.doc_count : 0;
1506
+ const prevCount = typeof aggs.es_previous_window.doc_count === 'number' ? aggs.es_previous_window.doc_count : 0;
1507
+ total = curCount;
1508
+ totalRelation = 'eq';
1509
+ metricValue =
1510
+ metricType === 'count' || !spec.chart?.metricField
1511
+ ? curCount
1512
+ : extractMetricValue(aggs.es_current_window.es_metric, metricType, curCount);
1513
+ previousMetricValue =
1514
+ metricType === 'count' || !spec.chart?.metricField
1515
+ ? prevCount
1516
+ : extractMetricValue(aggs.es_previous_window.es_metric, metricType, prevCount);
1517
+ if (metricValue !== null && previousMetricValue !== null && previousMetricValue !== 0) {
1518
+ deltaPercent = Number((((metricValue - previousMetricValue) / Math.abs(previousMetricValue)) * 100).toFixed(2));
1519
+ } else {
1520
+ deltaPercent = null;
1521
+ }
1522
+ } else if (metricType === 'count' || !spec.chart?.metricField) {
1523
+ metricValue = total;
1524
+ } else {
1525
+ metricValue = extractMetricValue(aggs.es_metric, metricType, total);
1526
+ }
1527
+ }
1528
+
1529
+ const responsePitId = typeof res.pit_id === 'string' && res.pit_id ? res.pit_id : undefined;
1530
+
1531
+ return {
1532
+ total,
1533
+ totalRelation,
1534
+ tookMs,
1535
+ ...(timedOut ? { timedOut: true } : {}),
1536
+ ...(shards ? { shards } : {}),
1537
+ ...(warnings.length > 0 ? { warnings } : {}),
1538
+ visualization: spec.visualization,
1539
+ rows,
1540
+ columns,
1541
+ ...(nextSearchAfter ? { nextSearchAfter } : {}),
1542
+ ...(responsePitId ? { pitId: responsePitId } : {}),
1543
+ series,
1544
+ ...(seenSeriesKeys.size > 0 ? { seriesKeys: Array.from(seenSeriesKeys) } : {}),
1545
+ histogram,
1546
+ metricValue,
1547
+ ...(previousMetricValue !== undefined ? { previousMetricValue } : {}),
1548
+ ...(deltaPercent !== undefined ? { deltaPercent } : {}),
1549
+ metricLabel: buildDefaultMetricLabel(spec),
1550
+ compiledDsl,
1551
+ };
1552
+ }