@mhjuma/traverse 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/package.json +18 -4
  3. package/src/bootstrap.spec.tsx +191 -1
  4. package/src/bootstrap.tsx +172 -6
  5. package/src/components/Explorer/Explorer.spec.tsx +47 -3
  6. package/src/components/Explorer/Explorer.tsx +33 -0
  7. package/src/components/Explorer/MonacoConfigErrorBanner.tsx +86 -0
  8. package/src/components/ExplorerWorkspace/ExplorerWorkspace.spec.tsx +53 -17
  9. package/src/components/ExplorerWorkspace/ExplorerWorkspace.tsx +78 -74
  10. package/src/components/ExplorerWorkspace/bootstrapKustoLanguage.spec.ts +150 -0
  11. package/src/components/ExplorerWorkspace/bootstrapKustoLanguage.ts +95 -0
  12. package/src/components/ExplorerWorkspace/kustoSchemaQueue.spec.ts +322 -0
  13. package/src/components/ExplorerWorkspace/kustoSchemaQueue.ts +188 -0
  14. package/src/components/ExplorerWorkspace/monacoLoader.spec.ts +82 -0
  15. package/src/components/ExplorerWorkspace/monacoLoader.ts +57 -0
  16. package/src/components/ExplorerWorkspace/monacoWorkers.spec.ts +146 -0
  17. package/src/components/ExplorerWorkspace/monacoWorkers.ts +179 -0
  18. package/src/index.ts +3 -0
  19. package/src/services/kusto.spec.ts +155 -1
  20. package/src/services/kusto.ts +117 -7
  21. package/src/services/schema.spec.ts +107 -28
  22. package/src/services/schema.ts +66 -25
  23. package/src/test-setup.ts +3 -0
  24. package/src/vite-plugin.spec.ts +118 -0
  25. package/src/vite-plugin.ts +114 -0
  26. package/vitest.config.ts +7 -0
  27. package/src/components/ExplorerWorkspace/kqlLanguage.spec.ts +0 -321
  28. package/src/components/ExplorerWorkspace/kqlLanguage.ts +0 -155
@@ -13,6 +13,9 @@ import type { Priority } from './concurrency';
13
13
  const MAX_CONCURRENT = 8;
14
14
  const MAX_RETRIES = 3;
15
15
  const RETRY_BASE_MS = 2000;
16
+ /** Cap on Retry-After honour. Prevents hostile servers (or stale dates) from
17
+ * stalling Traverse's UI for arbitrarily long. */
18
+ const RETRY_AFTER_CAP_MS = 60_000;
16
19
 
17
20
  export interface KustoTarget {
18
21
  clusterUrl: string;
@@ -236,6 +239,13 @@ export interface KustoClientConfig {
236
239
  defaultTarget: KustoTarget;
237
240
  getToken: (clusterUrl: string) => Promise<string>;
238
241
  stateService: KustoStateService;
242
+ /**
243
+ * Optional fetch implementation. Defaults to `globalThis.fetch`. Provide
244
+ * an override to route HTTP requests through a custom transport — for
245
+ * example a Tauri `tauri-plugin-http` shim (CORS-free desktop) or a
246
+ * server-side proxy.
247
+ */
248
+ fetch?: typeof fetch;
239
249
  }
240
250
 
241
251
  export interface KustoClient {
@@ -251,12 +261,105 @@ export interface KustoClient {
251
261
  getQueryCacheSize(): number;
252
262
  }
253
263
 
254
- async function fetchWithRetry(url: string, init: RequestInit, retries = MAX_RETRIES): Promise<Response> {
264
+ /**
265
+ * Parse a `Retry-After` header value (RFC 7231): either delta-seconds or an
266
+ * HTTP-date. Returns the wait in milliseconds, capped at
267
+ * {@link RETRY_AFTER_CAP_MS}. Returns `null` when the header is absent or
268
+ * cannot be parsed so the caller falls back to exponential backoff.
269
+ */
270
+ export function parseRetryAfter(value: string | null | undefined, now: number = Date.now()): number | null {
271
+ if (value === null || value === undefined || value.trim() === '') {
272
+ return null;
273
+ }
274
+ const trimmed = value.trim();
275
+ // Numeric form: non-negative integer or float, in seconds. Anchored at
276
+ // both ends; leading signs are explicitly rejected so '-1' doesn't fall
277
+ // through to the much more permissive Date.parse below.
278
+ if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
279
+ const seconds = Number(trimmed);
280
+ if (Number.isFinite(seconds) && seconds >= 0) {
281
+ return Math.min(seconds * 1000, RETRY_AFTER_CAP_MS);
282
+ }
283
+ return null;
284
+ }
285
+ // Anything that looks numeric-ish (signed, exponent, etc.) is also
286
+ // rejected — Retry-After's delta-seconds form is strict.
287
+ if (/^[+-]?\d/.test(trimmed) && !/[a-zA-Z]/.test(trimmed)) {
288
+ return null;
289
+ }
290
+ // HTTP-date form.
291
+ const dateMs = Date.parse(trimmed);
292
+ if (Number.isFinite(dateMs)) {
293
+ const delta = dateMs - now;
294
+ if (delta < 0) {
295
+ return 0;
296
+ }
297
+ return Math.min(delta, RETRY_AFTER_CAP_MS);
298
+ }
299
+ return null;
300
+ }
301
+
302
+ /**
303
+ * Sleep for `ms` milliseconds. Rejects with an `AbortError` the moment
304
+ * `signal` aborts. Cleans up its event listener / timer either way.
305
+ */
306
+ export function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
307
+ return new Promise((resolve, reject) => {
308
+ if (signal?.aborted) {
309
+ reject(makeAbortError());
310
+ return;
311
+ }
312
+ const timer = setTimeout(() => {
313
+ if (signal && onAbort) {
314
+ signal.removeEventListener('abort', onAbort);
315
+ }
316
+ resolve();
317
+ }, ms);
318
+ const onAbort = signal
319
+ ? () => {
320
+ clearTimeout(timer);
321
+ signal.removeEventListener('abort', onAbort!);
322
+ reject(makeAbortError());
323
+ }
324
+ : null;
325
+ if (signal && onAbort) {
326
+ signal.addEventListener('abort', onAbort, { once: true });
327
+ }
328
+ });
329
+ }
330
+
331
+ function makeAbortError(): Error {
332
+ if (typeof DOMException !== 'undefined') {
333
+ return new DOMException('Aborted', 'AbortError');
334
+ }
335
+ const err = new Error('Aborted');
336
+ err.name = 'AbortError';
337
+ return err;
338
+ }
339
+
340
+ async function fetchWithRetry(
341
+ fetchImpl: typeof fetch,
342
+ url: string,
343
+ init: RequestInit,
344
+ retries = MAX_RETRIES,
345
+ ): Promise<Response> {
346
+ const signal = init.signal ?? undefined;
255
347
  for (let attempt = 0; attempt <= retries; attempt++) {
256
- const response = await fetch(url, init);
257
- if (response.status === 429 && attempt < retries) {
258
- const delay = RETRY_BASE_MS * Math.pow(2, attempt);
259
- await new Promise((r) => setTimeout(r, delay));
348
+ if (signal?.aborted) {
349
+ throw makeAbortError();
350
+ }
351
+ const response = await fetchImpl(url, init);
352
+ const retryable = response.status === 429 || response.status === 503;
353
+ if (retryable && attempt < retries) {
354
+ // Defensive: real Response always has headers, but test doubles
355
+ // often omit them; fall through to exponential backoff in that
356
+ // case.
357
+ const headerVal = typeof response.headers?.get === 'function'
358
+ ? response.headers.get('Retry-After')
359
+ : null;
360
+ const fromHeader = parseRetryAfter(headerVal);
361
+ const delay = fromHeader !== null ? fromHeader : RETRY_BASE_MS * Math.pow(2, attempt);
362
+ await abortableSleep(delay, signal);
260
363
  continue;
261
364
  }
262
365
  return response;
@@ -266,6 +369,13 @@ async function fetchWithRetry(url: string, init: RequestInit, retries = MAX_RETR
266
369
 
267
370
  export function createKustoClient(config: KustoClientConfig): KustoClient {
268
371
  const { defaultTarget, getToken, stateService } = config;
372
+ /**
373
+ * Resolve the fetch implementation at call time rather than capturing it
374
+ * at construction. Tests stub `globalThis.fetch` after creating the
375
+ * client; capturing at construction would freeze the stale reference.
376
+ */
377
+ const resolveFetch = (): typeof fetch =>
378
+ config.fetch ?? globalThis.fetch.bind(globalThis);
269
379
  const limiter = new ConcurrencyLimiter(MAX_CONCURRENT);
270
380
  const inflightQueries = new Map<string, Promise<KustoResult<unknown>>>();
271
381
 
@@ -296,7 +406,7 @@ export function createKustoClient(config: KustoClientConfig): KustoClient {
296
406
  }
297
407
 
298
408
  try {
299
- const response = await fetchWithRetry(`${t.clusterUrl}/v1/rest/query`, {
409
+ const response = await fetchWithRetry(resolveFetch(), `${t.clusterUrl}/v1/rest/query`, {
300
410
  method: 'POST',
301
411
  headers: {
302
412
  'Authorization': `Bearer ${token}`,
@@ -409,7 +519,7 @@ export function createKustoClient(config: KustoClientConfig): KustoClient {
409
519
  const timeout = setTimeout(() => controller.abort(), 60000);
410
520
 
411
521
  try {
412
- const response = await fetchWithRetry(`${t.clusterUrl}/v1/rest/mgmt`, {
522
+ const response = await fetchWithRetry(resolveFetch(), `${t.clusterUrl}/v1/rest/mgmt`, {
413
523
  method: 'POST',
414
524
  headers: {
415
525
  'Authorization': `Bearer ${token}`,
@@ -1,7 +1,7 @@
1
1
  import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
2
 
3
- import { parseSchema, loadSchema, reloadSchema, getSchema, getSchemaFolders, listDatabases, getPersistedDatabases, persistDatabases, KQL_FUNCTIONS, KQL_AGGREGATIONS, KQL_SCALAR_FUNCTIONS } from './schema';
4
- import type { KustoSchemaDb } from './schema';
3
+ import { parseSchema, loadSchema, reloadSchema, getSchema, getSchemaFolders, getRawShowSchema, listDatabases, getPersistedDatabases, persistDatabases } from './schema';
4
+ import type { KustoSchemaDb, RawShowSchema } from './schema';
5
5
  import type { KustoClient } from './kusto';
6
6
 
7
7
  const mockStore = new Map<string, unknown>();
@@ -364,32 +364,6 @@ describe('getSchemaFolders', () => {
364
364
  });
365
365
  });
366
366
 
367
- describe('KQL constants', () => {
368
- it('KQL_FUNCTIONS contains expected keywords', () => {
369
- expect(KQL_FUNCTIONS).toContain('where');
370
- expect(KQL_FUNCTIONS).toContain('project');
371
- expect(KQL_FUNCTIONS).toContain('summarize');
372
- expect(KQL_FUNCTIONS).toContain('join');
373
- expect(KQL_FUNCTIONS).toContain('union');
374
- });
375
-
376
- it('KQL_AGGREGATIONS contains expected functions', () => {
377
- expect(KQL_AGGREGATIONS).toContain('count');
378
- expect(KQL_AGGREGATIONS).toContain('sum');
379
- expect(KQL_AGGREGATIONS).toContain('avg');
380
- expect(KQL_AGGREGATIONS).toContain('dcount');
381
- expect(KQL_AGGREGATIONS).toContain('percentile');
382
- });
383
-
384
- it('KQL_SCALAR_FUNCTIONS contains expected functions', () => {
385
- expect(KQL_SCALAR_FUNCTIONS).toContain('ago');
386
- expect(KQL_SCALAR_FUNCTIONS).toContain('now');
387
- expect(KQL_SCALAR_FUNCTIONS).toContain('strlen');
388
- expect(KQL_SCALAR_FUNCTIONS).toContain('iif');
389
- expect(KQL_SCALAR_FUNCTIONS).toContain('parse_json');
390
- });
391
- });
392
-
393
367
  describe('per-cluster schema', () => {
394
368
  it('getSchema returns empty for unknown target', () => {
395
369
  const schema = getSchema({ clusterUrl: 'https://unknown.kusto.windows.net', database: 'UnknownDB' });
@@ -616,3 +590,108 @@ describe('listDatabases with forceRefresh', () => {
616
590
  expect(getPersistedDatabases(clusterUrl)).toEqual(['NewDB']);
617
591
  });
618
592
  });
593
+
594
+ describe('getRawShowSchema', () => {
595
+ it('returns the raw .show schema payload that loadSchema captured', async () => {
596
+ const mockDb: KustoSchemaDb = {
597
+ Tables: {
598
+ RawTable: { Folder: 'Raw', OrderedColumns: [{ Name: 'X', CslType: 'long' }] },
599
+ },
600
+ };
601
+ const raw: RawShowSchema = { Plugins: [], Databases: { rawdb: mockDb as never } };
602
+ const client = createMockClient({
603
+ rows: [{ DatabaseSchema: JSON.stringify(raw) }],
604
+ columns: [],
605
+ });
606
+ const target = { clusterUrl: 'https://raw.kusto.windows.net', database: 'rawdb' };
607
+
608
+ await reloadSchema(client, target);
609
+
610
+ const result = getRawShowSchema(target);
611
+ expect(result).not.toBeNull();
612
+ expect(result?.Databases['rawdb']).toBeDefined();
613
+ expect(result?.Plugins).toEqual([]);
614
+ });
615
+
616
+ it('returns null when no schema has been loaded for the target', () => {
617
+ const target = { clusterUrl: 'https://never-loaded.kusto.windows.net', database: 'x' };
618
+ expect(getRawShowSchema(target)).toBeNull();
619
+ });
620
+
621
+ it('restores the raw payload from persistent storage when in-memory is empty', () => {
622
+ const mockDb: KustoSchemaDb = {
623
+ Tables: { PersistedTable: { OrderedColumns: [] } },
624
+ };
625
+ const raw: RawShowSchema = { Plugins: [], Databases: { persistdb: mockDb as never } };
626
+ const target = { clusterUrl: 'https://restore.kusto.windows.net', database: 'persistdb' };
627
+
628
+ // Seed the persistent store directly, simulating a prior session writing
629
+ // raw-schema:<cluster>|<db>. No prior in-memory load for this target.
630
+ mockStore.set(`raw-schema:${target.clusterUrl}|${target.database}`, raw);
631
+
632
+ const result = getRawShowSchema(target);
633
+ expect(result).not.toBeNull();
634
+ expect(result?.Databases['persistdb']).toBeDefined();
635
+ // Second call should hit the warmed in-memory cache (still equal payload).
636
+ expect(getRawShowSchema(target)).toBe(result);
637
+ });
638
+
639
+ it('persists raw payload under both target and effectiveTarget cache keys when auto-discovering', async () => {
640
+ const mockDb: KustoSchemaDb = {
641
+ Tables: { AutoDiscoveredTable: { OrderedColumns: [] } },
642
+ };
643
+ const raw: RawShowSchema = { Plugins: [], Databases: { autodb: mockDb as never } };
644
+ const clusterUrl = 'https://auto.kusto.windows.net';
645
+ // Mgmt query #1 (auto-discovery): list databases; returns one db.
646
+ // Mgmt query #2: schema for that db.
647
+ const queryKustoMgmt = vi.fn()
648
+ .mockResolvedValueOnce({ rows: [{ DatabaseName: 'autodb' }], columns: [] })
649
+ .mockResolvedValueOnce({ rows: [{ DatabaseSchema: JSON.stringify(raw) }], columns: [] });
650
+ const client: KustoClient = {
651
+ queryKusto: vi.fn(),
652
+ queryKustoMgmt,
653
+ clearQueryCache: vi.fn(),
654
+ getQueryCacheSize: vi.fn().mockReturnValue(0),
655
+ };
656
+ const originalTarget = { clusterUrl, database: '' };
657
+
658
+ await reloadSchema(client, originalTarget);
659
+
660
+ // Raw payload retrievable under the original (empty-db) target.
661
+ expect(getRawShowSchema(originalTarget)).not.toBeNull();
662
+ // …and under the effective target after auto-discovery.
663
+ expect(getRawShowSchema({ clusterUrl, database: 'autodb' })).not.toBeNull();
664
+ });
665
+
666
+ it('clears the raw cache on reloadSchema', async () => {
667
+ const mockDb: KustoSchemaDb = {
668
+ Tables: { ClearedTable: { OrderedColumns: [] } },
669
+ };
670
+ const raw: RawShowSchema = { Plugins: [], Databases: { cleardb: mockDb as never } };
671
+ const target = { clusterUrl: 'https://clear.kusto.windows.net', database: 'cleardb' };
672
+
673
+ const client = createMockClient({
674
+ rows: [{ DatabaseSchema: JSON.stringify(raw) }],
675
+ columns: [],
676
+ });
677
+
678
+ await reloadSchema(client, target);
679
+ expect(getRawShowSchema(target)).not.toBeNull();
680
+
681
+ // Reload with a client that returns a brand-new payload; the old one
682
+ // should not be retained.
683
+ const newRaw: RawShowSchema = { Plugins: [], Databases: { cleardb: { Tables: { NewTable: {} } } as never } };
684
+ const client2 = createMockClient({
685
+ rows: [{ DatabaseSchema: JSON.stringify(newRaw) }],
686
+ columns: [],
687
+ });
688
+ await reloadSchema(client2, target);
689
+
690
+ const result = getRawShowSchema(target);
691
+ expect(result?.Databases['cleardb']).toBeDefined();
692
+ // Verify the new payload took the place of the old one (different Tables key).
693
+ const tables = (result?.Databases['cleardb'] as { Tables: Record<string, unknown> } | undefined)?.Tables;
694
+ expect(tables && 'NewTable' in tables).toBe(true);
695
+ expect(tables && 'ClearedTable' in tables).toBe(false);
696
+ });
697
+ });
@@ -25,9 +25,33 @@ export interface KustoSchemaDb {
25
25
  ExternalTables?: Record<string, { Folder?: string; DocString?: string; OrderedColumns?: { Name: string; CslType: string }[] }>;
26
26
  }
27
27
 
28
+ /**
29
+ * Root payload returned by Kusto's `.show database schema as json` command.
30
+ * Shape matches what `@kusto/monaco-kusto`'s `setSchemaFromShowSchema` expects.
31
+ * Kept loose (optional fields) so older cluster responses still parse.
32
+ */
33
+ export interface RawShowSchema {
34
+ readonly Plugins?: readonly unknown[];
35
+ readonly Databases: Record<string, RawShowSchemaDatabase>;
36
+ }
37
+
38
+ export interface RawShowSchemaDatabase {
39
+ readonly Name?: string;
40
+ readonly Tables?: Record<string, unknown>;
41
+ readonly ExternalTables?: Record<string, unknown>;
42
+ readonly MaterializedViews?: Record<string, unknown>;
43
+ readonly Functions?: Record<string, unknown>;
44
+ readonly EntityGroups?: Record<string, readonly string[]>;
45
+ readonly Graphs?: Record<string, unknown>;
46
+ readonly MajorVersion?: number;
47
+ readonly MinorVersion?: number;
48
+ readonly DatabaseAccessMode?: string;
49
+ }
50
+
28
51
  // Per-cluster schema cache
29
52
  const schemaCache = new Map<string, SchemaTable[]>();
30
53
  const foldersCache = new Map<string, string[]>();
54
+ const rawSchemaCache = new Map<string, RawShowSchema>();
31
55
  const loadingPromises = new Map<string, Promise<void>>();
32
56
 
33
57
  function cacheKey(target?: KustoTarget): string {
@@ -41,6 +65,10 @@ function persistSchemaKey(target: KustoTarget): string {
41
65
  return `schema:${target.clusterUrl}|${target.database}`;
42
66
  }
43
67
 
68
+ function persistRawSchemaKey(target: KustoTarget): string {
69
+ return `raw-schema:${target.clusterUrl}|${target.database}`;
70
+ }
71
+
44
72
  function persistDbKey(clusterUrl: string): string {
45
73
  return `dbs:${clusterUrl}`;
46
74
  }
@@ -54,6 +82,11 @@ function restoreSchemaFromStore(target: KustoTarget): boolean {
54
82
  if (stored && stored.length > 0) {
55
83
  schemaCache.set(key, stored);
56
84
  foldersCache.set(key, [...new Set(stored.map((t) => t.folder))].filter(Boolean).sort());
85
+ // Best-effort raw restore — language service IntelliSense needs this.
86
+ const rawStored = stateService.get<RawShowSchema>('explorerCache', persistRawSchemaKey(target));
87
+ if (rawStored && rawStored.Databases) {
88
+ rawSchemaCache.set(key, rawStored);
89
+ }
57
90
  return true;
58
91
  }
59
92
  return false;
@@ -63,6 +96,10 @@ function persistSchema(target: KustoTarget, schema: SchemaTable[]): void {
63
96
  stateService.set('explorerCache', persistSchemaKey(target), schema);
64
97
  }
65
98
 
99
+ function persistRawSchema(target: KustoTarget, raw: RawShowSchema): void {
100
+ stateService.set('explorerCache', persistRawSchemaKey(target), raw);
101
+ }
102
+
66
103
  export function getPersistedDatabases(clusterUrl: string): string[] | null {
67
104
  return stateService.get<string[]>('explorerCache', persistDbKey(clusterUrl));
68
105
  }
@@ -172,21 +209,25 @@ export async function loadSchema(client: KustoClient, target?: KustoTarget): Pro
172
209
  try {
173
210
  const result = await client.queryKustoMgmt<{ DatabaseSchema: string }>('.show database schema as json', effectiveTarget);
174
211
  if (result.rows.length > 0) {
175
- const schemaJson = JSON.parse(result.rows[0].DatabaseSchema);
212
+ const schemaJson = JSON.parse(result.rows[0].DatabaseSchema) as RawShowSchema;
176
213
  const dbName = Object.keys(schemaJson.Databases)[0];
177
214
  const db = schemaJson.Databases[dbName] as KustoSchemaDb;
178
215
  const parsed = parseSchema(db);
179
216
  schemaCache.set(key, parsed);
180
217
  foldersCache.set(key, [...new Set(parsed.map((t) => t.folder))].filter(Boolean).sort());
218
+ rawSchemaCache.set(key, schemaJson);
181
219
  // Persist to IndexedDB
182
220
  if (effectiveTarget) {
183
221
  persistSchema(effectiveTarget, parsed);
222
+ persistRawSchema(effectiveTarget, schemaJson);
184
223
  }
185
224
  // Also cache under the original target key if different
186
225
  if (target && cacheKey(target) !== key) {
187
226
  schemaCache.set(cacheKey(target), parsed);
188
227
  foldersCache.set(cacheKey(target), [...new Set(parsed.map((t) => t.folder))].filter(Boolean).sort());
228
+ rawSchemaCache.set(cacheKey(target), schemaJson);
189
229
  persistSchema(target, parsed);
230
+ persistRawSchema(target, schemaJson);
190
231
  }
191
232
  } else {
192
233
  schemaCache.set(key, []);
@@ -223,8 +264,10 @@ export async function reloadSchema(client: KustoClient, target?: KustoTarget): P
223
264
  const key = cacheKey(target);
224
265
  schemaCache.delete(key);
225
266
  foldersCache.delete(key);
267
+ rawSchemaCache.delete(key);
226
268
  if (target) {
227
269
  stateService.delete('explorerCache', persistSchemaKey(target));
270
+ stateService.delete('explorerCache', persistRawSchemaKey(target));
228
271
  }
229
272
  return loadSchema(client, target);
230
273
  }
@@ -247,6 +290,28 @@ export function getSchemaFolders(target?: KustoTarget): string[] {
247
290
  return target ? [] : [];
248
291
  }
249
292
 
293
+ /**
294
+ * Returns the raw `.show database schema as json` payload for the given target,
295
+ * if known. The payload's shape matches what `@kusto/monaco-kusto`'s
296
+ * `setSchemaFromShowSchema` accepts. Returns null when no schema has been
297
+ * loaded (or persisted) for this target.
298
+ */
299
+ export function getRawShowSchema(target?: KustoTarget): RawShowSchema | null {
300
+ const key = cacheKey(target);
301
+ const cached = rawSchemaCache.get(key);
302
+ if (cached) {
303
+ return cached;
304
+ }
305
+ if (target) {
306
+ const persisted = stateService.get<RawShowSchema>('explorerCache', persistRawSchemaKey(target));
307
+ if (persisted && persisted.Databases) {
308
+ rawSchemaCache.set(key, persisted);
309
+ return persisted;
310
+ }
311
+ }
312
+ return null;
313
+ }
314
+
250
315
  /** List databases on a Kusto cluster. Uses persistent cache; pass forceRefresh to bypass. */
251
316
  export async function listDatabases(client: KustoClient, clusterUrl: string, forceRefresh = false): Promise<string[]> {
252
317
  if (!forceRefresh) {
@@ -268,27 +333,3 @@ export async function listDatabases(client: KustoClient, clusterUrl: string, for
268
333
  return [];
269
334
  }
270
335
  }
271
-
272
- // --- KQL language tokens (not from Kusto, always static) ---
273
-
274
- export const KQL_FUNCTIONS = [
275
- 'where', 'project', 'extend', 'summarize', 'count', 'take', 'top', 'order', 'sort',
276
- 'join', 'union', 'lookup', 'mv-expand', 'parse', 'evaluate',
277
- 'render', 'as', 'let', 'set', 'alias', 'restrict', 'pattern',
278
- ];
279
-
280
- export const KQL_AGGREGATIONS = [
281
- 'count', 'countif', 'dcount', 'sum', 'sumif', 'avg', 'min', 'max',
282
- 'percentile', 'percentiles', 'stdev', 'variance', 'make_list', 'make_set',
283
- 'arg_max', 'arg_min', 'any', 'take_any',
284
- ];
285
-
286
- export const KQL_SCALAR_FUNCTIONS = [
287
- 'ago', 'now', 'datetime', 'timespan', 'bin', 'floor', 'ceiling',
288
- 'strlen', 'substring', 'tolower', 'toupper', 'trim', 'replace',
289
- 'strcat', 'split', 'parse_json', 'tostring', 'toint', 'tolong', 'todouble', 'tobool',
290
- 'iif', 'iff', 'case', 'coalesce', 'isempty', 'isnotempty', 'isnull', 'isnotnull',
291
- 'format_datetime', 'datetime_diff', 'startofday', 'startofweek', 'startofmonth',
292
- 'round', 'abs', 'log', 'pow', 'sqrt',
293
- 'array_length', 'pack', 'bag_keys',
294
- ];
@@ -0,0 +1,3 @@
1
+ import { vi } from 'vitest';
2
+
3
+ vi.mock('monaco-editor', () => ({}));
@@ -0,0 +1,118 @@
1
+ import { describe, it, expect } from 'vitest';
2
+
3
+ import { traverseVitePlugin, TRAVERSE_OPTIMIZE_DEPS_INCLUDE } from './vite-plugin';
4
+
5
+ describe('traverseVitePlugin', () => {
6
+ it('returns a plugin with the expected metadata', () => {
7
+ const p = traverseVitePlugin();
8
+ expect(p.name).toBe('@mhjuma/traverse');
9
+ expect(p.enforce).toBe('pre');
10
+ });
11
+
12
+ it('config() returns optimizeDeps.include matching the exported constant', () => {
13
+ const p = traverseVitePlugin();
14
+ const cfg = p.config!();
15
+ expect(cfg?.optimizeDeps?.include).toEqual([...TRAVERSE_OPTIMIZE_DEPS_INCLUDE]);
16
+ });
17
+
18
+ it('config() returns a fresh array each call (not the frozen constant)', () => {
19
+ // Vite mutates the `include` array internally; returning the frozen
20
+ // singleton would throw later. Verify we hand back a writable copy.
21
+ const cfg = traverseVitePlugin().config!()!;
22
+ expect(() => { (cfg.optimizeDeps!.include as string[]).push('test'); }).not.toThrow();
23
+ });
24
+
25
+ describe('transform() — Bridge.NET CJS shim', () => {
26
+ const SHIM_PREFIX = 'var global=globalThis;var module={exports:{}};var exports=module.exports;\n';
27
+
28
+ it('prepends the shim to bridge.min.js inside @kusto/language-service', () => {
29
+ const p = traverseVitePlugin();
30
+ const id = '/somewhere/node_modules/@kusto/language-service/bridge.min.js';
31
+ const got = p.transform!('(function(n){n.Bridge=1})(this);', id);
32
+ expect(got).not.toBeNull();
33
+ expect(got!.code).toBe(SHIM_PREFIX + '(function(n){n.Bridge=1})(this);');
34
+ expect(got!.map).toBeNull();
35
+ });
36
+
37
+ it('prepends the shim to Kusto.JavaScript.Client.min.js', () => {
38
+ const p = traverseVitePlugin();
39
+ const id = '/n_m/@kusto/language-service/Kusto.JavaScript.Client.min.js';
40
+ const got = p.transform!('orig;', id);
41
+ expect(got!.code).toBe(SHIM_PREFIX + 'orig;');
42
+ });
43
+
44
+ it('prepends the shim to newtonsoft.json.min.js', () => {
45
+ const p = traverseVitePlugin();
46
+ const id = '/n_m/@kusto/language-service/newtonsoft.json.min.js';
47
+ const got = p.transform!('orig;', id);
48
+ expect(got!.code).toBe(SHIM_PREFIX + 'orig;');
49
+ });
50
+
51
+ it('prepends the shim to Kusto.Language.Bridge.min.js inside @kusto/language-service-next', () => {
52
+ const p = traverseVitePlugin();
53
+ const id = '/n_m/@kusto/language-service-next/Kusto.Language.Bridge.min.js';
54
+ const got = p.transform!('orig;', id);
55
+ expect(got!.code).toBe(SHIM_PREFIX + 'orig;');
56
+ });
57
+
58
+ it('matches paths with query-string suffixes (Vite ?import, ?worker_file)', () => {
59
+ const p = traverseVitePlugin();
60
+ const id = '/n_m/@kusto/language-service/bridge.min.js?worker_file&type=module';
61
+ const got = p.transform!('orig;', id);
62
+ expect(got).not.toBeNull();
63
+ expect(got!.code).toBe(SHIM_PREFIX + 'orig;');
64
+ });
65
+
66
+ it('matches paths with Windows-style backslashes', () => {
67
+ const p = traverseVitePlugin();
68
+ const id = 'C:\\app\\node_modules\\@kusto\\language-service\\bridge.min.js';
69
+ const got = p.transform!('orig;', id);
70
+ expect(got).not.toBeNull();
71
+ });
72
+
73
+ it('does NOT match unrelated files in @kusto', () => {
74
+ const p = traverseVitePlugin();
75
+ const id = '/n_m/@kusto/language-service/index.js';
76
+ expect(p.transform!('orig;', id)).toBeNull();
77
+ });
78
+
79
+ it('does NOT match arbitrary .min.js files outside @kusto', () => {
80
+ const p = traverseVitePlugin();
81
+ const id = '/n_m/other/bridge.min.js';
82
+ expect(p.transform!('orig;', id)).toBeNull();
83
+ });
84
+
85
+ it('does NOT match a file whose path superficially contains "bridge.min.js" but in wrong scope', () => {
86
+ const p = traverseVitePlugin();
87
+ const id = '/n_m/@kusto/other-package/bridge.min.js';
88
+ expect(p.transform!('orig;', id)).toBeNull();
89
+ });
90
+
91
+ it('does NOT touch normal JS files', () => {
92
+ const p = traverseVitePlugin();
93
+ expect(p.transform!('const x = 1;', '/src/foo.js')).toBeNull();
94
+ });
95
+ });
96
+
97
+ describe('TRAVERSE_OPTIMIZE_DEPS_INCLUDE', () => {
98
+ it('is frozen so consumers cannot accidentally mutate the canonical list', () => {
99
+ expect(Object.isFrozen(TRAVERSE_OPTIMIZE_DEPS_INCLUDE)).toBe(true);
100
+ });
101
+
102
+ it('includes both worker entries', () => {
103
+ expect(TRAVERSE_OPTIMIZE_DEPS_INCLUDE).toContain('monaco-editor/esm/vs/editor/editor.worker');
104
+ expect(TRAVERSE_OPTIMIZE_DEPS_INCLUDE).toContain('@kusto/monaco-kusto/release/esm/kusto.worker');
105
+ });
106
+
107
+ it('includes all four Bridge.NET subdeps in the parent > child form', () => {
108
+ expect(TRAVERSE_OPTIMIZE_DEPS_INCLUDE).toContain('@kusto/monaco-kusto > @kusto/language-service/bridge.min');
109
+ expect(TRAVERSE_OPTIMIZE_DEPS_INCLUDE).toContain('@kusto/monaco-kusto > @kusto/language-service/Kusto.JavaScript.Client.min');
110
+ expect(TRAVERSE_OPTIMIZE_DEPS_INCLUDE).toContain('@kusto/monaco-kusto > @kusto/language-service/newtonsoft.json.min');
111
+ expect(TRAVERSE_OPTIMIZE_DEPS_INCLUDE).toContain('@kusto/monaco-kusto > @kusto/language-service-next/Kusto.Language.Bridge.min');
112
+ });
113
+
114
+ it('includes xregexp (kusto plugin sub-dep with strict pnpm resolution)', () => {
115
+ expect(TRAVERSE_OPTIMIZE_DEPS_INCLUDE).toContain('@kusto/monaco-kusto > xregexp');
116
+ });
117
+ });
118
+ });