@mhjuma/traverse 0.3.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,73 @@
1
1
  # @mhjuma/traverse
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 240f4ba: Make consumer setup foot-gun-free and add a Vite plugin to reduce boilerplate.
8
+
9
+ **New:**
10
+
11
+ - **`@mhjuma/traverse/vite-plugin`** subpath export — a single Vite plugin that
12
+ bundles the Bridge.NET CJS shim and the `optimizeDeps.include` entries the
13
+ kusto worker's transitive deps need to pre-bundle. Replaces ~50 lines of
14
+ boilerplate in each consumer's `vite.config.ts` with one import + one
15
+ `traverseVitePlugin()` plugin entry. (Consumers still add
16
+ `vite-plugin-node-polyfills` separately — kept out of the plugin so its
17
+ config story stays orthogonal.)
18
+ - **`getMonacoWorkerConfigurationError()`** — sentinel-based assertion that
19
+ detects when `configureTraverseMonacoWorkers` hasn't been called or
20
+ `getKustoWorker` is missing. A host-installed
21
+ `globalThis.MonacoEnvironment.getWorker` is NOT enough — it might not route
22
+ the `'kusto'` label to a real kusto worker.
23
+ - **`<MonacoConfigErrorBanner>`** — actionable placeholder rendered by
24
+ `<Explorer>` when the assertion fails, with the exact code snippet the
25
+ consumer needs to copy. Pure inline styles so it works even without a host
26
+ `<FluentProvider>`. Optional `monacoConfigErrorFallback` prop on `<Explorer>`
27
+ lets embedders supply their own fallback UI.
28
+ - New `KustoClientConfig.fetch?` injection point. Defaults to
29
+ `globalThis.fetch`. Resolved at call time so tests can stub
30
+ `globalThis.fetch` after construction and so hosts can hot-swap their
31
+ transport (Tauri plugin-http) post-mount.
32
+
33
+ **Improvements:**
34
+
35
+ - **`fetchWithRetry` honours `Retry-After`** (RFC 7231 — both delta-seconds
36
+ and HTTP-date) for both `429` and `503`. Capped at 60s to defend against
37
+ hostile servers / stale dates. Inter-retry sleep is now abort-aware via
38
+ the new `abortableSleep()` helper, so user-initiated cancels no longer have
39
+ to wait for an in-flight backoff to elapse.
40
+ - **MSAL popup post-back bridge handoff.** `bootstrapExplorer` now
41
+ dynamically imports `@azure/msal-browser/redirect-bridge` and calls
42
+ `broadcastResponseToMainFrame()` before any normal app bootstrap. Without
43
+ this, MSAL.js 5.x popup interactions silently failed — the popup would load
44
+ the full SPA and the parent window's `acquireTokenPopup` would time out
45
+ waiting for a `BroadcastChannel` message that only the bridge knows how to
46
+ send. Gracefully degrades for embedders pinned to older MSAL versions.
47
+ - **MSAL recovery from stale URL fragments.** `bootstrapExplorer` now catches
48
+ `no_token_request_cache_error`, `state_not_found`, and `no_state_in_hash`
49
+ from `handleRedirectPromise()`, strips the auth fragments / params from the
50
+ URL, and falls through to the normal silent / loginRedirect flow. Prevents
51
+ the SPA from getting stuck in a loop after a popup that closed before
52
+ posting back.
53
+ - **XSS-hardened auth error banner.** The startup auth-failure banner uses
54
+ safe DOM construction (`createElement` + `textContent`) instead of
55
+ `innerHTML` interpolation. MSAL / AAD error strings can carry
56
+ attacker-controlled content (via `error_description`); the old approach was
57
+ an XSS hazard.
58
+ - **`peerDependencies.monaco-editor` tightened to `^0.52.0`.**
59
+ `@kusto/monaco-kusto@14.x` only supports monaco-editor `^0.52.0`; newer
60
+ versions (0.55+) break the kusto plugin's `createWebWorker` integration in
61
+ subtle ways. The peer pin makes pnpm warn at install time instead of
62
+ letting consumers silently install an incompatible version.
63
+
64
+ **Docs:**
65
+
66
+ - Rewrote `docs/guide/quick-start.md` with a Vite-first three-step setup
67
+ (workers boilerplate → vite.config.ts with `traverseVitePlugin()` → mount
68
+ the Explorer). Documents the kusto worker setup explicitly so consumers
69
+ don't have to discover it through bug reports.
70
+
3
71
  ## 0.3.0
4
72
 
5
73
  ### Minor Changes
package/package.json CHANGED
@@ -1,12 +1,23 @@
1
1
  {
2
2
  "name": "@mhjuma/traverse",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
8
8
  "main": "src/index.ts",
9
9
  "types": "src/index.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./src/index.ts",
13
+ "default": "./src/index.ts"
14
+ },
15
+ "./vite-plugin": {
16
+ "types": "./src/vite-plugin.ts",
17
+ "default": "./src/vite-plugin.ts"
18
+ },
19
+ "./package.json": "./package.json"
20
+ },
10
21
  "dependencies": {
11
22
  "@fluentui/react-components": "9.73.7",
12
23
  "@fluentui/react-icons": "2.0.323",
@@ -21,7 +32,7 @@
21
32
  "peerDependencies": {
22
33
  "@azure/msal-browser": ">=3.0.0",
23
34
  "@monaco-editor/react": "4.7.0",
24
- "monaco-editor": "0.52.2"
35
+ "monaco-editor": "^0.52.0"
25
36
  },
26
37
  "peerDependenciesMeta": {
27
38
  "@azure/msal-browser": {
@@ -280,11 +280,201 @@ describe('bootstrapExplorer', () => {
280
280
  database: 'Samples',
281
281
  });
282
282
 
283
+ // Bootstrap is now wrapped in an async IIFE (so the MSAL redirect
284
+ // bridge can short-circuit before any normal app bootstrap), so
285
+ // hydrate is called asynchronously after the bridge precheck.
286
+ await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
287
+
283
288
  expect(hydrateSpy).toHaveBeenCalled();
284
289
 
285
- // Wait for the async chain (hydrate → auth → render) to settle
290
+ rootEl.remove();
291
+ });
292
+ });
293
+
294
+ describe('bootstrapExplorer MSAL redirect bridge handoff', () => {
295
+ let originalLocation: Location;
296
+
297
+ beforeEach(() => {
298
+ originalLocation = window.location;
299
+ // The shared hydrate mock from the top-level vi.mock factory persists
300
+ // across tests; reset its call count so each test sees a clean slate.
301
+ const sharedHydrate = (stateService as unknown as { hydrate: ReturnType<typeof vi.fn> }).hydrate;
302
+ if (sharedHydrate?.mockClear) {
303
+ sharedHydrate.mockClear();
304
+ }
305
+ });
306
+
307
+ afterEach(() => {
308
+ Object.defineProperty(window, 'location', { value: originalLocation, configurable: true });
309
+ vi.doUnmock('@azure/msal-browser/redirect-bridge');
310
+ vi.resetModules();
311
+ });
312
+
313
+ function stubLocation(url: string): void {
314
+ const parsed = new URL(url);
315
+ Object.defineProperty(window, 'location', {
316
+ value: { ...originalLocation, href: url, search: parsed.search, hash: parsed.hash },
317
+ configurable: true,
318
+ });
319
+ }
320
+
321
+ it('hands off to the MSAL redirect bridge when the URL carries an auth response and skips normal bootstrap', async () => {
322
+ const rootEl = document.createElement('div');
323
+ rootEl.id = 'root';
324
+ document.body.appendChild(rootEl);
325
+
326
+ stubLocation('http://localhost:3000/#code=abc&state=eyJpZCI6InRlc3QifQ==');
327
+
328
+ const broadcastSpy = vi.fn().mockResolvedValue(undefined);
329
+ vi.doMock('@azure/msal-browser/redirect-bridge', () => ({
330
+ broadcastResponseToMainFrame: broadcastSpy,
331
+ }));
332
+
333
+ // Re-import bootstrap so its dynamic-import call resolves through
334
+ // the new vi.doMock factory.
335
+ vi.resetModules();
336
+ const { bootstrapExplorer: freshBootstrap } = await import('./bootstrap');
337
+ const { stateService: freshState } = await import('./services/state-service');
338
+ const hydrateSpy = vi.spyOn(freshState, 'hydrate');
339
+
340
+ freshBootstrap({
341
+ msalClientId: 'test-client',
342
+ tenantId: 'test-tenant',
343
+ redirectUri: 'http://localhost:3000',
344
+ clusterUrl: 'https://help.kusto.windows.net',
345
+ database: 'Samples',
346
+ });
347
+
348
+ await act(async () => { await new Promise((r) => setTimeout(r, 80)); });
349
+
350
+ expect(broadcastSpy).toHaveBeenCalled();
351
+ expect(hydrateSpy).not.toHaveBeenCalled();
352
+
353
+ rootEl.remove();
354
+ });
355
+
356
+ it('falls through to normal bootstrap when the URL has no auth response', async () => {
357
+ const rootEl = document.createElement('div');
358
+ rootEl.id = 'root';
359
+ document.body.appendChild(rootEl);
360
+
361
+ stubLocation('http://localhost:3000/');
362
+
363
+ const hydrateSpy = vi.spyOn(stateService, 'hydrate');
364
+
365
+ bootstrapExplorer({
366
+ msalClientId: 'test-client',
367
+ tenantId: 'test-tenant',
368
+ redirectUri: 'http://localhost:3000',
369
+ clusterUrl: 'https://help.kusto.windows.net',
370
+ database: 'Samples',
371
+ });
372
+
286
373
  await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
287
374
 
375
+ expect(hydrateSpy).toHaveBeenCalled();
376
+
288
377
  rootEl.remove();
289
378
  });
379
+
380
+ it('falls through to normal bootstrap when the bridge import fails (older MSAL versions)', async () => {
381
+ const rootEl = document.createElement('div');
382
+ rootEl.id = 'root';
383
+ document.body.appendChild(rootEl);
384
+
385
+ stubLocation('http://localhost:3000/#code=abc&state=xyz');
386
+
387
+ vi.doMock('@azure/msal-browser/redirect-bridge', () => {
388
+ throw new Error('Module not found');
389
+ });
390
+
391
+ vi.resetModules();
392
+ const { bootstrapExplorer: freshBootstrap } = await import('./bootstrap');
393
+ const { stateService: freshState } = await import('./services/state-service');
394
+ const hydrateSpy = vi.spyOn(freshState, 'hydrate');
395
+
396
+ freshBootstrap({
397
+ msalClientId: 'test-client',
398
+ tenantId: 'test-tenant',
399
+ redirectUri: 'http://localhost:3000',
400
+ clusterUrl: 'https://help.kusto.windows.net',
401
+ database: 'Samples',
402
+ });
403
+
404
+ await act(async () => { await new Promise((r) => setTimeout(r, 80)); });
405
+
406
+ // Bridge failed → graceful degradation, normal bootstrap still ran.
407
+ expect(hydrateSpy).toHaveBeenCalled();
408
+
409
+ rootEl.remove();
410
+ });
411
+ });
412
+
413
+ describe('bootstrapExplorer auth error banner safety', () => {
414
+ let originalLocation: Location;
415
+
416
+ beforeEach(() => {
417
+ originalLocation = window.location;
418
+ });
419
+
420
+ afterEach(() => {
421
+ Object.defineProperty(window, 'location', { value: originalLocation, configurable: true });
422
+ vi.doUnmock('@azure/msal-browser');
423
+ vi.resetModules();
424
+ });
425
+
426
+ function stubLocation(url: string): void {
427
+ const parsed = new URL(url);
428
+ Object.defineProperty(window, 'location', {
429
+ value: { ...originalLocation, href: url, search: parsed.search, hash: parsed.hash },
430
+ configurable: true,
431
+ });
432
+ }
433
+
434
+ it('renders the auth-failure banner using safe DOM construction (no innerHTML)', async () => {
435
+ const rootEl = document.createElement('div');
436
+ rootEl.id = 'root';
437
+ document.body.appendChild(rootEl);
438
+
439
+ stubLocation('http://localhost:3000/');
440
+
441
+ // Re-mock @azure/msal-browser so handleRedirectPromise throws a
442
+ // non-recoverable error containing an XSS payload.
443
+ const xssMsg = '<img src=x onerror="window.__pwn__=true">';
444
+ vi.doMock('@azure/msal-browser', () => {
445
+ class FailingMsal {
446
+ initialize = vi.fn().mockResolvedValue(undefined);
447
+ getAllAccounts = vi.fn().mockReturnValue([]);
448
+ acquireTokenPopup = vi.fn().mockResolvedValue({ accessToken: 'token' });
449
+ acquireTokenSilent = vi.fn().mockResolvedValue({ accessToken: 'token' });
450
+ handleRedirectPromise = vi.fn().mockRejectedValue(new Error(xssMsg));
451
+ loginRedirect = vi.fn().mockResolvedValue(undefined);
452
+ }
453
+ return { PublicClientApplication: FailingMsal };
454
+ });
455
+
456
+ vi.resetModules();
457
+ const { bootstrapExplorer: freshBootstrap } = await import('./bootstrap');
458
+
459
+ try {
460
+ freshBootstrap({
461
+ msalClientId: 'test-client',
462
+ tenantId: 'test-tenant',
463
+ redirectUri: 'http://localhost:3000',
464
+ clusterUrl: 'https://help.kusto.windows.net',
465
+ database: 'Samples',
466
+ });
467
+
468
+ await act(async () => { await new Promise((r) => setTimeout(r, 100)); });
469
+
470
+ // The malicious payload must NOT be parsed as HTML — neither the
471
+ // img tag nor the script should appear in the DOM as elements.
472
+ expect(rootEl.querySelector('img')).toBeNull();
473
+ expect((window as unknown as { __pwn__?: boolean }).__pwn__).toBeUndefined();
474
+ // But the message text should still be present as text.
475
+ expect(rootEl.textContent).toContain(xssMsg);
476
+ } finally {
477
+ rootEl.remove();
478
+ }
479
+ });
290
480
  });
package/src/bootstrap.tsx CHANGED
@@ -98,11 +98,140 @@ export interface BootstrapExplorerOptions {
98
98
  colors?: ExplorerColorConfig;
99
99
  }
100
100
 
101
+ /**
102
+ * MSAL error codes that mean: "I tried to process a redirect response, but
103
+ * I can't find the request that initiated it." This happens after a popup
104
+ * closes prematurely, after sessionStorage is cleared between redirect and
105
+ * return, or when the user reloads with auth fragments still in the URL
106
+ * from a previous broken flow. All recoverable — clear the URL and proceed
107
+ * with a fresh auth attempt.
108
+ */
109
+ const RECOVERABLE_MSAL_ERROR_CODES = new Set([
110
+ 'no_token_request_cache_error',
111
+ 'state_not_found',
112
+ 'no_state_in_hash',
113
+ ]);
114
+
115
+ function isRecoverableMsalError(err: unknown): boolean {
116
+ if (!err || typeof err !== 'object') {
117
+ return false;
118
+ }
119
+ const code = (err as { errorCode?: unknown }).errorCode;
120
+ return typeof code === 'string' && RECOVERABLE_MSAL_ERROR_CODES.has(code);
121
+ }
122
+
123
+ function clearAuthFragmentsFromUrl(): void {
124
+ if (typeof window === 'undefined' || !window.history?.replaceState) {
125
+ return;
126
+ }
127
+ try {
128
+ const url = new URL(window.location.href);
129
+ // The auth response lives in the URL hash for the implicit/fragment
130
+ // flow MSAL uses. Drop it entirely.
131
+ url.hash = '';
132
+ // Also strip OAuth-related query params (auth-code flow).
133
+ const oauthParams = ['code', 'state', 'session_state', 'error', 'error_description', 'client-request-id'];
134
+ for (const p of oauthParams) {
135
+ url.searchParams.delete(p);
136
+ }
137
+ window.history.replaceState({}, document.title, url.toString());
138
+ } catch {
139
+ // Best-effort — if URL parsing fails we leave the address bar alone.
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Cheap precheck: does the current URL look like an MSAL auth response?
145
+ * MSAL always includes `state` alongside either `code` or `error`, in either
146
+ * the URL fragment (implicit/fragment flow) or the query string (auth-code
147
+ * flow). We only kick off the bridge handoff when this is true to avoid
148
+ * paying the dynamic import cost on every page load.
149
+ */
150
+ function hasAuthResponseInUrl(): boolean {
151
+ if (typeof window === 'undefined') {
152
+ return false;
153
+ }
154
+ const inSearch = (() => {
155
+ const params = new URLSearchParams(window.location.search);
156
+ return params.has('state') && (params.has('code') || params.has('error'));
157
+ })();
158
+ if (inSearch) {
159
+ return true;
160
+ }
161
+ const hash = window.location.hash;
162
+ if (hash.length > 1) {
163
+ const params = new URLSearchParams(hash.startsWith('#') ? hash.slice(1) : hash);
164
+ if (params.has('state') && (params.has('code') || params.has('error'))) {
165
+ return true;
166
+ }
167
+ }
168
+ return false;
169
+ }
170
+
171
+ /**
172
+ * Hand off to MSAL's official redirect bridge when this page is loaded as
173
+ * the redirect URI of a popup or redirect interaction. The bridge:
174
+ *
175
+ * - For popup interactions: parses the auth payload from the URL,
176
+ * broadcasts it on the `BroadcastChannel` the parent window is
177
+ * listening to, then closes this window.
178
+ * - For redirect interactions: caches the payload to sessionStorage and
179
+ * navigates to the home page, where the next `handleRedirectPromise`
180
+ * call picks it up.
181
+ *
182
+ * Without this, popup completion would never reach the parent window in
183
+ * MSAL.js 5.x — the popup would load the full Traverse SPA and the
184
+ * parent's `acquireTokenPopup` would time out waiting for a
185
+ * `BroadcastChannel` message that only the bridge knows how to send.
186
+ *
187
+ * Returns true when the bridge fired (caller should NOT bootstrap the
188
+ * normal app), false when the URL didn't have an auth response or the
189
+ * bridge couldn't process it (caller should fall through; existing
190
+ * recovery handles malformed URLs).
191
+ *
192
+ * The bridge is dynamically imported so embedders on older
193
+ * `@azure/msal-browser` versions (pre-5.x, where the `/redirect-bridge`
194
+ * subpath doesn't exist) gracefully degrade rather than failing at module
195
+ * load.
196
+ */
197
+ async function tryHandleMsalRedirectBridge(): Promise<boolean> {
198
+ if (!hasAuthResponseInUrl()) {
199
+ return false;
200
+ }
201
+ try {
202
+ const mod = await import('@azure/msal-browser/redirect-bridge');
203
+ await mod.broadcastResponseToMainFrame();
204
+ return true;
205
+ } catch (err) {
206
+ // eslint-disable-next-line no-console
207
+ console.warn('[traverse] MSAL redirect bridge handoff failed; falling back to normal bootstrap.', err);
208
+ return false;
209
+ }
210
+ }
211
+
101
212
  /**
102
213
  * Bootstraps a standalone Explorer app: handles MSAL auth, StateService
103
214
  * hydration, and renders the Explorer into #root.
104
215
  */
105
216
  export function bootstrapExplorer(options: BootstrapExplorerOptions): void {
217
+ void (async () => {
218
+ // Front door: if this page load is an MSAL popup post-back or a
219
+ // redirect post-back, hand off to MSAL's official bridge and DO
220
+ // NOT bootstrap the Traverse app. The bridge either broadcasts to
221
+ // the parent window and closes (popup) or navigates to the home
222
+ // page (redirect).
223
+ //
224
+ // This is a hard requirement of MSAL.js 5.x's popup flow — the
225
+ // parent's `acquireTokenPopup` is waiting on a `BroadcastChannel`
226
+ // message that only the bridge knows how to send.
227
+ if (await tryHandleMsalRedirectBridge()) {
228
+ return;
229
+ }
230
+ runNormalBootstrap(options);
231
+ })();
232
+ }
233
+
234
+ function runNormalBootstrap(options: BootstrapExplorerOptions): void {
106
235
  const {
107
236
  msalClientId, tenantId, redirectUri,
108
237
  clusterUrl, database,
@@ -141,9 +270,24 @@ export function bootstrapExplorer(options: BootstrapExplorerOptions): void {
141
270
 
142
271
  async function ensureAuthenticated(): Promise<void> {
143
272
  await msalInstance.initialize();
144
- const redirectResult = await msalInstance.handleRedirectPromise();
145
- if (redirectResult) {
146
- return;
273
+ try {
274
+ const redirectResult = await msalInstance.handleRedirectPromise();
275
+ if (redirectResult) {
276
+ return;
277
+ }
278
+ } catch (err) {
279
+ if (isRecoverableMsalError(err)) {
280
+ // Residue from a previous incomplete redirect (popup that
281
+ // closed before posting back, sessionStorage cleared
282
+ // between redirect and return, scope rejected by AAD with
283
+ // no matching request, etc). The auth fragments in the URL
284
+ // no longer match anything in MSAL's cache. Strip them so
285
+ // the next reload doesn't keep hitting the same error, and
286
+ // fall through to the normal silent / loginRedirect flow.
287
+ clearAuthFragmentsFromUrl();
288
+ } else {
289
+ throw err;
290
+ }
147
291
  }
148
292
  const accounts = msalInstance.getAllAccounts();
149
293
  if (accounts.length > 0) {
@@ -180,9 +324,7 @@ export function bootstrapExplorer(options: BootstrapExplorerOptions): void {
180
324
  try {
181
325
  await ensureAuthenticated();
182
326
  } 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>`;
327
+ renderAuthErrorBanner(err);
186
328
  return;
187
329
  }
188
330
 
@@ -193,3 +335,27 @@ export function bootstrapExplorer(options: BootstrapExplorerOptions): void {
193
335
  );
194
336
  });
195
337
  }
338
+
339
+ /**
340
+ * Render the startup auth-failure banner using safe DOM construction —
341
+ * never injects raw error text via `innerHTML` (the old approach was an
342
+ * XSS hazard, since MSAL/AAD error strings can contain attacker-controlled
343
+ * content from the URL, e.g. `error_description`).
344
+ */
345
+ function renderAuthErrorBanner(err: unknown): void {
346
+ const root = document.getElementById('root');
347
+ if (!root) {
348
+ return;
349
+ }
350
+ const msg = err instanceof Error ? err.message : 'Unknown error';
351
+
352
+ // Replace any prior content.
353
+ while (root.firstChild) {
354
+ root.removeChild(root.firstChild);
355
+ }
356
+
357
+ const wrapper = document.createElement('div');
358
+ wrapper.style.cssText = 'display:flex;align-items:center;justify-content:center;height:100vh;color:#bc5653;padding:24px;text-align:center;font-family:system-ui,sans-serif';
359
+ wrapper.textContent = `Authentication failed: ${msg}`;
360
+ root.appendChild(wrapper);
361
+ }
@@ -3,6 +3,7 @@ import React from 'react';
3
3
  import { createRoot } from 'react-dom/client';
4
4
  import { act } from 'react';
5
5
  import { Explorer } from './Explorer';
6
+ import { configureTraverseMonacoWorkers, __resetWorkerConfigForTests } from '../ExplorerWorkspace/monacoWorkers';
6
7
 
7
8
  vi.mock('@monaco-editor/react', () => ({
8
9
  Editor: () => React.createElement('div', { 'data-testid': 'monaco-editor' }),
@@ -165,6 +166,12 @@ describe('Explorer', () => {
165
166
  mockExplorerState.mockReturnValue(defaultExplorerState);
166
167
  mockActiveTabs.mockReturnValue({ activeTab: mockActiveTab, splitTab: null });
167
168
  mockDispatch.mockClear();
169
+ // Satisfy the new render-time worker-config check. The stub Worker
170
+ // is never actually invoked because @monaco-editor/react is mocked
171
+ // out — it only needs to be a function so the assertion passes.
172
+ __resetWorkerConfigForTests();
173
+ const stub = (() => ({})) as unknown as () => Worker;
174
+ configureTraverseMonacoWorkers({ getEditorWorker: stub, getKustoWorker: stub });
168
175
  });
169
176
 
170
177
  afterEach(() => {
@@ -183,6 +190,32 @@ describe('Explorer', () => {
183
190
  expect(container.innerHTML).not.toBe('');
184
191
  });
185
192
 
193
+ it('renders the MonacoConfigErrorBanner when workers are not configured', () => {
194
+ // Tear down the test-setup config so the assertion fires.
195
+ __resetWorkerConfigForTests();
196
+ act(() => {
197
+ root.render(React.createElement(Explorer));
198
+ });
199
+ // The banner shows the actionable hint.
200
+ expect(container.innerHTML).toContain('configureTraverseMonacoWorkers');
201
+ expect(container.innerHTML).toContain('Monaco workers');
202
+ // None of the editor / sidebar children should be in the tree —
203
+ // the early return short-circuited before ExplorerWorkspace mounted.
204
+ expect(container.querySelector('[data-testid="monaco-editor"]')).toBeNull();
205
+ expect(container.querySelector('[data-testid="schema-sidebar"]')).toBeNull();
206
+ });
207
+
208
+ it('renders a user-supplied fallback when monacoConfigErrorFallback prop is given', () => {
209
+ __resetWorkerConfigForTests();
210
+ const fallback = vi.fn((err: { summary: string }) =>
211
+ React.createElement('div', { 'data-testid': 'custom-fallback' }, err.summary));
212
+ act(() => {
213
+ root.render(React.createElement(Explorer, { monacoConfigErrorFallback: fallback } as never));
214
+ });
215
+ expect(container.querySelector('[data-testid="custom-fallback"]')).not.toBeNull();
216
+ expect(fallback).toHaveBeenCalled();
217
+ });
218
+
186
219
  it('renders with split mode enabled', () => {
187
220
  mockExplorerState.mockReturnValue({
188
221
  ...defaultExplorerState,
@@ -649,6 +682,9 @@ describe('Explorer snapshot persistence', () => {
649
682
  mockExplorerState.mockReturnValue(defaultExplorerState);
650
683
  mockActiveTabs.mockReturnValue({ activeTab: mockActiveTab, splitTab: null });
651
684
  originalLocation = window.location;
685
+ __resetWorkerConfigForTests();
686
+ const stub = (() => ({})) as unknown as () => Worker;
687
+ configureTraverseMonacoWorkers({ getEditorWorker: stub, getKustoWorker: stub });
652
688
 
653
689
  const persistence = await import('../../state/persistence');
654
690
  saveSpy = persistence.saveSnapshot as unknown as ReturnType<typeof vi.fn>;
@@ -12,6 +12,9 @@ import { DEFAULT_QUERY, buildWellKnownClusters } from '../ExplorerWorkspace/Expl
12
12
  import type { WellKnownCluster } from '../ExplorerWorkspace/ExplorerWorkspace.logic';
13
13
  import { ExplorerWorkspace } from '../ExplorerWorkspace/ExplorerWorkspace';
14
14
  import { preloadKustoLanguage } from '../ExplorerWorkspace/monacoLoader';
15
+ import { getMonacoWorkerConfigurationError } from '../ExplorerWorkspace/monacoWorkers';
16
+ import type { MonacoWorkerConfigurationError } from '../ExplorerWorkspace/monacoWorkers';
17
+ import { MonacoConfigErrorBanner } from './MonacoConfigErrorBanner';
15
18
 
16
19
  export interface ExplorerProps {
17
20
  className?: string;
@@ -26,6 +29,12 @@ export interface ExplorerProps {
26
29
  * Falls back to the package's built-in `DEFAULT_QUERY` when omitted.
27
30
  */
28
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;
29
38
  }
30
39
 
31
40
  /**
@@ -36,6 +45,19 @@ export interface ExplorerProps {
36
45
  const SNAPSHOT_SAVE_DEBOUNCE_MS = 300;
37
46
 
38
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
+
39
61
  // Trigger kusto language preload on first Explorer render. Editor-gated
40
62
  // by design (here, not at module load) so consumers using only
41
63
  // non-editor APIs from `@mhjuma/traverse` don't pay the kusto chunk cost.