@mhjuma/traverse 0.2.0 → 0.4.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 (28) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/package.json +18 -4
  3. package/src/bootstrap.spec.tsx +191 -1
  4. package/src/bootstrap.tsx +172 -6
  5. package/src/components/Explorer/Explorer.spec.tsx +47 -3
  6. package/src/components/Explorer/Explorer.tsx +33 -0
  7. package/src/components/Explorer/MonacoConfigErrorBanner.tsx +86 -0
  8. package/src/components/ExplorerWorkspace/ExplorerWorkspace.spec.tsx +53 -17
  9. package/src/components/ExplorerWorkspace/ExplorerWorkspace.tsx +78 -74
  10. package/src/components/ExplorerWorkspace/bootstrapKustoLanguage.spec.ts +150 -0
  11. package/src/components/ExplorerWorkspace/bootstrapKustoLanguage.ts +95 -0
  12. package/src/components/ExplorerWorkspace/kustoSchemaQueue.spec.ts +322 -0
  13. package/src/components/ExplorerWorkspace/kustoSchemaQueue.ts +188 -0
  14. package/src/components/ExplorerWorkspace/monacoLoader.spec.ts +82 -0
  15. package/src/components/ExplorerWorkspace/monacoLoader.ts +57 -0
  16. package/src/components/ExplorerWorkspace/monacoWorkers.spec.ts +146 -0
  17. package/src/components/ExplorerWorkspace/monacoWorkers.ts +179 -0
  18. package/src/index.ts +3 -0
  19. package/src/services/kusto.spec.ts +155 -1
  20. package/src/services/kusto.ts +117 -7
  21. package/src/services/schema.spec.ts +107 -28
  22. package/src/services/schema.ts +66 -25
  23. package/src/test-setup.ts +3 -0
  24. package/src/vite-plugin.spec.ts +118 -0
  25. package/src/vite-plugin.ts +114 -0
  26. package/vitest.config.ts +7 -0
  27. package/src/components/ExplorerWorkspace/kqlLanguage.spec.ts +0 -321
  28. package/src/components/ExplorerWorkspace/kqlLanguage.ts +0 -155
@@ -11,6 +11,10 @@ import type { ExplorerTabsSnapshot } from '../../state/persistence';
11
11
  import { DEFAULT_QUERY, buildWellKnownClusters } from '../ExplorerWorkspace/ExplorerWorkspace.logic';
12
12
  import type { WellKnownCluster } from '../ExplorerWorkspace/ExplorerWorkspace.logic';
13
13
  import { ExplorerWorkspace } from '../ExplorerWorkspace/ExplorerWorkspace';
14
+ import { preloadKustoLanguage } from '../ExplorerWorkspace/monacoLoader';
15
+ import { getMonacoWorkerConfigurationError } from '../ExplorerWorkspace/monacoWorkers';
16
+ import type { MonacoWorkerConfigurationError } from '../ExplorerWorkspace/monacoWorkers';
17
+ import { MonacoConfigErrorBanner } from './MonacoConfigErrorBanner';
14
18
 
15
19
  export interface ExplorerProps {
16
20
  className?: string;
@@ -25,6 +29,12 @@ export interface ExplorerProps {
25
29
  * Falls back to the package's built-in `DEFAULT_QUERY` when omitted.
26
30
  */
27
31
  initialQuery?: string;
32
+ /**
33
+ * Override the rendered placeholder when Monaco workers haven't been
34
+ * configured. Defaults to the built-in `MonacoConfigErrorBanner` —
35
+ * supply your own to integrate with your app's error UI.
36
+ */
37
+ monacoConfigErrorFallback?: (error: MonacoWorkerConfigurationError) => React.ReactNode;
28
38
  }
29
39
 
30
40
  /**
@@ -35,6 +45,25 @@ export interface ExplorerProps {
35
45
  const SNAPSHOT_SAVE_DEBOUNCE_MS = 300;
36
46
 
37
47
  export function Explorer(props: ExplorerProps) {
48
+ // Synchronous, render-time check: bail out with an actionable placeholder
49
+ // before any kusto code can fire. Without `configureTraverseMonacoWorkers`,
50
+ // Monaco silently falls back to in-thread mode and the @kusto/monaco-kusto
51
+ // schema queue cascades through "Missing requestHandler", "doFolding is
52
+ // not a function", and friends — none of which surface the real problem.
53
+ const monacoConfigError = getMonacoWorkerConfigurationError();
54
+ if (monacoConfigError) {
55
+ if (props.monacoConfigErrorFallback) {
56
+ return <>{props.monacoConfigErrorFallback(monacoConfigError)}</>;
57
+ }
58
+ return <MonacoConfigErrorBanner error={monacoConfigError} className={props.className} />;
59
+ }
60
+
61
+ // Trigger kusto language preload on first Explorer render. Editor-gated
62
+ // by design (here, not at module load) so consumers using only
63
+ // non-editor APIs from `@mhjuma/traverse` don't pay the kusto chunk cost.
64
+ // Idempotent — internally guarded so subsequent renders are no-ops.
65
+ preloadKustoLanguage();
66
+
38
67
  const { initialQuery: providedInitialQuery } = props;
39
68
 
40
69
  const { initialQuery, hasUrlQuery } = useMemo(() => {
@@ -100,6 +129,10 @@ export function Explorer(props: ExplorerProps) {
100
129
  };
101
130
  }, [hasUrlQuery]);
102
131
 
132
+ // The Kusto language is pre-bootstrapped in monacoLoader.ts at module
133
+ // load time so the editor's first paint already has Monarch tokens and
134
+ // themes registered. No idle-callback prefetch needed here.
135
+
103
136
  return (
104
137
  <KustoClientContext.Provider value={props.kustoClient}>
105
138
  <ExplorerColorProvider value={props.colors}>
@@ -0,0 +1,86 @@
1
+ import type { MonacoWorkerConfigurationError } from '../ExplorerWorkspace/monacoWorkers';
2
+
3
+ interface MonacoConfigErrorBannerProps {
4
+ error: MonacoWorkerConfigurationError;
5
+ className?: string;
6
+ }
7
+
8
+ const WRAPPER_STYLE: React.CSSProperties = {
9
+ display: 'flex',
10
+ flexDirection: 'column',
11
+ alignItems: 'center',
12
+ justifyContent: 'center',
13
+ height: '100%',
14
+ minHeight: '300px',
15
+ padding: '32px',
16
+ boxSizing: 'border-box',
17
+ fontFamily:
18
+ '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
19
+ color: '#d4d4d4',
20
+ background: '#1f1f1f',
21
+ };
22
+
23
+ const CARD_STYLE: React.CSSProperties = {
24
+ maxWidth: '720px',
25
+ width: '100%',
26
+ background: '#2b2b2b',
27
+ border: '1px solid #3f3f46',
28
+ borderRadius: '8px',
29
+ padding: '24px',
30
+ boxShadow: '0 4px 12px rgba(0, 0, 0, 0.3)',
31
+ };
32
+
33
+ const HEADING_STYLE: React.CSSProperties = {
34
+ margin: '0 0 12px 0',
35
+ fontSize: '18px',
36
+ fontWeight: 600,
37
+ color: '#e8912d',
38
+ };
39
+
40
+ const HINT_STYLE: React.CSSProperties = {
41
+ margin: '0 0 16px 0',
42
+ fontSize: '14px',
43
+ lineHeight: '1.5',
44
+ whiteSpace: 'pre-wrap',
45
+ color: '#cccccc',
46
+ };
47
+
48
+ const PRE_STYLE: React.CSSProperties = {
49
+ background: '#0d0d0d',
50
+ border: '1px solid #3f3f46',
51
+ borderRadius: '4px',
52
+ padding: '12px 16px',
53
+ fontSize: '13px',
54
+ fontFamily:
55
+ '"SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
56
+ color: '#9cdcfe',
57
+ overflowX: 'auto',
58
+ margin: 0,
59
+ };
60
+
61
+ /**
62
+ * Rendered in place of the Explorer when Monaco workers have not been
63
+ * configured. The message is verbatim from the assertion helper so the
64
+ * fix instructions stay in lockstep with the actual check.
65
+ *
66
+ * Pure presentational component — no imports from FluentUI to keep it
67
+ * usable even when the host hasn't wrapped us in `<FluentProvider>`.
68
+ */
69
+ export function MonacoConfigErrorBanner({ error, className }: MonacoConfigErrorBannerProps): React.ReactElement {
70
+ // Split the hint into the conversational prose and the code snippet.
71
+ // The convention is: anything before the first blank line is prose,
72
+ // anything after is code that should render in a <pre> block.
73
+ const blankLineIdx = error.hint.indexOf('\n\n');
74
+ const prose = blankLineIdx >= 0 ? error.hint.slice(0, blankLineIdx) : error.hint;
75
+ const code = blankLineIdx >= 0 ? error.hint.slice(blankLineIdx + 2) : '';
76
+
77
+ return (
78
+ <div className={className} style={WRAPPER_STYLE} role="alert" aria-live="polite">
79
+ <div style={CARD_STYLE}>
80
+ <h2 style={HEADING_STYLE}>⚠ {error.summary}</h2>
81
+ <p style={HINT_STYLE}>{prose}</p>
82
+ {code ? <pre style={PRE_STYLE}><code>{code}</code></pre> : null}
83
+ </div>
84
+ </div>
85
+ );
86
+ }
@@ -5,9 +5,10 @@ import { createRoot } from 'react-dom/client';
5
5
  import { act } from 'react';
6
6
  import { ExplorerWorkspace } from './ExplorerWorkspace';
7
7
 
8
- import { loadSchema, getSchema } from '../../services/schema';
8
+ import { loadSchema, getSchema, getRawShowSchema } from '../../services/schema';
9
9
  import { getHistory } from '../../services/queryHistory';
10
- import { registerKqlLanguage, setKqlSchemaResolver } from './kqlLanguage';
10
+ import { bootstrapKustoLanguage } from './bootstrapKustoLanguage';
11
+ import { applyKustoSchema } from './kustoSchemaQueue';
11
12
  import { saveActiveConnectionId } from './ExplorerWorkspace.logic';
12
13
 
13
14
  vi.mock('../EditorToolbar/EditorToolbar', () => ({
@@ -53,8 +54,18 @@ vi.mock('@monaco-editor/react', () => ({
53
54
  getValue: () => 'TestTable | take 10',
54
55
  };
55
56
  const mockMonaco = {
56
- languages: { register: vi.fn(), setMonarchTokensProvider: vi.fn(), registerCompletionItemProvider: vi.fn() },
57
- editor: { defineTheme: vi.fn() },
57
+ languages: {
58
+ register: vi.fn(),
59
+ setMonarchTokensProvider: vi.fn(),
60
+ registerCompletionItemProvider: vi.fn(),
61
+ getLanguages: vi.fn(() => [{ id: 'kusto' }]),
62
+ },
63
+ editor: {
64
+ defineTheme: vi.fn(),
65
+ setTheme: vi.fn(),
66
+ getModels: vi.fn(() => []),
67
+ onDidCreateModel: vi.fn(() => ({ dispose: vi.fn() })),
68
+ },
58
69
  KeyMod: { CtrlCmd: 2048, Shift: 1024, Alt: 512 },
59
70
  KeyCode: { Enter: 3, KeyR: 48, KeyF: 36 },
60
71
  };
@@ -114,6 +125,7 @@ vi.mock('../../services/queryHistory', () => ({
114
125
  vi.mock('../../services/schema', () => ({
115
126
  getSchema: vi.fn().mockReturnValue([]),
116
127
  loadSchema: vi.fn().mockResolvedValue(undefined),
128
+ getRawShowSchema: vi.fn().mockReturnValue(null),
117
129
  }));
118
130
  vi.mock('./ExplorerWorkspace.logic', () => ({
119
131
  formatKql: (s: string) => s,
@@ -154,9 +166,11 @@ vi.mock('./ExplorerWorkspace.logic', () => ({
154
166
  vi.mock('./ExplorerWorkspace.styles', () => ({
155
167
  useExplorerStyles: () => new Proxy({}, { get: (_, p) => String(p) }),
156
168
  }));
157
- vi.mock('./kqlLanguage', () => ({
158
- registerKqlLanguage: vi.fn(),
159
- setKqlSchemaResolver: vi.fn(),
169
+ vi.mock('./bootstrapKustoLanguage', () => ({
170
+ bootstrapKustoLanguage: vi.fn().mockResolvedValue(undefined),
171
+ }));
172
+ vi.mock('./kustoSchemaQueue', () => ({
173
+ applyKustoSchema: vi.fn(),
160
174
  }));
161
175
 
162
176
 
@@ -378,13 +392,14 @@ describe('ExplorerWorkspace', () => {
378
392
  expect(getHistory).toHaveBeenCalled();
379
393
  });
380
394
 
381
- // --- Injects run-highlight CSS on mount ---
382
- it('injects traverse-run-highlight style element', () => {
395
+ // --- No custom run-highlight CSS on mount ---
396
+ it('does not inject the legacy traverse-run-highlight style element', () => {
383
397
  act(() => { root.render(React.createElement(ExplorerWorkspace, defaultProps)); });
384
398
 
399
+ // monaco-kusto's built-in KustoCommandHighlighter replaces our custom
400
+ // block decoration; the global style element must no longer be added.
385
401
  const styleEl = document.getElementById('traverse-run-highlight-style');
386
- expect(styleEl).toBeTruthy();
387
- expect(styleEl?.textContent).toContain('traverse-run-highlight');
402
+ expect(styleEl).toBeFalsy();
388
403
  });
389
404
 
390
405
  // --- DragOver on primary editor ---
@@ -418,16 +433,37 @@ describe('ExplorerWorkspace', () => {
418
433
  expect(toolbar?.getAttribute('data-show-cancel')).toBe('false');
419
434
  });
420
435
 
421
- // --- setKqlSchemaResolver called ---
422
- it('sets KQL schema resolver on mount', () => {
436
+ // --- applyKustoSchema called when schema available ---
437
+ it('pushes schema to the Kusto worker on mount when schema is cached', () => {
438
+ const fakeRaw = { Plugins: [], Databases: { DB: { Name: 'DB', Tables: {}, Functions: {} } } };
439
+ vi.mocked(getRawShowSchema).mockReturnValue(fakeRaw as unknown as ReturnType<typeof getRawShowSchema>);
440
+ act(() => { root.render(React.createElement(ExplorerWorkspace, defaultProps)); });
441
+ expect(applyKustoSchema).toHaveBeenCalled();
442
+ const call = vi.mocked(applyKustoSchema).mock.calls.at(-1)?.[0];
443
+ expect(call?.raw).toBe(fakeRaw);
444
+ expect(call?.clusterUri).toBe('https://test.kusto.windows.net');
445
+ expect(call?.dbName).toBe('DB');
446
+ expect(call?.monaco).toBeTruthy();
447
+ vi.mocked(getRawShowSchema).mockReturnValue(null);
448
+ });
449
+
450
+ // --- bootstrapKustoLanguage called on editor mount ---
451
+ it('bootstraps the Kusto language on editor mount', () => {
423
452
  act(() => { root.render(React.createElement(ExplorerWorkspace, defaultProps)); });
424
- expect(setKqlSchemaResolver).toHaveBeenCalled();
453
+ expect(bootstrapKustoLanguage).toHaveBeenCalled();
454
+ // Bootstrap receives the same Monaco instance the editor was given —
455
+ // this is the contract the schema queue relies on to apply settings
456
+ // and themes against the right Monaco copy.
457
+ const bootstrapArg = vi.mocked(bootstrapKustoLanguage).mock.calls[0]?.[0];
458
+ expect(bootstrapArg).toBeTruthy();
425
459
  });
426
460
 
427
- // --- registerKqlLanguage called ---
428
- it('registers KQL language on editor mount', () => {
461
+ // --- no schema push when raw schema is not yet cached ---
462
+ it('does not push schema when getRawShowSchema returns null', () => {
463
+ vi.mocked(getRawShowSchema).mockReturnValue(null);
464
+ vi.mocked(applyKustoSchema).mockClear();
429
465
  act(() => { root.render(React.createElement(ExplorerWorkspace, defaultProps)); });
430
- expect(registerKqlLanguage).toHaveBeenCalled();
466
+ expect(applyKustoSchema).not.toHaveBeenCalled();
431
467
  });
432
468
 
433
469
  // --- saveActiveConnectionId called ---
@@ -3,11 +3,10 @@ import type { Monaco } from '@monaco-editor/react';
3
3
  import type { editor } from 'monaco-editor';
4
4
  import React, { useState, useCallback, useRef, useEffect, useMemo } from 'react';
5
5
 
6
- import { useExplorerColors } from '../../context/ExplorerColorContext';
7
6
  import type { KustoTarget } from '../../services/kusto';
8
7
  import { normalizeQuery, getHistory, saveHistoryEntry, recallResult } from '../../services/queryHistory';
9
8
  import type { QueryHistoryEntry } from '../../services/queryHistory';
10
- import { getSchema, loadSchema } from '../../services/schema';
9
+ import { getSchema, loadSchema, getRawShowSchema } from '../../services/schema';
11
10
  import { EditorToolbar } from '../EditorToolbar/EditorToolbar';
12
11
  import { ResultsPanel } from '../ResultsPanel/ResultsPanel';
13
12
  import { SchemaSidebar } from '../SchemaSidebar/SchemaSidebar';
@@ -26,7 +25,8 @@ import {
26
25
  import { useExplorerStyles } from './ExplorerWorkspace.styles';
27
26
  import type { ExplorerProps } from '../Explorer/Explorer';
28
27
  import { useKustoClient } from '../../context/KustoClientContext';
29
- import { registerKqlLanguage, setKqlSchemaResolver } from './kqlLanguage';
28
+ import { bootstrapKustoLanguage } from './bootstrapKustoLanguage';
29
+ import { applyKustoSchema } from './kustoSchemaQueue';
30
30
 
31
31
 
32
32
  const positionRelativeStyle = { position: 'relative' as const } as const;
@@ -38,12 +38,15 @@ const editorOptions = {
38
38
  overviewRulerBorder: false, padding: { top: 4, bottom: 4 }, lineDecorationsWidth: 8,
39
39
  glyphMargin: false, folding: false,
40
40
  dropIntoEditor: { enabled: false },
41
+ // monaco-kusto exposes semantic-token-based highlighting (columns,
42
+ // functions, tables distinguished by AST role). Enable it explicitly —
43
+ // Monaco's default for standalone editors is false.
44
+ 'semanticHighlighting.enabled': true,
41
45
  } as const;
42
46
 
43
47
  export function ExplorerWorkspace(props: ExplorerProps) {
44
48
  const styles = useExplorerStyles();
45
49
  const { isDark = false } = props;
46
- const explorerColors = useExplorerColors();
47
50
  const client = useKustoClient();
48
51
  const state = useExplorerState();
49
52
  const dispatch = useExplorerDispatch();
@@ -115,9 +118,8 @@ export function ExplorerWorkspace(props: ExplorerProps) {
115
118
  );
116
119
 
117
120
  useEffect(() => {
118
- setKqlSchemaResolver(() => getSchema(focusedTarget));
119
121
  saveActiveConnectionId(focusedConn.id);
120
- }, [focusedConn.id, focusedTarget]);
122
+ }, [focusedConn.id]);
121
123
 
122
124
  // Setter shims — dispatch to reducer, keep same call signatures for existing callbacks
123
125
  const setHasSelection = useCallback((v: boolean) => dispatch({ type: 'SET_HAS_SELECTION', hasSelection: v }), [dispatch]);
@@ -133,8 +135,17 @@ export function ExplorerWorkspace(props: ExplorerProps) {
133
135
  // --- Editor refs (primary + secondary for split) ---
134
136
  const primaryEditorRef = useRef<editor.IStandaloneCodeEditor | null>(null);
135
137
  const secondaryEditorRef = useRef<editor.IStandaloneCodeEditor | null>(null);
136
- const primaryDecorationsRef = useRef<editor.IEditorDecorationsCollection | null>(null);
137
- const secondaryDecorationsRef = useRef<editor.IEditorDecorationsCollection | null>(null);
138
+ // Monaco instance is captured at first editor mount. Stored in state (not
139
+ // a ref) so the schema-push effect re-runs when it becomes available.
140
+ const [monacoInstance, setMonacoInstance] = useState<Monaco | null>(null);
141
+ // Track when monaco-kusto's themed token colors (`kusto-light` /
142
+ // `kusto-dark`) have been registered. Before bootstrap resolves, those
143
+ // theme names don't exist yet — passing them as the Editor's `theme`
144
+ // prop on first mount makes Monaco silently fall back to the default
145
+ // `vs` (light) theme, which causes a brief white flash for dark-mode
146
+ // users on first paint. We render with the built-in `vs-dark` / `vs`
147
+ // theme until bootstrap completes, then swap to the kusto themes.
148
+ const [kustoThemeReady, setKustoThemeReady] = useState(false);
138
149
  const runQueryRef = useRef<() => void>(() => {});
139
150
  const recallQueryRef = useRef<() => void>(() => {});
140
151
  const containerRef = useRef<HTMLDivElement | null>(null);
@@ -142,6 +153,49 @@ export function ExplorerWorkspace(props: ExplorerProps) {
142
153
  const historyKeysRef = useRef<Set<string>>(new Set());
143
154
  const abortRef = useRef<AbortController | null>(null);
144
155
 
156
+ // Push the latest schema to the Kusto language worker whenever connection
157
+ // or schema changes. Debounce + identity-skip live in the queue.
158
+ useEffect(() => {
159
+ const monaco = monacoInstance;
160
+ if (!monaco) {
161
+ return;
162
+ }
163
+ const raw = getRawShowSchema(focusedTarget);
164
+ if (!raw) {
165
+ return;
166
+ }
167
+ applyKustoSchema({
168
+ monaco,
169
+ raw,
170
+ clusterUri: focusedTarget.clusterUrl,
171
+ dbName: focusedTarget.database,
172
+ });
173
+ }, [monacoInstance, focusedTarget, schema]);
174
+
175
+ // Apply monaco-kusto's themed token colors once the language plugin has
176
+ // registered its themes (`kusto-light` / `kusto-dark`). Until bootstrap
177
+ // resolves we render with the built-in `vs` / `vs-dark` theme via the
178
+ // `effectiveTheme` prop below to avoid the white-flash described where
179
+ // `kustoThemeReady` is declared.
180
+ useEffect(() => {
181
+ const monaco = monacoInstance;
182
+ if (!monaco) {
183
+ return;
184
+ }
185
+ let cancelled = false;
186
+ void bootstrapKustoLanguage(monaco).then(() => {
187
+ if (cancelled) {
188
+ return;
189
+ }
190
+ setKustoThemeReady(true);
191
+ }).catch(() => { /* bootstrap errors surface elsewhere */ });
192
+ return () => { cancelled = true; };
193
+ }, [monacoInstance]);
194
+
195
+ const effectiveTheme = kustoThemeReady
196
+ ? (isDark ? 'kusto-dark' : 'kusto-light')
197
+ : (isDark ? 'vs-dark' : 'vs');
198
+
145
199
  // Convenience: the focused editor
146
200
  const getFocusedEditor = useCallback(() => {
147
201
  return focusedPane === 'primary' ? primaryEditorRef.current : secondaryEditorRef.current;
@@ -168,49 +222,6 @@ export function ExplorerWorkspace(props: ExplorerProps) {
168
222
  setCanRecall(historyKeysRef.current.has(normalizeQuery(toRun.query)));
169
223
  }, [setCanRecall]);
170
224
 
171
- const updateStatementHighlight = useCallback((ed: editor.IStandaloneCodeEditor) => {
172
- const decRef = ed === primaryEditorRef.current ? primaryDecorationsRef : secondaryDecorationsRef;
173
- if (!decRef.current) {
174
- return;
175
- }
176
- const selection = ed.getSelection();
177
- // When the user has an explicit selection, don't show the block highlight
178
- if (selection && !selection.isEmpty()) {
179
- decRef.current.set([]);
180
- checkCanRecall(ed);
181
- return;
182
- }
183
- const model = ed.getModel();
184
- if (!model) {
185
- return;
186
- }
187
- const cursorLine = ed.getPosition()?.lineNumber ?? 1;
188
- const totalLines = model.getLineCount();
189
-
190
- let startLine = cursorLine;
191
- while (startLine > 1 && model.getLineContent(startLine - 1).trim() !== '') {
192
- startLine--;
193
- }
194
- let endLine = cursorLine;
195
- while (endLine < totalLines && model.getLineContent(endLine + 1).trim() !== '') {
196
- endLine++;
197
- }
198
-
199
- decRef.current.set([{
200
- range: {
201
- startLineNumber: startLine,
202
- startColumn: 1,
203
- endLineNumber: endLine,
204
- endColumn: model.getLineMaxColumn(endLine),
205
- },
206
- options: {
207
- isWholeLine: true,
208
- className: 'traverse-run-highlight',
209
- },
210
- }]);
211
- checkCanRecall(ed);
212
- }, [checkCanRecall]);
213
-
214
225
  const cancelQuery = useCallback(() => {
215
226
  abortRef.current?.abort();
216
227
  }, []);
@@ -317,10 +328,14 @@ export function ExplorerWorkspace(props: ExplorerProps) {
317
328
  const createEditorMountHandler = useCallback((pane: 'primary' | 'secondary') => {
318
329
  return (ed: editor.IStandaloneCodeEditor, monaco: Monaco) => {
319
330
  const edRef = pane === 'primary' ? primaryEditorRef : secondaryEditorRef;
320
- const decRef = pane === 'primary' ? primaryDecorationsRef : secondaryDecorationsRef;
321
331
  edRef.current = ed;
322
- decRef.current = ed.createDecorationsCollection([]);
323
- registerKqlLanguage(monaco);
332
+ setMonacoInstance(monaco);
333
+ // Kick off the @kusto/monaco-kusto bootstrap; fire-and-forget — the
334
+ // schema queue awaits this internally before applying schema.
335
+ // monaco-kusto also installs its own KustoCommandHighlighter, which
336
+ // visually marks the current command (delimited by blank lines) —
337
+ // that replaces our previous custom decoration.
338
+ void bootstrapKustoLanguage(monaco);
324
339
  ed.addAction({
325
340
  id: 'run-query',
326
341
  label: 'Run Query',
@@ -340,35 +355,24 @@ export function ExplorerWorkspace(props: ExplorerProps) {
340
355
  run: () => { formatQueryRef.current(); },
341
356
  });
342
357
 
343
- ed.onDidChangeCursorPosition(() => updateStatementHighlight(ed));
358
+ ed.onDidChangeCursorPosition(() => checkCanRecall(ed));
344
359
  ed.onDidChangeCursorSelection((e) => {
345
360
  setHasSelection(!e.selection.isEmpty());
346
- updateStatementHighlight(ed);
361
+ checkCanRecall(ed);
347
362
  });
348
- ed.onDidChangeModelContent(() => updateStatementHighlight(ed));
363
+ ed.onDidChangeModelContent(() => checkCanRecall(ed));
349
364
  ed.onDidFocusEditorWidget(() => setFocusedPane(pane));
350
365
 
351
- updateStatementHighlight(ed);
366
+ checkCanRecall(ed);
352
367
  if (pane === 'primary') {
353
368
  ed.focus();
354
369
  }
355
370
  };
356
- }, [updateStatementHighlight, setHasSelection, setFocusedPane]);
371
+ }, [checkCanRecall, setHasSelection, setFocusedPane]);
357
372
 
358
373
  useEffect(() => { runQueryRef.current = runQuery; }, [runQuery]);
359
374
  useEffect(() => { recallQueryRef.current = doRecall; }, [doRecall]);
360
375
 
361
- // Inject global CSS for the run-highlight decoration (Monaco needs a real class)
362
- useEffect(() => {
363
- const id = 'traverse-run-highlight-style';
364
- if (!document.getElementById(id)) {
365
- const style = document.createElement('style');
366
- style.id = id;
367
- style.textContent = `.traverse-run-highlight { background-color: ${explorerColors.semantic.selectionBg}; transition: background-color 0.3s ease; }`;
368
- document.head.appendChild(style);
369
- }
370
- }, [explorerColors.semantic.selectionBg]);
371
-
372
376
  const insertText = useCallback((text: string) => {
373
377
  const ed = getFocusedEditor();
374
378
  if (!ed) {
@@ -595,8 +599,8 @@ export function ExplorerWorkspace(props: ExplorerProps) {
595
599
  )}
596
600
  <Editor
597
601
  height="100%"
598
- language="kql"
599
- theme={isDark ? 'vs-dark' : 'vs'}
602
+ language="kusto"
603
+ theme={effectiveTheme}
600
604
  value={activeTab.kql}
601
605
  onChange={handlePrimaryEditorChange}
602
606
  onMount={handlePrimaryMount}
@@ -615,8 +619,8 @@ export function ExplorerWorkspace(props: ExplorerProps) {
615
619
  onKeyDown={focusSecondaryPaneKeyDown}>
616
620
  <Editor
617
621
  height="100%"
618
- language="kql"
619
- theme={isDark ? 'vs-dark' : 'vs'}
622
+ language="kusto"
623
+ theme={effectiveTheme}
620
624
  value={splitTab.kql}
621
625
  onChange={handleSecondaryEditorChange}
622
626
  onMount={handleSecondaryMount}
@@ -0,0 +1,150 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import type * as Monaco from 'monaco-editor';
3
+
4
+ import {
5
+ bootstrapKustoLanguage,
6
+ __resetBootstrapForTests,
7
+ } from './bootstrapKustoLanguage';
8
+
9
+ const setLanguageSettings = vi.fn();
10
+ const setMaximumWorkerIdleTime = vi.fn();
11
+ const kustoDefaults = { setLanguageSettings, setMaximumWorkerIdleTime };
12
+
13
+ vi.mock('@kusto/monaco-kusto', () => ({
14
+ get kustoDefaults() {
15
+ return kustoDefaults;
16
+ },
17
+ }));
18
+
19
+ function makeMonaco(languages: { id: string }[] = [{ id: 'kusto' }]): typeof Monaco {
20
+ return {
21
+ languages: {
22
+ getLanguages: vi.fn(() => languages),
23
+ },
24
+ } as unknown as typeof Monaco;
25
+ }
26
+
27
+ beforeEach(() => {
28
+ __resetBootstrapForTests();
29
+ setLanguageSettings.mockReset();
30
+ setMaximumWorkerIdleTime.mockReset();
31
+ vi.spyOn(console, 'error').mockImplementation(() => {});
32
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
33
+ });
34
+
35
+ afterEach(() => {
36
+ vi.restoreAllMocks();
37
+ });
38
+
39
+ describe('bootstrapKustoLanguage', () => {
40
+ it('imports @kusto/monaco-kusto and applies default settings on first call', async () => {
41
+ const monaco = makeMonaco();
42
+
43
+ await bootstrapKustoLanguage(monaco);
44
+
45
+ expect(setLanguageSettings).toHaveBeenCalledTimes(1);
46
+ const settings = setLanguageSettings.mock.calls[0][0];
47
+ expect(settings.enableHover).toBe(true);
48
+ expect(settings.enableQueryWarnings).toBe(true);
49
+ expect(settings.enableQuerySuggestions).toBe(true);
50
+ expect(settings.includeControlCommands).toBe(true);
51
+ expect(settings.completionOptions).toEqual({ includeExtendedSyntax: false });
52
+ });
53
+
54
+ it('is idempotent — repeated calls return the same promise without re-applying settings', async () => {
55
+ const monaco = makeMonaco();
56
+
57
+ const p1 = bootstrapKustoLanguage(monaco);
58
+ const p2 = bootstrapKustoLanguage(monaco);
59
+
60
+ expect(p1).toBe(p2);
61
+ await p1;
62
+ await p2;
63
+ expect(setLanguageSettings).toHaveBeenCalledTimes(1);
64
+ });
65
+
66
+ it('merges caller-provided settings over defaults', async () => {
67
+ const monaco = makeMonaco();
68
+
69
+ await bootstrapKustoLanguage(monaco, {
70
+ languageSettings: {
71
+ enableHover: false,
72
+ disabledDiagnosticCodes: ['KS107'],
73
+ },
74
+ });
75
+
76
+ const settings = setLanguageSettings.mock.calls[0][0];
77
+ expect(settings.enableHover).toBe(false);
78
+ expect(settings.enableQueryWarnings).toBe(true);
79
+ expect(settings.disabledDiagnosticCodes).toEqual(['KS107']);
80
+ expect(settings.completionOptions).toEqual({ includeExtendedSyntax: false });
81
+ });
82
+
83
+ it('falls back to default completionOptions when caller passes undefined', async () => {
84
+ const monaco = makeMonaco();
85
+
86
+ await bootstrapKustoLanguage(monaco, {
87
+ languageSettings: { completionOptions: undefined as never },
88
+ });
89
+
90
+ const settings = setLanguageSettings.mock.calls[0][0];
91
+ expect(settings.completionOptions).toEqual({ includeExtendedSyntax: false });
92
+ });
93
+
94
+ it('uses caller-provided completionOptions when present', async () => {
95
+ const monaco = makeMonaco();
96
+
97
+ await bootstrapKustoLanguage(monaco, {
98
+ languageSettings: { completionOptions: { includeExtendedSyntax: true } },
99
+ });
100
+
101
+ const settings = setLanguageSettings.mock.calls[0][0];
102
+ expect(settings.completionOptions).toEqual({ includeExtendedSyntax: true });
103
+ });
104
+
105
+ it('applies workerMaxIdleTimeMs when provided', async () => {
106
+ const monaco = makeMonaco();
107
+
108
+ await bootstrapKustoLanguage(monaco, { workerMaxIdleTimeMs: 5 * 60_000 });
109
+
110
+ expect(setMaximumWorkerIdleTime).toHaveBeenCalledWith(5 * 60_000);
111
+ });
112
+
113
+ it('does not call setMaximumWorkerIdleTime when not provided', async () => {
114
+ const monaco = makeMonaco();
115
+
116
+ await bootstrapKustoLanguage(monaco);
117
+
118
+ expect(setMaximumWorkerIdleTime).not.toHaveBeenCalled();
119
+ });
120
+
121
+ it('throws when the Monaco instance has no kusto language after import (two-Monaco)', async () => {
122
+ const monaco = makeMonaco([{ id: 'javascript' }]);
123
+
124
+ await expect(bootstrapKustoLanguage(monaco)).rejects.toThrow(/different Monaco instance/);
125
+ });
126
+
127
+ it('clears the cached promise on failure so a subsequent call can retry', async () => {
128
+ const monaco = makeMonaco([{ id: 'javascript' }]);
129
+
130
+ await expect(bootstrapKustoLanguage(monaco)).rejects.toThrow();
131
+
132
+ // After failure, the next call should re-attempt (and re-invoke setLanguageSettings).
133
+ const monaco2 = makeMonaco();
134
+ await bootstrapKustoLanguage(monaco2);
135
+
136
+ expect(setLanguageSettings).toHaveBeenCalledTimes(2);
137
+ });
138
+
139
+ it('throws a helpful error when @kusto/monaco-kusto did not expose kustoDefaults', async () => {
140
+ const monaco = makeMonaco();
141
+ const broken = kustoDefaults.setLanguageSettings;
142
+ kustoDefaults.setLanguageSettings = undefined as never;
143
+
144
+ try {
145
+ await expect(bootstrapKustoLanguage(monaco)).rejects.toThrow(/did not expose kustoDefaults/);
146
+ } finally {
147
+ kustoDefaults.setLanguageSettings = broken;
148
+ }
149
+ });
150
+ });