@mhjuma/traverse 0.1.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 (90) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +46 -0
  3. package/src/bootstrap.spec.tsx +290 -0
  4. package/src/bootstrap.tsx +195 -0
  5. package/src/colors.ts +23 -0
  6. package/src/components/ChartPanel/ChartPanel.logic.spec.ts +358 -0
  7. package/src/components/ChartPanel/ChartPanel.logic.ts +318 -0
  8. package/src/components/ChartPanel/ChartPanel.spec.tsx +331 -0
  9. package/src/components/ChartPanel/ChartPanel.styles.ts +14 -0
  10. package/src/components/ChartPanel/ChartPanel.tsx +151 -0
  11. package/src/components/ConnectionDialog/ConnectionDialog.spec.tsx +767 -0
  12. package/src/components/ConnectionDialog/ConnectionDialog.tsx +652 -0
  13. package/src/components/ConnectionDialog/ConnectionRow.spec.tsx +104 -0
  14. package/src/components/ConnectionDialog/ConnectionRow.tsx +177 -0
  15. package/src/components/EditorToolbar/EditorToolbar.spec.tsx +599 -0
  16. package/src/components/EditorToolbar/EditorToolbar.tsx +259 -0
  17. package/src/components/Explorer/Explorer.spec.tsx +615 -0
  18. package/src/components/Explorer/Explorer.tsx +49 -0
  19. package/src/components/ExplorerWorkspace/ExplorerWorkspace.logic.spec.ts +715 -0
  20. package/src/components/ExplorerWorkspace/ExplorerWorkspace.logic.ts +324 -0
  21. package/src/components/ExplorerWorkspace/ExplorerWorkspace.spec.tsx +450 -0
  22. package/src/components/ExplorerWorkspace/ExplorerWorkspace.styles.ts +478 -0
  23. package/src/components/ExplorerWorkspace/ExplorerWorkspace.tsx +648 -0
  24. package/src/components/ExplorerWorkspace/kqlLanguage.spec.ts +321 -0
  25. package/src/components/ExplorerWorkspace/kqlLanguage.ts +155 -0
  26. package/src/components/ResultsPanel/ElapsedTimer.spec.tsx +51 -0
  27. package/src/components/ResultsPanel/ElapsedTimer.tsx +15 -0
  28. package/src/components/ResultsPanel/HistoryItem.spec.tsx +123 -0
  29. package/src/components/ResultsPanel/HistoryItem.tsx +56 -0
  30. package/src/components/ResultsPanel/ResultSetTab.tsx +18 -0
  31. package/src/components/ResultsPanel/ResultsPanel.spec.tsx +1194 -0
  32. package/src/components/ResultsPanel/ResultsPanel.tsx +321 -0
  33. package/src/components/ResultsPanel/TabButton.tsx +11 -0
  34. package/src/components/ResultsTable/ColumnHeader.tsx +42 -0
  35. package/src/components/ResultsTable/ColumnPickerItem.tsx +16 -0
  36. package/src/components/ResultsTable/FilterCell.tsx +24 -0
  37. package/src/components/ResultsTable/ResultsTable.logic.spec.ts +655 -0
  38. package/src/components/ResultsTable/ResultsTable.logic.ts +264 -0
  39. package/src/components/ResultsTable/ResultsTable.spec.tsx +930 -0
  40. package/src/components/ResultsTable/ResultsTable.styles.ts +108 -0
  41. package/src/components/ResultsTable/ResultsTable.tsx +501 -0
  42. package/src/components/ResultsTable/VirtualCell.spec.tsx +55 -0
  43. package/src/components/ResultsTable/VirtualCell.tsx +32 -0
  44. package/src/components/ResultsTable/VirtualRow.tsx +55 -0
  45. package/src/components/SchemaSidebar/FolderRow.tsx +35 -0
  46. package/src/components/SchemaSidebar/SchemaColumnItem.tsx +41 -0
  47. package/src/components/SchemaSidebar/SchemaContextMenu.spec.tsx +148 -0
  48. package/src/components/SchemaSidebar/SchemaContextMenu.tsx +49 -0
  49. package/src/components/SchemaSidebar/SchemaSidebar.logic.spec.ts +230 -0
  50. package/src/components/SchemaSidebar/SchemaSidebar.logic.ts +74 -0
  51. package/src/components/SchemaSidebar/SchemaSidebar.spec.tsx +1111 -0
  52. package/src/components/SchemaSidebar/SchemaSidebar.tsx +244 -0
  53. package/src/components/SchemaSidebar/SchemaTableItem.tsx +77 -0
  54. package/src/components/TabBar/TabBar.logic.spec.ts +127 -0
  55. package/src/components/TabBar/TabBar.logic.ts +35 -0
  56. package/src/components/TabBar/TabBar.spec.tsx +929 -0
  57. package/src/components/TabBar/TabBar.tsx +284 -0
  58. package/src/components/TabBar/TabItem.tsx +166 -0
  59. package/src/components/VegaChart/VegaChart.spec.tsx +126 -0
  60. package/src/components/VegaChart/VegaChart.tsx +224 -0
  61. package/src/config.spec.ts +44 -0
  62. package/src/config.ts +47 -0
  63. package/src/context/ExplorerColorContext.ts +14 -0
  64. package/src/context/ExplorerStateContext.ts +49 -0
  65. package/src/context/KustoClientContext.ts +12 -0
  66. package/src/context/context.spec.tsx +183 -0
  67. package/src/index.ts +14 -0
  68. package/src/services/cache.spec.ts +31 -0
  69. package/src/services/cache.ts +16 -0
  70. package/src/services/concurrency.spec.ts +139 -0
  71. package/src/services/concurrency.ts +46 -0
  72. package/src/services/kusto.spec.ts +919 -0
  73. package/src/services/kusto.ts +472 -0
  74. package/src/services/queryHistory.spec.ts +287 -0
  75. package/src/services/queryHistory.ts +146 -0
  76. package/src/services/schema.spec.ts +618 -0
  77. package/src/services/schema.ts +294 -0
  78. package/src/services/state-service.spec.ts +670 -0
  79. package/src/services/state-service.ts +602 -0
  80. package/src/services/useKustoQuery.spec.ts +234 -0
  81. package/src/services/useKustoQuery.ts +124 -0
  82. package/src/state/actions.ts +50 -0
  83. package/src/state/index.ts +3 -0
  84. package/src/state/reducer.spec.ts +644 -0
  85. package/src/state/reducer.ts +207 -0
  86. package/src/state/types.ts +54 -0
  87. package/tsconfig.json +7 -0
  88. package/tsconfig.lint.json +4 -0
  89. package/tsconfig.spec.json +7 -0
  90. package/vitest.config.ts +34 -0
@@ -0,0 +1,919 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+
3
+ import { extractStats, createKustoClient, parseVisualizationMetadata, buildResultSets } from './kusto';
4
+ import type { QueryStats, KustoClient, KustoStateService, RawTable, KustoVisualization } from './kusto';
5
+
6
+ const KUSTO_CLUSTER = 'https://test-kusto.kusto.windows.net';
7
+ const KUSTO_DATABASE = 'TestDB';
8
+
9
+ function createMockStateService(): KustoStateService {
10
+ const stores = new Map<string, Map<string, unknown>>();
11
+ return {
12
+ get<T>(store: string, key: string): T | null {
13
+ return (stores.get(store)?.get(key) as T) ?? null;
14
+ },
15
+ set<T>(store: string, key: string, value: T): void {
16
+ if (!stores.has(store)) {
17
+ stores.set(store, new Map());
18
+ }
19
+ stores.get(store)!.set(key, value);
20
+ },
21
+ clear(store: string): void {
22
+ stores.get(store)?.clear();
23
+ },
24
+ entryCount(store: string): number {
25
+ return stores.get(store)?.size ?? 0;
26
+ },
27
+ };
28
+ }
29
+
30
+ function createTestClient(): { client: KustoClient; stateService: KustoStateService } {
31
+ const stateService = createMockStateService();
32
+ const client = createKustoClient({
33
+ defaultTarget: { clusterUrl: KUSTO_CLUSTER, database: KUSTO_DATABASE },
34
+ getToken: vi.fn().mockResolvedValue('mock-kusto-token'),
35
+ stateService,
36
+ });
37
+ return { client, stateService };
38
+ }
39
+
40
+ // Helper to build a minimal Kusto v1 response body
41
+ function makeKustoResponse(
42
+ primaryRows: unknown[][] = [],
43
+ primaryColumns: { ColumnName: string; ColumnType?: string }[] = [{ ColumnName: 'Col1', ColumnType: 'string' }],
44
+ extraTables: { Columns: { ColumnName: string }[]; Rows: unknown[][] }[] = [],
45
+ ) {
46
+ const toc = {
47
+ Columns: [
48
+ { ColumnName: 'Ordinal' },
49
+ { ColumnName: 'Kind' },
50
+ { ColumnName: 'Name' },
51
+ ],
52
+ Rows: [[0, 'QueryResult', 'PrimaryResult']],
53
+ };
54
+
55
+ return {
56
+ Tables: [
57
+ { Columns: primaryColumns, Rows: primaryRows },
58
+ ...extraTables,
59
+ toc,
60
+ ],
61
+ };
62
+ }
63
+
64
+ function stubFetch(body: unknown, ok = true, status = 200): void {
65
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
66
+ ok,
67
+ status,
68
+ json: () => Promise.resolve(body),
69
+ text: () => Promise.resolve(JSON.stringify(body)),
70
+ }));
71
+ }
72
+
73
+ describe('extractStats', () => {
74
+ it('returns empty stats when no matching tables exist', () => {
75
+ const tables = [
76
+ { Columns: [{ ColumnName: 'Col1' }], Rows: [['val']] },
77
+ ];
78
+ const stats = extractStats(tables);
79
+ expect(stats).toEqual({});
80
+ });
81
+
82
+ it('extracts executionTime from numeric ExecutionTime', () => {
83
+ const payload = { ExecutionTime: 0.5 };
84
+ const tables = [
85
+ { Columns: [{ ColumnName: 'Col1' }], Rows: [] },
86
+ {
87
+ Columns: [{ ColumnName: 'SeverityName' }, { ColumnName: 'StatusDescription' }],
88
+ Rows: [['Stats', JSON.stringify(payload)]],
89
+ },
90
+ ];
91
+ const stats = extractStats(tables);
92
+ expect(stats.executionTime).toBe('500.0 ms');
93
+ });
94
+
95
+ it('extracts executionTime from string ExecutionTime', () => {
96
+ const payload = { ExecutionTime: '00:00:01.234' };
97
+ const tables = [
98
+ { Columns: [{ ColumnName: 'Col1' }], Rows: [] },
99
+ {
100
+ Columns: [{ ColumnName: 'SeverityName' }, { ColumnName: 'StatusDescription' }],
101
+ Rows: [['Stats', JSON.stringify(payload)]],
102
+ },
103
+ ];
104
+ const stats = extractStats(tables);
105
+ expect(stats.executionTime).toBe('00:00:01.234');
106
+ });
107
+
108
+ it('extracts resource_usage cpu and memory', () => {
109
+ const payload = {
110
+ ExecutionTime: null,
111
+ resource_usage: {
112
+ cpu: { 'total cpu': '00:00:02.000' },
113
+ memory: { peak_per_node: 1024 },
114
+ },
115
+ };
116
+ const tables = [
117
+ { Columns: [{ ColumnName: 'Col1' }], Rows: [] },
118
+ {
119
+ Columns: [{ ColumnName: 'SeverityName' }, { ColumnName: 'StatusDescription' }],
120
+ Rows: [['Stats', JSON.stringify(payload)]],
121
+ },
122
+ ];
123
+ const stats = extractStats(tables);
124
+ expect(stats.cpuTime).toBe('00:00:02.000');
125
+ expect(stats.memoryPeak).toBe(1024);
126
+ });
127
+
128
+ it('extracts cache shard hit/miss bytes', () => {
129
+ const payload = {
130
+ ExecutionTime: null,
131
+ resource_usage: {
132
+ cache: {
133
+ shards: {
134
+ hot: { hitbytes: 100, missbytes: 10 },
135
+ cold: { hitbytes: 50, missbytes: 5 },
136
+ },
137
+ },
138
+ },
139
+ };
140
+ const tables = [
141
+ { Columns: [{ ColumnName: 'Col1' }], Rows: [] },
142
+ {
143
+ Columns: [{ ColumnName: 'SeverityName' }, { ColumnName: 'StatusDescription' }],
144
+ Rows: [['Stats', JSON.stringify(payload)]],
145
+ },
146
+ ];
147
+ const stats = extractStats(tables);
148
+ expect(stats.cacheHitBytes).toBe(150);
149
+ expect(stats.cacheMissBytes).toBe(15);
150
+ });
151
+
152
+ it('detects results_cache_origin as fromCache', () => {
153
+ const payload = {
154
+ ExecutionTime: null,
155
+ resource_usage: {
156
+ cache: { results_cache_origin: 'hit' },
157
+ },
158
+ };
159
+ const tables = [
160
+ { Columns: [{ ColumnName: 'Col1' }], Rows: [] },
161
+ {
162
+ Columns: [{ ColumnName: 'SeverityName' }, { ColumnName: 'StatusDescription' }],
163
+ Rows: [['Stats', JSON.stringify(payload)]],
164
+ },
165
+ ];
166
+ const stats = extractStats(tables);
167
+ expect(stats.fromCache).toBe(true);
168
+ });
169
+
170
+ it('extracts input_dataset_statistics extents and rows', () => {
171
+ const payload = {
172
+ ExecutionTime: null,
173
+ input_dataset_statistics: {
174
+ extents: { scanned: 10, total: 100 },
175
+ rows: { scanned: 500, total: 5000 },
176
+ },
177
+ };
178
+ const tables = [
179
+ { Columns: [{ ColumnName: 'Col1' }], Rows: [] },
180
+ {
181
+ Columns: [{ ColumnName: 'SeverityName' }, { ColumnName: 'StatusDescription' }],
182
+ Rows: [['Stats', JSON.stringify(payload)]],
183
+ },
184
+ ];
185
+ const stats = extractStats(tables);
186
+ expect(stats.extentsScanned).toBe(10);
187
+ expect(stats.extentsTotal).toBe(100);
188
+ expect(stats.rowsScanned).toBe(500);
189
+ expect(stats.rowsTotal).toBe(5000);
190
+ });
191
+
192
+ it('extracts dataset_statistics result size', () => {
193
+ const payload = {
194
+ ExecutionTime: null,
195
+ dataset_statistics: [{ table_row_count: 42, table_size: 1024 }],
196
+ };
197
+ const tables = [
198
+ { Columns: [{ ColumnName: 'Col1' }], Rows: [] },
199
+ {
200
+ Columns: [{ ColumnName: 'SeverityName' }, { ColumnName: 'StatusDescription' }],
201
+ Rows: [['Stats', JSON.stringify(payload)]],
202
+ },
203
+ ];
204
+ const stats = extractStats(tables);
205
+ expect(stats.resultRows).toBe(42);
206
+ expect(stats.resultSize).toBe(1024);
207
+ });
208
+
209
+ it('handles malformed JSON in StatusDescription gracefully', () => {
210
+ const tables = [
211
+ { Columns: [{ ColumnName: 'Col1' }], Rows: [] },
212
+ {
213
+ Columns: [{ ColumnName: 'SeverityName' }, { ColumnName: 'StatusDescription' }],
214
+ Rows: [['Stats', 'not-json']],
215
+ },
216
+ ];
217
+ const stats = extractStats(tables);
218
+ expect(stats).toEqual({});
219
+ });
220
+
221
+ it('skips non-Stats severity rows', () => {
222
+ const tables = [
223
+ { Columns: [{ ColumnName: 'Col1' }], Rows: [] },
224
+ {
225
+ Columns: [{ ColumnName: 'SeverityName' }, { ColumnName: 'StatusDescription' }],
226
+ Rows: [
227
+ ['Info', JSON.stringify({ ExecutionTime: 999 })],
228
+ ],
229
+ },
230
+ ];
231
+ const stats = extractStats(tables);
232
+ expect(stats.executionTime).toBeUndefined();
233
+ });
234
+
235
+ it('skips rows where StatusDescription is not a string', () => {
236
+ const tables = [
237
+ { Columns: [{ ColumnName: 'Col1' }], Rows: [] },
238
+ {
239
+ Columns: [{ ColumnName: 'SeverityName' }, { ColumnName: 'StatusDescription' }],
240
+ Rows: [['Stats', 42]],
241
+ },
242
+ ];
243
+ const stats = extractStats(tables);
244
+ expect(stats).toEqual({});
245
+ });
246
+
247
+ it('handles cache shards without cold data', () => {
248
+ const payload = {
249
+ ExecutionTime: null,
250
+ resource_usage: {
251
+ cache: {
252
+ shards: {
253
+ hot: { hitbytes: 200, missbytes: 20 },
254
+ },
255
+ },
256
+ },
257
+ };
258
+ const tables = [
259
+ { Columns: [{ ColumnName: 'Col1' }], Rows: [] },
260
+ {
261
+ Columns: [{ ColumnName: 'SeverityName' }, { ColumnName: 'StatusDescription' }],
262
+ Rows: [['Stats', JSON.stringify(payload)]],
263
+ },
264
+ ];
265
+ const stats = extractStats(tables);
266
+ expect(stats.cacheHitBytes).toBe(200);
267
+ expect(stats.cacheMissBytes).toBe(20);
268
+ });
269
+
270
+ it('handles empty dataset_statistics array', () => {
271
+ const payload = {
272
+ ExecutionTime: null,
273
+ dataset_statistics: [],
274
+ };
275
+ const tables = [
276
+ { Columns: [{ ColumnName: 'Col1' }], Rows: [] },
277
+ {
278
+ Columns: [{ ColumnName: 'SeverityName' }, { ColumnName: 'StatusDescription' }],
279
+ Rows: [['Stats', JSON.stringify(payload)]],
280
+ },
281
+ ];
282
+ const stats = extractStats(tables);
283
+ expect(stats.resultRows).toBeUndefined();
284
+ expect(stats.resultSize).toBeUndefined();
285
+ });
286
+
287
+ it('extracts a comprehensive stats object with all fields', () => {
288
+ const payload = {
289
+ ExecutionTime: 0.123,
290
+ resource_usage: {
291
+ cpu: { 'total cpu': '00:00:05.000' },
292
+ memory: { peak_per_node: 2048 },
293
+ cache: {
294
+ shards: {
295
+ hot: { hitbytes: 300, missbytes: 30 },
296
+ cold: { hitbytes: 100, missbytes: 10 },
297
+ },
298
+ results_cache_origin: 'partial',
299
+ },
300
+ },
301
+ input_dataset_statistics: {
302
+ extents: { scanned: 5, total: 50 },
303
+ rows: { scanned: 1000, total: 10000 },
304
+ },
305
+ dataset_statistics: [{ table_row_count: 100, table_size: 4096 }],
306
+ };
307
+ const tables = [
308
+ { Columns: [{ ColumnName: 'Col1' }], Rows: [] },
309
+ {
310
+ Columns: [{ ColumnName: 'SeverityName' }, { ColumnName: 'StatusDescription' }],
311
+ Rows: [['Stats', JSON.stringify(payload)]],
312
+ },
313
+ ];
314
+ const stats: QueryStats = extractStats(tables);
315
+ expect(stats.executionTime).toBe('123.0 ms');
316
+ expect(stats.cpuTime).toBe('00:00:05.000');
317
+ expect(stats.memoryPeak).toBe(2048);
318
+ expect(stats.cacheHitBytes).toBe(400);
319
+ expect(stats.cacheMissBytes).toBe(40);
320
+ expect(stats.fromCache).toBe(true);
321
+ expect(stats.extentsScanned).toBe(5);
322
+ expect(stats.extentsTotal).toBe(50);
323
+ expect(stats.rowsScanned).toBe(1000);
324
+ expect(stats.rowsTotal).toBe(10000);
325
+ expect(stats.resultRows).toBe(100);
326
+ expect(stats.resultSize).toBe(4096);
327
+ });
328
+ });
329
+
330
+ describe('clearQueryCache / getQueryCacheSize', () => {
331
+ it('reports 0 after clearing', () => {
332
+ const { client } = createTestClient();
333
+ client.clearQueryCache();
334
+ expect(client.getQueryCacheSize()).toBe(0);
335
+ });
336
+ });
337
+
338
+ describe('queryKusto', () => {
339
+ let client: KustoClient;
340
+
341
+ beforeEach(() => {
342
+ vi.useFakeTimers();
343
+ ({ client } = createTestClient());
344
+ });
345
+
346
+ afterEach(() => {
347
+ vi.useRealTimers();
348
+ vi.restoreAllMocks();
349
+ });
350
+
351
+ it('sends a POST request and parses primary result set', async () => {
352
+ const body = makeKustoResponse(
353
+ [['hello', 1]],
354
+ [
355
+ { ColumnName: 'Name', ColumnType: 'string' },
356
+ { ColumnName: 'Value', ColumnType: 'int' },
357
+ ],
358
+ );
359
+ stubFetch(body);
360
+
361
+ const result = await client.queryKusto('TestTable | take 1');
362
+
363
+ expect(result.columns).toHaveLength(2);
364
+ expect(result.columns[0].ColumnName).toBe('Name');
365
+ expect(result.rows).toHaveLength(1);
366
+ expect(result.rows[0]).toEqual({ Name: 'hello', Value: 1 });
367
+ expect(result.resultSets).toHaveLength(1);
368
+ });
369
+
370
+ it('uses cached result on second call', async () => {
371
+ const body = makeKustoResponse([['a']]);
372
+ stubFetch(body);
373
+
374
+ const result1 = await client.queryKusto('cached query');
375
+ const result2 = await client.queryKusto('cached query');
376
+
377
+ expect(result1).toStrictEqual(result2);
378
+ expect(fetch).toHaveBeenCalledTimes(1);
379
+ });
380
+
381
+ it('bypasses cached results and disables server-side query caching when requested', async () => {
382
+ const body = makeKustoResponse([['fresh']]);
383
+ stubFetch(body);
384
+
385
+ await client.queryKusto('fresh query');
386
+ await client.queryKusto('fresh query', undefined, undefined, undefined, { bypassCache: true });
387
+
388
+ expect(fetch).toHaveBeenCalledTimes(2);
389
+ const fetchBody = JSON.parse(vi.mocked(fetch).mock.calls[1][1]?.body as string);
390
+ expect(JSON.parse(fetchBody.properties).Options.query_results_cache_max_age).toBe('00:00:00');
391
+ });
392
+
393
+ it('deduplicates concurrent identical queries', async () => {
394
+ const body = makeKustoResponse([['a']]);
395
+ stubFetch(body);
396
+
397
+ const [r1, r2] = await Promise.all([
398
+ client.queryKusto('dedup query'),
399
+ client.queryKusto('dedup query'),
400
+ ]);
401
+
402
+ expect(r1).toBe(r2);
403
+ expect(fetch).toHaveBeenCalledTimes(1);
404
+ });
405
+
406
+ it('throws on non-ok response', async () => {
407
+ stubFetch({ error: 'bad' }, false, 400);
408
+
409
+ await expect(client.queryKusto('bad query')).rejects.toThrow('Kusto query failed: 400');
410
+ });
411
+
412
+ it('retries on 429 with exponential backoff', async () => {
413
+ const body = makeKustoResponse([['ok']]);
414
+ const mockFetch = vi.fn()
415
+ .mockResolvedValueOnce({ ok: false, status: 429, text: () => Promise.resolve('throttled') })
416
+ .mockResolvedValueOnce({
417
+ ok: true,
418
+ status: 200,
419
+ json: () => Promise.resolve(body),
420
+ text: () => Promise.resolve(JSON.stringify(body)),
421
+ });
422
+ vi.stubGlobal('fetch', mockFetch);
423
+
424
+ const promise = client.queryKusto('retry query');
425
+ // Advance timers for the retry delay
426
+ await vi.advanceTimersByTimeAsync(2000);
427
+ const result = await promise;
428
+
429
+ expect(result.rows).toHaveLength(1);
430
+ expect(mockFetch).toHaveBeenCalledTimes(2);
431
+ });
432
+
433
+ it('includes auth header in request', async () => {
434
+ const body = makeKustoResponse([]);
435
+ stubFetch(body);
436
+
437
+ await client.queryKusto('auth check');
438
+
439
+ const fetchCall = vi.mocked(fetch).mock.calls[0];
440
+ expect(fetchCall[0]).toContain('/v1/rest/query');
441
+ expect((fetchCall[1]!.headers as Record<string, string>)['Authorization']).toBe('Bearer mock-kusto-token');
442
+ });
443
+
444
+ it('falls back to index 0 when TOC has no QueryResult kind', async () => {
445
+ const body = {
446
+ Tables: [
447
+ {
448
+ Columns: [{ ColumnName: 'A', ColumnType: 'string' }],
449
+ Rows: [['val']],
450
+ },
451
+ {
452
+ Columns: [{ ColumnName: 'X' }],
453
+ Rows: [],
454
+ },
455
+ ],
456
+ };
457
+ stubFetch(body);
458
+
459
+ const result = await client.queryKusto('no-toc query');
460
+ expect(result.rows).toHaveLength(1);
461
+ expect(result.rows[0]).toEqual({ A: 'val' });
462
+ });
463
+
464
+ it('extracts stats when response has multiple tables', async () => {
465
+ const statsPayload = { ExecutionTime: 0.05, dataset_statistics: [{ table_row_count: 1, table_size: 64 }] };
466
+ const body = {
467
+ Tables: [
468
+ { Columns: [{ ColumnName: 'A', ColumnType: 'string' }], Rows: [['v']] },
469
+ {
470
+ Columns: [{ ColumnName: 'SeverityName' }, { ColumnName: 'StatusDescription' }],
471
+ Rows: [['Stats', JSON.stringify(statsPayload)]],
472
+ },
473
+ {
474
+ Columns: [{ ColumnName: 'Ordinal' }, { ColumnName: 'Kind' }, { ColumnName: 'Name' }],
475
+ Rows: [[0, 'QueryResult', 'PrimaryResult']],
476
+ },
477
+ ],
478
+ };
479
+ stubFetch(body);
480
+
481
+ const result = await client.queryKusto('stats query');
482
+ expect(result.stats).toBeDefined();
483
+ expect(result.stats?.executionTime).toBe('50.0 ms');
484
+ });
485
+ });
486
+
487
+ describe('queryKustoMgmt', () => {
488
+ let client: KustoClient;
489
+
490
+ beforeEach(() => {
491
+ vi.useFakeTimers();
492
+ ({ client } = createTestClient());
493
+ });
494
+
495
+ afterEach(() => {
496
+ vi.useRealTimers();
497
+ vi.restoreAllMocks();
498
+ });
499
+
500
+ it('sends request to mgmt endpoint and parses result', async () => {
501
+ const body = {
502
+ Tables: [{
503
+ Columns: [
504
+ { ColumnName: 'TableName', ColumnType: 'string' },
505
+ { ColumnName: 'Count', ColumnType: 'long' },
506
+ ],
507
+ Rows: [['MyTable', 42]],
508
+ }],
509
+ };
510
+ stubFetch(body);
511
+
512
+ const result = await client.queryKustoMgmt('.show tables');
513
+
514
+ expect(result.columns).toHaveLength(2);
515
+ expect(result.rows).toHaveLength(1);
516
+ expect(result.rows[0]).toEqual({ TableName: 'MyTable', Count: 42 });
517
+ expect(result.resultSets).toHaveLength(1);
518
+ });
519
+
520
+ it('uses cached mgmt result on second call', async () => {
521
+ const body = {
522
+ Tables: [{
523
+ Columns: [{ ColumnName: 'A', ColumnType: 'string' }],
524
+ Rows: [['cached']],
525
+ }],
526
+ };
527
+ stubFetch(body);
528
+
529
+ const r1 = await client.queryKustoMgmt('.show databases');
530
+ const r2 = await client.queryKustoMgmt('.show databases');
531
+
532
+ expect(r1).toStrictEqual(r2);
533
+ expect(fetch).toHaveBeenCalledTimes(1);
534
+ });
535
+
536
+ it('throws on non-ok response', async () => {
537
+ stubFetch({ error: 'fail' }, false, 500);
538
+
539
+ await expect(client.queryKustoMgmt('.bad command')).rejects.toThrow('Kusto mgmt command failed: 500');
540
+ });
541
+
542
+ it('sends request to /v1/rest/mgmt', async () => {
543
+ const body = {
544
+ Tables: [{
545
+ Columns: [{ ColumnName: 'A', ColumnType: 'string' }],
546
+ Rows: [],
547
+ }],
548
+ };
549
+ stubFetch(body);
550
+
551
+ await client.queryKustoMgmt('.show version');
552
+
553
+ const fetchCall = vi.mocked(fetch).mock.calls[0];
554
+ expect(fetchCall[0]).toContain('/v1/rest/mgmt');
555
+ });
556
+
557
+ it('uses custom target cluster and database', async () => {
558
+
559
+ const body = {
560
+ Tables: [{
561
+ Columns: [{ ColumnName: 'Val', ColumnType: 'string' }],
562
+ Rows: [['ok']],
563
+ }],
564
+ };
565
+ stubFetch(body);
566
+
567
+ const target = { clusterUrl: 'https://custom.westus2.kusto.windows.net', database: 'CustomDB' };
568
+ await client.queryKustoMgmt('.show tables', target);
569
+
570
+ const fetchCall = vi.mocked(fetch).mock.calls[0];
571
+ expect(fetchCall[0]).toContain('custom.westus2.kusto.windows.net/v1/rest/mgmt');
572
+ const fetchBody = JSON.parse(fetchCall[1]?.body as string);
573
+ expect(fetchBody.db).toBe('CustomDB');
574
+ });
575
+ });
576
+
577
+ // ---------------------------------------------------------------------------
578
+ // parseVisualizationMetadata
579
+ // ---------------------------------------------------------------------------
580
+
581
+ describe('parseVisualizationMetadata', () => {
582
+ function makeTocTable(rows: unknown[][]): RawTable {
583
+ return {
584
+ Columns: [
585
+ { ColumnName: 'Ordinal' },
586
+ { ColumnName: 'Kind' },
587
+ { ColumnName: 'Name' },
588
+ ],
589
+ Rows: rows,
590
+ };
591
+ }
592
+
593
+ it('returns empty map when TOC has no QueryProperties', () => {
594
+ const tocTable = makeTocTable([[0, 'QueryResult', 'PrimaryResult']]);
595
+ const allTables: RawTable[] = [
596
+ { Columns: [{ ColumnName: 'A' }], Rows: [['val']] },
597
+ tocTable,
598
+ ];
599
+
600
+ const result = parseVisualizationMetadata(allTables, tocTable, [0]);
601
+ expect(result.size).toBe(0);
602
+ });
603
+
604
+ it('parses valid visualization JSON from QueryProperties', () => {
605
+ const vizJson = JSON.stringify({ Visualization: 'barchart', XColumn: 'Name', YColumns: 'Value', Series: 'Cat' });
606
+ const propTable: RawTable = {
607
+ Columns: [{ ColumnName: 'Key' }, { ColumnName: 'Value' }],
608
+ Rows: [['viz', vizJson]],
609
+ };
610
+ const primaryTable: RawTable = {
611
+ Columns: [{ ColumnName: 'Name' }, { ColumnName: 'Value' }],
612
+ Rows: [['a', 1]],
613
+ };
614
+ const tocTable = makeTocTable([
615
+ [0, 'QueryResult', 'PrimaryResult'],
616
+ [1, 'QueryProperties', 'Properties'],
617
+ ]);
618
+ const allTables = [primaryTable, propTable, tocTable];
619
+
620
+ const result = parseVisualizationMetadata(allTables, tocTable, [0]);
621
+ expect(result.size).toBe(1);
622
+ const viz = result.get(0)!;
623
+ expect(viz.type).toBe('barchart');
624
+ expect(viz.xColumn).toBe('Name');
625
+ expect(viz.series).toBe('Cat');
626
+ });
627
+
628
+ it('parses yColumns as comma-separated string', () => {
629
+ const vizJson = JSON.stringify({ Visualization: 'linechart', YColumns: 'A, B, C' });
630
+ const propTable: RawTable = {
631
+ Columns: [{ ColumnName: 'Value' }],
632
+ Rows: [[vizJson]],
633
+ };
634
+ const primaryTable: RawTable = { Columns: [{ ColumnName: 'A' }], Rows: [] };
635
+ const tocTable = makeTocTable([
636
+ [0, 'QueryResult', 'PrimaryResult'],
637
+ [1, 'QueryProperties', 'Props'],
638
+ ]);
639
+ const allTables = [primaryTable, propTable, tocTable];
640
+
641
+ const result = parseVisualizationMetadata(allTables, tocTable, [0]);
642
+ expect(result.get(0)!.yColumns).toEqual(['A', 'B', 'C']);
643
+ });
644
+
645
+ it('parses yColumns as array', () => {
646
+ const vizJson = JSON.stringify({ Visualization: 'barchart', YColumns: ['X', 'Y'] });
647
+ const propTable: RawTable = {
648
+ Columns: [{ ColumnName: 'Value' }],
649
+ Rows: [[vizJson]],
650
+ };
651
+ const primaryTable: RawTable = { Columns: [{ ColumnName: 'X' }], Rows: [] };
652
+ const tocTable = makeTocTable([
653
+ [0, 'QueryResult', 'PrimaryResult'],
654
+ [1, 'QueryProperties', 'Props'],
655
+ ]);
656
+ const allTables = [primaryTable, propTable, tocTable];
657
+
658
+ const result = parseVisualizationMetadata(allTables, tocTable, [0]);
659
+ expect(result.get(0)!.yColumns).toEqual(['X', 'Y']);
660
+ });
661
+
662
+ it('excludes visualization type "table"', () => {
663
+ const vizJson = JSON.stringify({ Visualization: 'table' });
664
+ const propTable: RawTable = {
665
+ Columns: [{ ColumnName: 'Value' }],
666
+ Rows: [[vizJson]],
667
+ };
668
+ const primaryTable: RawTable = { Columns: [{ ColumnName: 'A' }], Rows: [] };
669
+ const tocTable = makeTocTable([
670
+ [0, 'QueryResult', 'PrimaryResult'],
671
+ [1, 'QueryProperties', 'Props'],
672
+ ]);
673
+ const allTables = [primaryTable, propTable, tocTable];
674
+
675
+ const result = parseVisualizationMetadata(allTables, tocTable, [0]);
676
+ expect(result.size).toBe(0);
677
+ });
678
+
679
+ it('handles malformed JSON in QueryProperties gracefully', () => {
680
+ const propTable: RawTable = {
681
+ Columns: [{ ColumnName: 'Value' }],
682
+ Rows: [['not-valid-json{{{']],
683
+ };
684
+ const primaryTable: RawTable = { Columns: [{ ColumnName: 'A' }], Rows: [] };
685
+ const tocTable = makeTocTable([
686
+ [0, 'QueryResult', 'PrimaryResult'],
687
+ [1, 'QueryProperties', 'Props'],
688
+ ]);
689
+ const allTables = [primaryTable, propTable, tocTable];
690
+
691
+ const result = parseVisualizationMetadata(allTables, tocTable, [0]);
692
+ expect(result.size).toBe(0);
693
+ });
694
+
695
+ it('handles empty QueryProperties table (no rows)', () => {
696
+ const propTable: RawTable = {
697
+ Columns: [{ ColumnName: 'Value' }],
698
+ Rows: [],
699
+ };
700
+ const primaryTable: RawTable = { Columns: [{ ColumnName: 'A' }], Rows: [] };
701
+ const tocTable = makeTocTable([
702
+ [0, 'QueryResult', 'PrimaryResult'],
703
+ [1, 'QueryProperties', 'Props'],
704
+ ]);
705
+ const allTables = [primaryTable, propTable, tocTable];
706
+
707
+ const result = parseVisualizationMetadata(allTables, tocTable, [0]);
708
+ expect(result.size).toBe(0);
709
+ });
710
+
711
+ it('returns empty map when TOC is missing Kind/Ordinal columns', () => {
712
+ const tocTable: RawTable = {
713
+ Columns: [{ ColumnName: 'SomeOtherCol' }],
714
+ Rows: [],
715
+ };
716
+ const result = parseVisualizationMetadata([], tocTable, [0]);
717
+ expect(result.size).toBe(0);
718
+ });
719
+
720
+ it('maps visualization to correct primary result with multiple primaries', () => {
721
+ const primary1: RawTable = { Columns: [{ ColumnName: 'A' }], Rows: [['a']] };
722
+ const primary2: RawTable = { Columns: [{ ColumnName: 'B' }], Rows: [['b']] };
723
+ const vizJson = JSON.stringify({ Visualization: 'piechart' });
724
+ const propTable: RawTable = {
725
+ Columns: [{ ColumnName: 'Value' }],
726
+ Rows: [[vizJson]],
727
+ };
728
+ const tocTable = makeTocTable([
729
+ [0, 'QueryResult', 'Result1'],
730
+ [1, 'QueryResult', 'Result2'],
731
+ [2, 'QueryProperties', 'Props'],
732
+ ]);
733
+ const allTables = [primary1, primary2, propTable, tocTable];
734
+
735
+ const result = parseVisualizationMetadata(allTables, tocTable, [0, 1]);
736
+ // ordinal=2 for QueryProperties, closest preceding primary is index 1
737
+ expect(result.has(1)).toBe(true);
738
+ expect(result.get(1)!.type).toBe('piechart');
739
+ });
740
+
741
+ it('falls back to first primary when no preceding primary exists', () => {
742
+ const vizJson = JSON.stringify({ Visualization: 'linechart' });
743
+ const propTable: RawTable = {
744
+ Columns: [{ ColumnName: 'Value' }],
745
+ Rows: [[vizJson]],
746
+ };
747
+ const primaryTable: RawTable = { Columns: [{ ColumnName: 'A' }], Rows: [] };
748
+ const tocTable = makeTocTable([
749
+ [0, 'QueryProperties', 'Props'],
750
+ [1, 'QueryResult', 'PrimaryResult'],
751
+ ]);
752
+ const allTables = [propTable, primaryTable, tocTable];
753
+
754
+ const result = parseVisualizationMetadata(allTables, tocTable, [1]);
755
+ // ordinal=0 for QueryProperties, no primary before it → falls back to first primary [1]
756
+ expect(result.has(1)).toBe(true);
757
+ });
758
+
759
+ it('includes Title when present', () => {
760
+ const vizJson = JSON.stringify({ Visualization: 'barchart', Title: 'My Chart' });
761
+ const propTable: RawTable = {
762
+ Columns: [{ ColumnName: 'Value' }],
763
+ Rows: [[vizJson]],
764
+ };
765
+ const primaryTable: RawTable = { Columns: [{ ColumnName: 'A' }], Rows: [] };
766
+ const tocTable = makeTocTable([
767
+ [0, 'QueryResult', 'PrimaryResult'],
768
+ [1, 'QueryProperties', 'Props'],
769
+ ]);
770
+ const allTables = [primaryTable, propTable, tocTable];
771
+
772
+ const result = parseVisualizationMetadata(allTables, tocTable, [0]);
773
+ expect(result.get(0)!.title).toBe('My Chart');
774
+ });
775
+ });
776
+
777
+ // ---------------------------------------------------------------------------
778
+ // buildResultSets
779
+ // ---------------------------------------------------------------------------
780
+
781
+ describe('buildResultSets', () => {
782
+ it('builds a simple single result set', () => {
783
+ const table: RawTable = {
784
+ Columns: [
785
+ { ColumnName: 'Name', ColumnType: 'string' },
786
+ { ColumnName: 'Count', ColumnType: 'long' },
787
+ ],
788
+ Rows: [['Alice', 10], ['Bob', 20]],
789
+ };
790
+ const allTables = [table];
791
+ const vizMap = new Map<number, KustoVisualization>();
792
+
793
+ const results = buildResultSets(allTables, [0], vizMap);
794
+ expect(results).toHaveLength(1);
795
+ expect(results[0].columns).toHaveLength(2);
796
+ expect(results[0].columns[0].ColumnName).toBe('Name');
797
+ expect(results[0].rows).toHaveLength(2);
798
+ expect(results[0].rows[0]).toEqual({ Name: 'Alice', Count: 10 });
799
+ expect(results[0].rows[1]).toEqual({ Name: 'Bob', Count: 20 });
800
+ expect(results[0].visualization).toBeUndefined();
801
+ });
802
+
803
+ it('attaches visualization metadata to result set', () => {
804
+ const table: RawTable = {
805
+ Columns: [
806
+ { ColumnName: 'Name', ColumnType: 'string' },
807
+ { ColumnName: 'Value', ColumnType: 'int' },
808
+ ],
809
+ Rows: [['X', 5]],
810
+ };
811
+ const vizMap = new Map<number, KustoVisualization>();
812
+ vizMap.set(0, { type: 'barchart', xColumn: 'Name', yColumns: ['Value'] });
813
+
814
+ const results = buildResultSets([table], [0], vizMap);
815
+ expect(results[0].visualization).toBeDefined();
816
+ expect(results[0].visualization!.type).toBe('barchart');
817
+ expect(results[0].visualization!.xColumn).toBe('Name');
818
+ expect(results[0].visualization!.yColumns).toEqual(['Value']);
819
+ });
820
+
821
+ it('drops viz columns that are not in the result set', () => {
822
+ const table: RawTable = {
823
+ Columns: [
824
+ { ColumnName: 'Name', ColumnType: 'string' },
825
+ { ColumnName: 'Value', ColumnType: 'int' },
826
+ ],
827
+ Rows: [['X', 5]],
828
+ };
829
+ const vizMap = new Map<number, KustoVisualization>();
830
+ vizMap.set(0, {
831
+ type: 'barchart',
832
+ xColumn: 'MissingCol',
833
+ yColumns: ['Value', 'AlsoMissing'],
834
+ series: 'NoSuchCol',
835
+ });
836
+
837
+ const results = buildResultSets([table], [0], vizMap);
838
+ const viz = results[0].visualization!;
839
+ expect(viz.type).toBe('barchart');
840
+ expect(viz.xColumn).toBeUndefined();
841
+ expect(viz.yColumns).toEqual(['Value']);
842
+ expect(viz.series).toBeUndefined();
843
+ });
844
+
845
+ it('omits yColumns entirely when none are valid', () => {
846
+ const table: RawTable = {
847
+ Columns: [{ ColumnName: 'A', ColumnType: 'string' }],
848
+ Rows: [],
849
+ };
850
+ const vizMap = new Map<number, KustoVisualization>();
851
+ vizMap.set(0, { type: 'barchart', yColumns: ['Missing1', 'Missing2'] });
852
+
853
+ const results = buildResultSets([table], [0], vizMap);
854
+ expect(results[0].visualization!.yColumns).toBeUndefined();
855
+ });
856
+
857
+ it('builds multiple result sets', () => {
858
+ const table1: RawTable = {
859
+ Columns: [{ ColumnName: 'A', ColumnType: 'string' }],
860
+ Rows: [['a1']],
861
+ };
862
+ const table2: RawTable = {
863
+ Columns: [{ ColumnName: 'B', ColumnType: 'long' }],
864
+ Rows: [[42]],
865
+ };
866
+ const vizMap = new Map<number, KustoVisualization>();
867
+
868
+ const results = buildResultSets([table1, table2], [0, 1], vizMap);
869
+ expect(results).toHaveLength(2);
870
+ expect(results[0].rows[0]).toEqual({ A: 'a1' });
871
+ expect(results[1].rows[0]).toEqual({ B: 42 });
872
+ });
873
+
874
+ it('defaults ColumnType to string when not provided', () => {
875
+ const table: RawTable = {
876
+ Columns: [{ ColumnName: 'X' }],
877
+ Rows: [['val']],
878
+ };
879
+ const results = buildResultSets([table], [0], new Map());
880
+ expect(results[0].columns[0].ColumnType).toBe('string');
881
+ });
882
+
883
+ it('preserves viz title', () => {
884
+ const table: RawTable = {
885
+ Columns: [{ ColumnName: 'A', ColumnType: 'string' }],
886
+ Rows: [],
887
+ };
888
+ const vizMap = new Map<number, KustoVisualization>();
889
+ vizMap.set(0, { type: 'linechart', title: 'My Title' });
890
+
891
+ const results = buildResultSets([table], [0], vizMap);
892
+ expect(results[0].visualization!.title).toBe('My Title');
893
+ });
894
+ });
895
+
896
+ describe('queryKusto with custom target', () => {
897
+ it('passes custom cluster URL and database', async () => {
898
+ const { client } = createTestClient();
899
+
900
+ const body = {
901
+ Tables: [{
902
+ Columns: [{ ColumnName: 'Id', ColumnType: 'long' }],
903
+ Rows: [[1]],
904
+ }, {
905
+ Columns: [{ ColumnName: 'Kind' }, { ColumnName: 'Ordinal' }],
906
+ Rows: [['QueryResult', 0]],
907
+ }],
908
+ };
909
+ stubFetch(body);
910
+
911
+ const target = { clusterUrl: 'https://other.kusto.windows.net', database: 'OtherDB' };
912
+ await client.queryKusto('OtherTable | take 1', undefined, undefined, target);
913
+
914
+ const fetchCall = vi.mocked(fetch).mock.calls[0];
915
+ expect(fetchCall[0]).toContain('other.kusto.windows.net/v1/rest/query');
916
+ const fetchBody = JSON.parse(fetchCall[1]?.body as string);
917
+ expect(fetchBody.db).toBe('OtherDB');
918
+ });
919
+ });