@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
@@ -0,0 +1,322 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import type * as Monaco from 'monaco-editor';
3
+
4
+ import type { RawShowSchema } from '../../services/schema';
5
+
6
+ import {
7
+ applyKustoSchema,
8
+ DEBOUNCE_MS,
9
+ __resetKustoSchemaQueueForTests,
10
+ } from './kustoSchemaQueue';
11
+ import { __resetBootstrapForTests } from './bootstrapKustoLanguage';
12
+
13
+ const setLanguageSettings = vi.fn();
14
+ const setMaximumWorkerIdleTime = vi.fn();
15
+ const setSchemaFromShowSchema = vi.fn().mockResolvedValue(undefined);
16
+ const workerProxy = { setSchemaFromShowSchema };
17
+ const accessor = vi.fn().mockResolvedValue(workerProxy);
18
+ const getKustoWorker = vi.fn().mockResolvedValue(accessor);
19
+
20
+ vi.mock('@kusto/monaco-kusto', () => ({
21
+ kustoDefaults: {
22
+ setLanguageSettings,
23
+ setMaximumWorkerIdleTime,
24
+ },
25
+ getKustoWorker,
26
+ }));
27
+
28
+ interface FakeMonaco {
29
+ languages: { getLanguages: () => { id: string }[] };
30
+ editor: {
31
+ getModels: () => { getLanguageId: () => string; uri: Monaco.Uri }[];
32
+ onDidCreateModel: (cb: (m: { getLanguageId: () => string }) => void) => Monaco.IDisposable;
33
+ };
34
+ }
35
+
36
+ function makeMonaco({
37
+ models = [{ getLanguageId: () => 'kusto', uri: { toString: () => 'inmemory://model/1' } as unknown as Monaco.Uri }],
38
+ languages = [{ id: 'kusto' }],
39
+ }: Partial<{ models: { getLanguageId: () => string; uri: Monaco.Uri }[]; languages: { id: string }[] }> = {}): FakeMonaco & { __fireCreate: (m: { getLanguageId: () => string }) => void } {
40
+ const modelListeners: ((m: { getLanguageId: () => string }) => void)[] = [];
41
+ return {
42
+ languages: { getLanguages: () => languages },
43
+ editor: {
44
+ getModels: () => models,
45
+ onDidCreateModel: (cb) => {
46
+ modelListeners.push(cb);
47
+ return { dispose: () => { modelListeners.splice(modelListeners.indexOf(cb), 1); } };
48
+ },
49
+ },
50
+ __fireCreate: (m) => modelListeners.forEach((cb) => cb(m)),
51
+ };
52
+ }
53
+
54
+ const RAW: RawShowSchema = { Plugins: [], Databases: { db: { Name: 'db', Tables: {} } } };
55
+
56
+ beforeEach(() => {
57
+ vi.useFakeTimers();
58
+ __resetKustoSchemaQueueForTests();
59
+ __resetBootstrapForTests();
60
+ setLanguageSettings.mockClear();
61
+ setMaximumWorkerIdleTime.mockClear();
62
+ setSchemaFromShowSchema.mockClear();
63
+ accessor.mockClear();
64
+ getKustoWorker.mockClear();
65
+ vi.spyOn(console, 'error').mockImplementation(() => {});
66
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
67
+ });
68
+
69
+ afterEach(() => {
70
+ vi.useRealTimers();
71
+ vi.restoreAllMocks();
72
+ });
73
+
74
+ async function flushAsync(): Promise<void> {
75
+ // Drain pending microtasks while fake timers are active.
76
+ for (let i = 0; i < 32; i++) {
77
+ await Promise.resolve();
78
+ }
79
+ }
80
+
81
+ describe('kustoSchemaQueue', () => {
82
+ it('applies the schema after the debounce window, then calls bootstrap + setSchemaFromShowSchema', async () => {
83
+ const monaco = makeMonaco();
84
+
85
+ applyKustoSchema({
86
+ monaco: monaco as unknown as typeof Monaco,
87
+ raw: RAW,
88
+ clusterUri: 'https://c.kusto.windows.net',
89
+ dbName: 'db',
90
+ });
91
+
92
+ // Before the debounce window, nothing has fired.
93
+ expect(setSchemaFromShowSchema).not.toHaveBeenCalled();
94
+
95
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
96
+ await flushAsync();
97
+
98
+ expect(setLanguageSettings).toHaveBeenCalledTimes(1);
99
+ expect(setSchemaFromShowSchema).toHaveBeenCalledTimes(1);
100
+ expect(setSchemaFromShowSchema).toHaveBeenCalledWith(RAW, 'https://c.kusto.windows.net', 'db');
101
+ });
102
+
103
+ it('coalesces bursts within the debounce window — only the latest schema is applied', async () => {
104
+ const monaco = makeMonaco();
105
+ const raw2: RawShowSchema = { Plugins: [], Databases: { db: { Name: 'db', Tables: { A: {} } } } };
106
+
107
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c', dbName: 'db' });
108
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS / 2);
109
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: raw2, clusterUri: 'c', dbName: 'db' });
110
+
111
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
112
+ await flushAsync();
113
+
114
+ expect(setSchemaFromShowSchema).toHaveBeenCalledTimes(1);
115
+ expect(setSchemaFromShowSchema).toHaveBeenCalledWith(raw2, 'c', 'db');
116
+ });
117
+
118
+ it('skips redundant calls when the (cluster, db, raw) hash matches the last applied schema', async () => {
119
+ const monaco = makeMonaco();
120
+
121
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c', dbName: 'db' });
122
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
123
+ await flushAsync();
124
+ expect(setSchemaFromShowSchema).toHaveBeenCalledTimes(1);
125
+
126
+ // Same payload again — no new debounce or worker call.
127
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c', dbName: 'db' });
128
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS * 2);
129
+ await flushAsync();
130
+
131
+ expect(setSchemaFromShowSchema).toHaveBeenCalledTimes(1);
132
+ });
133
+
134
+ it('re-applies when the cluster URI or database changes', async () => {
135
+ const monaco = makeMonaco();
136
+
137
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c1', dbName: 'db' });
138
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
139
+ await flushAsync();
140
+
141
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c2', dbName: 'db' });
142
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
143
+ await flushAsync();
144
+
145
+ expect(setSchemaFromShowSchema).toHaveBeenCalledTimes(2);
146
+ expect(setSchemaFromShowSchema.mock.calls[0][1]).toBe('c1');
147
+ expect(setSchemaFromShowSchema.mock.calls[1][1]).toBe('c2');
148
+ });
149
+
150
+ it('defers until a kusto-language model exists, then applies on model creation', async () => {
151
+ const monaco = makeMonaco({ models: [] });
152
+
153
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c', dbName: 'db' });
154
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
155
+ await flushAsync();
156
+
157
+ // Bootstrap ran but no worker call yet (no model).
158
+ expect(setLanguageSettings).toHaveBeenCalledTimes(1);
159
+ expect(setSchemaFromShowSchema).not.toHaveBeenCalled();
160
+
161
+ // Now a kusto model is created — the deferred flush retries.
162
+ const newModel = { getLanguageId: () => 'kusto', uri: { toString: () => 'inmemory://new' } as Monaco.Uri };
163
+ monaco.editor.getModels = () => [newModel];
164
+ monaco.__fireCreate(newModel);
165
+ await flushAsync();
166
+
167
+ expect(setSchemaFromShowSchema).toHaveBeenCalledTimes(1);
168
+ });
169
+
170
+ it('does not retry on non-kusto model creation', async () => {
171
+ const monaco = makeMonaco({ models: [] });
172
+
173
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c', dbName: 'db' });
174
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
175
+ await flushAsync();
176
+
177
+ // Fire a non-kusto model — the watcher should ignore it.
178
+ monaco.__fireCreate({ getLanguageId: () => 'javascript' });
179
+ await flushAsync();
180
+
181
+ expect(setSchemaFromShowSchema).not.toHaveBeenCalled();
182
+ });
183
+
184
+ it('keeps pending when bootstrap fails so a later call retries', async () => {
185
+ // First attempt with a broken monaco (no kusto language registered).
186
+ const brokenMonaco = makeMonaco({ languages: [{ id: 'javascript' }] });
187
+
188
+ applyKustoSchema({ monaco: brokenMonaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c', dbName: 'db' });
189
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
190
+ await flushAsync();
191
+
192
+ expect(setSchemaFromShowSchema).not.toHaveBeenCalled();
193
+
194
+ // Retry with a working monaco. Reset bootstrap (real `bootstrapKustoLanguage` does this
195
+ // automatically on failure, but the queue may have already consumed it).
196
+ __resetBootstrapForTests();
197
+ const monaco = makeMonaco();
198
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c', dbName: 'db' });
199
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
200
+ await flushAsync();
201
+
202
+ expect(setSchemaFromShowSchema).toHaveBeenCalledTimes(1);
203
+ });
204
+
205
+ it('re-flushes when a newer schema lands while one is being applied', async () => {
206
+ const monaco = makeMonaco();
207
+
208
+ // Slow the worker apply: hold the promise until we resolve it.
209
+ let resolveFirst!: () => void;
210
+ setSchemaFromShowSchema.mockImplementationOnce(() => new Promise<void>((r) => { resolveFirst = r; }));
211
+
212
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c', dbName: 'db' });
213
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
214
+ await flushAsync();
215
+
216
+ // While the first apply is in-flight, queue a newer payload.
217
+ const raw2: RawShowSchema = { Plugins: [], Databases: { db: { Name: 'db', Tables: { LATER: {} } } } };
218
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: raw2, clusterUri: 'c', dbName: 'db' });
219
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
220
+ await flushAsync();
221
+
222
+ // Now release the first apply.
223
+ resolveFirst();
224
+ await flushAsync();
225
+ await flushAsync();
226
+
227
+ // Both apply in order — the in-flight serialize fix guarantees the
228
+ // newer payload comes AFTER the older one, not the other way around.
229
+ expect(setSchemaFromShowSchema).toHaveBeenCalledTimes(2);
230
+ expect(setSchemaFromShowSchema.mock.calls[0][0]).toBe(RAW);
231
+ expect(setSchemaFromShowSchema.mock.calls[1][0]).toBe(raw2);
232
+ });
233
+
234
+ it('skips immediately when called with the same RawShowSchema reference and target', async () => {
235
+ const monaco = makeMonaco();
236
+
237
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c', dbName: 'db' });
238
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
239
+ await flushAsync();
240
+ expect(setSchemaFromShowSchema).toHaveBeenCalledTimes(1);
241
+
242
+ // Same `raw` reference — cheap skip path, no debounce timer should be scheduled.
243
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c', dbName: 'db' });
244
+ // Even an arbitrary wait doesn't trigger another apply because the timer was never set.
245
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS * 10);
246
+ await flushAsync();
247
+ expect(setSchemaFromShowSchema).toHaveBeenCalledTimes(1);
248
+ });
249
+
250
+ it('warns to the console when bootstrap fails', async () => {
251
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
252
+ const monaco = makeMonaco({ languages: [{ id: 'javascript' }] });
253
+
254
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c', dbName: 'db' });
255
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
256
+ await flushAsync();
257
+
258
+ const matchingCall = warnSpy.mock.calls.find((c) => String(c[0]).includes('Kusto language bootstrap failed'));
259
+ expect(matchingCall).toBeDefined();
260
+ });
261
+
262
+ it('warns to the console when setSchemaFromShowSchema fails', async () => {
263
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
264
+ const monaco = makeMonaco();
265
+
266
+ setSchemaFromShowSchema.mockRejectedValueOnce(new Error('worker boom'));
267
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c', dbName: 'db' });
268
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
269
+ await flushAsync();
270
+
271
+ const matchingCall = warnSpy.mock.calls.find((c) => String(c[0]).includes('setSchemaFromShowSchema failed'));
272
+ expect(matchingCall).toBeDefined();
273
+ });
274
+
275
+ it('swallows worker errors and leaves pending so the next apply call retries', async () => {
276
+ const monaco = makeMonaco();
277
+
278
+ setSchemaFromShowSchema.mockRejectedValueOnce(new Error('worker boom'));
279
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c', dbName: 'db' });
280
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
281
+ await flushAsync();
282
+
283
+ expect(setSchemaFromShowSchema).toHaveBeenCalledTimes(1);
284
+
285
+ // Trigger a different hash so identity check doesn't short-circuit.
286
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c2', dbName: 'db' });
287
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
288
+ await flushAsync();
289
+
290
+ expect(setSchemaFromShowSchema).toHaveBeenCalledTimes(2);
291
+ });
292
+
293
+ it('skips redundant content even when given a fresh RawShowSchema object with same content', async () => {
294
+ const monaco = makeMonaco();
295
+
296
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c', dbName: 'db' });
297
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
298
+ await flushAsync();
299
+ expect(setSchemaFromShowSchema).toHaveBeenCalledTimes(1);
300
+
301
+ // Fresh object reference (so cheap reference-skip misses) but identical
302
+ // content — the content-hash check in flush must still skip.
303
+ const cloneRaw = JSON.parse(JSON.stringify(RAW)) as RawShowSchema;
304
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: cloneRaw, clusterUri: 'c', dbName: 'db' });
305
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS);
306
+ await flushAsync();
307
+
308
+ expect(setSchemaFromShowSchema).toHaveBeenCalledTimes(1);
309
+ });
310
+
311
+ it('__resetKustoSchemaQueueForTests clears a pending debounce timer', async () => {
312
+ const monaco = makeMonaco();
313
+
314
+ applyKustoSchema({ monaco: monaco as unknown as typeof Monaco, raw: RAW, clusterUri: 'c', dbName: 'db' });
315
+ // Reset BEFORE the debounce fires.
316
+ __resetKustoSchemaQueueForTests();
317
+ await vi.advanceTimersByTimeAsync(DEBOUNCE_MS * 2);
318
+ await flushAsync();
319
+
320
+ expect(setSchemaFromShowSchema).not.toHaveBeenCalled();
321
+ });
322
+ });
@@ -0,0 +1,188 @@
1
+ import type * as Monaco from 'monaco-editor';
2
+
3
+ import type { RawShowSchema } from '../../services/schema';
4
+
5
+ import { bootstrapKustoLanguage } from './bootstrapKustoLanguage';
6
+
7
+ /**
8
+ * Debounce window (ms) used to coalesce successive schema-apply calls
9
+ * triggered by React effects or connection switches.
10
+ */
11
+ export const DEBOUNCE_MS = 200;
12
+
13
+ interface PendingSchema {
14
+ raw: RawShowSchema;
15
+ clusterUri: string;
16
+ dbName: string;
17
+ }
18
+
19
+ // Module-level state.
20
+ //
21
+ // This module is intentionally a singleton. The Explorer is the only host of
22
+ // the KQL editor (see D8 in the migration plan) — multiple side-by-side
23
+ // Explorer instances on the same page are out of scope and would currently
24
+ // share queue state. If that requirement appears later, wrap this state in a
25
+ // factory and instantiate per-Explorer.
26
+ let pending: PendingSchema | null = null;
27
+ let lastAppliedHash: string | null = null;
28
+ let lastAppliedRaw: RawShowSchema | null = null;
29
+ let lastAppliedClusterUri: string | null = null;
30
+ let lastAppliedDbName: string | null = null;
31
+ let debounceTimer: ReturnType<typeof setTimeout> | null = null;
32
+ let awaitingFirstKustoModel = false;
33
+ let modelWatcherSub: Monaco.IDisposable | null = null;
34
+ let flushing = false;
35
+
36
+ /** Tiny djb2 — sufficient for content-identity skip; not cryptographic. */
37
+ function fastHash(s: string): string {
38
+ let h = 5381;
39
+ for (let i = 0; i < s.length; i++) {
40
+ h = ((h * 33) ^ s.charCodeAt(i)) >>> 0;
41
+ }
42
+ return h.toString(36);
43
+ }
44
+
45
+ function warn(message: string, err: unknown): void {
46
+ // eslint-disable-next-line no-console
47
+ console.warn(`[traverse:kustoSchemaQueue] ${message}`, err);
48
+ }
49
+
50
+ export interface ApplyKustoSchemaArgs {
51
+ monaco: typeof Monaco;
52
+ raw: RawShowSchema;
53
+ clusterUri: string;
54
+ dbName: string;
55
+ }
56
+
57
+ /**
58
+ * Queue a Kusto schema to be applied to the language service worker. Latest
59
+ * call wins: if a newer schema arrives before the previous one is applied,
60
+ * the older one is dropped. Debounced by {@link DEBOUNCE_MS} to coalesce
61
+ * bursts from effects/connection switches.
62
+ *
63
+ * A cheap reference-identity skip avoids JSON.stringify on the hot path —
64
+ * the deeper content hash is computed lazily inside the (debounced) flush so
65
+ * the React effect does no heavy work.
66
+ */
67
+ export function applyKustoSchema(args: ApplyKustoSchemaArgs): void {
68
+ // Cheap reference-based skip: when the schema cache hands us the same
69
+ // object reference for the same target, we know nothing changed.
70
+ if (
71
+ pending === null &&
72
+ args.raw === lastAppliedRaw &&
73
+ args.clusterUri === lastAppliedClusterUri &&
74
+ args.dbName === lastAppliedDbName
75
+ ) {
76
+ return;
77
+ }
78
+ pending = {
79
+ raw: args.raw,
80
+ clusterUri: args.clusterUri,
81
+ dbName: args.dbName,
82
+ };
83
+ if (debounceTimer) {
84
+ clearTimeout(debounceTimer);
85
+ }
86
+ debounceTimer = setTimeout(() => {
87
+ debounceTimer = null;
88
+ void flush(args.monaco);
89
+ }, DEBOUNCE_MS);
90
+ }
91
+
92
+ async function flush(monaco: typeof Monaco): Promise<void> {
93
+ // Serialize: only one apply at a time. While we're applying, newer
94
+ // payloads can land in `pending`; the while-loop below drains them in
95
+ // order. This prevents an older apply from finishing after a newer one
96
+ // and overwriting the worker's schema (a real correctness bug).
97
+ if (flushing) {
98
+ return;
99
+ }
100
+ flushing = true;
101
+ try {
102
+ while (pending) {
103
+ const snapshot = pending;
104
+
105
+ try {
106
+ await bootstrapKustoLanguage(monaco);
107
+ } catch (err) {
108
+ warn('Kusto language bootstrap failed; leaving pending schema for retry.', err);
109
+ return;
110
+ }
111
+
112
+ const kustoModel = monaco.editor.getModels().find((m) => m.getLanguageId() === 'kusto');
113
+ if (!kustoModel) {
114
+ // The kusto worker accessor only resolves once a kusto model
115
+ // exists. Defer via a single onDidCreateModel watcher.
116
+ if (!awaitingFirstKustoModel) {
117
+ awaitingFirstKustoModel = true;
118
+ modelWatcherSub = monaco.editor.onDidCreateModel((m) => {
119
+ if (m.getLanguageId() === 'kusto') {
120
+ modelWatcherSub?.dispose();
121
+ modelWatcherSub = null;
122
+ awaitingFirstKustoModel = false;
123
+ void flush(monaco);
124
+ }
125
+ });
126
+ }
127
+ return;
128
+ }
129
+
130
+ // Compute the content hash lazily; this is the only place the
131
+ // expensive JSON.stringify happens.
132
+ const hash = fastHash(
133
+ `${snapshot.clusterUri}|${snapshot.dbName}|${JSON.stringify(snapshot.raw)}`,
134
+ );
135
+ if (hash === lastAppliedHash) {
136
+ // Worker already has this exact schema content. Clear pending
137
+ // only if it's still the same snapshot; otherwise let the
138
+ // loop pick up the newer one.
139
+ if (pending === snapshot) {
140
+ pending = null;
141
+ }
142
+ continue;
143
+ }
144
+
145
+ try {
146
+ const mod = await import('@kusto/monaco-kusto');
147
+ const accessor = await mod.getKustoWorker();
148
+ const worker = await accessor(kustoModel.uri);
149
+ await worker.setSchemaFromShowSchema(
150
+ snapshot.raw,
151
+ snapshot.clusterUri,
152
+ snapshot.dbName,
153
+ );
154
+ lastAppliedHash = hash;
155
+ lastAppliedRaw = snapshot.raw;
156
+ lastAppliedClusterUri = snapshot.clusterUri;
157
+ lastAppliedDbName = snapshot.dbName;
158
+ if (pending === snapshot) {
159
+ pending = null;
160
+ }
161
+ // If pending changed during the apply, the while-loop will
162
+ // pick it up on the next iteration.
163
+ } catch (err) {
164
+ warn('setSchemaFromShowSchema failed; leaving pending schema for retry.', err);
165
+ return;
166
+ }
167
+ }
168
+ } finally {
169
+ flushing = false;
170
+ }
171
+ }
172
+
173
+ /** Test-only: reset queue state between tests. */
174
+ export function __resetKustoSchemaQueueForTests(): void {
175
+ pending = null;
176
+ lastAppliedHash = null;
177
+ lastAppliedRaw = null;
178
+ lastAppliedClusterUri = null;
179
+ lastAppliedDbName = null;
180
+ awaitingFirstKustoModel = false;
181
+ flushing = false;
182
+ modelWatcherSub?.dispose();
183
+ modelWatcherSub = null;
184
+ if (debounceTimer) {
185
+ clearTimeout(debounceTimer);
186
+ debounceTimer = null;
187
+ }
188
+ }
@@ -0,0 +1,82 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+
3
+ vi.mock('monaco-editor', () => ({}));
4
+
5
+ const loaderConfig = vi.fn();
6
+ vi.mock('@monaco-editor/react', () => ({
7
+ loader: { config: loaderConfig },
8
+ }));
9
+
10
+ const bootstrapKustoLanguage = vi.fn().mockResolvedValue(undefined);
11
+ vi.mock('./bootstrapKustoLanguage', () => ({
12
+ bootstrapKustoLanguage,
13
+ }));
14
+
15
+ describe('monacoLoader', () => {
16
+ beforeEach(() => {
17
+ loaderConfig.mockClear();
18
+ bootstrapKustoLanguage.mockClear();
19
+ vi.resetModules();
20
+ });
21
+
22
+ it('calls loader.config with the locally bundled monaco on first import', async () => {
23
+ await import('./monacoLoader');
24
+ expect(loaderConfig).toHaveBeenCalledTimes(1);
25
+ expect(loaderConfig.mock.calls[0]?.[0]).toMatchObject({ monaco: expect.anything() });
26
+ });
27
+
28
+ it('does NOT trigger bootstrapKustoLanguage on module load (editor-gated)', async () => {
29
+ await import('./monacoLoader');
30
+ // Pre-loading the kusto language is gated behind preloadKustoLanguage()
31
+ // so non-editor consumers (createKustoClient only) don't pay the cost.
32
+ expect(bootstrapKustoLanguage).not.toHaveBeenCalled();
33
+ });
34
+
35
+ it('preloadKustoLanguage triggers bootstrap on first call', async () => {
36
+ const mod = await import('./monacoLoader');
37
+ expect(bootstrapKustoLanguage).not.toHaveBeenCalled();
38
+ mod.preloadKustoLanguage();
39
+ expect(bootstrapKustoLanguage).toHaveBeenCalledTimes(1);
40
+ expect(bootstrapKustoLanguage.mock.calls[0]?.[0]).toBe(loaderConfig.mock.calls[0]?.[0].monaco);
41
+ });
42
+
43
+ it('preloadKustoLanguage is idempotent across repeated calls', async () => {
44
+ const mod = await import('./monacoLoader');
45
+ mod.preloadKustoLanguage();
46
+ mod.preloadKustoLanguage();
47
+ mod.preloadKustoLanguage();
48
+ expect(bootstrapKustoLanguage).toHaveBeenCalledTimes(1);
49
+ });
50
+
51
+ it('preloadKustoLanguage swallows bootstrap rejections so callers never throw', async () => {
52
+ bootstrapKustoLanguage.mockRejectedValueOnce(new Error('boom'));
53
+ const mod = await import('./monacoLoader');
54
+ // Must not throw synchronously and must not produce an unhandled
55
+ // rejection that fails the test runner — the error is surfaced later
56
+ // via ExplorerWorkspace's mount-time bootstrap on retry.
57
+ expect(() => mod.preloadKustoLanguage()).not.toThrow();
58
+ // Allow the rejection's microtask to drain.
59
+ await Promise.resolve();
60
+ await Promise.resolve();
61
+ });
62
+
63
+ it('__resetPreloadStateForTests clears the preload guard', async () => {
64
+ const mod = await import('./monacoLoader');
65
+ mod.preloadKustoLanguage();
66
+ expect(bootstrapKustoLanguage).toHaveBeenCalledTimes(1);
67
+ mod.__resetPreloadStateForTests();
68
+ mod.preloadKustoLanguage();
69
+ expect(bootstrapKustoLanguage).toHaveBeenCalledTimes(2);
70
+ });
71
+
72
+ it('is idempotent: configureMonacoLoader is a no-op after the first call', async () => {
73
+ const mod = await import('./monacoLoader');
74
+ // The module-level side-effect call counts as the first invocation.
75
+ loaderConfig.mockClear();
76
+ bootstrapKustoLanguage.mockClear();
77
+ mod.configureMonacoLoader();
78
+ mod.configureMonacoLoader();
79
+ expect(loaderConfig).not.toHaveBeenCalled();
80
+ expect(bootstrapKustoLanguage).not.toHaveBeenCalled();
81
+ });
82
+ });
@@ -0,0 +1,57 @@
1
+ import { loader } from '@monaco-editor/react';
2
+ import * as monaco from 'monaco-editor';
3
+
4
+ import { bootstrapKustoLanguage } from './bootstrapKustoLanguage';
5
+
6
+ /**
7
+ * Configure `@monaco-editor/react` to use the locally bundled Monaco instance
8
+ * instead of fetching it from the default CDN. This is required so that any
9
+ * Monaco contributions registered by this library (e.g. `@kusto/monaco-kusto`)
10
+ * attach to the same Monaco instance the `<Editor>` component uses — otherwise
11
+ * contributions are silently dropped ("two Monacos" problem).
12
+ *
13
+ * The call is idempotent and a no-op on the server. It is intentionally
14
+ * lightweight — it only configures the loader. Pre-loading the kusto
15
+ * language is gated behind `preloadKustoLanguage()` so consumers using only
16
+ * non-editor APIs (e.g. `createKustoClient`) do not pay for the multi-MB
17
+ * `@kusto/monaco-kusto` chunk.
18
+ */
19
+ let configured = false;
20
+ export function configureMonacoLoader(): void {
21
+ if (configured || typeof window === 'undefined') {
22
+ return;
23
+ }
24
+ configured = true;
25
+ loader.config({ monaco });
26
+ }
27
+
28
+ configureMonacoLoader();
29
+
30
+ /**
31
+ * Trigger registration of the kusto language (Monarch tokens provider, themes,
32
+ * completion/hover providers) ahead of the editor first mounting. Call from
33
+ * any component that will render the KQL editor (e.g. `<Explorer>`) so the
34
+ * dynamic import of `@kusto/monaco-kusto` overlaps with React/auth init —
35
+ * the editor's first paint then shows colored keywords/strings/numbers
36
+ * instead of plain text that "upgrades" a beat later.
37
+ *
38
+ * Editor-gated by design: consumers of `@mhjuma/traverse` that use only
39
+ * non-editor APIs (e.g. `createKustoClient`) should not call this and will
40
+ * not incur the kusto chunk download.
41
+ *
42
+ * Idempotent — repeated calls are no-ops. Errors are swallowed here and
43
+ * surfaced by `ExplorerWorkspace`'s mount-time bootstrap on retry.
44
+ */
45
+ let preloadStarted = false;
46
+ export function preloadKustoLanguage(): void {
47
+ if (preloadStarted || typeof window === 'undefined') {
48
+ return;
49
+ }
50
+ preloadStarted = true;
51
+ void bootstrapKustoLanguage(monaco).catch(() => { /* surfaced in ExplorerWorkspace */ });
52
+ }
53
+
54
+ /** Test-only: reset preload state so each test exercises the first-call path. */
55
+ export function __resetPreloadStateForTests(): void {
56
+ preloadStarted = false;
57
+ }