@xh/hoist-docs-builder 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,1845 @@
1
+ /*
2
+ * This file belongs to Hoist, an application development toolkit
3
+ * developed by Extremely Heavy Industries (www.xh.io | info@xh.io)
4
+ *
5
+ * Copyright © 2026 Extremely Heavy Industries Inc.
6
+ */
7
+ /**
8
+ * TypeScript symbol extraction data layer for the Hoist MCP server.
9
+ *
10
+ * Wraps ts-morph to parse hoist-react's TypeScript source files, builds a
11
+ * searchable symbol index, and provides on-demand extraction of detailed type
12
+ * information. This module is consumed by the three TypeScript MCP tools:
13
+ * hoist-search-symbols, hoist-get-symbol, and hoist-get-members.
14
+ *
15
+ * Initialization is kicked off asynchronously after server startup via
16
+ * `beginInitialization()`, so the index is typically ready before the first
17
+ * tool call arrives. If a tool call arrives before init completes,
18
+ * `ensureInitialized()` awaits the in-flight init. Once created, a
19
+ * lightweight symbol index and parallel member index are built using
20
+ * AST-level methods for fast search without per-query AST traversal.
21
+ * Detailed symbol info is extracted on-demand.
22
+ */
23
+ import { Project, Node, Scope, SyntaxKind } from 'ts-morph';
24
+ import { resolve } from 'node:path';
25
+ import { log } from '../util/logger.js';
26
+ import { isLibrarySource, resolveRepoRoot, resolveRepoRootPosix, toPosixPath } from '../util/paths.js';
27
+ import { createImportPathResolver } from './import-paths.js';
28
+ import { computeFingerprint, loadCache, writeCache } from './index-cache.js';
29
+ //------------------------------------------------------------------
30
+ // Module state (lazy initialization)
31
+ //------------------------------------------------------------------
32
+ let project = null;
33
+ let symbolIndex = null;
34
+ let memberIndex = null;
35
+ /** Pre-computed detail for Promise prototype extensions (not extractable via standard AST lookup). */
36
+ let promiseExtensionDetails = null;
37
+ //------------------------------------------------------------------
38
+ // Package derivation
39
+ //------------------------------------------------------------------
40
+ /** Known top-level package directories in hoist-react. */
41
+ const TOP_LEVEL_PACKAGES = [
42
+ 'core',
43
+ 'data',
44
+ 'svc',
45
+ 'cmp',
46
+ 'desktop',
47
+ 'mobile',
48
+ 'format',
49
+ 'appcontainer',
50
+ 'utils',
51
+ 'promise',
52
+ 'mobx',
53
+ 'public',
54
+ 'static',
55
+ 'admin',
56
+ 'inspector',
57
+ 'icon',
58
+ 'test-support'
59
+ ];
60
+ /**
61
+ * Which classes and interfaces have their public members indexed for member search
62
+ * is determined by rule (see `shouldIndexClassMembers` / `shouldIndexInterfaceMembers`):
63
+ *
64
+ * - every exported class
65
+ * - every exported interface whose name ends in `Config`, `Spec`, or `Options` (the Hoist
66
+ * conventions for configuration-object shapes consumed by class constructors, grid/column/
67
+ * view definitions, and option bags such as `FetchOptions` and `PersistOptions`)
68
+ * - every exported interface whose name ends in `Props` - indexed, but only searched when the
69
+ * query names the owner (see `symbol-search.ts`), since generic prop names such as `title`
70
+ * or `disabled` would otherwise flood results
71
+ *
72
+ * Each indexed owner can carry an optional short hint via an `@mcpHint` JSDoc tag
73
+ * on its declaration (e.g. `@mcpHint model backing all grid components`). The tag
74
+ * text is extracted by `extractMcpHint` and shown alongside the owner name in
75
+ * member search results. Collocating the hint with the declaration avoids the
76
+ * name-collision and maintenance-drift problems of a separate hand-curated registry.
77
+ */
78
+ /** True if the given class should have its public members indexed for search. */
79
+ function shouldIndexClassMembers(cls) {
80
+ return cls.isExported();
81
+ }
82
+ /** True if the given interface should have its public members indexed for search. */
83
+ function shouldIndexInterfaceMembers(name, isExported) {
84
+ return isExported && /(Config|Spec|Options|Props)$/.test(name);
85
+ }
86
+ /** True for `*Props` owners, whose members are searched only when the query names the owner. */
87
+ export function isPropsOwner(ownerName) {
88
+ return ownerName.endsWith('Props');
89
+ }
90
+ /**
91
+ * True for a Promise prototype extension entry (`catchDefault`, `linkTo`), which is public API
92
+ * that needs no import - the one kind of exported symbol the tools show no import path for.
93
+ */
94
+ export function isPromiseExtension(entry) {
95
+ const detail = promiseExtensionDetails?.get(entry.name);
96
+ return detail != null && detail.filePath === entry.filePath;
97
+ }
98
+ /** Longest property initializer surfaced as a member default. */
99
+ const MAX_DEFAULT_LENGTH = 60;
100
+ /**
101
+ * Derive the source package from a file's absolute path.
102
+ * e.g. `/repo/core/HoistBase.ts` maps to `core`,
103
+ * `/repo/cmp/grid/GridModel.ts` maps to `cmp/grid`.
104
+ */
105
+ function derivePackage(filePath, repoRoot) {
106
+ const rel = filePath.slice(repoRoot.length + 1);
107
+ const parts = rel.split('/');
108
+ if (parts.length > 0 && TOP_LEVEL_PACKAGES.includes(parts[0])) {
109
+ const pkgParts = [parts[0]];
110
+ for (let i = 1; i < parts.length - 1; i++) {
111
+ if (!parts[i].includes('.')) {
112
+ pkgParts.push(parts[i]);
113
+ }
114
+ else {
115
+ break;
116
+ }
117
+ }
118
+ return pkgParts.join('/');
119
+ }
120
+ return parts[0] || 'unknown';
121
+ }
122
+ //------------------------------------------------------------------
123
+ // Index building
124
+ //------------------------------------------------------------------
125
+ /**
126
+ * Add a symbol entry to the index, keyed by lowercase name.
127
+ * Skips symbols with empty or anonymous names.
128
+ */
129
+ function addToIndex(index, entry) {
130
+ if (!entry.name || entry.name === '(anonymous)')
131
+ return;
132
+ const key = entry.name.toLowerCase();
133
+ const existing = index.get(key);
134
+ if (existing) {
135
+ existing.push(entry);
136
+ }
137
+ else {
138
+ index.set(key, [entry]);
139
+ }
140
+ }
141
+ /** Add a member entry to the member index, keyed by lowercase member name. */
142
+ function addToMemberIndex(index, entry) {
143
+ const key = entry.name.toLowerCase();
144
+ const existing = index.get(key);
145
+ if (existing) {
146
+ existing.push(entry);
147
+ }
148
+ else {
149
+ index.set(key, [entry]);
150
+ }
151
+ }
152
+ /**
153
+ * Check if a member should be excluded from the index as private/internal.
154
+ * Excludes members with the `private` keyword or names starting with `_`.
155
+ */
156
+ function isPrivateMember(member, cls) {
157
+ if (member.name.startsWith('_'))
158
+ return true;
159
+ // Check for explicit `private` keyword on the AST node
160
+ try {
161
+ const node = cls.getProperty(member.name) ??
162
+ cls.getGetAccessor(member.name) ??
163
+ cls.getMethod(member.name) ??
164
+ cls.getStaticProperty(member.name) ??
165
+ cls.getStaticMethod(member.name);
166
+ if (node) {
167
+ const scope = node.getScope?.();
168
+ if (scope === Scope.Private)
169
+ return true;
170
+ }
171
+ }
172
+ catch {
173
+ // If we can't determine scope, keep the member (assume public)
174
+ }
175
+ return false;
176
+ }
177
+ /** Format a method's parameter list and return type as a compact type string. */
178
+ function formatMethodType(member) {
179
+ const params = (member.parameters ?? []).map(p => `${p.name}: ${p.type}`).join(', ');
180
+ const ret = member.returnType ?? 'void';
181
+ return `(${params}) => ${ret}`;
182
+ }
183
+ /**
184
+ * Build the symbol index by scanning all source files using AST-level methods.
185
+ * Also builds a parallel member index for every exported class and every exported `*Config`,
186
+ * `*Spec`, `*Options`, and `*Props` interface (see `shouldIndexClassMembers` /
187
+ * `shouldIndexInterfaceMembers`). `*Props` members are searched only when the query names the
188
+ * owner (see `symbol-search.ts`).
189
+ *
190
+ * Uses getClasses(), getInterfaces(), getTypeAliases(), getFunctions(),
191
+ * getEnums(), and getVariableStatements() -- NOT getExportedDeclarations(),
192
+ * which triggers full type binding and is ~1000x slower.
193
+ */
194
+ function buildSymbolIndex(proj) {
195
+ const index = new Map();
196
+ const mIndex = new Map();
197
+ // POSIX form: compared against ts-morph `getFilePath()`, which always uses
198
+ // forward slashes even on Windows.
199
+ const repoRoot = resolveRepoRootPosix();
200
+ const resolveImportPath = createImportPathResolver(proj, repoRoot);
201
+ const importPathFor = (filePath, name, isExported) => isExported ? resolveImportPath(filePath, name) : null;
202
+ const counts = { total: 0, exported: 0, byKind: {} };
203
+ let memberCount = 0;
204
+ const memberNamesByOwner = new Map();
205
+ const ownerKey = (name, filePath) => `${name}|${filePath}`;
206
+ for (const sourceFile of proj.getSourceFiles()) {
207
+ const filePath = sourceFile.getFilePath();
208
+ if (!isLibrarySource(filePath, repoRoot))
209
+ continue;
210
+ const pkg = derivePackage(filePath, repoRoot);
211
+ // Classes
212
+ for (const cls of sourceFile.getClasses()) {
213
+ const name = cls.getName();
214
+ if (!name)
215
+ continue;
216
+ const mcpHint = extractMcpHint(cls);
217
+ const entry = {
218
+ name,
219
+ kind: 'class',
220
+ filePath,
221
+ isExported: cls.isExported(),
222
+ sourcePackage: pkg,
223
+ importPath: importPathFor(filePath, name, cls.isExported()),
224
+ jsDoc: extractJsDoc(cls),
225
+ mcpHint
226
+ };
227
+ addToIndex(index, entry);
228
+ counts.total++;
229
+ if (entry.isExported)
230
+ counts.exported++;
231
+ counts.byKind['class'] = (counts.byKind['class'] || 0) + 1;
232
+ // Index public members for every exported class.
233
+ if (shouldIndexClassMembers(cls)) {
234
+ const ownerHint = mcpHint;
235
+ try {
236
+ const members = extractClassMembers(sourceFile, name);
237
+ const classPublicNames = [];
238
+ for (const m of members) {
239
+ if (isPrivateMember(m, cls))
240
+ continue;
241
+ classPublicNames.push(m.name);
242
+ const mEntry = {
243
+ name: m.name,
244
+ memberKind: m.kind,
245
+ ownerName: name,
246
+ ownerHint,
247
+ filePath,
248
+ sourcePackage: pkg,
249
+ isStatic: m.isStatic,
250
+ type: m.kind === 'method' ? formatMethodType(m) : m.type,
251
+ jsDoc: m.jsDoc,
252
+ ...(m.default != null ? { default: m.default } : {}),
253
+ decorators: m.decorators
254
+ };
255
+ addToMemberIndex(mIndex, mEntry);
256
+ memberCount++;
257
+ }
258
+ memberNamesByOwner.set(ownerKey(name, filePath), {
259
+ name,
260
+ filePath,
261
+ memberNames: classPublicNames
262
+ });
263
+ }
264
+ catch (e) {
265
+ log.warn(`Failed to index members for ${name}: ${e}`);
266
+ }
267
+ }
268
+ }
269
+ // Interfaces
270
+ for (const iface of sourceFile.getInterfaces()) {
271
+ const name = iface.getName();
272
+ if (!name)
273
+ continue;
274
+ let jsDoc = extractJsDoc(iface);
275
+ if (!jsDoc)
276
+ jsDoc = extractCompanionJsDoc(sourceFile, name);
277
+ const isExported = iface.isExported();
278
+ const mcpHint = extractMcpHint(iface);
279
+ const entry = {
280
+ name,
281
+ kind: 'interface',
282
+ filePath,
283
+ isExported,
284
+ sourcePackage: pkg,
285
+ importPath: importPathFor(filePath, name, isExported),
286
+ jsDoc,
287
+ mcpHint
288
+ };
289
+ addToIndex(index, entry);
290
+ counts.total++;
291
+ if (entry.isExported)
292
+ counts.exported++;
293
+ counts.byKind['interface'] = (counts.byKind['interface'] || 0) + 1;
294
+ // Index public members for exported `*Config`, `*Spec`, `*Options`, and `*Props`
295
+ // interfaces, which describe the configuration surface of classes and components.
296
+ if (shouldIndexInterfaceMembers(name, isExported)) {
297
+ const ownerHint = mcpHint;
298
+ try {
299
+ const members = extractInterfaceMembers(sourceFile, name);
300
+ const publicNames = [];
301
+ for (const m of members) {
302
+ if (m.name.startsWith('_'))
303
+ continue;
304
+ publicNames.push(m.name);
305
+ const mEntry = {
306
+ name: m.name,
307
+ memberKind: m.kind,
308
+ ownerName: name,
309
+ ownerHint,
310
+ filePath,
311
+ sourcePackage: pkg,
312
+ isStatic: m.isStatic,
313
+ type: m.kind === 'method' ? formatMethodType(m) : m.type,
314
+ jsDoc: m.jsDoc,
315
+ decorators: m.decorators
316
+ };
317
+ addToMemberIndex(mIndex, mEntry);
318
+ memberCount++;
319
+ }
320
+ // Props owners are searched only when named, so their member names do
321
+ // not expand the owner's own searchable text either.
322
+ if (!isPropsOwner(name)) {
323
+ memberNamesByOwner.set(ownerKey(name, filePath), {
324
+ name,
325
+ filePath,
326
+ memberNames: publicNames
327
+ });
328
+ }
329
+ }
330
+ catch (e) {
331
+ log.warn(`Failed to index members for ${name}: ${e}`);
332
+ }
333
+ }
334
+ }
335
+ // Type aliases
336
+ for (const typeAlias of sourceFile.getTypeAliases()) {
337
+ const name = typeAlias.getName();
338
+ if (!name)
339
+ continue;
340
+ const entry = {
341
+ name,
342
+ kind: 'type',
343
+ filePath,
344
+ isExported: typeAlias.isExported(),
345
+ sourcePackage: pkg,
346
+ importPath: importPathFor(filePath, name, typeAlias.isExported()),
347
+ jsDoc: extractJsDoc(typeAlias)
348
+ };
349
+ addToIndex(index, entry);
350
+ counts.total++;
351
+ if (entry.isExported)
352
+ counts.exported++;
353
+ counts.byKind['type'] = (counts.byKind['type'] || 0) + 1;
354
+ }
355
+ // Functions
356
+ for (const func of sourceFile.getFunctions()) {
357
+ const name = func.getName();
358
+ if (!name)
359
+ continue;
360
+ const entry = {
361
+ name,
362
+ kind: 'function',
363
+ filePath,
364
+ isExported: func.isExported(),
365
+ sourcePackage: pkg,
366
+ importPath: importPathFor(filePath, name, func.isExported()),
367
+ jsDoc: extractFunctionJsDoc(func)
368
+ };
369
+ addToIndex(index, entry);
370
+ counts.total++;
371
+ if (entry.isExported)
372
+ counts.exported++;
373
+ counts.byKind['function'] = (counts.byKind['function'] || 0) + 1;
374
+ }
375
+ // Enums
376
+ for (const enumDecl of sourceFile.getEnums()) {
377
+ const name = enumDecl.getName();
378
+ if (!name)
379
+ continue;
380
+ const entry = {
381
+ name,
382
+ kind: 'enum',
383
+ filePath,
384
+ isExported: enumDecl.isExported(),
385
+ sourcePackage: pkg,
386
+ importPath: importPathFor(filePath, name, enumDecl.isExported()),
387
+ jsDoc: extractJsDoc(enumDecl)
388
+ };
389
+ addToIndex(index, entry);
390
+ counts.total++;
391
+ if (entry.isExported)
392
+ counts.exported++;
393
+ counts.byKind['enum'] = (counts.byKind['enum'] || 0) + 1;
394
+ }
395
+ // Exported const variables
396
+ for (const stmt of sourceFile.getVariableStatements()) {
397
+ if (!stmt.isExported())
398
+ continue;
399
+ const stmtJsDoc = extractJsDoc(stmt);
400
+ for (const decl of stmt.getDeclarations()) {
401
+ // For destructured exports (e.g. `export const [Foo, foo] = ...`),
402
+ // index each binding element as a separate symbol so both the
403
+ // PascalCase component and camelCase factory are individually
404
+ // searchable and resolvable via exact name lookup.
405
+ const nameNode = decl.getNameNode();
406
+ const names = [];
407
+ if (nameNode.isKind(SyntaxKind.ArrayBindingPattern)) {
408
+ for (const el of nameNode.getElements()) {
409
+ if (Node.isOmittedExpression(el))
410
+ continue;
411
+ const n = el.getName();
412
+ if (n)
413
+ names.push(n);
414
+ }
415
+ }
416
+ else if (nameNode.isKind(SyntaxKind.ObjectBindingPattern)) {
417
+ for (const el of nameNode.getElements()) {
418
+ const n = el.getName();
419
+ if (n)
420
+ names.push(n);
421
+ }
422
+ }
423
+ else {
424
+ const n = decl.getName();
425
+ if (n)
426
+ names.push(n);
427
+ }
428
+ for (const name of names) {
429
+ const entry = {
430
+ name,
431
+ kind: 'const',
432
+ filePath,
433
+ isExported: true,
434
+ sourcePackage: pkg,
435
+ importPath: importPathFor(filePath, name, true),
436
+ jsDoc: stmtJsDoc
437
+ };
438
+ addToIndex(index, entry);
439
+ counts.total++;
440
+ counts.exported++;
441
+ counts.byKind['const'] = (counts.byKind['const'] || 0) + 1;
442
+ }
443
+ }
444
+ }
445
+ }
446
+ // Index Promise prototype extensions from promise/Promise.ts
447
+ const promiseFile = proj.getSourceFile(sf => sf.getFilePath().endsWith('/promise/Promise.ts'));
448
+ if (promiseFile) {
449
+ indexPromiseExtensions(promiseFile, index, mIndex, resolveRepoRootPosix());
450
+ }
451
+ // Populate `memberNames` on symbol entries for every member-indexed owner except
452
+ // `*Props` (classes and `*Config`, `*Spec`, and `*Options` interfaces). Excludes
453
+ // inherited HoistBase/HoistModel members so that queries like "StoreRecord raw"
454
+ // surface StoreRecord, but generic terms like "destroy" or "addReaction" do not match
455
+ // every class. HoistBase and HoistModel each exist in exactly one file so a name-based
456
+ // lookup is sufficient for computing `baseMemberNames`.
457
+ const collectByName = (n) => {
458
+ for (const v of memberNamesByOwner.values()) {
459
+ if (v.name === n)
460
+ return v.memberNames;
461
+ }
462
+ return [];
463
+ };
464
+ const baseMemberNames = new Set([...collectByName('HoistBase'), ...collectByName('HoistModel')].map(n => n.toLowerCase()));
465
+ for (const { name: ownerName, filePath: ownerFile, memberNames: allNames } of memberNamesByOwner.values()) {
466
+ if (ownerName === 'HoistBase' || ownerName === 'HoistModel')
467
+ continue;
468
+ const ownNames = allNames.filter(n => !baseMemberNames.has(n.toLowerCase()));
469
+ if (ownNames.length === 0)
470
+ continue;
471
+ const entries = index.get(ownerName.toLowerCase());
472
+ if (entries) {
473
+ for (const entry of entries) {
474
+ if (entry.name === ownerName && entry.filePath === ownerFile) {
475
+ entry.memberNames = ownNames.join(' ');
476
+ }
477
+ }
478
+ }
479
+ }
480
+ const kindSummary = Object.entries(counts.byKind)
481
+ .map(([kind, count]) => `${kind}: ${count}`)
482
+ .join(', ');
483
+ log.info(`Symbol index built: ${counts.total} total symbols (${counts.exported} exported) -- ${kindSummary}`);
484
+ log.info(`Member index built: ${memberCount} public members across ${memberNamesByOwner.size} owners`);
485
+ return { symbols: index, members: mIndex };
486
+ }
487
+ /**
488
+ * Index Promise prototype extension methods declared in promise/Promise.ts.
489
+ *
490
+ * These are declared via `declare global { interface Promise<T> { ... } }` and
491
+ * implemented on `Promise.prototype`. They're a core part of Hoist's async API
492
+ * but don't appear as standalone symbols or class members without special handling.
493
+ *
494
+ * Adds each method to the member index (searchable as members of "Promise") and
495
+ * as standalone function entries in the symbol index (searchable by name).
496
+ */
497
+ function indexPromiseExtensions(sourceFile, symbolIdx, memberIdx, repoRoot) {
498
+ const filePath = sourceFile.getFilePath();
499
+ const pkg = derivePackage(filePath, repoRoot);
500
+ promiseExtensionDetails = new Map();
501
+ // Find the `declare global { interface Promise<T> { ... } }` block
502
+ for (const globalDecl of sourceFile.getChildrenOfKind(SyntaxKind.ModuleDeclaration)) {
503
+ if (globalDecl.getName() !== 'global')
504
+ continue;
505
+ const body = globalDecl.getBody();
506
+ if (!body || !Node.isModuleBlock(body))
507
+ continue;
508
+ for (const iface of body.getChildrenOfKind(SyntaxKind.InterfaceDeclaration)) {
509
+ if (iface.getName() !== 'Promise')
510
+ continue;
511
+ for (const method of iface.getMethods()) {
512
+ const name = method.getName();
513
+ if (!name || name === 'throwIfFailsSelector')
514
+ continue;
515
+ const jsDoc = extractJsDoc(method);
516
+ const params = method.getParameters().map(p => ({
517
+ name: p.getName(),
518
+ type: safeGetTypeText(p, p)
519
+ }));
520
+ let returnType;
521
+ try {
522
+ returnType = method.getReturnType().getText(method);
523
+ }
524
+ catch {
525
+ returnType = 'Promise<T>';
526
+ }
527
+ // Add to member index as a Promise method
528
+ const paramStr = params.map(p => `${p.name}: ${p.type}`).join(', ');
529
+ addToMemberIndex(memberIdx, {
530
+ name,
531
+ memberKind: 'method',
532
+ ownerName: 'Promise',
533
+ ownerHint: 'Promise prototype extension (Hoist async utility)',
534
+ filePath,
535
+ sourcePackage: pkg,
536
+ isStatic: false,
537
+ type: `(${paramStr}) => ${returnType}`,
538
+ jsDoc,
539
+ decorators: []
540
+ });
541
+ // Add as a searchable symbol entry. Prototype extensions need no import, so
542
+ // they carry no import path.
543
+ addToIndex(symbolIdx, {
544
+ name,
545
+ kind: 'function',
546
+ filePath,
547
+ isExported: true,
548
+ sourcePackage: pkg,
549
+ importPath: null,
550
+ jsDoc
551
+ });
552
+ // Pre-compute detail for `getSymbolDetail()` since these can't be
553
+ // found via standard `sourceFile.getFunction()` lookup.
554
+ const sig = `${name}(${paramStr}): ${returnType}`;
555
+ promiseExtensionDetails.set(name, {
556
+ name,
557
+ kind: 'function',
558
+ filePath,
559
+ sourcePackage: pkg,
560
+ isExported: true,
561
+ importPath: null,
562
+ signature: sig,
563
+ jsDoc
564
+ });
565
+ }
566
+ }
567
+ }
568
+ log.info('Indexed Promise prototype extensions from promise/Promise.ts');
569
+ }
570
+ //------------------------------------------------------------------
571
+ // Public API
572
+ //------------------------------------------------------------------
573
+ /** Promise for in-flight initialization, used to coordinate eager and on-demand init. */
574
+ let initPromise = null;
575
+ /**
576
+ * Populate the symbol/member indexes - via the on-disk cache when source files
577
+ * haven't changed, otherwise via a fresh ts-morph build. The live `Project` is
578
+ * NOT built here on cache hit; detail extraction calls (`getSymbolDetail`,
579
+ * `getMembers`) construct it lazily via `ensureProject` when AST access is
580
+ * actually needed.
581
+ */
582
+ function loadOrBuildIndexes() {
583
+ if (symbolIndex)
584
+ return;
585
+ const repoRoot = resolveRepoRoot();
586
+ const cacheStart = Date.now();
587
+ const cached = loadCache(repoRoot);
588
+ if (cached) {
589
+ symbolIndex = cached.symbols;
590
+ memberIndex = cached.members;
591
+ promiseExtensionDetails = cached.promiseExtensions;
592
+ log.info(`TypeScript registry loaded from cache in ${Date.now() - cacheStart}ms ` +
593
+ `(${cached.symbols.size} symbol keys, ${cached.members.size} member keys)`);
594
+ return;
595
+ }
596
+ buildIndexesFresh(repoRoot);
597
+ }
598
+ /**
599
+ * Build the symbol/member indexes from scratch via ts-morph and persist the
600
+ * result to disk. Called when no valid cache exists.
601
+ */
602
+ function buildIndexesFresh(repoRoot) {
603
+ const startMs = Date.now();
604
+ const proj = ensureProject();
605
+ const projectMs = Date.now() - startMs;
606
+ const buildStart = Date.now();
607
+ const result = buildSymbolIndex(proj);
608
+ symbolIndex = result.symbols;
609
+ memberIndex = result.members;
610
+ const buildMs = Date.now() - buildStart;
611
+ // Second pass: now that the symbol index is fully populated, fill in
612
+ // member-index JSDoc from `implements` clauses and sibling `*Spec`/`*Config`
613
+ // interfaces for class members with no own JSDoc. Has to run after
614
+ // `symbolIndex`/`memberIndex` are assigned because the fallback resolves
615
+ // interfaces via `findIndexEntry`.
616
+ const enrichStart = Date.now();
617
+ enrichMemberIndexJsDoc(proj);
618
+ const enrichMs = Date.now() - enrichStart;
619
+ const elapsed = Date.now() - startMs;
620
+ log.info(`TypeScript registry built in ${elapsed}ms ` +
621
+ `(project=${projectMs}ms build=${buildMs}ms enrich=${enrichMs}ms)`);
622
+ if (elapsed > 5000) {
623
+ log.warn(`TypeScript registry build exceeded 5s target (${elapsed}ms)`);
624
+ }
625
+ try {
626
+ writeCache(repoRoot, computeFingerprint(repoRoot), {
627
+ symbols: symbolIndex,
628
+ members: memberIndex,
629
+ promiseExtensions: promiseExtensionDetails ?? new Map()
630
+ });
631
+ }
632
+ catch (e) {
633
+ log.warn(`Failed to persist registry cache: ${e}`);
634
+ }
635
+ }
636
+ /**
637
+ * Lazily construct the ts-morph `Project`. Required for any path that needs
638
+ * live AST access (detail extraction, member walks, the index build itself).
639
+ * Pure search calls served from the cached index never trigger this.
640
+ */
641
+ function ensureProject() {
642
+ if (project)
643
+ return project;
644
+ const start = Date.now();
645
+ project = new Project({
646
+ tsConfigFilePath: resolve(resolveRepoRoot(), 'tsconfig.json'),
647
+ skipFileDependencyResolution: true
648
+ });
649
+ project.resolveSourceFileDependencies();
650
+ log.info(`ts-morph Project initialized in ${Date.now() - start}ms`);
651
+ return project;
652
+ }
653
+ /**
654
+ * Post-build pass that walks every member-indexed class with an `implements`
655
+ * clause or a sibling `*Spec`/`*Config` interface and, for each public member
656
+ * with empty own JSDoc, copies the matching interface member's JSDoc into the
657
+ * corresponding `MemberIndexEntry` (mutating in place). Mirrors the on-demand
658
+ * fallback in {@link extractClassMembersWithInheritance} so that the member
659
+ * index surfaces the same JSDoc text the `getMembers` path produces - critical
660
+ * for member search queries that match against JSDoc content.
661
+ *
662
+ * Runs once at init, after the main `buildSymbolIndex` pass populates
663
+ * `symbolIndex` and `memberIndex`. Trivially cheap relative to the main
664
+ * build (only touches members with empty JSDoc on classes that have a
665
+ * documentation source).
666
+ */
667
+ function enrichMemberIndexJsDoc(proj) {
668
+ // POSIX form: compared against ts-morph `getFilePath()` (see buildSymbolIndex).
669
+ const repoRoot = resolveRepoRootPosix();
670
+ for (const sourceFile of proj.getSourceFiles()) {
671
+ const filePath = sourceFile.getFilePath();
672
+ if (!isLibrarySource(filePath, repoRoot))
673
+ continue;
674
+ for (const cls of sourceFile.getClasses()) {
675
+ if (!shouldIndexClassMembers(cls))
676
+ continue;
677
+ const ownerName = cls.getName();
678
+ if (!ownerName)
679
+ continue;
680
+ if (cls.getImplements().length === 0 && findSiblingSpecs(cls).length === 0)
681
+ continue;
682
+ let members;
683
+ try {
684
+ members = extractClassMembers(sourceFile, ownerName);
685
+ }
686
+ catch {
687
+ continue;
688
+ }
689
+ for (const m of members) {
690
+ if (m.jsDoc)
691
+ continue;
692
+ if (isPrivateMember(m, cls))
693
+ continue;
694
+ const fallback = findJsDocFallback(cls, m);
695
+ if (!fallback)
696
+ continue;
697
+ const key = m.name.toLowerCase();
698
+ const entries = memberIndex.get(key);
699
+ if (!entries)
700
+ continue;
701
+ for (const entry of entries) {
702
+ if (entry.ownerName === ownerName && entry.filePath === filePath) {
703
+ entry.jsDoc = fallback.jsDoc;
704
+ entry.jsDocInheritedFrom = fallback.inheritedFrom;
705
+ }
706
+ }
707
+ }
708
+ }
709
+ }
710
+ }
711
+ /**
712
+ * Begin TypeScript registry initialization in the background.
713
+ *
714
+ * Call this after server startup to warm the index asynchronously, so the
715
+ * first tool invocation doesn't pay the full init cost. On a cache hit this
716
+ * completes in ~100ms; on a cache miss it runs the full ts-morph build.
717
+ * Safe to call multiple times - subsequent calls are no-ops.
718
+ */
719
+ export function beginInitialization() {
720
+ if (symbolIndex || initPromise)
721
+ return;
722
+ initPromise = Promise.resolve().then(() => {
723
+ loadOrBuildIndexes();
724
+ initPromise = null;
725
+ });
726
+ }
727
+ /**
728
+ * Ensure the symbol and member indexes are populated (from cache or via a
729
+ * fresh build). Pure search paths (`searchSymbols` in `symbol-search.ts`) only need
730
+ * this; detail-extraction paths additionally call {@link ensureProject} to
731
+ * construct the live ts-morph `Project` on demand.
732
+ *
733
+ * If {@link beginInitialization} was called, awaits the in-flight init.
734
+ * Otherwise initializes synchronously. Safe to call multiple times.
735
+ */
736
+ export async function ensureInitialized() {
737
+ if (symbolIndex)
738
+ return;
739
+ if (initPromise)
740
+ return initPromise;
741
+ loadOrBuildIndexes();
742
+ }
743
+ /** The symbol and member indexes, keyed by lowercase name. Ranked search lives in `symbol-search.ts`. */
744
+ export async function getIndexes() {
745
+ await ensureInitialized();
746
+ return { symbols: symbolIndex, members: memberIndex };
747
+ }
748
+ /**
749
+ * Get detailed information about a specific symbol.
750
+ *
751
+ * Finds the symbol in the index by exact name match (case-sensitive).
752
+ * If filePath is provided, filters to that specific file. If multiple matches
753
+ * and no filePath, returns the first exported match.
754
+ */
755
+ export async function getSymbolDetail(name, options = {}) {
756
+ await ensureInitialized();
757
+ const entry = findIndexEntry(name, options.filePath, options.kind);
758
+ return entry ? detailFor(entry) : null;
759
+ }
760
+ /**
761
+ * Get every declaration of a name within the file the name resolves to, primary first. A
762
+ * `type` and a `const` (or class) that share a name in one file - `FieldType` - describe one
763
+ * API, so callers show them together rather than silently picking one. Passing `kind` narrows
764
+ * the result to that declaration.
765
+ */
766
+ export async function getSymbolDeclarations(name, options = {}) {
767
+ await ensureInitialized();
768
+ const primary = findIndexEntry(name, options.filePath, options.kind);
769
+ if (!primary)
770
+ return [];
771
+ const siblings = options.kind
772
+ ? []
773
+ : (symbolIndex.get(name.toLowerCase()) ?? []).filter(e => e !== primary && e.name === name && e.filePath === primary.filePath);
774
+ return [primary, ...siblings].map(detailFor).filter((d) => d != null);
775
+ }
776
+ /** Extract detail for an index entry, constructing the ts-morph Project only when needed. */
777
+ function detailFor(entry) {
778
+ // Pre-computed Promise prototype extensions don't need the live Project;
779
+ // skip the AST construction in that case.
780
+ if (!promiseExtensionDetails?.has(entry.name)) {
781
+ ensureProject();
782
+ }
783
+ try {
784
+ return extractSymbolDetail(entry);
785
+ }
786
+ catch (e) {
787
+ log.warn(`Failed to extract detail for symbol "${entry.name}": ${e}`);
788
+ return null;
789
+ }
790
+ }
791
+ /**
792
+ * Find companion symbols for cross-referencing in detail output.
793
+ *
794
+ * For a Props interface (e.g. `PanelProps`), returns the companion component
795
+ * consts (`Panel`, `panel`) from the same file. For a component const, returns
796
+ * the companion Props interface. Returns an empty array if no companions found.
797
+ */
798
+ export async function getCompanionSymbols(entry) {
799
+ await ensureInitialized();
800
+ if (entry.kind === 'interface' && entry.name.endsWith('Props')) {
801
+ // Props interface → look for companion component consts
802
+ const baseName = entry.name.slice(0, -5);
803
+ if (!baseName)
804
+ return [];
805
+ return findCompanionEntries(baseName, entry.filePath);
806
+ }
807
+ if (entry.kind === 'const') {
808
+ // Component const → look for companion Props interface
809
+ const pascalName = entry.name[0].toUpperCase() + entry.name.slice(1) + 'Props';
810
+ const key = pascalName.toLowerCase();
811
+ const entries = symbolIndex.get(key);
812
+ if (!entries)
813
+ return [];
814
+ return entries.filter(e => e.name === pascalName && e.kind === 'interface' && e.filePath === entry.filePath);
815
+ }
816
+ return [];
817
+ }
818
+ /** Find companion const entries (PascalCase and camelCase) in the same file. */
819
+ function findCompanionEntries(baseName, filePath) {
820
+ const results = [];
821
+ const camelName = baseName[0].toLowerCase() + baseName.slice(1);
822
+ for (const name of [baseName, camelName]) {
823
+ const key = name.toLowerCase();
824
+ const entries = symbolIndex.get(key);
825
+ if (!entries)
826
+ continue;
827
+ for (const e of entries) {
828
+ if (e.name === name && e.kind === 'const' && e.filePath === filePath) {
829
+ results.push(e);
830
+ }
831
+ }
832
+ }
833
+ return results;
834
+ }
835
+ /**
836
+ * Get members (properties, methods, accessors) of a class or interface.
837
+ *
838
+ * For classes, walks the inheritance chain and includes inherited members tagged
839
+ * with their declaring class. Filters out `_`-prefixed and `private` members to
840
+ * match the member index behavior. Members inherited from types outside the index
841
+ * (React, Blueprint) are listed separately via the type checker - see
842
+ * {@link extractExternalMembers}.
843
+ *
844
+ * A name that resolves to something other than a class or interface is reported
845
+ * as `no-members` with the declarations found, so callers can explain it.
846
+ */
847
+ export async function getMembers(name, options = {}) {
848
+ await ensureInitialized();
849
+ const entry = findIndexEntry(name, options.filePath, 'class') ??
850
+ findIndexEntry(name, options.filePath, 'interface') ??
851
+ findIndexEntry(name, options.filePath);
852
+ if (!entry)
853
+ return { ok: false, reason: 'not-found' };
854
+ if (entry.kind !== 'class' && entry.kind !== 'interface') {
855
+ const entries = (symbolIndex.get(name.toLowerCase()) ?? []).filter(e => e.name === name && e.filePath === entry.filePath);
856
+ return { ok: false, reason: 'no-members', entries };
857
+ }
858
+ ensureProject();
859
+ try {
860
+ const detail = extractSymbolDetail(entry);
861
+ if (!detail)
862
+ return { ok: false, reason: 'not-found' };
863
+ const all = entry.kind === 'class'
864
+ ? extractClassMembersWithInheritance(entry.filePath, entry.name)
865
+ : extractInterfaceMembersWithInheritance(entry.filePath, entry.name);
866
+ // Filter out _-prefixed members (match member index behavior)
867
+ const members = all.filter(m => !m.name.startsWith('_')), known = new Set(all.map(m => m.name)), external = extractExternalMembers(entry, known);
868
+ return {
869
+ ok: true,
870
+ symbol: detail,
871
+ members: applyMemberFilter(members, options),
872
+ totalMembers: members.length,
873
+ externalMembers: applyExternalFilter(external, options),
874
+ totalExternal: external.reduce((n, g) => n + g.members.length, 0)
875
+ };
876
+ }
877
+ catch (e) {
878
+ log.warn(`Failed to extract members for symbol "${name}": ${e}`);
879
+ return { ok: false, reason: 'not-found' };
880
+ }
881
+ }
882
+ function applyMemberFilter(members, f) {
883
+ const needle = f.filter?.toLowerCase();
884
+ return members.filter(m => (!needle || m.name.toLowerCase().includes(needle)) &&
885
+ (!f.memberKind || m.kind === f.memberKind) &&
886
+ (!f.include ||
887
+ f.include === 'all' ||
888
+ (f.include === 'own') === (m.inheritedFrom == null)));
889
+ }
890
+ function applyExternalFilter(groups, f) {
891
+ if (f.include === 'own')
892
+ return [];
893
+ const needle = f.filter?.toLowerCase(), kind = f.memberKind === 'accessor' ? 'property' : f.memberKind;
894
+ return groups
895
+ .map(g => ({
896
+ ...g,
897
+ members: g.members.filter(m => (!needle || m.name.toLowerCase().includes(needle)) && (!kind || m.kind === kind))
898
+ }))
899
+ .filter(g => g.members.length > 0);
900
+ }
901
+ /** Longest declared type text carried on an external member. */
902
+ const MAX_EXTERNAL_TYPE_LENGTH = 80;
903
+ /**
904
+ * Members the type checker sees on a class or interface that the declaration walkers did
905
+ * not reach - inherited from types outside the index such as React's `HTMLAttributes` or
906
+ * Blueprint's `ButtonProps` (also through `Omit<...>` and other type operators). Grouped by
907
+ * declaring type. Types come from the declaration's annotation, which is cheap; nothing is
908
+ * resolved through the checker beyond the property list itself.
909
+ */
910
+ function extractExternalMembers(entry, known) {
911
+ const sourceFile = project.getSourceFile(entry.filePath), decl = entry.kind === 'class'
912
+ ? sourceFile?.getClass(entry.name)
913
+ : sourceFile?.getInterface(entry.name);
914
+ if (!decl)
915
+ return [];
916
+ const groups = new Map();
917
+ for (const sym of decl.getType().getProperties()) {
918
+ const name = sym.getName();
919
+ if (known.has(name) || name.startsWith('_'))
920
+ continue;
921
+ const d = sym.getDeclarations()[0], parent = d?.getParent(), declaredIn = parent?.getName?.();
922
+ if (!d || !declaredIn)
923
+ continue;
924
+ // The checker also lists private members, which the declaration walkers filter out.
925
+ if (Node.isModifierable(d) && d.hasModifier(SyntaxKind.PrivateKeyword))
926
+ continue;
927
+ const filePath = d.getSourceFile().getFilePath(), module = filePath
928
+ .match(/node_modules\/((?:@[^/]+\/)?[^/@]+)/g)
929
+ ?.at(-1)
930
+ ?.slice(13) ?? null, key = `${declaredIn}|${module}`, typeText = d.getTypeNode?.()?.getText(), type = typeText?.replace(/\s+/g, ' ').trim();
931
+ let group = groups.get(key);
932
+ if (!group) {
933
+ group = { declaredIn, module, members: [] };
934
+ groups.set(key, group);
935
+ }
936
+ group.members.push({
937
+ name,
938
+ kind: Node.isMethodSignature(d) || Node.isMethodDeclaration(d) ? 'method' : 'property',
939
+ ...(type && type.length <= MAX_EXTERNAL_TYPE_LENGTH ? { type } : {})
940
+ });
941
+ }
942
+ // The checker's property order varies with what it has already resolved, so sort for
943
+ // stable output: hoist-react types first, then by module and declaring type, members by name.
944
+ const byName = (a, b) => a.name.localeCompare(b.name);
945
+ return [...groups.values()]
946
+ .map(g => ({ ...g, members: g.members.sort(byName) }))
947
+ .sort((a, b) => (a.module ?? '').localeCompare(b.module ?? '') ||
948
+ a.declaredIn.localeCompare(b.declaredIn));
949
+ }
950
+ //------------------------------------------------------------------
951
+ // Internal helpers for detail extraction
952
+ //------------------------------------------------------------------
953
+ /**
954
+ * Walk the inheritance chain of a class and collect members from each level.
955
+ * Members from the target class itself have no `inheritedFrom` tag; members
956
+ * from ancestor classes are tagged with the declaring class name.
957
+ *
958
+ * Deduplicates by member name - if a subclass overrides a parent member, only
959
+ * the subclass version is included.
960
+ *
961
+ * Implements-JSDoc fallback: at each level, if a member has no own JSDoc,
962
+ * walks the class's `implements` clause (declaration order) and inherits the
963
+ * matching interface member's JSDoc, parameter descriptions, and `@returns`.
964
+ * Recorded as `jsDocInheritedFrom` rather than `inheritedFrom` because only
965
+ * the docs cross the boundary - the member itself is declared on the class.
966
+ * See {@link findImplementsJsDocFallback}.
967
+ */
968
+ function extractClassMembersWithInheritance(filePath, name) {
969
+ const allMembers = [];
970
+ const seen = new Set();
971
+ let currentFilePath = filePath;
972
+ let currentName = name;
973
+ let isFirst = true;
974
+ while (currentFilePath && currentName) {
975
+ const sourceFile = project.getSourceFile(currentFilePath);
976
+ if (!sourceFile)
977
+ break;
978
+ const cls = sourceFile.getClass(currentName);
979
+ if (!cls)
980
+ break;
981
+ const members = extractClassMembers(sourceFile, currentName);
982
+ const classChainInheritedFrom = isFirst ? undefined : currentName;
983
+ for (const m of members) {
984
+ // Skip private members at this level
985
+ if (isPrivateMember(m, cls))
986
+ continue;
987
+ // Deduplicate: subclass overrides win
988
+ const key = `${m.isStatic ? 'static:' : ''}${m.name}`;
989
+ if (seen.has(key))
990
+ continue;
991
+ seen.add(key);
992
+ const enriched = { ...m, inheritedFrom: classChainInheritedFrom };
993
+ // JSDoc fallback: when a member declares no own JSDoc, surface matching
994
+ // JSDoc from an implemented interface or a sibling `*Spec`/`*Config`.
995
+ // Recorded separately as `jsDocInheritedFrom` because the member itself
996
+ // is declared on the class - only the docs are inherited, not the member
997
+ // or its behavior.
998
+ if (!enriched.jsDoc) {
999
+ const fallback = findJsDocFallback(cls, m);
1000
+ if (fallback) {
1001
+ enriched.jsDoc = fallback.jsDoc;
1002
+ enriched.jsDocInheritedFrom = fallback.inheritedFrom;
1003
+ if (m.kind === 'method' && enriched.parameters) {
1004
+ enriched.parameters = enriched.parameters.map(p => {
1005
+ const desc = fallback.paramDescriptions.get(p.name);
1006
+ return desc ? { ...p, description: desc } : p;
1007
+ });
1008
+ }
1009
+ if (m.kind === 'method' && fallback.returns) {
1010
+ enriched.returns = {
1011
+ type: enriched.returnType ?? 'void',
1012
+ description: fallback.returns
1013
+ };
1014
+ }
1015
+ }
1016
+ }
1017
+ allMembers.push(enriched);
1018
+ }
1019
+ // Walk up to the parent class
1020
+ isFirst = false;
1021
+ const extendsExpr = cls.getExtends();
1022
+ if (!extendsExpr)
1023
+ break;
1024
+ // Resolve the base class name (strip type parameters)
1025
+ const baseClassName = extendsExpr.getExpression().getText();
1026
+ const baseEntry = findIndexEntry(baseClassName);
1027
+ if (!baseEntry || baseEntry.kind !== 'class')
1028
+ break;
1029
+ currentFilePath = baseEntry.filePath;
1030
+ currentName = baseEntry.name;
1031
+ }
1032
+ return allMembers;
1033
+ }
1034
+ /**
1035
+ * Sibling `*Spec` / `*Config` interfaces for a class - `ColumnSpec` for `Column`, `GridConfig`
1036
+ * for `GridModel`. A same-file interface is preferred, then any in the same package. These
1037
+ * mirror the class's properties and usually carry the documentation the class omits.
1038
+ */
1039
+ function findSiblingSpecs(cls) {
1040
+ const name = cls.getName();
1041
+ if (!name)
1042
+ return [];
1043
+ const filePath = cls.getSourceFile().getFilePath(), pkg = derivePackage(filePath, resolveRepoRootPosix()), base = name.endsWith('Model') ? name.slice(0, -'Model'.length) : name, found = [];
1044
+ for (const candidate of [`${name}Spec`, `${name}Config`, `${base}Spec`, `${base}Config`]) {
1045
+ const entries = (symbolIndex.get(candidate.toLowerCase()) ?? []).filter(e => e.name === candidate &&
1046
+ e.kind === 'interface' &&
1047
+ e.isExported &&
1048
+ e.sourcePackage === pkg &&
1049
+ !found.includes(e));
1050
+ found.push(...entries.sort((a, b) => Number(b.filePath === filePath) - Number(a.filePath === filePath)));
1051
+ }
1052
+ return found;
1053
+ }
1054
+ /**
1055
+ * For a class member with no own JSDoc, return the JSDoc + tag info from the
1056
+ * first interface that declares a matching member with non-empty JSDoc. The
1057
+ * class's `implements` clause is consulted first (declaration order), then its
1058
+ * sibling `*Spec` / `*Config` interfaces (see {@link findSiblingSpecs}) - a
1059
+ * `Column` property mirrored from `ColumnSpec` inherits the spec's docs.
1060
+ *
1061
+ * Only inspects the given class's direct implements clause - does not walk up
1062
+ * the extends chain to inspect ancestor implements (that case is naturally
1063
+ * handled by the outer chain walk, since each level applies its own fallback
1064
+ * before dedup excludes it).
1065
+ *
1066
+ * Interface-side `extends` is also NOT walked - if a class implements `Derived`
1067
+ * where `interface Derived extends Base`, the lookup only finds members
1068
+ * declared on `Derived` itself, not on `Base`. In practice this is rarely a
1069
+ * problem because Hoist classes that need members from a base interface tend
1070
+ * to list both in their `implements` clause directly. Worth knowing if a future
1071
+ * call site silently fails to surface inherited interface members.
1072
+ *
1073
+ * Static class members are skipped entirely - TS interfaces declare only
1074
+ * instance members, so a class static with the same name as an interface
1075
+ * member is unrelated and must not pick up the interface's JSDoc.
1076
+ *
1077
+ * Multi-interface case: a class may `implements A, B`. Resolution is
1078
+ * deterministic by declaration order - the first interface with a JSDoc-bearing
1079
+ * matching member wins.
1080
+ *
1081
+ * Returns null when no match is found, including when interfaces resolve to
1082
+ * something outside our index (e.g. React's HTMLAttributes).
1083
+ */
1084
+ function findJsDocFallback(cls, member) {
1085
+ // Static members never inherit from interfaces (interfaces declare instance
1086
+ // members only). Bail before doing any lookup work.
1087
+ if (member.isStatic)
1088
+ return null;
1089
+ const sources = [];
1090
+ for (const impExpr of cls.getImplements()) {
1091
+ const ifaceEntry = findIndexEntry(impExpr.getExpression().getText());
1092
+ if (ifaceEntry?.kind === 'interface')
1093
+ sources.push(ifaceEntry);
1094
+ }
1095
+ sources.push(...findSiblingSpecs(cls));
1096
+ for (const ifaceEntry of sources) {
1097
+ const sf = project.getSourceFile(ifaceEntry.filePath);
1098
+ if (!sf)
1099
+ continue;
1100
+ const iface = sf.getInterface(ifaceEntry.name);
1101
+ if (!iface)
1102
+ continue;
1103
+ if (member.kind === 'method') {
1104
+ const target = iface.getMethod(member.name);
1105
+ if (!target)
1106
+ continue;
1107
+ const jsDoc = extractJsDoc(target);
1108
+ if (!jsDoc)
1109
+ continue;
1110
+ const tags = extractJsDocTags(target);
1111
+ return {
1112
+ jsDoc,
1113
+ paramDescriptions: tags.paramDescriptions,
1114
+ returns: tags.returns,
1115
+ inheritedFrom: ifaceEntry.name
1116
+ };
1117
+ }
1118
+ // Properties + accessors both map to interface property declarations
1119
+ // (TS interfaces don't distinguish accessors from properties).
1120
+ const target = iface.getProperty(member.name);
1121
+ if (!target)
1122
+ continue;
1123
+ const jsDoc = extractJsDoc(target);
1124
+ if (!jsDoc)
1125
+ continue;
1126
+ return {
1127
+ jsDoc,
1128
+ paramDescriptions: new Map(),
1129
+ returns: '',
1130
+ inheritedFrom: ifaceEntry.name
1131
+ };
1132
+ }
1133
+ return null;
1134
+ }
1135
+ /**
1136
+ * Walk the inheritance chain of an interface and collect members from each level.
1137
+ * Uses BFS to handle multiple parent interfaces (interfaces support multiple extends).
1138
+ * Members from the target interface itself have no `inheritedFrom` tag; members
1139
+ * from ancestor interfaces are tagged with the declaring interface name.
1140
+ *
1141
+ * Deduplicates by member name - first occurrence wins (root › first parent › ...).
1142
+ * Parents not found in our symbol index (e.g. React's HTMLAttributes) are skipped.
1143
+ */
1144
+ function extractInterfaceMembersWithInheritance(filePath, name) {
1145
+ const allMembers = [];
1146
+ const seen = new Set();
1147
+ const visited = new Set();
1148
+ const queue = [
1149
+ { filePath, name, isRoot: true }
1150
+ ];
1151
+ while (queue.length > 0) {
1152
+ const current = queue.shift();
1153
+ const visitKey = `${current.filePath}:${current.name}`;
1154
+ if (visited.has(visitKey))
1155
+ continue;
1156
+ visited.add(visitKey);
1157
+ const sourceFile = project.getSourceFile(current.filePath);
1158
+ if (!sourceFile)
1159
+ continue;
1160
+ const iface = sourceFile.getInterface(current.name);
1161
+ if (!iface)
1162
+ continue;
1163
+ const members = extractInterfaceMembers(sourceFile, current.name);
1164
+ const inheritedFrom = current.isRoot ? undefined : current.name;
1165
+ for (const m of members) {
1166
+ const key = `${m.isStatic ? 'static:' : ''}${m.name}`;
1167
+ if (seen.has(key))
1168
+ continue;
1169
+ seen.add(key);
1170
+ allMembers.push({ ...m, inheritedFrom });
1171
+ }
1172
+ // Enqueue all parent interfaces from extends clauses
1173
+ for (const extendsExpr of iface.getExtends()) {
1174
+ const parentName = extendsExpr.getExpression().getText();
1175
+ const parentEntry = findIndexEntry(parentName);
1176
+ if (!parentEntry || parentEntry.kind !== 'interface')
1177
+ continue;
1178
+ queue.push({ filePath: parentEntry.filePath, name: parentEntry.name, isRoot: false });
1179
+ }
1180
+ }
1181
+ return allMembers;
1182
+ }
1183
+ /**
1184
+ * Find other exported symbols with the same name as the given entry, excluding
1185
+ * dynamics stubs. Used to surface disambiguation hints when multiple real symbols
1186
+ * share a name (e.g. `View` in both `cmp/viewmanager` and `data/cube`).
1187
+ */
1188
+ export function findAlternateEntries(name, selectedFilePath) {
1189
+ const key = name.toLowerCase();
1190
+ const entries = symbolIndex.get(key);
1191
+ if (!entries)
1192
+ return [];
1193
+ return entries.filter(e => e.name === name &&
1194
+ e.isExported &&
1195
+ e.filePath !== selectedFilePath &&
1196
+ !e.sourcePackage.startsWith('dynamics'));
1197
+ }
1198
+ /**
1199
+ * Find a symbol in the index by exact name.
1200
+ * Prefers exported symbols when multiple matches exist and no filePath filter.
1201
+ */
1202
+ export function findIndexEntry(name, filePath, kind) {
1203
+ const key = name.toLowerCase();
1204
+ const entries = symbolIndex.get(key);
1205
+ if (!entries)
1206
+ return null;
1207
+ // Exact name match (case-sensitive)
1208
+ const exact = entries.filter(e => e.name === name && (!kind || e.kind === kind));
1209
+ if (exact.length === 0)
1210
+ return null;
1211
+ if (filePath) {
1212
+ // Resolve relative paths against repo root -- search results display repo-relative
1213
+ // paths, so callers will typically pass those rather than absolute paths. Normalize
1214
+ // to POSIX so the comparison matches entry.filePath (ts-morph forward slashes) on
1215
+ // Windows, and recognize Windows drive-letter absolutes (e.g. `D:/...`) as absolute.
1216
+ const posix = toPosixPath(filePath);
1217
+ const isAbsolute = posix.startsWith('/') || /^[a-zA-Z]:\//.test(posix);
1218
+ const resolved = isAbsolute ? posix : toPosixPath(resolve(resolveRepoRoot(), posix));
1219
+ return exact.find(e => e.filePath === resolved) ?? null;
1220
+ }
1221
+ // Prefer exported symbols, and among those prefer class/interface over const/type stubs
1222
+ // (e.g. dynamics/desktop.ts re-exports `export let Foo = null` alongside the real class).
1223
+ const exported = exact.filter(e => e.isExported);
1224
+ if (exported.length > 1) {
1225
+ const preferred = exported.find(e => e.kind === 'class' || e.kind === 'interface');
1226
+ if (preferred)
1227
+ return preferred;
1228
+ }
1229
+ return exported[0] ?? exact[0];
1230
+ }
1231
+ /**
1232
+ * Extract detailed information from a symbol's AST node.
1233
+ */
1234
+ function extractSymbolDetail(entry) {
1235
+ // Promise extensions are pre-computed since they live inside `declare global`
1236
+ // and can't be found by standard sourceFile.getFunction() lookup.
1237
+ const precomputed = promiseExtensionDetails?.get(entry.name);
1238
+ if (precomputed && entry.filePath === precomputed.filePath)
1239
+ return precomputed;
1240
+ const sourceFile = project.getSourceFile(entry.filePath);
1241
+ if (!sourceFile)
1242
+ return null;
1243
+ const base = {
1244
+ name: entry.name,
1245
+ kind: entry.kind,
1246
+ filePath: entry.filePath,
1247
+ sourcePackage: entry.sourcePackage,
1248
+ isExported: entry.isExported,
1249
+ importPath: entry.importPath
1250
+ };
1251
+ switch (entry.kind) {
1252
+ case 'class':
1253
+ return extractClassDetail(sourceFile, entry.name, base);
1254
+ case 'interface':
1255
+ return extractInterfaceDetail(sourceFile, entry.name, base);
1256
+ case 'type':
1257
+ return extractTypeAliasDetail(sourceFile, entry.name, base);
1258
+ case 'function':
1259
+ return extractFunctionDetail(sourceFile, entry.name, base);
1260
+ case 'enum':
1261
+ return extractEnumDetail(sourceFile, entry.name, base);
1262
+ case 'const':
1263
+ return extractConstDetail(sourceFile, entry.name, base);
1264
+ default:
1265
+ return null;
1266
+ }
1267
+ }
1268
+ /**
1269
+ * Extract the human-readable description from one JSDoc block, fence-aware.
1270
+ *
1271
+ * `JSDoc.getDescription()` returns the text before the first JSDoc block tag,
1272
+ * but the TS parser treats ANY line whose first non-whitespace char is `@` as a
1273
+ * tag boundary - even inside a fenced code block. So a canonical-usage
1274
+ * example containing e.g. `@observableRef` silently truncates the description
1275
+ * mid-example, dropping everything after it (further examples, "SEE ALSO"
1276
+ * lists, trailing prose). See #4352.
1277
+ *
1278
+ * Instead we take the full inner text and cut at the first block-tag line that
1279
+ * is NOT inside a fenced code block. This is behaviorally identical to
1280
+ * `getDescription()` for well-formed JSDoc (both stop at the first real tag),
1281
+ * but preserves fenced `@`-lines. Real trailing tags (`@param`, `@returns`,
1282
+ * `@mcpHint`, `@see`, ...) fall after the cut, so they never leak into the
1283
+ * description - they are surfaced through their own structured channels
1284
+ * ({@link extractJsDocTags}, {@link extractMcpHint}).
1285
+ *
1286
+ * Falls back to `getDescription()` if `getInnerText` is unavailable.
1287
+ */
1288
+ function descriptionFromJsDoc(doc) {
1289
+ const inner = doc.getInnerText?.();
1290
+ if (inner == null)
1291
+ return doc.getDescription();
1292
+ const out = [];
1293
+ let inFence = false;
1294
+ for (const line of inner.split('\n')) {
1295
+ const trimmed = line.trim();
1296
+ if (trimmed.startsWith('```') || trimmed.startsWith('~~~')) {
1297
+ inFence = !inFence;
1298
+ out.push(line);
1299
+ continue;
1300
+ }
1301
+ // First real (non-fenced) block tag ends the description.
1302
+ if (!inFence && /^@\w/.test(trimmed))
1303
+ break;
1304
+ out.push(line);
1305
+ }
1306
+ // `getInnerText()` retains a stray trailing `*` from comments mistakenly
1307
+ // closed with `**/` instead of `*/` (e.g. `/** Foo **/`); `getDescription()`
1308
+ // drops it. Strip it to avoid a cosmetic regression. The required leading
1309
+ // whitespace means real prose is unaffected, and a fenced block always ends
1310
+ // with its closing ``` fence rather than ` *`.
1311
+ return out.join('\n').replace(/\s+\*+\s*$/, '');
1312
+ }
1313
+ /** Extract JSDoc description from a node that supports getJsDocs(). */
1314
+ function extractJsDoc(node) {
1315
+ try {
1316
+ const docs = node.getJsDocs?.() ?? [];
1317
+ return docs.map(descriptionFromJsDoc).join('\n').trim();
1318
+ }
1319
+ catch {
1320
+ return '';
1321
+ }
1322
+ }
1323
+ /**
1324
+ * Extract structured `@param` / `@returns` info from a JSDocable node.
1325
+ *
1326
+ * The base description (preamble before any `@`-tag) is intentionally not returned
1327
+ * here - it's already extracted by {@link extractJsDoc} via `getDescription()`,
1328
+ * which excludes tag content. This helper is a complement, not a replacement.
1329
+ */
1330
+ function extractJsDocTags(node) {
1331
+ const paramDescriptions = new Map();
1332
+ let returns = '';
1333
+ try {
1334
+ const docs = (node.getJsDocs?.() ?? []);
1335
+ for (const doc of docs) {
1336
+ const tags = (doc.getTags?.() ?? []);
1337
+ for (const tag of tags) {
1338
+ const tagName = tag.getTagName?.();
1339
+ if (!tagName)
1340
+ continue;
1341
+ const raw = tag.getCommentText?.();
1342
+ const text = normalizeTagComment(raw);
1343
+ if (!text)
1344
+ continue;
1345
+ if (tagName === 'param') {
1346
+ const paramName = tag.compilerNode?.name?.getText?.();
1347
+ if (paramName)
1348
+ paramDescriptions.set(paramName, text);
1349
+ }
1350
+ else if (tagName === 'returns' || tagName === 'return') {
1351
+ if (!returns)
1352
+ returns = text;
1353
+ }
1354
+ }
1355
+ }
1356
+ }
1357
+ catch {
1358
+ // Best-effort - return whatever was collected before the failure
1359
+ }
1360
+ return { paramDescriptions, returns };
1361
+ }
1362
+ /**
1363
+ * Normalize a JSDoc tag comment for surfacing to consumers.
1364
+ *
1365
+ * Trims surrounding whitespace and strips a leading TSDoc-style separator
1366
+ * (`- ` / `– ` / `— ` after the param name). The separator is purely a
1367
+ * syntactic convention - authors who write `@param foo - description.` mean
1368
+ * the description to read "description.", not "- description.". A leading
1369
+ * dash on its own line would also render as a markdown bullet for tools that
1370
+ * interpret the output, which is not what was intended.
1371
+ */
1372
+ function normalizeTagComment(text) {
1373
+ if (!text)
1374
+ return '';
1375
+ return text.trim().replace(/^[-–—]\s+/, '');
1376
+ }
1377
+ /**
1378
+ * Extract the `@mcpHint` tag text, if present. This is a Hoist-specific JSDoc tag
1379
+ * that framework authors can attach to a class or interface to provide a short
1380
+ * hint used in MCP search results (e.g. "model backing all grid components").
1381
+ * Collocating this with the declaration avoids the name collisions and
1382
+ * maintenance drift of a separate hand-curated lookup table.
1383
+ *
1384
+ * Returns `undefined` if no tag is present or the comment is empty.
1385
+ */
1386
+ function extractMcpHint(node) {
1387
+ try {
1388
+ for (const doc of node.getJsDocs() ?? []) {
1389
+ for (const tag of doc.getTags() ?? []) {
1390
+ if (tag.getTagName() !== 'mcpHint')
1391
+ continue;
1392
+ const text = tag.getCommentText();
1393
+ if (typeof text === 'string') {
1394
+ const trimmed = text.trim();
1395
+ if (trimmed)
1396
+ return trimmed;
1397
+ }
1398
+ }
1399
+ }
1400
+ return undefined;
1401
+ }
1402
+ catch {
1403
+ return undefined;
1404
+ }
1405
+ }
1406
+ /**
1407
+ * For a Props interface (e.g. `PanelProps`), look up the companion component's
1408
+ * JSDoc from the same file. Uses the reliable `FooProps → Foo/foo` naming
1409
+ * convention: strips the `Props` suffix and checks for a matching exported const.
1410
+ *
1411
+ * Returns the companion JSDoc string, or empty string if no match is found.
1412
+ */
1413
+ function extractCompanionJsDoc(sourceFile, propsName) {
1414
+ if (!propsName.endsWith('Props'))
1415
+ return '';
1416
+ const companionName = propsName.slice(0, -5);
1417
+ if (!companionName)
1418
+ return '';
1419
+ // Look for `const [Foo, foo] = ...` or `const foo = ...` in the same file
1420
+ const varDecl = sourceFile.getVariableDeclaration(companionName) ??
1421
+ sourceFile.getVariableDeclaration(companionName[0].toLowerCase() + companionName.slice(1));
1422
+ if (!varDecl)
1423
+ return '';
1424
+ const varStmt = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);
1425
+ return varStmt ? extractJsDoc(varStmt) : '';
1426
+ }
1427
+ /**
1428
+ * Extract JSDoc from a function, falling back to the first overload signature if the
1429
+ * implementation has no JSDoc. TypeScript best practice places JSDoc on overload signatures
1430
+ * (which are visible to consumers) rather than the implementation (which is hidden).
1431
+ */
1432
+ function extractFunctionJsDoc(func) {
1433
+ const implDoc = extractJsDoc(func);
1434
+ if (implDoc)
1435
+ return implDoc;
1436
+ const overloads = func.getOverloads();
1437
+ for (const overload of overloads) {
1438
+ const doc = extractJsDoc(overload);
1439
+ if (doc)
1440
+ return doc;
1441
+ }
1442
+ return '';
1443
+ }
1444
+ /** Safely extract a type's text representation. */
1445
+ function safeGetTypeText(node, enclosing) {
1446
+ try {
1447
+ const type = node.getType();
1448
+ return type.getText(enclosing ?? node);
1449
+ }
1450
+ catch {
1451
+ return 'unknown';
1452
+ }
1453
+ }
1454
+ /**
1455
+ * Fast type-text extraction that avoids TypeScript's type checker for the common
1456
+ * case of an explicit annotation. Returns the annotated type as written (e.g.
1457
+ * `GridGroupSortFn`, `string | null`) via ts-morph's syntactic `getTypeNode()` path.
1458
+ * Falls back to `safeGetTypeText` when the declaration has no explicit annotation
1459
+ * (e.g. an inferred property type). Roughly an order of magnitude cheaper than
1460
+ * `safeGetTypeText` because it skips cross-file type resolution.
1461
+ */
1462
+ function fastGetTypeText(node, enclosing) {
1463
+ try {
1464
+ const typed = node;
1465
+ const tn = typed.getTypeNode?.();
1466
+ if (tn)
1467
+ return tn.getText().trim();
1468
+ }
1469
+ catch {
1470
+ // fall through
1471
+ }
1472
+ return safeGetTypeText(node, enclosing);
1473
+ }
1474
+ /**
1475
+ * Extract the class declaration header (everything up to the opening brace).
1476
+ */
1477
+ function extractClassSignature(cls) {
1478
+ const text = cls.getText();
1479
+ const braceIdx = text.indexOf('{');
1480
+ if (braceIdx === -1)
1481
+ return text.trim();
1482
+ return text.slice(0, braceIdx).trim();
1483
+ }
1484
+ function extractClassDetail(sourceFile, name, base) {
1485
+ const cls = sourceFile.getClass(name);
1486
+ if (!cls)
1487
+ return null;
1488
+ const extendsClause = cls.getExtends()?.getText();
1489
+ const implementsClauses = cls.getImplements().map(i => i.getText());
1490
+ const decorators = cls.getDecorators().map(d => d.getName());
1491
+ // Detect constructor config type (e.g. `constructor(config: GridConfig)`)
1492
+ let constructorType;
1493
+ const ctors = cls.getConstructors();
1494
+ if (ctors.length > 0) {
1495
+ const params = ctors[0].getParameters();
1496
+ if (params.length === 1) {
1497
+ const paramType = params[0].getTypeNode()?.getText();
1498
+ if (paramType)
1499
+ constructorType = paramType;
1500
+ }
1501
+ }
1502
+ return {
1503
+ ...base,
1504
+ signature: extractClassSignature(cls),
1505
+ jsDoc: extractJsDoc(cls),
1506
+ ...(extendsClause ? { extends: extendsClause } : {}),
1507
+ ...(implementsClauses.length > 0 ? { implements: implementsClauses } : {}),
1508
+ ...(decorators.length > 0 ? { decorators } : {}),
1509
+ ...(constructorType ? { constructorType } : {})
1510
+ };
1511
+ }
1512
+ function extractInterfaceDetail(sourceFile, name, base) {
1513
+ const iface = sourceFile.getInterface(name);
1514
+ if (!iface)
1515
+ return null;
1516
+ const extendsClauses = iface.getExtends().map(e => e.getText());
1517
+ const text = iface.getText();
1518
+ const braceIdx = text.indexOf('{');
1519
+ const signature = braceIdx === -1 ? text.trim() : text.slice(0, braceIdx).trim();
1520
+ // For Props interfaces without their own JSDoc, inherit from the companion component
1521
+ let jsDoc = extractJsDoc(iface);
1522
+ if (!jsDoc)
1523
+ jsDoc = extractCompanionJsDoc(sourceFile, name);
1524
+ return {
1525
+ ...base,
1526
+ signature,
1527
+ jsDoc,
1528
+ ...(extendsClauses.length > 0 ? { extends: extendsClauses.join(', ') } : {})
1529
+ };
1530
+ }
1531
+ function extractTypeAliasDetail(sourceFile, name, base) {
1532
+ const typeAlias = sourceFile.getTypeAlias(name);
1533
+ if (!typeAlias)
1534
+ return null;
1535
+ return {
1536
+ ...base,
1537
+ signature: typeAlias.getText().trim(),
1538
+ jsDoc: extractJsDoc(typeAlias)
1539
+ };
1540
+ }
1541
+ function extractFunctionDetail(sourceFile, name, base) {
1542
+ const func = sourceFile.getFunction(name);
1543
+ if (!func)
1544
+ return null;
1545
+ // Build signature from parameters and return type (without the body)
1546
+ const params = func
1547
+ .getParameters()
1548
+ .map(p => {
1549
+ const pName = p.getName();
1550
+ const pType = safeGetTypeText(p);
1551
+ const optional = p.hasQuestionToken() ? '?' : '';
1552
+ return `${pName}${optional}: ${pType}`;
1553
+ })
1554
+ .join(', ');
1555
+ let returnType;
1556
+ try {
1557
+ returnType = func.getReturnType().getText(func);
1558
+ }
1559
+ catch {
1560
+ returnType = 'unknown';
1561
+ }
1562
+ const exportPrefix = func.isExported() ? 'export ' : '';
1563
+ const asyncPrefix = func.isAsync() ? 'async ' : '';
1564
+ const typeParams = func.getTypeParameters();
1565
+ const typeParamStr = typeParams.length > 0 ? `<${typeParams.map(tp => tp.getText()).join(', ')}>` : '';
1566
+ const signature = `${exportPrefix}${asyncPrefix}function ${name}${typeParamStr}(${params}): ${returnType}`;
1567
+ return {
1568
+ ...base,
1569
+ signature,
1570
+ jsDoc: extractFunctionJsDoc(func)
1571
+ };
1572
+ }
1573
+ function extractEnumDetail(sourceFile, name, base) {
1574
+ const enumDecl = sourceFile.getEnum(name);
1575
+ if (!enumDecl)
1576
+ return null;
1577
+ return {
1578
+ ...base,
1579
+ signature: enumDecl.getText().trim(),
1580
+ jsDoc: extractJsDoc(enumDecl)
1581
+ };
1582
+ }
1583
+ function extractConstDetail(sourceFile, name, base) {
1584
+ const varDecl = sourceFile.getVariableDeclaration(name);
1585
+ if (!varDecl)
1586
+ return null;
1587
+ // Get the variable statement for JSDoc (JSDoc is on the statement, not the declaration)
1588
+ const varStmt = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);
1589
+ // A data literal (`Object.freeze({...})`, an options object) is the API and is kept whole.
1590
+ // Anything else - `hoistCmp.withFactory({...})`, `new Foo({...})`, an arrow function - is
1591
+ // implementation, so the signature stops at its first line.
1592
+ const initializer = varDecl.getInitializer(), fullText = varDecl.getText().trim(), declText = fullText.includes('\n') && !(initializer && isDataLiteral(initializer))
1593
+ ? fullText.slice(0, fullText.indexOf('\n')).trimEnd() + ' ...'
1594
+ : fullText, exportPrefix = varStmt?.isExported() ? 'export const ' : 'const ', signature = `${exportPrefix}${declText}`, instanceOf = findInstanceClass(varDecl);
1595
+ return {
1596
+ ...base,
1597
+ signature: signature.length > 500 ? signature.slice(0, 500) + '...' : signature,
1598
+ jsDoc: varStmt ? extractJsDoc(varStmt) : '',
1599
+ ...(instanceOf ? { instanceOf } : {})
1600
+ };
1601
+ }
1602
+ /** True for an object or array literal, optionally under `as const` or `Object.freeze(...)`. */
1603
+ function isDataLiteral(node) {
1604
+ if (Node.isAsExpression(node) || Node.isSatisfiesExpression(node)) {
1605
+ return isDataLiteral(node.getExpression());
1606
+ }
1607
+ if (Node.isCallExpression(node)) {
1608
+ const arg = node.getArguments()[0];
1609
+ return node.getExpression().getText() === 'Object.freeze' && !!arg && isDataLiteral(arg);
1610
+ }
1611
+ return Node.isObjectLiteralExpression(node) || Node.isArrayLiteralExpression(node);
1612
+ }
1613
+ /**
1614
+ * The indexed class a const is an instance of, if any: from a `new Class()` initializer, then
1615
+ * a type annotation, then the checker's resolved type. Only the checker step costs anything,
1616
+ * and it runs for one declaration on demand.
1617
+ */
1618
+ function findInstanceClass(varDecl) {
1619
+ const isIndexedClass = (name) => name && findIndexEntry(name, undefined, 'class') ? name : undefined;
1620
+ const initializer = varDecl.getInitializer();
1621
+ if (initializer && Node.isNewExpression(initializer)) {
1622
+ const named = isIndexedClass(initializer.getExpression().getText());
1623
+ if (named)
1624
+ return named;
1625
+ }
1626
+ const annotation = varDecl.getTypeNode();
1627
+ if (annotation && Node.isTypeReference(annotation)) {
1628
+ const named = isIndexedClass(annotation.getTypeName().getText());
1629
+ if (named)
1630
+ return named;
1631
+ }
1632
+ try {
1633
+ return isIndexedClass(varDecl.getType().getSymbol()?.getName());
1634
+ }
1635
+ catch {
1636
+ return undefined;
1637
+ }
1638
+ }
1639
+ //------------------------------------------------------------------
1640
+ // Member extraction
1641
+ //------------------------------------------------------------------
1642
+ /**
1643
+ * Extract all members from a class declaration.
1644
+ */
1645
+ function extractClassMembers(sourceFile, name) {
1646
+ const cls = sourceFile.getClass(name);
1647
+ if (!cls)
1648
+ return [];
1649
+ const members = [];
1650
+ // Instance properties
1651
+ for (const prop of cls.getInstanceProperties()) {
1652
+ try {
1653
+ const propName = prop.getName();
1654
+ if (!propName)
1655
+ continue;
1656
+ const isAccessor = Node.isGetAccessorDeclaration(prop);
1657
+ const decorators = getNodeDecorators(prop);
1658
+ members.push({
1659
+ name: propName,
1660
+ kind: isAccessor ? 'accessor' : 'property',
1661
+ type: fastGetTypeText(prop, prop),
1662
+ isStatic: false,
1663
+ isOptional: Node.isPropertyDeclaration(prop) ? prop.hasQuestionToken() : undefined,
1664
+ decorators,
1665
+ jsDoc: extractJsDoc(prop),
1666
+ ...extractDefault(prop)
1667
+ });
1668
+ }
1669
+ catch (e) {
1670
+ log.warn(`Failed to extract instance property from ${name}: ${e}`);
1671
+ }
1672
+ }
1673
+ // Static properties
1674
+ for (const prop of cls.getStaticProperties()) {
1675
+ try {
1676
+ const propName = prop.getName();
1677
+ if (!propName)
1678
+ continue;
1679
+ const isAccessor = Node.isGetAccessorDeclaration(prop);
1680
+ const decorators = getNodeDecorators(prop);
1681
+ members.push({
1682
+ name: propName,
1683
+ kind: isAccessor ? 'accessor' : 'property',
1684
+ type: fastGetTypeText(prop, prop),
1685
+ isStatic: true,
1686
+ decorators,
1687
+ jsDoc: extractJsDoc(prop),
1688
+ ...extractDefault(prop)
1689
+ });
1690
+ }
1691
+ catch (e) {
1692
+ log.warn(`Failed to extract static property from ${name}: ${e}`);
1693
+ }
1694
+ }
1695
+ // Instance methods
1696
+ for (const method of cls.getInstanceMethods()) {
1697
+ try {
1698
+ members.push(extractMethodInfo(method, false));
1699
+ }
1700
+ catch (e) {
1701
+ log.warn(`Failed to extract instance method from ${name}: ${e}`);
1702
+ }
1703
+ }
1704
+ // Static methods
1705
+ for (const method of cls.getStaticMethods()) {
1706
+ try {
1707
+ members.push(extractMethodInfo(method, true));
1708
+ }
1709
+ catch (e) {
1710
+ log.warn(`Failed to extract static method from ${name}: ${e}`);
1711
+ }
1712
+ }
1713
+ return members;
1714
+ }
1715
+ /**
1716
+ * Extract all members from an interface declaration.
1717
+ */
1718
+ function extractInterfaceMembers(sourceFile, name) {
1719
+ const iface = sourceFile.getInterface(name);
1720
+ if (!iface)
1721
+ return [];
1722
+ const members = [];
1723
+ // Properties
1724
+ for (const prop of iface.getProperties()) {
1725
+ try {
1726
+ members.push({
1727
+ name: prop.getName(),
1728
+ kind: 'property',
1729
+ type: fastGetTypeText(prop, prop),
1730
+ isStatic: false,
1731
+ isOptional: prop.hasQuestionToken(),
1732
+ decorators: [],
1733
+ jsDoc: extractJsDoc(prop)
1734
+ });
1735
+ }
1736
+ catch (e) {
1737
+ log.warn(`Failed to extract interface property from ${name}: ${e}`);
1738
+ }
1739
+ }
1740
+ // Methods
1741
+ for (const method of iface.getMethods()) {
1742
+ try {
1743
+ const tags = extractJsDocTags(method);
1744
+ const params = method.getParameters().map(p => {
1745
+ const pName = p.getName();
1746
+ const desc = tags.paramDescriptions.get(pName);
1747
+ return {
1748
+ name: pName,
1749
+ type: fastGetTypeText(p, p),
1750
+ ...(desc ? { description: desc } : {})
1751
+ };
1752
+ });
1753
+ // Prefer the declared return-type annotation (cheap AST lookup) and only
1754
+ // fall through to the checker's `getReturnType()` when unavailable.
1755
+ const retNode = method.getReturnTypeNode();
1756
+ let returnType;
1757
+ if (retNode) {
1758
+ returnType = retNode.getText().trim();
1759
+ }
1760
+ else {
1761
+ try {
1762
+ returnType = method.getReturnType().getText(method);
1763
+ }
1764
+ catch {
1765
+ returnType = 'unknown';
1766
+ }
1767
+ }
1768
+ members.push({
1769
+ name: method.getName(),
1770
+ kind: 'method',
1771
+ type: returnType,
1772
+ isStatic: false,
1773
+ decorators: [],
1774
+ jsDoc: extractJsDoc(method),
1775
+ parameters: params,
1776
+ returnType,
1777
+ ...(tags.returns ? { returns: { type: returnType, description: tags.returns } } : {})
1778
+ });
1779
+ }
1780
+ catch (e) {
1781
+ log.warn(`Failed to extract interface method from ${name}: ${e}`);
1782
+ }
1783
+ }
1784
+ return members;
1785
+ }
1786
+ /** Extract method info from a class method declaration. */
1787
+ function extractMethodInfo(method, isStatic) {
1788
+ const tags = extractJsDocTags(method);
1789
+ const params = method.getParameters().map(p => {
1790
+ const pName = p.getName();
1791
+ const desc = tags.paramDescriptions.get(pName);
1792
+ return {
1793
+ name: pName,
1794
+ type: fastGetTypeText(p, p),
1795
+ ...(desc ? { description: desc } : {})
1796
+ };
1797
+ });
1798
+ // Prefer the declared return-type annotation. Falling back to the checker's
1799
+ // `getReturnType()` is ~order-of-magnitude slower and drives most of the
1800
+ // index-build cost when many classes are indexed.
1801
+ const retNode = method.getReturnTypeNode();
1802
+ let returnType;
1803
+ if (retNode) {
1804
+ returnType = retNode.getText().trim();
1805
+ }
1806
+ else {
1807
+ try {
1808
+ returnType = method.getReturnType().getText(method);
1809
+ }
1810
+ catch {
1811
+ returnType = 'unknown';
1812
+ }
1813
+ }
1814
+ return {
1815
+ name: method.getName(),
1816
+ kind: 'method',
1817
+ type: returnType,
1818
+ isStatic,
1819
+ decorators: getNodeDecorators(method),
1820
+ jsDoc: extractJsDoc(method),
1821
+ parameters: params,
1822
+ returnType,
1823
+ ...(tags.returns ? { returns: { type: returnType, description: tags.returns } } : {})
1824
+ };
1825
+ }
1826
+ /**
1827
+ * A property's initializer as its `default`, when it is a single short expression
1828
+ * (`= true`, `= 'grid'`, `= []`). Long or multi-line initializers are not worth quoting.
1829
+ */
1830
+ function extractDefault(node) {
1831
+ if (!Node.isPropertyDeclaration(node))
1832
+ return {};
1833
+ const text = node.getInitializer()?.getText().trim();
1834
+ return text && text.length <= MAX_DEFAULT_LENGTH && !text.includes('\n') ? { default: text } : {};
1835
+ }
1836
+ /** Safely get decorator names from a node (not all node types support getDecorators). */
1837
+ function getNodeDecorators(node) {
1838
+ try {
1839
+ const decorated = node;
1840
+ return decorated.getDecorators?.()?.map(d => d.getName()) ?? [];
1841
+ }
1842
+ catch {
1843
+ return [];
1844
+ }
1845
+ }