@mhjuma/traverse 0.1.0 → 0.3.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 (29) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/package.json +7 -4
  3. package/src/components/Explorer/Explorer.spec.tsx +122 -3
  4. package/src/components/Explorer/Explorer.tsx +82 -6
  5. package/src/components/ExplorerWorkspace/ExplorerWorkspace.logic.ts +26 -0
  6. package/src/components/ExplorerWorkspace/ExplorerWorkspace.spec.tsx +53 -17
  7. package/src/components/ExplorerWorkspace/ExplorerWorkspace.tsx +78 -74
  8. package/src/components/ExplorerWorkspace/bootstrapKustoLanguage.spec.ts +150 -0
  9. package/src/components/ExplorerWorkspace/bootstrapKustoLanguage.ts +95 -0
  10. package/src/components/ExplorerWorkspace/kustoSchemaQueue.spec.ts +322 -0
  11. package/src/components/ExplorerWorkspace/kustoSchemaQueue.ts +188 -0
  12. package/src/components/ExplorerWorkspace/monacoLoader.spec.ts +82 -0
  13. package/src/components/ExplorerWorkspace/monacoLoader.ts +57 -0
  14. package/src/components/ExplorerWorkspace/monacoWorkers.spec.ts +81 -0
  15. package/src/components/ExplorerWorkspace/monacoWorkers.ts +90 -0
  16. package/src/index.ts +4 -0
  17. package/src/services/schema.spec.ts +107 -28
  18. package/src/services/schema.ts +66 -25
  19. package/src/services/state-service.spec.ts +16 -0
  20. package/src/services/state-service.ts +12 -5
  21. package/src/state/persistence.spec.ts +239 -0
  22. package/src/state/persistence.ts +140 -0
  23. package/src/state/reducer.spec.ts +134 -3
  24. package/src/state/reducer.ts +39 -14
  25. package/src/state/types.ts +6 -0
  26. package/src/test-setup.ts +3 -0
  27. package/vitest.config.ts +7 -0
  28. package/src/components/ExplorerWorkspace/kqlLanguage.spec.ts +0 -321
  29. package/src/components/ExplorerWorkspace/kqlLanguage.ts +0 -155
package/CHANGELOG.md ADDED
@@ -0,0 +1,61 @@
1
+ # @mhjuma/traverse
2
+
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 57f602c: Replace the hand-rolled KQL Monarch tokenizer and regex completion provider
8
+ with the official `@kusto/monaco-kusto` language plugin (Kusto.Language engine
9
+ running in a Web Worker). This gives semantic highlighting, full IntelliSense
10
+ (let-bindings, joins, function defs, plugin functions), hover, signature help,
11
+ diagnostics, and formatting.
12
+
13
+ Breaking changes for hosts:
14
+
15
+ - `monaco-editor` and `@monaco-editor/react` are now peer dependencies. Hosts
16
+ must install them directly; `monaco-editor` must be pinned to `0.52.x` for
17
+ compatibility with `@kusto/monaco-kusto@14.x`.
18
+ - A new `configureTraverseMonacoWorkers({ getEditorWorker, getKustoWorker })`
19
+ must be called once before mounting `<Explorer>` to wire up the Monaco and
20
+ Kusto language workers. See the Quick Start guide for the Vite recipe and
21
+ notes on Webpack/Next.js hosts.
22
+
23
+ Bundle impact: the Kusto language service ships ~6 MB of compiled engine code
24
+ in a dedicated worker chunk, loaded lazily only when an editor mounts.
25
+
26
+ Perceived-perf optimizations: the kusto language registers (Monarch tokens
27
+ provider + themes) on first `<Explorer>` render via an internal
28
+ `preloadKustoLanguage()` call, so first paint already shows colored keywords
29
+ and strings. Hosts can additionally pre-warm the kusto worker during
30
+ `requestIdleCallback` (see Quick Start) to overlap Bridge.NET evaluation with
31
+ auth/React init — semantic-token colors then arrive without a visible delay.
32
+
33
+ ## 0.2.0
34
+
35
+ ### Minor Changes
36
+
37
+ - 286839b: Persist Explorer tabs across sessions and accept a custom default query.
38
+
39
+ - New optional `initialQuery` prop on `<Explorer />`. When set, it seeds the
40
+ editor on first load if there's no persisted snapshot and no `?query=`
41
+ URL parameter. Falls back to the package's `DEFAULT_QUERY` when omitted.
42
+ - New `explorerTabs` `StateService` store (persisted to IndexedDB and
43
+ mirrored to localStorage for synchronous bootstrap on page load).
44
+ - The Explorer reducer now hydrates `tabs`, `activeTabId`, and split-pane
45
+ state from a versioned snapshot. Stale connection ids on restored tabs
46
+ are remapped to the active connection so KQL is never lost. Invalid
47
+ split state is reset.
48
+ - The `tabs[]` and split slices are saved with a 300ms debounce on every
49
+ reducer transition that mutates them. Pending writes are flushed on
50
+ component unmount and on `pagehide` so edits made just before a refresh
51
+ or tab close are not dropped.
52
+ - Deep-links with `?query=` continue to win for the initial render and
53
+ are now treated as ephemeral: they bypass the snapshot on load AND do
54
+ not write back to it, so a shared link cannot clobber the user's
55
+ saved workspace.
56
+ - New exports: `loadSnapshot`, `saveSnapshot`, `clearSnapshot`,
57
+ `validateAndCleanSnapshot`, `extractSnapshot`, `SNAPSHOT_VERSION`,
58
+ and the `ExplorerTabsSnapshot` type.
59
+
60
+ The IndexedDB schema version is bumped to `2` to create the new object
61
+ store for existing users; no data migration is required.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mhjuma/traverse",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -10,9 +10,8 @@
10
10
  "dependencies": {
11
11
  "@fluentui/react-components": "9.73.7",
12
12
  "@fluentui/react-icons": "2.0.323",
13
- "@monaco-editor/react": "4.7.0",
13
+ "@kusto/monaco-kusto": "14.1.0",
14
14
  "@tanstack/react-virtual": "3.13.23",
15
- "monaco-editor": "0.55.1",
16
15
  "react": "19.2.5",
17
16
  "react-dom": "19.2.5",
18
17
  "vega": "6.2.0",
@@ -20,7 +19,9 @@
20
19
  "vega-tooltip": "1.1.0"
21
20
  },
22
21
  "peerDependencies": {
23
- "@azure/msal-browser": ">=3.0.0"
22
+ "@azure/msal-browser": ">=3.0.0",
23
+ "@monaco-editor/react": "4.7.0",
24
+ "monaco-editor": "0.52.2"
24
25
  },
25
26
  "peerDependenciesMeta": {
26
27
  "@azure/msal-browser": {
@@ -29,6 +30,8 @@
29
30
  },
30
31
  "devDependencies": {
31
32
  "@azure/msal-browser": "5.6.3",
33
+ "@monaco-editor/react": "4.7.0",
34
+ "monaco-editor": "0.52.2",
32
35
  "@types/react": "19.2.14",
33
36
  "@types/react-dom": "19.2.3",
34
37
  "oxlint": "1.59.0",
@@ -6,6 +6,7 @@ import { Explorer } from './Explorer';
6
6
 
7
7
  vi.mock('@monaco-editor/react', () => ({
8
8
  Editor: () => React.createElement('div', { 'data-testid': 'monaco-editor' }),
9
+ loader: { config: vi.fn() },
9
10
  }));
10
11
  vi.mock('../../services/kusto', () => ({
11
12
  queryKusto: vi.fn().mockResolvedValue({ columns: [], rows: [] }),
@@ -61,6 +62,7 @@ vi.mock('../ExplorerWorkspace/ExplorerWorkspace.logic', () => ({
61
62
  getQueryToRunFromEditor: vi.fn(() => ''),
62
63
  KEYBOARD_SHORTCUTS: [],
63
64
  createTab: vi.fn((q: string, title: string) => ({ id: '1', query: q, title, kql: '', connectionId: 'test-conn' })),
65
+ bumpTabCounterPast: vi.fn(),
64
66
  loadConnections: vi.fn(() => [{ id: 'test-conn', name: 'Test Cluster', clusterUrl: 'https://help.kusto.windows.net', database: 'Telemetry', color: '#909d63' }]),
65
67
  loadActiveConnectionId: vi.fn(() => 'test-conn'),
66
68
  saveConnections: vi.fn(),
@@ -74,10 +76,27 @@ vi.mock('../ExplorerWorkspace/ExplorerWorkspace.logic', () => ({
74
76
  DEFAULT_CONNECTION: { id: 'test-conn', name: 'Test Cluster', clusterUrl: 'https://help.kusto.windows.net', database: 'Telemetry', color: '#909d63' },
75
77
  CONNECTION_COLORS: ['#909d63', '#6a8799', '#ebc17a', '#bc5653', '#b06698'],
76
78
  }));
77
- vi.mock('../ExplorerWorkspace/kqlLanguage', () => ({
78
- registerKqlLanguage: vi.fn(),
79
- setKqlSchemaResolver: vi.fn(),
79
+ // Stub persistence so the save effect doesn't write to a real stateService
80
+ // and the createInitialState hydration path returns null deterministically.
81
+ vi.mock('../../state/persistence', () => ({
82
+ SNAPSHOT_VERSION: 1,
83
+ loadSnapshot: vi.fn(() => null),
84
+ saveSnapshot: vi.fn(),
85
+ clearSnapshot: vi.fn(),
86
+ validateAndCleanSnapshot: vi.fn(() => null),
87
+ extractSnapshot: vi.fn((s: { tabs: unknown[]; activeTabId: string }) => ({ version: 1, tabs: s.tabs, activeTabId: s.activeTabId, splitEnabled: false, splitDirection: 'vertical', splitTabId: null, focusedPane: 'primary' })),
80
88
  }));
89
+ vi.mock('../ExplorerWorkspace/bootstrapKustoLanguage', () => ({
90
+ bootstrapKustoLanguage: vi.fn().mockResolvedValue(undefined),
91
+ }));
92
+ vi.mock('../ExplorerWorkspace/kustoSchemaQueue', () => ({
93
+ applyKustoSchema: vi.fn(),
94
+ }));
95
+ // Stub `@kusto/monaco-kusto` — Vitest cannot resolve the real package
96
+ // against jsdom (engine + worker globals are not available). Keeping the
97
+ // stub minimal avoids unhandled-rejection noise from `kustoSchemaQueue`'s
98
+ // dynamic import path.
99
+ vi.mock('@kusto/monaco-kusto', () => ({ kustoDefaults: {}, getKustoWorker: () => Promise.resolve(() => Promise.resolve({})) }));
81
100
  vi.mock('@fluentui/react-components', () => ({
82
101
  Button: (p: Record<string, unknown>) => React.createElement('button', p, p['children'] as React.ReactNode),
83
102
  Tooltip: (p: Record<string, unknown>) => React.createElement('div', null, p['children'] as React.ReactNode),
@@ -613,3 +632,103 @@ describe('Explorer', () => {
613
632
  expect(container.innerHTML).not.toBe('');
614
633
  });
615
634
  });
635
+
636
+ describe('Explorer snapshot persistence', () => {
637
+ let container: HTMLDivElement;
638
+ let root: ReturnType<typeof createRoot>;
639
+ let originalLocation: Location;
640
+ let saveSpy: ReturnType<typeof vi.fn>;
641
+
642
+ beforeEach(async () => {
643
+ vi.useFakeTimers();
644
+ vi.spyOn(console, 'error').mockImplementation(() => {});
645
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
646
+ container = document.createElement('div');
647
+ document.body.appendChild(container);
648
+ root = createRoot(container);
649
+ mockExplorerState.mockReturnValue(defaultExplorerState);
650
+ mockActiveTabs.mockReturnValue({ activeTab: mockActiveTab, splitTab: null });
651
+ originalLocation = window.location;
652
+
653
+ const persistence = await import('../../state/persistence');
654
+ saveSpy = persistence.saveSnapshot as unknown as ReturnType<typeof vi.fn>;
655
+ saveSpy.mockClear();
656
+ });
657
+
658
+ afterEach(() => {
659
+ act(() => { root.unmount(); });
660
+ container.remove();
661
+ vi.useRealTimers();
662
+ Object.defineProperty(window, 'location', { value: originalLocation, writable: true });
663
+ vi.restoreAllMocks();
664
+ });
665
+
666
+ function setUrlQuery(query: string | null) {
667
+ const search = query ? `?query=${encodeURIComponent(query)}` : '';
668
+ Object.defineProperty(window, 'location', {
669
+ value: { ...originalLocation, search } as Location,
670
+ writable: true,
671
+ });
672
+ }
673
+
674
+ it('persists the tab snapshot after the debounce window', () => {
675
+ setUrlQuery(null);
676
+ act(() => { root.render(React.createElement(Explorer)); });
677
+ expect(saveSpy).not.toHaveBeenCalled();
678
+
679
+ act(() => { vi.advanceTimersByTime(300); });
680
+
681
+ expect(saveSpy).toHaveBeenCalledTimes(1);
682
+ const arg = saveSpy.mock.calls[0][0] as { version: number; tabs: unknown[] };
683
+ expect(arg.version).toBe(1);
684
+ expect(Array.isArray(arg.tabs)).toBe(true);
685
+ });
686
+
687
+ it('does not persist when in deep-link (?query=) mode', () => {
688
+ setUrlQuery('SomeTable | take 5');
689
+ act(() => { root.render(React.createElement(Explorer)); });
690
+ act(() => { vi.advanceTimersByTime(1000); });
691
+ expect(saveSpy).not.toHaveBeenCalled();
692
+ });
693
+
694
+ it('does not persist on pagehide while in deep-link mode', () => {
695
+ setUrlQuery('SomeTable | take 5');
696
+ act(() => { root.render(React.createElement(Explorer)); });
697
+ act(() => { window.dispatchEvent(new Event('pagehide')); });
698
+ act(() => { vi.advanceTimersByTime(1000); });
699
+ expect(saveSpy).not.toHaveBeenCalled();
700
+ });
701
+
702
+ it('flushes a pending snapshot on component unmount', () => {
703
+ setUrlQuery(null);
704
+ act(() => { root.render(React.createElement(Explorer)); });
705
+ // Pending in the debounce window — debounce timer not yet elapsed.
706
+ expect(saveSpy).not.toHaveBeenCalled();
707
+
708
+ act(() => { root.unmount(); });
709
+
710
+ expect(saveSpy).toHaveBeenCalledTimes(1);
711
+ });
712
+
713
+ it('flushes a pending snapshot on pagehide', () => {
714
+ setUrlQuery(null);
715
+ act(() => { root.render(React.createElement(Explorer)); });
716
+ expect(saveSpy).not.toHaveBeenCalled();
717
+
718
+ act(() => { window.dispatchEvent(new Event('pagehide')); });
719
+
720
+ expect(saveSpy).toHaveBeenCalledTimes(1);
721
+ });
722
+
723
+ it('does not double-flush after the debounce already saved', () => {
724
+ setUrlQuery(null);
725
+ act(() => { root.render(React.createElement(Explorer)); });
726
+ act(() => { vi.advanceTimersByTime(300); });
727
+ expect(saveSpy).toHaveBeenCalledTimes(1);
728
+
729
+ act(() => { window.dispatchEvent(new Event('pagehide')); });
730
+
731
+ // Debounced write already cleared pendingRef; pagehide is a no-op.
732
+ expect(saveSpy).toHaveBeenCalledTimes(1);
733
+ });
734
+ });
@@ -1,4 +1,4 @@
1
- import { useMemo, useReducer } from 'react';
1
+ import { useEffect, useMemo, useReducer, useRef } from 'react';
2
2
 
3
3
  import type { ExplorerColorConfig } from '../../colors';
4
4
  import type { KustoClient } from '../../services/kusto';
@@ -6,9 +6,12 @@ import { KustoClientContext } from '../../context/KustoClientContext';
6
6
  import { ExplorerColorProvider } from '../../context/ExplorerColorContext';
7
7
  import { ExplorerStateContext, ExplorerDispatchContext } from '../../context/ExplorerStateContext';
8
8
  import { explorerReducer, createInitialState } from '../../state';
9
+ import { SNAPSHOT_VERSION, saveSnapshot } from '../../state/persistence';
10
+ import type { ExplorerTabsSnapshot } from '../../state/persistence';
9
11
  import { DEFAULT_QUERY, buildWellKnownClusters } from '../ExplorerWorkspace/ExplorerWorkspace.logic';
10
12
  import type { WellKnownCluster } from '../ExplorerWorkspace/ExplorerWorkspace.logic';
11
13
  import { ExplorerWorkspace } from '../ExplorerWorkspace/ExplorerWorkspace';
14
+ import { preloadKustoLanguage } from '../ExplorerWorkspace/monacoLoader';
12
15
 
13
16
  export interface ExplorerProps {
14
17
  className?: string;
@@ -17,24 +20,97 @@ export interface ExplorerProps {
17
20
  colors: ExplorerColorConfig;
18
21
  clusters?: readonly WellKnownCluster[];
19
22
  enableTabShortcuts?: boolean;
23
+ /**
24
+ * Query to seed the editor with on first load when there is no
25
+ * persisted tab snapshot and no `?query=` URL parameter.
26
+ * Falls back to the package's built-in `DEFAULT_QUERY` when omitted.
27
+ */
28
+ initialQuery?: string;
20
29
  }
21
30
 
31
+ /**
32
+ * Debounce window (ms) for persisting the tab snapshot. Long enough to
33
+ * coalesce keystrokes into a single write, short enough that a casual
34
+ * tab-switch or refresh after typing still captures the user's edits.
35
+ */
36
+ const SNAPSHOT_SAVE_DEBOUNCE_MS = 300;
37
+
22
38
  export function Explorer(props: ExplorerProps) {
23
- const initialQuery = useMemo(() => {
39
+ // Trigger kusto language preload on first Explorer render. Editor-gated
40
+ // by design (here, not at module load) so consumers using only
41
+ // non-editor APIs from `@mhjuma/traverse` don't pay the kusto chunk cost.
42
+ // Idempotent — internally guarded so subsequent renders are no-ops.
43
+ preloadKustoLanguage();
44
+
45
+ const { initialQuery: providedInitialQuery } = props;
46
+
47
+ const { initialQuery, hasUrlQuery } = useMemo(() => {
24
48
  try {
25
49
  const params = new URLSearchParams(window.location.search);
26
50
  const q = params.get('query');
27
51
  if (q) {
28
- return q;
52
+ return { initialQuery: q, hasUrlQuery: true };
29
53
  }
30
54
  } catch { /* ignore */ }
31
- return DEFAULT_QUERY;
32
- }, []);
55
+ return { initialQuery: providedInitialQuery ?? DEFAULT_QUERY, hasUrlQuery: false };
56
+ }, [providedInitialQuery]);
33
57
 
34
58
  const defaultClusters = useMemo(() => buildWellKnownClusters(props.clusters ?? []), [props.clusters]);
35
- const initArgs = useMemo(() => ({ initialQuery, defaultClusters }), [initialQuery, defaultClusters]);
59
+ const initArgs = useMemo(
60
+ () => ({ initialQuery, defaultClusters, skipSnapshot: hasUrlQuery }),
61
+ [initialQuery, defaultClusters, hasUrlQuery],
62
+ );
36
63
  const [state, dispatch] = useReducer(explorerReducer, initArgs, createInitialState);
37
64
 
65
+ // Persist tab/split state with a small debounce.
66
+ //
67
+ // - Deep-link mode (URL `?query=`) treats the visible workspace as
68
+ // ephemeral. We never write it back to the snapshot store, so the
69
+ // user's normal saved workspace is preserved.
70
+ // - On rapid unmount or page-hide (refresh, tab close), a pending
71
+ // debounced save would otherwise be cancelled. `pendingRef` lets
72
+ // us flush the latest snapshot synchronously in those moments so
73
+ // recent edits are not dropped.
74
+ const { tabs, activeTabId, splitEnabled, splitDirection, splitTabId, focusedPane } = state;
75
+ const pendingRef = useRef<ExplorerTabsSnapshot | null>(null);
76
+
77
+ useEffect(() => {
78
+ if (hasUrlQuery) {
79
+ return;
80
+ }
81
+ const snap: ExplorerTabsSnapshot = {
82
+ version: SNAPSHOT_VERSION,
83
+ tabs, activeTabId, splitEnabled, splitDirection, splitTabId, focusedPane,
84
+ };
85
+ pendingRef.current = snap;
86
+ const handle = setTimeout(() => {
87
+ saveSnapshot(snap);
88
+ pendingRef.current = null;
89
+ }, SNAPSHOT_SAVE_DEBOUNCE_MS);
90
+ return () => clearTimeout(handle);
91
+ }, [hasUrlQuery, tabs, activeTabId, splitEnabled, splitDirection, splitTabId, focusedPane]);
92
+
93
+ useEffect(() => {
94
+ if (hasUrlQuery) {
95
+ return;
96
+ }
97
+ const flush = () => {
98
+ if (pendingRef.current) {
99
+ saveSnapshot(pendingRef.current);
100
+ pendingRef.current = null;
101
+ }
102
+ };
103
+ window.addEventListener('pagehide', flush);
104
+ return () => {
105
+ window.removeEventListener('pagehide', flush);
106
+ flush();
107
+ };
108
+ }, [hasUrlQuery]);
109
+
110
+ // The Kusto language is pre-bootstrapped in monacoLoader.ts at module
111
+ // load time so the editor's first paint already has Monarch tokens and
112
+ // themes registered. No idle-callback prefetch needed here.
113
+
38
114
  return (
39
115
  <KustoClientContext.Provider value={props.kustoClient}>
40
116
  <ExplorerColorProvider value={props.colors}>
@@ -53,6 +53,32 @@ export function createTab(kql = '', title?: string, connectionId = ''): QueryTab
53
53
  return { id, title: title ?? `Query ${n}`, kql, connectionId };
54
54
  }
55
55
 
56
+ /**
57
+ * Bump the internal tab counter so it sits past the highest numeric suffix
58
+ * in the supplied tab ids. Used by snapshot hydration to ensure ids created
59
+ * by subsequent createTab() calls do not collide with restored ids.
60
+ */
61
+ export function bumpTabCounterPast(tabs: readonly QueryTab[]): void {
62
+ let max = 0;
63
+ for (const t of tabs) {
64
+ const m = /^tab-(\d+)$/.exec(t.id);
65
+ if (m) {
66
+ const n = Number(m[1]);
67
+ if (Number.isFinite(n) && n > max) {
68
+ max = n;
69
+ }
70
+ }
71
+ }
72
+ if (max + 1 > tabCounter) {
73
+ tabCounter = max + 1;
74
+ }
75
+ }
76
+
77
+ /** Test-only helper to reset the module-scoped tab counter. */
78
+ export function _resetTabCounter(n: number = 1): void {
79
+ tabCounter = n;
80
+ }
81
+
56
82
  export function nextQueryTitle(existingTabs: QueryTab[]): string {
57
83
  const used = new Set(
58
84
  existingTabs
@@ -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 ---