@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 M Juma
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@mhjuma/traverse",
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "main": "src/index.ts",
9
+ "types": "src/index.ts",
10
+ "dependencies": {
11
+ "@fluentui/react-components": "9.73.7",
12
+ "@fluentui/react-icons": "2.0.323",
13
+ "@monaco-editor/react": "4.7.0",
14
+ "@tanstack/react-virtual": "3.13.23",
15
+ "monaco-editor": "0.55.1",
16
+ "react": "19.2.5",
17
+ "react-dom": "19.2.5",
18
+ "vega": "6.2.0",
19
+ "vega-lite": "6.4.2",
20
+ "vega-tooltip": "1.1.0"
21
+ },
22
+ "peerDependencies": {
23
+ "@azure/msal-browser": ">=3.0.0"
24
+ },
25
+ "peerDependenciesMeta": {
26
+ "@azure/msal-browser": {
27
+ "optional": true
28
+ }
29
+ },
30
+ "devDependencies": {
31
+ "@azure/msal-browser": "5.6.3",
32
+ "@types/react": "19.2.14",
33
+ "@types/react-dom": "19.2.3",
34
+ "oxlint": "1.59.0",
35
+ "oxlint-tsgolint": "0.20.0",
36
+ "typescript": "6.0.2",
37
+ "@vitest/coverage-v8": "4.1.4",
38
+ "vitest": "4.1.4",
39
+ "jsdom": "29.0.2"
40
+ },
41
+ "scripts": {
42
+ "build": "tsc --noEmit",
43
+ "lint": "oxlint -c ../../oxlintrc.react.json --tsconfig tsconfig.lint.json --type-aware src/",
44
+ "test": "vitest run"
45
+ }
46
+ }
@@ -0,0 +1,290 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import { createElement } from 'react';
3
+ import { createRoot } from 'react-dom/client';
4
+ import { act } from 'react';
5
+ import { webDarkTheme, webLightTheme } from '@fluentui/react-components';
6
+
7
+ import { useExplorerTheme, bootstrapExplorer } from './bootstrap';
8
+ import { stateService } from './services/state-service';
9
+
10
+ vi.mock('./services/state-service', () => {
11
+ const store = new Map<string, unknown>();
12
+ return {
13
+ stateService: {
14
+ get: (_s: string, key: string) => store.get(key) ?? null,
15
+ set: (_s: string, key: string, value: unknown) => { store.set(key, value); },
16
+ hydrate: vi.fn().mockResolvedValue(undefined),
17
+ },
18
+ };
19
+ });
20
+ vi.mock('./services/kusto', () => ({
21
+ createKustoClient: vi.fn().mockReturnValue({
22
+ queryKusto: vi.fn(),
23
+ queryKustoMgmt: vi.fn(),
24
+ clearQueryCache: vi.fn(),
25
+ getQueryCacheSize: vi.fn().mockReturnValue(0),
26
+ }),
27
+ }));
28
+ vi.mock('./components/Explorer/Explorer', () => ({
29
+ Explorer: () => createElement('div', { 'data-testid': 'explorer' }),
30
+ }));
31
+ vi.mock('./context/KustoClientContext', () => ({
32
+ KustoClientContext: { Provider: (p: Record<string, unknown>) => createElement('div', null, p['children'] as React.ReactNode) },
33
+ }));
34
+ vi.mock('@azure/msal-browser', () => {
35
+ class MockPublicClientApplication {
36
+ initialize = vi.fn().mockResolvedValue(undefined);
37
+ getAllAccounts = vi.fn().mockReturnValue([]);
38
+ acquireTokenPopup = vi.fn().mockResolvedValue({ accessToken: 'token' });
39
+ acquireTokenSilent = vi.fn().mockResolvedValue({ accessToken: 'token' });
40
+ handleRedirectPromise = vi.fn().mockResolvedValue(null);
41
+ loginRedirect = vi.fn().mockResolvedValue(undefined);
42
+ }
43
+ return { PublicClientApplication: MockPublicClientApplication };
44
+ });
45
+
46
+ let container: HTMLDivElement;
47
+ let root: ReturnType<typeof createRoot>;
48
+
49
+ beforeEach(() => {
50
+ vi.spyOn(console, 'error').mockImplementation(() => {});
51
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
52
+ // Reset stored theme between tests
53
+ stateService.set('config', 'theme', null);
54
+ if (!window.matchMedia) {
55
+ Object.defineProperty(window, 'matchMedia', {
56
+ writable: true,
57
+ value: vi.fn().mockReturnValue({
58
+ matches: false,
59
+ addEventListener: vi.fn(),
60
+ removeEventListener: vi.fn(),
61
+ }),
62
+ });
63
+ }
64
+ container = document.createElement('div');
65
+ document.body.appendChild(container);
66
+ root = createRoot(container);
67
+ });
68
+
69
+ afterEach(() => {
70
+ act(() => { root.unmount(); });
71
+ container.remove();
72
+ vi.restoreAllMocks();
73
+ delete (window as unknown as Record<string, unknown>)['__explorerSetTheme'];
74
+ });
75
+
76
+ function renderThemeHook(dark = webDarkTheme, light = webLightTheme): { isDark: boolean; theme: unknown } {
77
+ let result = { isDark: false, theme: null as unknown };
78
+ function TestComponent() {
79
+ const r = useExplorerTheme(dark, light);
80
+ result = r;
81
+ return null;
82
+ }
83
+ act(() => { root.render(createElement(TestComponent)); });
84
+ return result;
85
+ }
86
+
87
+ describe('useExplorerTheme', () => {
88
+ it('defaults to system preference', () => {
89
+ const result = renderThemeHook();
90
+ expect(typeof result.isDark).toBe('boolean');
91
+ });
92
+
93
+ it('returns dark theme when system prefers dark', () => {
94
+ const matchMediaMock = vi.fn().mockReturnValue({
95
+ matches: true,
96
+ addEventListener: vi.fn(),
97
+ removeEventListener: vi.fn(),
98
+ });
99
+ vi.stubGlobal('matchMedia', matchMediaMock);
100
+
101
+ const result = renderThemeHook();
102
+ expect(result.isDark).toBe(true);
103
+
104
+ vi.unstubAllGlobals();
105
+ });
106
+
107
+ it('returns light theme when system prefers light', () => {
108
+ const matchMediaMock = vi.fn().mockReturnValue({
109
+ matches: false,
110
+ addEventListener: vi.fn(),
111
+ removeEventListener: vi.fn(),
112
+ });
113
+ vi.stubGlobal('matchMedia', matchMediaMock);
114
+
115
+ const result = renderThemeHook();
116
+ expect(result.isDark).toBe(false);
117
+
118
+ vi.unstubAllGlobals();
119
+ });
120
+
121
+ it('returns correct theme object for light mode', () => {
122
+ const matchMediaMock = vi.fn().mockReturnValue({
123
+ matches: false,
124
+ addEventListener: vi.fn(),
125
+ removeEventListener: vi.fn(),
126
+ });
127
+ vi.stubGlobal('matchMedia', matchMediaMock);
128
+
129
+ const result = renderThemeHook();
130
+ expect(result.theme).toBe(webLightTheme);
131
+
132
+ vi.unstubAllGlobals();
133
+ });
134
+
135
+ it('returns correct theme object for dark mode', () => {
136
+ const matchMediaMock = vi.fn().mockReturnValue({
137
+ matches: true,
138
+ addEventListener: vi.fn(),
139
+ removeEventListener: vi.fn(),
140
+ });
141
+ vi.stubGlobal('matchMedia', matchMediaMock);
142
+
143
+ const result = renderThemeHook();
144
+ expect(result.theme).toBe(webDarkTheme);
145
+
146
+ vi.unstubAllGlobals();
147
+ });
148
+
149
+ it('exposes __explorerSetTheme on window', () => {
150
+ renderThemeHook();
151
+ expect(typeof (window as unknown as Record<string, unknown>)['__explorerSetTheme']).toBe('function');
152
+ });
153
+
154
+ it('__explorerSetTheme switches to dark mode', () => {
155
+ const matchMediaMock = vi.fn().mockReturnValue({
156
+ matches: false,
157
+ addEventListener: vi.fn(),
158
+ removeEventListener: vi.fn(),
159
+ });
160
+ vi.stubGlobal('matchMedia', matchMediaMock);
161
+
162
+ let result = { isDark: false, theme: null as unknown };
163
+ function TestComponent() {
164
+ const r = useExplorerTheme(webDarkTheme, webLightTheme);
165
+ result = r;
166
+ return null;
167
+ }
168
+ act(() => { root.render(createElement(TestComponent)); });
169
+ expect(result.isDark).toBe(false);
170
+
171
+ // Invoke the exposed setter
172
+ const setTheme = (window as unknown as Record<string, unknown>)['__explorerSetTheme'] as (mode: string) => void;
173
+ act(() => { setTheme('dark'); });
174
+ expect(result.isDark).toBe(true);
175
+
176
+ vi.unstubAllGlobals();
177
+ });
178
+
179
+ it('responds to system media query change events', () => {
180
+ // Reset stored theme to ensure system preference is used
181
+ stateService.set('config', 'theme', 'system');
182
+
183
+ let capturedHandler: ((e: MediaQueryListEvent) => void) | null = null;
184
+ const matchMediaMock = vi.fn().mockReturnValue({
185
+ matches: false,
186
+ addEventListener: (_: string, handler: (e: MediaQueryListEvent) => void) => {
187
+ capturedHandler = handler;
188
+ },
189
+ removeEventListener: vi.fn(),
190
+ });
191
+ vi.stubGlobal('matchMedia', matchMediaMock);
192
+
193
+ let result = { isDark: false, theme: null as unknown };
194
+ function TestComponent() {
195
+ const r = useExplorerTheme(webDarkTheme, webLightTheme);
196
+ result = r;
197
+ return null;
198
+ }
199
+ act(() => { root.render(createElement(TestComponent)); });
200
+ expect(result.isDark).toBe(false);
201
+
202
+ // Simulate system dark mode change
203
+ if (capturedHandler) {
204
+ act(() => { capturedHandler!({ matches: true } as MediaQueryListEvent); });
205
+ expect(result.isDark).toBe(true);
206
+ }
207
+
208
+ vi.unstubAllGlobals();
209
+ });
210
+
211
+ it('persists theme to stateService when changed', () => {
212
+ const setSpy = vi.spyOn(stateService, 'set');
213
+ const matchMediaMock = vi.fn().mockReturnValue({
214
+ matches: false,
215
+ addEventListener: vi.fn(),
216
+ removeEventListener: vi.fn(),
217
+ });
218
+ vi.stubGlobal('matchMedia', matchMediaMock);
219
+
220
+ function TestComponent() {
221
+ useExplorerTheme(webDarkTheme, webLightTheme);
222
+ return null;
223
+ }
224
+ act(() => { root.render(createElement(TestComponent)); });
225
+
226
+ // The hook persists the theme mode on mount
227
+ expect(setSpy).toHaveBeenCalled();
228
+
229
+ vi.unstubAllGlobals();
230
+ });
231
+
232
+ it('reads saved theme from stateService', () => {
233
+
234
+ stateService.set('config', 'theme', 'dark');
235
+
236
+ const matchMediaMock = vi.fn().mockReturnValue({
237
+ matches: false,
238
+ addEventListener: vi.fn(),
239
+ removeEventListener: vi.fn(),
240
+ });
241
+ vi.stubGlobal('matchMedia', matchMediaMock);
242
+
243
+ const result = renderThemeHook();
244
+ expect(result.isDark).toBe(true);
245
+
246
+ vi.unstubAllGlobals();
247
+ });
248
+
249
+ it('cleans up __explorerSetTheme on unmount', () => {
250
+ function TestComponent() {
251
+ useExplorerTheme(webDarkTheme, webLightTheme);
252
+ return null;
253
+ }
254
+ act(() => { root.render(createElement(TestComponent)); });
255
+ expect((window as unknown as Record<string, unknown>)['__explorerSetTheme']).toBeDefined();
256
+
257
+ act(() => { root.unmount(); });
258
+ root = createRoot(container);
259
+ expect((window as unknown as Record<string, unknown>)['__explorerSetTheme']).toBeUndefined();
260
+ });
261
+ });
262
+
263
+ describe('bootstrapExplorer', () => {
264
+ it('is a function', () => {
265
+ expect(typeof bootstrapExplorer).toBe('function');
266
+ });
267
+
268
+ it('calls stateService.hydrate on invocation', async () => {
269
+ const rootEl = document.createElement('div');
270
+ rootEl.id = 'root';
271
+ document.body.appendChild(rootEl);
272
+
273
+ const hydrateSpy = vi.spyOn(stateService, 'hydrate');
274
+
275
+ bootstrapExplorer({
276
+ msalClientId: 'test-client',
277
+ tenantId: 'test-tenant',
278
+ redirectUri: 'http://localhost:3000',
279
+ clusterUrl: 'https://help.kusto.windows.net',
280
+ database: 'Samples',
281
+ });
282
+
283
+ expect(hydrateSpy).toHaveBeenCalled();
284
+
285
+ // Wait for the async chain (hydrate → auth → render) to settle
286
+ await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
287
+
288
+ rootEl.remove();
289
+ });
290
+ });
@@ -0,0 +1,195 @@
1
+ import { StrictMode, useState, useEffect, useMemo } from 'react';
2
+ import { createRoot } from 'react-dom/client';
3
+ import { FluentProvider, makeStyles, webDarkTheme, webLightTheme } from '@fluentui/react-components';
4
+ import type { Theme } from '@fluentui/react-components';
5
+ import { PublicClientApplication } from '@azure/msal-browser';
6
+
7
+ import { stateService } from './services/state-service';
8
+ import { createKustoClient } from './services/kusto';
9
+ import { Explorer } from './components/Explorer/Explorer';
10
+ import { KustoClientContext } from './context/KustoClientContext';
11
+ import type { ExplorerColorConfig } from './colors';
12
+ import type { WellKnownCluster } from './config';
13
+
14
+ type ThemeMode = 'system' | 'light' | 'dark';
15
+
16
+ const fullHeightStyle = { height: '100%' } as const;
17
+
18
+ const DEFAULT_COLORS: ExplorerColorConfig = {
19
+ semantic: {
20
+ backdrop: 'rgba(0, 0, 0, 0.4)',
21
+ functionBadge: '#4caf50',
22
+ highlightHoverBg: 'rgba(255, 200, 0, 0.2)',
23
+ lookupBadge: '#e8912d',
24
+ materializedViewBadge: '#9c6ade',
25
+ scrollThumb: 'rgba(128, 128, 128, 0.4)',
26
+ scrollThumbHover: 'rgba(128, 128, 128, 0.6)',
27
+ selectionBg: 'rgba(0, 120, 212, 0.15)',
28
+ selectionSubtle: 'rgba(0, 120, 212, 0.06)',
29
+ shadowLight: 'rgba(0, 0, 0, 0.15)',
30
+ shadowMedium: 'rgba(0, 0, 0, 0.3)',
31
+ },
32
+ chart: {
33
+ palette: ['#6a8799', '#909d63', '#ebc17a', '#bc5653', '#b06698', '#c9dfff', '#7eaac7', '#acbbd0', '#636363', '#d9d9d9'],
34
+ },
35
+ };
36
+
37
+ const useStyles = makeStyles({
38
+ fullPage: {
39
+ display: 'flex',
40
+ flexDirection: 'column',
41
+ height: '100vh',
42
+ overflow: 'hidden',
43
+ },
44
+ });
45
+
46
+ export function useExplorerTheme(darkTheme: Theme, lightTheme: Theme): { theme: Theme; isDark: boolean } {
47
+ const [themeMode, setThemeMode] = useState<ThemeMode>(() => {
48
+ const saved = stateService.get<ThemeMode>('config', 'theme');
49
+ return saved === 'light' || saved === 'dark' || saved === 'system' ? saved : 'system';
50
+ });
51
+ const [systemPref, setSystemPref] = useState<'light' | 'dark'>(
52
+ () => window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light',
53
+ );
54
+
55
+ useEffect(() => {
56
+ stateService.set('config', 'theme', themeMode);
57
+ }, [themeMode]);
58
+
59
+ useEffect(() => {
60
+ const mq = window.matchMedia('(prefers-color-scheme: dark)');
61
+ const handler = (e: MediaQueryListEvent) => {
62
+ setSystemPref(e.matches ? 'dark' : 'light');
63
+ };
64
+ mq.addEventListener('change', handler);
65
+ return () => mq.removeEventListener('change', handler);
66
+ }, []);
67
+
68
+ // Expose setThemeMode on the window for settings UI (optional)
69
+ useEffect(() => {
70
+ (window as unknown as Record<string, unknown>)['__explorerSetTheme'] = setThemeMode;
71
+ return () => { delete (window as unknown as Record<string, unknown>)['__explorerSetTheme']; };
72
+ }, []);
73
+
74
+ const isDark = themeMode === 'dark' || (themeMode === 'system' && systemPref === 'dark');
75
+ const theme = useMemo(() => isDark ? darkTheme : lightTheme, [isDark, darkTheme, lightTheme]);
76
+
77
+ return { theme, isDark };
78
+ }
79
+
80
+ export interface BootstrapExplorerOptions {
81
+ /** MSAL client ID for Azure AD authentication. */
82
+ msalClientId: string;
83
+ /** Azure AD tenant ID. */
84
+ tenantId: string;
85
+ /** MSAL redirect URI (e.g. 'http://localhost:3000'). */
86
+ redirectUri: string;
87
+ /** Default Kusto cluster URL. */
88
+ clusterUrl: string;
89
+ /** Default Kusto database name. */
90
+ database: string;
91
+ /** Fluent UI theme for dark mode. @default webDarkTheme */
92
+ darkTheme?: Theme;
93
+ /** Fluent UI theme for light mode. @default webLightTheme */
94
+ lightTheme?: Theme;
95
+ /** Pre-seeded cluster list shown in the connection picker. */
96
+ clusters?: WellKnownCluster[];
97
+ /** Override the default explorer color config. */
98
+ colors?: ExplorerColorConfig;
99
+ }
100
+
101
+ /**
102
+ * Bootstraps a standalone Explorer app: handles MSAL auth, StateService
103
+ * hydration, and renders the Explorer into #root.
104
+ */
105
+ export function bootstrapExplorer(options: BootstrapExplorerOptions): void {
106
+ const {
107
+ msalClientId, tenantId, redirectUri,
108
+ clusterUrl, database,
109
+ darkTheme = webDarkTheme,
110
+ lightTheme = webLightTheme,
111
+ clusters = [{ id: 'default', name: clusterUrl.replace(/^https?:\/\//, '').replace(/\.kusto\.windows\.net$/, ''), clusterUrl, database }],
112
+ colors = DEFAULT_COLORS,
113
+ } = options;
114
+
115
+ const msalInstance = new PublicClientApplication({
116
+ auth: {
117
+ clientId: msalClientId,
118
+ authority: `https://login.microsoftonline.com/${tenantId}`,
119
+ redirectUri,
120
+ },
121
+ });
122
+
123
+ async function getToken(cluster: string): Promise<string> {
124
+ const scope = `${cluster}/.default`;
125
+ await msalInstance.initialize();
126
+ const accounts = msalInstance.getAllAccounts();
127
+
128
+ if (accounts.length === 0) {
129
+ const result = await msalInstance.acquireTokenPopup({ scopes: [scope] });
130
+ return result.accessToken;
131
+ }
132
+
133
+ try {
134
+ const result = await msalInstance.acquireTokenSilent({ scopes: [scope], account: accounts[0] });
135
+ return result.accessToken;
136
+ } catch {
137
+ const result = await msalInstance.acquireTokenPopup({ scopes: [scope], account: accounts[0] });
138
+ return result.accessToken;
139
+ }
140
+ }
141
+
142
+ async function ensureAuthenticated(): Promise<void> {
143
+ await msalInstance.initialize();
144
+ const redirectResult = await msalInstance.handleRedirectPromise();
145
+ if (redirectResult) {
146
+ return;
147
+ }
148
+ const accounts = msalInstance.getAllAccounts();
149
+ if (accounts.length > 0) {
150
+ try {
151
+ await msalInstance.acquireTokenSilent({ scopes: [`${clusterUrl}/.default`], account: accounts[0] });
152
+ return;
153
+ } catch {
154
+ // Silent token renewal failed — fall through to redirect
155
+ }
156
+ }
157
+ await msalInstance.loginRedirect({ scopes: [`${clusterUrl}/.default`] });
158
+ }
159
+
160
+ const kustoClient = createKustoClient({
161
+ defaultTarget: { clusterUrl, database },
162
+ getToken,
163
+ stateService,
164
+ });
165
+
166
+ function App() {
167
+ const styles = useStyles();
168
+ const { theme, isDark } = useExplorerTheme(darkTheme, lightTheme);
169
+
170
+ return (
171
+ <FluentProvider theme={theme} style={fullHeightStyle}>
172
+ <KustoClientContext.Provider value={kustoClient}>
173
+ <Explorer isDark={isDark} kustoClient={kustoClient} className={styles.fullPage} colors={colors} clusters={clusters} />
174
+ </KustoClientContext.Provider>
175
+ </FluentProvider>
176
+ );
177
+ }
178
+
179
+ void stateService.hydrate().then(async () => {
180
+ try {
181
+ await ensureAuthenticated();
182
+ } catch (err) {
183
+ const msg = err instanceof Error ? err.message : 'Unknown error';
184
+ document.getElementById('root')!.innerHTML =
185
+ `<div style="display:flex;align-items:center;justify-content:center;height:100vh;color:#bc5653">Authentication failed: ${msg}</div>`;
186
+ return;
187
+ }
188
+
189
+ createRoot(document.getElementById('root')!).render(
190
+ <StrictMode>
191
+ <App />
192
+ </StrictMode>,
193
+ );
194
+ });
195
+ }
package/src/colors.ts ADDED
@@ -0,0 +1,23 @@
1
+ /** Color tokens that the host app provides to the explorer. */
2
+ export interface ExplorerSemanticColors {
3
+ backdrop: string;
4
+ functionBadge: string;
5
+ highlightHoverBg: string;
6
+ lookupBadge: string;
7
+ materializedViewBadge: string;
8
+ scrollThumb: string;
9
+ scrollThumbHover: string;
10
+ selectionBg: string;
11
+ selectionSubtle: string;
12
+ shadowLight: string;
13
+ shadowMedium: string;
14
+ }
15
+
16
+ export interface ExplorerChartColors {
17
+ palette: string[];
18
+ }
19
+
20
+ export interface ExplorerColorConfig {
21
+ semantic: ExplorerSemanticColors;
22
+ chart: ExplorerChartColors;
23
+ }