scip-query 0.3.5 → 0.4.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.
Files changed (152) hide show
  1. package/README.md +2 -1
  2. package/dist/{chunk-VMM4SYV4.js → chunk-24LF6IZB.js} +17 -4
  3. package/dist/{chunk-EPWLXXBL.js → chunk-3NJSJ7TE.js} +28 -30
  4. package/dist/{chunk-SMDCNPMK.js → chunk-43A4UCS7.js} +3 -3
  5. package/dist/{chunk-CHDJXYBG.js → chunk-5GCORUNV.js} +3 -3
  6. package/dist/{chunk-OIDHN6GD.js → chunk-6CH23IAS.js} +148 -7
  7. package/dist/chunk-6ECR2FLR.js +60 -0
  8. package/dist/{chunk-C7H5WBTJ.js → chunk-6UZU7DFL.js} +3 -3
  9. package/dist/chunk-7BS4CPJX.js +162 -0
  10. package/dist/{chunk-UGQKAVCD.js → chunk-A6XLXV6W.js} +3 -3
  11. package/dist/chunk-ALUFWH3U.js +2695 -0
  12. package/dist/{chunk-F7XU27LU.js → chunk-CBIWNZZZ.js} +27 -3
  13. package/dist/{chunk-26DOJ63W.js → chunk-DUJNJQPO.js} +14 -3
  14. package/dist/{chunk-GSH2FPKV.js → chunk-EAGKJFDX.js} +3 -3
  15. package/dist/{chunk-VIYSWZCO.js → chunk-ELFGD5EW.js} +32 -4
  16. package/dist/chunk-FVJE4MQL.js +37 -0
  17. package/dist/{chunk-NFS5W3PP.js → chunk-GNAMV3JC.js} +3 -3
  18. package/dist/{chunk-TRESG7OB.js → chunk-J47VSL6I.js} +3 -3
  19. package/dist/chunk-J6QXMYAQ.js +115 -0
  20. package/dist/{chunk-6FKIA6EI.js → chunk-JHVQB4Y5.js} +12 -12
  21. package/dist/{chunk-YY4QGUQ5.js → chunk-JKXHHV4B.js} +2 -2
  22. package/dist/{chunk-EN2Z2CLO.js → chunk-KG4OFQEN.js} +17 -20
  23. package/dist/chunk-KLNKDX6A.js +110 -0
  24. package/dist/{chunk-5OMVSV6E.js → chunk-KYPXKV64.js} +3 -3
  25. package/dist/chunk-NXUIWD6K.js +87 -0
  26. package/dist/{chunk-LFJQVJYJ.js → chunk-OXX3QF24.js} +2 -2
  27. package/dist/{chunk-NG5F43OU.js → chunk-P3VCDYMJ.js} +70 -1
  28. package/dist/{chunk-7HK5ZLOE.js → chunk-PCU455MX.js} +2 -2
  29. package/dist/{chunk-O7Q7FDUJ.js → chunk-POLELLNM.js} +3 -3
  30. package/dist/chunk-PU2254N2.js +115 -0
  31. package/dist/{chunk-WGAD3GNR.js → chunk-QMXSLHZP.js} +5 -5
  32. package/dist/{chunk-YDBXNPYU.js → chunk-R7HPHMRZ.js} +3 -3
  33. package/dist/{chunk-HLUS2HEB.js → chunk-RE7POFGI.js} +5 -4
  34. package/dist/{chunk-VT4JBH6L.js → chunk-RJ5GULL6.js} +2 -2
  35. package/dist/{chunk-7KIMF5PV.js → chunk-RL74LF47.js} +2 -2
  36. package/dist/chunk-SVLUJSY7.js +75 -0
  37. package/dist/chunk-SYQR4QGK.js +38 -0
  38. package/dist/{chunk-QIXNAB5K.js → chunk-TO3L4YNK.js} +1 -2
  39. package/dist/{chunk-P3E6L7KW.js → chunk-TWVXFKJA.js} +84 -4
  40. package/dist/chunk-UJWI5CBB.js +75 -0
  41. package/dist/{chunk-J3JSOSUO.js → chunk-VKBOLNYN.js} +3 -3
  42. package/dist/{chunk-KBOQX573.js → chunk-VY2L4TP6.js} +20 -3
  43. package/dist/{chunk-KKCHYLVI.js → chunk-W46L2BXT.js} +2 -2
  44. package/dist/chunk-XUVPQDXW.js +34 -0
  45. package/dist/{chunk-DH7G3DDV.js → chunk-Z5VSUOEE.js} +2 -2
  46. package/dist/{chunk-GEXE2T6I.js → chunk-ZVZAIIB5.js} +23 -15
  47. package/dist/cli.js +2838 -870
  48. package/dist/{db-viWlyVtv.d.ts → db-C4rPbKkI.d.ts} +6 -1
  49. package/dist/index.d.ts +4 -4
  50. package/dist/index.js +376 -142
  51. package/dist/postinstall.js +9 -3
  52. package/dist/queries/affected.d.ts +1 -1
  53. package/dist/queries/affected.js +3 -3
  54. package/dist/queries/bottlenecks.d.ts +1 -1
  55. package/dist/queries/bottlenecks.js +3 -2
  56. package/dist/queries/by-kind.d.ts +1 -1
  57. package/dist/queries/by-kind.js +3 -2
  58. package/dist/queries/call-graph.d.ts +1 -1
  59. package/dist/queries/call-graph.js +3 -3
  60. package/dist/queries/change-surface.d.ts +1 -1
  61. package/dist/queries/change-surface.js +3 -3
  62. package/dist/queries/code.d.ts +1 -1
  63. package/dist/queries/code.js +3 -3
  64. package/dist/queries/complexity-hotspots.d.ts +1 -1
  65. package/dist/queries/complexity-hotspots.js +3 -3
  66. package/dist/queries/complexity.d.ts +1 -1
  67. package/dist/queries/complexity.js +3 -3
  68. package/dist/queries/convergence.d.ts +1 -1
  69. package/dist/queries/convergence.js +3 -3
  70. package/dist/queries/coupling.d.ts +1 -1
  71. package/dist/queries/coupling.js +3 -3
  72. package/dist/queries/cycles.d.ts +1 -1
  73. package/dist/queries/cycles.js +3 -3
  74. package/dist/queries/dataflow.d.ts +1 -1
  75. package/dist/queries/dataflow.js +3 -3
  76. package/dist/queries/dead.d.ts +1 -1
  77. package/dist/queries/dead.js +4 -4
  78. package/dist/queries/deep-chains.d.ts +1 -1
  79. package/dist/queries/deep-chains.js +3 -3
  80. package/dist/queries/deps.d.ts +1 -1
  81. package/dist/queries/deps.js +3 -3
  82. package/dist/queries/diff-impact.d.ts +1 -1
  83. package/dist/queries/diff-impact.js +2 -2
  84. package/dist/queries/drift.d.ts +1 -1
  85. package/dist/queries/drift.js +3 -3
  86. package/dist/queries/extract-candidates.d.ts +1 -1
  87. package/dist/queries/extract-candidates.js +3 -3
  88. package/dist/queries/fan.d.ts +1 -1
  89. package/dist/queries/fan.js +3 -3
  90. package/dist/queries/files.d.ts +1 -1
  91. package/dist/queries/health.d.ts +1 -1
  92. package/dist/queries/health.js +14 -14
  93. package/dist/queries/hierarchy.d.ts +1 -1
  94. package/dist/queries/hierarchy.js +3 -3
  95. package/dist/queries/hotspots.d.ts +1 -1
  96. package/dist/queries/hotspots.js +3 -2
  97. package/dist/queries/imports.d.ts +1 -1
  98. package/dist/queries/imports.js +3 -3
  99. package/dist/queries/index.d.ts +1 -1
  100. package/dist/queries/index.js +44 -44
  101. package/dist/queries/isolated.d.ts +3 -4
  102. package/dist/queries/isolated.js +4 -4
  103. package/dist/queries/members.d.ts +1 -1
  104. package/dist/queries/members.js +3 -3
  105. package/dist/queries/methods.d.ts +1 -1
  106. package/dist/queries/methods.js +3 -2
  107. package/dist/queries/outline.d.ts +1 -1
  108. package/dist/queries/outline.js +3 -3
  109. package/dist/queries/passthrough-candidates.d.ts +1 -1
  110. package/dist/queries/passthrough-candidates.js +3 -3
  111. package/dist/queries/redundant-reexports.d.ts +1 -1
  112. package/dist/queries/redundant-reexports.js +4 -4
  113. package/dist/queries/refs.d.ts +1 -1
  114. package/dist/queries/refs.js +3 -3
  115. package/dist/queries/similar-chains.d.ts +1 -1
  116. package/dist/queries/similar-chains.js +3 -3
  117. package/dist/queries/similar-files.d.ts +1 -1
  118. package/dist/queries/similar-files.js +3 -3
  119. package/dist/queries/similar-signatures.d.ts +5 -3
  120. package/dist/queries/similar-signatures.js +3 -2
  121. package/dist/queries/similar.d.ts +1 -1
  122. package/dist/queries/similar.js +3 -3
  123. package/dist/queries/slice.d.ts +1 -1
  124. package/dist/queries/slice.js +3 -3
  125. package/dist/queries/stale-abstractions.d.ts +1 -1
  126. package/dist/queries/stale-abstractions.js +3 -3
  127. package/dist/queries/stats.d.ts +1 -1
  128. package/dist/queries/surface.d.ts +1 -1
  129. package/dist/queries/surface.js +3 -3
  130. package/dist/queries/symbols.d.ts +1 -1
  131. package/dist/queries/symbols.js +3 -3
  132. package/dist/queries/system.d.ts +1 -1
  133. package/dist/queries/system.js +3 -3
  134. package/dist/queries/trace.d.ts +1 -1
  135. package/dist/queries/trace.js +3 -3
  136. package/dist/queries/wrapper-candidates.d.ts +1 -1
  137. package/dist/queries/wrapper-candidates.js +3 -3
  138. package/dist/reindex-worker.js +216 -64
  139. package/package.json +5 -1
  140. package/skills/scip-language-playbook/SKILL.md +371 -0
  141. package/dist/chunk-4JCSOF2O.js +0 -97
  142. package/dist/chunk-AXQKUYKF.js +0 -1442
  143. package/dist/chunk-CPVAQJEC.js +0 -46
  144. package/dist/chunk-EOROMIFO.js +0 -41
  145. package/dist/chunk-GU2H5QRN.js +0 -28
  146. package/dist/chunk-LQJUPXQY.js +0 -109
  147. package/dist/chunk-MPGIHELS.js +0 -39
  148. package/dist/chunk-TOIEB3LG.js +0 -78
  149. package/dist/chunk-UQEQ6AHX.js +0 -60
  150. package/dist/chunk-VJJKSGIX.js +0 -121
  151. package/dist/chunk-YGGFLMTM.js +0 -83
  152. package/dist/chunk-ZEUCXQBN.js +0 -71
@@ -0,0 +1,2695 @@
1
+ import {
2
+ isFunctionLikeSymbol,
3
+ isModuleLikeSymbol,
4
+ leafName,
5
+ leafSuffix,
6
+ parseSymbol,
7
+ shortenSymbol
8
+ } from "./chunk-TO3L4YNK.js";
9
+
10
+ // src/source-analysis.ts
11
+ import {
12
+ existsSync,
13
+ readFileSync
14
+ } from "fs";
15
+ import {
16
+ basename,
17
+ dirname,
18
+ extname,
19
+ join,
20
+ relative,
21
+ resolve
22
+ } from "path";
23
+ var SOURCE_IMPORT_CACHE = /* @__PURE__ */ new WeakMap();
24
+ var SOURCE_EXPORT_CACHE = /* @__PURE__ */ new WeakMap();
25
+ var SOURCE_TEXT_CACHE = /* @__PURE__ */ new WeakMap();
26
+ var SOURCE_CALL_CACHE = /* @__PURE__ */ new WeakMap();
27
+ var SOURCE_BINDING_CACHE = /* @__PURE__ */ new WeakMap();
28
+ var INDEXED_PATH_CACHE = /* @__PURE__ */ new WeakMap();
29
+ var SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
30
+ var PYTHON_SOURCE_EXTENSIONS = [".py", ".pyi"];
31
+ var JVM_SOURCE_EXTENSIONS = [".java", ".scala", ".kt", ".kts"];
32
+ var RUST_SOURCE_EXTENSIONS = [".rs"];
33
+ var RUBY_SOURCE_EXTENSIONS = [".rb"];
34
+ var C_LIKE_SOURCE_EXTENSIONS = [".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hh", ".hxx"];
35
+ var DOTNET_SOURCE_EXTENSIONS = [".cs", ".vb"];
36
+ var DART_SOURCE_EXTENSIONS = [".dart"];
37
+ var PHP_SOURCE_EXTENSIONS = [".php"];
38
+ function getSourceImports(db, relativePath) {
39
+ const cache = getCachedMap(SOURCE_IMPORT_CACHE, db);
40
+ const normalized = normalizePath(relativePath);
41
+ const cached = cache.get(normalized);
42
+ if (cached) {
43
+ return cached;
44
+ }
45
+ const fullPath = join(db.config.projectRoot, normalized);
46
+ if (!existsSync(fullPath)) {
47
+ cache.set(normalized, []);
48
+ return [];
49
+ }
50
+ const source = readFileSync(fullPath, "utf-8");
51
+ const parsed = isPythonSourcePath(normalized) ? parsePythonImports(db, normalized, source) : isJavaScriptSourcePath(normalized) ? parseJavaScriptImports(db, normalized, source) : isJvmSourcePath(normalized) ? parseJvmImports(db, normalized, source) : isRustSourcePath(normalized) ? parseRustImports(db, normalized, source) : isRubySourcePath(normalized) ? parseRubyImports(db, normalized, source) : isCLikeSourcePath(normalized) ? parseCLikeImports(db, normalized, source) : isDotNetSourcePath(normalized) ? parseDotNetImports(db, normalized, source) : isDartSourcePath(normalized) ? parseDartImports(db, normalized, source) : isPhpSourcePath(normalized) ? parsePhpImports(db, normalized, source) : [];
52
+ cache.set(normalized, parsed);
53
+ return parsed;
54
+ }
55
+ function getSourceExports(db, relativePath) {
56
+ const cache = getCachedMap(SOURCE_EXPORT_CACHE, db);
57
+ const normalized = normalizePath(relativePath);
58
+ const cached = cache.get(normalized);
59
+ if (cached) {
60
+ return cached;
61
+ }
62
+ const fullPath = join(db.config.projectRoot, normalized);
63
+ if (!existsSync(fullPath)) {
64
+ cache.set(normalized, []);
65
+ return [];
66
+ }
67
+ const source = readFileSync(fullPath, "utf-8");
68
+ const parsed = isDartSourcePath(normalized) ? parseDartExports(db, normalized, source) : isRustSourcePath(normalized) ? parseRustExports(db, normalized, source) : [];
69
+ cache.set(normalized, parsed);
70
+ return parsed;
71
+ }
72
+ function getSourceCalls(db, relativePath, opts = {}) {
73
+ const normalized = normalizePath(relativePath);
74
+ if (!isPythonSourcePath(normalized) && !isJavaScriptSourcePath(normalized)) {
75
+ return [];
76
+ }
77
+ const cache = getCachedMap(SOURCE_CALL_CACHE, db);
78
+ const key = `${normalized}:${opts.startLine ?? 0}:${opts.endLine ?? Number.MAX_SAFE_INTEGER}`;
79
+ const cached = cache.get(key);
80
+ if (cached) {
81
+ return cached;
82
+ }
83
+ const source = getSourceText(db, normalized);
84
+ if (!source) {
85
+ cache.set(key, []);
86
+ return [];
87
+ }
88
+ const lines = source.split("\n");
89
+ const startLine = Math.max(0, opts.startLine ?? 0);
90
+ const endLine = Math.min(lines.length - 1, opts.endLine ?? lines.length - 1);
91
+ const scopedLines = lines.slice(startLine, endLine + 1);
92
+ const calls = isPythonSourcePath(normalized) ? parsePythonCalls(scopedLines, startLine) : parseJavaScriptCalls(scopedLines, startLine);
93
+ cache.set(key, calls);
94
+ return calls;
95
+ }
96
+ function getSourceConstructorBindings(db, relativePath, opts = {}) {
97
+ const normalized = normalizePath(relativePath);
98
+ if (!isPythonSourcePath(normalized) && !isJavaScriptSourcePath(normalized)) {
99
+ return [];
100
+ }
101
+ const cache = getCachedMap(SOURCE_BINDING_CACHE, db);
102
+ const key = `${normalized}:${opts.startLine ?? 0}:${opts.endLine ?? Number.MAX_SAFE_INTEGER}`;
103
+ const cached = cache.get(key);
104
+ if (cached) {
105
+ return cached;
106
+ }
107
+ const source = getSourceText(db, normalized);
108
+ if (!source) {
109
+ cache.set(key, []);
110
+ return [];
111
+ }
112
+ const lines = source.split("\n");
113
+ const startLine = Math.max(0, opts.startLine ?? 0);
114
+ const endLine = Math.min(lines.length - 1, opts.endLine ?? lines.length - 1);
115
+ const scopedLines = lines.slice(startLine, endLine + 1);
116
+ const bindings = isPythonSourcePath(normalized) ? parsePythonConstructorBindings(scopedLines) : parseJavaScriptConstructorBindings(scopedLines);
117
+ cache.set(key, bindings);
118
+ return bindings;
119
+ }
120
+ function findIdentifierLines(db, relativePath, identifier, opts = {}) {
121
+ if (!identifier) {
122
+ return [];
123
+ }
124
+ const source = getSourceText(db, normalizePath(relativePath));
125
+ if (!source) {
126
+ return [];
127
+ }
128
+ const lines = stripCommentsAndStrings(source).split("\n");
129
+ const regex = new RegExp(`\\b${escapeRegex(identifier)}\\b`);
130
+ const results = [];
131
+ for (let line = 0; line < lines.length; line++) {
132
+ if (typeof opts.excludeStartLine === "number" && typeof opts.excludeEndLine === "number" && line >= opts.excludeStartLine && line <= opts.excludeEndLine) {
133
+ continue;
134
+ }
135
+ if (regex.test(lines[line] ?? "")) {
136
+ results.push(line);
137
+ }
138
+ }
139
+ return results;
140
+ }
141
+ function parseJavaScriptImports(db, importerPath, source) {
142
+ return parseJavaScriptImportStatements(source).flatMap((statement) => parseJavaScriptImportStatement(
143
+ db,
144
+ importerPath,
145
+ statement.clause,
146
+ statement.specifier,
147
+ statement.start,
148
+ statement.end,
149
+ source
150
+ ));
151
+ }
152
+ function parseJavaScriptImportStatements(source) {
153
+ const statements = [];
154
+ const importFromRegex = /^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;
155
+ for (const match of source.matchAll(importFromRegex)) {
156
+ const full = match[0];
157
+ const clause = match[1];
158
+ const specifier = match[2];
159
+ if (!full || !specifier || typeof match.index !== "number") continue;
160
+ statements.push({
161
+ clause,
162
+ specifier,
163
+ start: match.index,
164
+ end: match.index + full.length
165
+ });
166
+ }
167
+ const sideEffectRegex = /^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;
168
+ for (const match of source.matchAll(sideEffectRegex)) {
169
+ const full = match[0];
170
+ const specifier = match[1];
171
+ if (!full || !specifier || typeof match.index !== "number") continue;
172
+ statements.push({
173
+ clause: null,
174
+ specifier,
175
+ start: match.index,
176
+ end: match.index + full.length
177
+ });
178
+ }
179
+ return statements.sort((a, b) => a.start - b.start);
180
+ }
181
+ function parseJavaScriptImportStatement(db, importerPath, clause, specifier, start, end, source) {
182
+ const resolvedSource = resolveImportPath(db, importerPath, specifier);
183
+ const body = buildUsageBody(source, start, end);
184
+ if (!clause) {
185
+ return [{
186
+ importedName: "*",
187
+ localName: null,
188
+ sourcePath: resolvedSource,
189
+ kind: "side-effect",
190
+ used: true,
191
+ usedMembers: []
192
+ }];
193
+ }
194
+ const bindings = parseImportClause(clause).map((binding) => ({
195
+ ...binding,
196
+ sourcePath: resolvedSource
197
+ }));
198
+ return bindings.map((binding) => {
199
+ if (binding.kind === "namespace") {
200
+ const usedMembers = collectNamespaceMembers(body, binding.localName);
201
+ return {
202
+ ...binding,
203
+ used: usedMembers.length > 0 || hasIdentifierUsage(body, binding.localName),
204
+ usedMembers
205
+ };
206
+ }
207
+ if (binding.kind === "side-effect") {
208
+ return { ...binding, used: true, usedMembers: [] };
209
+ }
210
+ return {
211
+ ...binding,
212
+ used: binding.localName ? hasIdentifierUsage(body, binding.localName) : false,
213
+ usedMembers: []
214
+ };
215
+ });
216
+ }
217
+ function parseJvmImports(db, importerPath, source) {
218
+ const statements = [];
219
+ for (const match of source.matchAll(/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm)) {
220
+ const clause = match[1]?.trim();
221
+ const full = match[0];
222
+ if (!clause || !full || typeof match.index !== "number") continue;
223
+ const body = buildUsageBody(source, match.index, match.index + full.length);
224
+ statements.push(...parseJvmImportClause(db, importerPath, clause, body));
225
+ }
226
+ return statements;
227
+ }
228
+ function parseJvmImportClause(db, importerPath, clause, body) {
229
+ if (clause.includes("{") && clause.includes("}")) {
230
+ const prefix = clause.slice(0, clause.indexOf("{")).replace(/\.$/, "").trim();
231
+ const inner = clause.slice(clause.indexOf("{") + 1, clause.lastIndexOf("}")).trim();
232
+ return splitTopLevel(inner).flatMap((entry) => {
233
+ const cleaned = entry.trim();
234
+ if (!cleaned) return [];
235
+ const [importedPart, aliasPart] = cleaned.includes("=>") ? cleaned.split(/\s*=>\s*/) : cleaned.split(/\s+as\s+/);
236
+ const importedName = importedPart?.trim();
237
+ if (!importedName || importedName === "_") return [];
238
+ const localName = (aliasPart ?? importedName.split(".").pop() ?? importedName).trim();
239
+ const qualified = importedName === "_" ? prefix : `${prefix}.${importedName}`.replace(/\.\./g, ".");
240
+ return [buildSimpleImport(db, importerPath, body, qualified, importedName, localName)];
241
+ });
242
+ }
243
+ return [buildSimpleImport(
244
+ db,
245
+ importerPath,
246
+ body,
247
+ clause,
248
+ clause.split(".").pop() ?? clause,
249
+ clause.split(".").pop() ?? clause
250
+ )];
251
+ }
252
+ function parseRustImports(db, importerPath, source) {
253
+ const statements = [];
254
+ for (const match of source.matchAll(/^[ \t]*use\s+(.+?)\s*;$/gm)) {
255
+ const clause = match[1]?.trim();
256
+ const full = match[0];
257
+ if (!clause || !full || typeof match.index !== "number") continue;
258
+ const body = buildUsageBody(source, match.index, match.index + full.length);
259
+ statements.push(...parseRustUseClause(db, importerPath, clause, body));
260
+ }
261
+ return statements;
262
+ }
263
+ function parseRustUseClause(db, importerPath, clause, body) {
264
+ const trimmed = clause.trim();
265
+ if (trimmed.includes("{") && trimmed.includes("}")) {
266
+ const prefix = trimmed.slice(0, trimmed.indexOf("{")).replace(/::$/, "").trim();
267
+ const inner = trimmed.slice(trimmed.indexOf("{") + 1, trimmed.lastIndexOf("}")).trim();
268
+ return splitTopLevel(inner).flatMap((entry) => {
269
+ const cleaned = entry.trim();
270
+ if (!cleaned || cleaned === "self") return [];
271
+ const [importedPart2, aliasPart2] = cleaned.split(/\s+as\s+/);
272
+ const importedName2 = importedPart2?.trim();
273
+ if (!importedName2) return [];
274
+ const localName2 = (aliasPart2 ?? importedName2.split("::").pop() ?? importedName2).trim();
275
+ const moduleSpecifier = `${prefix}::${importedName2}`.replace(/::::/g, "::");
276
+ return [buildSimpleImport(
277
+ db,
278
+ importerPath,
279
+ body,
280
+ moduleSpecifier,
281
+ importedName2.split("::").pop() ?? importedName2,
282
+ localName2,
283
+ resolveRustImportPath(db, importerPath, prefix)
284
+ )];
285
+ });
286
+ }
287
+ const [importedPart, aliasPart] = trimmed.split(/\s+as\s+/);
288
+ const importedName = importedPart?.trim() ?? trimmed;
289
+ const localName = (aliasPart ?? importedName.split("::").pop() ?? importedName).trim();
290
+ const resolved = resolveRustImportPath(db, importerPath, importedName) ?? resolveRustImportPath(db, importerPath, importedName.split("::").slice(0, -1).join("::"));
291
+ return [buildSimpleImport(
292
+ db,
293
+ importerPath,
294
+ body,
295
+ importedName,
296
+ importedName.split("::").pop() ?? importedName,
297
+ localName,
298
+ resolved
299
+ )];
300
+ }
301
+ function parseRustExports(db, importerPath, source) {
302
+ const statements = [];
303
+ for (const match of source.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)) {
304
+ const clause = match[1]?.trim();
305
+ if (!clause) continue;
306
+ statements.push(...parseRustExportClause(db, importerPath, clause));
307
+ }
308
+ return statements;
309
+ }
310
+ function parseRustExportClause(db, importerPath, clause) {
311
+ const trimmed = clause.trim();
312
+ if (trimmed.includes("{") && trimmed.includes("}")) {
313
+ const prefix = trimmed.slice(0, trimmed.indexOf("{")).replace(/::$/, "").trim();
314
+ const inner = trimmed.slice(trimmed.indexOf("{") + 1, trimmed.lastIndexOf("}")).trim();
315
+ return splitTopLevel(inner).flatMap((entry) => {
316
+ const cleaned = entry.trim();
317
+ if (!cleaned || cleaned === "self") return [];
318
+ const [qualifiedPart] = cleaned.split(/\s+as\s+/);
319
+ const qualified = `${prefix}::${qualifiedPart?.trim() ?? cleaned}`.replace(/::::/g, "::");
320
+ return [buildRustExport(db, importerPath, qualified)];
321
+ });
322
+ }
323
+ return [buildRustExport(db, importerPath, trimmed)];
324
+ }
325
+ function buildRustExport(db, importerPath, specifier) {
326
+ return {
327
+ specifier,
328
+ sourcePath: resolveRustImportPath(db, importerPath, specifier) ?? resolveRustImportPath(db, importerPath, specifier.split("::").slice(0, -1).join("::"))
329
+ };
330
+ }
331
+ function parseRubyImports(db, importerPath, source) {
332
+ const statements = [];
333
+ for (const match of source.matchAll(/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm)) {
334
+ const kind = match[1];
335
+ const specifier = match[2];
336
+ const full = match[0];
337
+ if (!kind || !specifier || !full || typeof match.index !== "number") continue;
338
+ const body = buildUsageBody(source, match.index, match.index + full.length);
339
+ const sourcePath = kind === "require_relative" ? resolveRubyImportPath(db, importerPath, specifier) : null;
340
+ if (sourcePath) {
341
+ const localName = rubyConstantName(specifier);
342
+ statements.push({
343
+ importedName: localName,
344
+ localName,
345
+ sourcePath,
346
+ kind: "named",
347
+ used: hasIdentifierUsage(body, localName),
348
+ usedMembers: []
349
+ });
350
+ continue;
351
+ }
352
+ statements.push({
353
+ importedName: specifier,
354
+ localName: null,
355
+ sourcePath,
356
+ kind: "side-effect",
357
+ used: true,
358
+ usedMembers: []
359
+ });
360
+ }
361
+ return statements;
362
+ }
363
+ function rubyConstantName(specifier) {
364
+ return basename(specifier).replace(/\.[^.]+$/, "").split("_").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
365
+ }
366
+ function parseCLikeImports(db, importerPath, source) {
367
+ const statements = [];
368
+ for (const match of source.matchAll(/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm)) {
369
+ const specifier = match[1]?.trim();
370
+ const full = match[0];
371
+ if (!specifier || !full || typeof match.index !== "number") continue;
372
+ const body = buildUsageBody(source, match.index, match.index + full.length);
373
+ const localName = basename(specifier).replace(/\.[^.]+$/, "");
374
+ statements.push({
375
+ importedName: specifier,
376
+ localName,
377
+ sourcePath: resolveCLikeImportPath(db, importerPath, specifier),
378
+ kind: "named",
379
+ used: hasIdentifierUsage(body, localName),
380
+ usedMembers: []
381
+ });
382
+ }
383
+ return statements;
384
+ }
385
+ function parseDotNetImports(db, importerPath, source) {
386
+ const statements = [];
387
+ const lineRegex = isVisualBasicSourcePath(importerPath) ? /^[ \t]*Imports\s+(.+?)\s*$/gm : /^[ \t]*using\s+(.+?)\s*;$/gm;
388
+ for (const match of source.matchAll(lineRegex)) {
389
+ const clause = match[1]?.trim();
390
+ const full = match[0];
391
+ if (!clause || !full || typeof match.index !== "number") continue;
392
+ const body = buildUsageBody(source, match.index, match.index + full.length);
393
+ const [aliasPart, targetPart] = isVisualBasicSourcePath(importerPath) ? clause.split(/\s*=\s*/) : clause.split(/\s*=\s*/);
394
+ const hasAlias = Boolean(targetPart);
395
+ const qualified = (hasAlias ? targetPart : aliasPart)?.trim() ?? clause;
396
+ const importedName = qualified.split(".").pop() ?? qualified;
397
+ const localName = hasAlias ? aliasPart?.trim() ?? importedName : importedName;
398
+ statements.push(buildSimpleImport(
399
+ db,
400
+ importerPath,
401
+ body,
402
+ qualified,
403
+ importedName,
404
+ localName,
405
+ resolveQualifiedImportPath(db, qualified, DOTNET_SOURCE_EXTENSIONS)
406
+ ));
407
+ }
408
+ return statements;
409
+ }
410
+ function parseDartImports(db, importerPath, source) {
411
+ const statements = [];
412
+ for (const match of source.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)) {
413
+ const specifier = match[1]?.trim();
414
+ const alias = match[2]?.trim() ?? null;
415
+ const full = match[0];
416
+ if (!specifier || !full || typeof match.index !== "number") continue;
417
+ const body = buildUsageBody(source, match.index, match.index + full.length);
418
+ statements.push({
419
+ importedName: specifier,
420
+ localName: alias,
421
+ sourcePath: resolveDartImportPath(db, importerPath, specifier),
422
+ kind: alias ? "namespace" : "side-effect",
423
+ used: alias ? hasIdentifierUsage(body, alias) : true,
424
+ usedMembers: alias ? collectNamespaceMembers(body, alias) : []
425
+ });
426
+ }
427
+ return statements;
428
+ }
429
+ function parseDartExports(db, importerPath, source) {
430
+ const statements = [];
431
+ for (const match of source.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)) {
432
+ const specifier = match[1]?.trim();
433
+ if (!specifier) continue;
434
+ statements.push({
435
+ specifier,
436
+ sourcePath: resolveDartImportPath(db, importerPath, specifier)
437
+ });
438
+ }
439
+ return statements;
440
+ }
441
+ function parsePhpImports(db, importerPath, source) {
442
+ const statements = [];
443
+ for (const match of source.matchAll(/^[ \t]*use\s+(.+?)\s*;$/gm)) {
444
+ const clause = match[1]?.trim();
445
+ const full = match[0];
446
+ if (!clause || !full || typeof match.index !== "number") continue;
447
+ const body = buildUsageBody(source, match.index, match.index + full.length);
448
+ for (const entry of splitTopLevel(clause)) {
449
+ const cleaned = entry.trim();
450
+ if (!cleaned) continue;
451
+ const [qualifiedPart, aliasPart] = cleaned.split(/\s+as\s+/i);
452
+ const qualified = qualifiedPart?.trim() ?? cleaned;
453
+ const importedName = qualified.split("\\").pop() ?? qualified;
454
+ const localName = (aliasPart ?? importedName).trim();
455
+ statements.push(buildSimpleImport(
456
+ db,
457
+ importerPath,
458
+ body,
459
+ qualified,
460
+ importedName,
461
+ localName,
462
+ resolveQualifiedImportPath(db, qualified.replace(/\\/g, "."), PHP_SOURCE_EXTENSIONS)
463
+ ));
464
+ }
465
+ }
466
+ return statements;
467
+ }
468
+ function buildSimpleImport(db, importerPath, body, qualifiedName, importedName, localName, sourcePath) {
469
+ return {
470
+ importedName,
471
+ localName,
472
+ sourcePath: sourcePath ?? resolveQualifiedImportPath(db, qualifiedName, extensionFamilyFor(importerPath)),
473
+ kind: "named",
474
+ used: hasIdentifierUsage(body, localName),
475
+ usedMembers: []
476
+ };
477
+ }
478
+ function parsePythonCalls(lines, baseLine) {
479
+ const calls = [];
480
+ const controlKeywords = /* @__PURE__ */ new Set([
481
+ "if",
482
+ "for",
483
+ "while",
484
+ "with",
485
+ "except",
486
+ "elif",
487
+ "return",
488
+ "yield",
489
+ "assert",
490
+ "raise",
491
+ "lambda",
492
+ "class",
493
+ "def"
494
+ ]);
495
+ for (let index = 0; index < lines.length; index++) {
496
+ const rawLine = lines[index] ?? "";
497
+ const stripped = stripCommentsAndStrings(rawLine);
498
+ if (!stripped.trim()) continue;
499
+ const attributeMatches = [...stripped.matchAll(/\b([A-Za-z_][\w]*)\s*\.\s*([A-Za-z_][\w]*)\s*\(/g)];
500
+ const attributeRanges = attributeMatches.map((match) => ({
501
+ start: match.index ?? -1,
502
+ end: (match.index ?? -1) + match[0].length
503
+ }));
504
+ for (const match of attributeMatches) {
505
+ const receiverName = match[1];
506
+ const calleeName = match[2];
507
+ if (!receiverName || !calleeName) continue;
508
+ calls.push({
509
+ receiverName,
510
+ calleeName,
511
+ line: baseLine + index
512
+ });
513
+ }
514
+ for (const match of stripped.matchAll(/\b([A-Za-z_][\w]*)\s*\(/g)) {
515
+ const calleeName = match[1];
516
+ const start = match.index ?? -1;
517
+ if (!calleeName || start < 0) continue;
518
+ if (controlKeywords.has(calleeName)) continue;
519
+ if (attributeRanges.some((range) => start >= range.start && start < range.end)) continue;
520
+ const prefix = stripped.slice(0, start).trimEnd();
521
+ if (prefix.endsWith("def") || prefix.endsWith("class") || prefix.endsWith("async def")) {
522
+ continue;
523
+ }
524
+ calls.push({
525
+ receiverName: null,
526
+ calleeName,
527
+ line: baseLine + index
528
+ });
529
+ }
530
+ }
531
+ return calls;
532
+ }
533
+ function parseJavaScriptCalls(lines, baseLine) {
534
+ const calls = [];
535
+ const controlKeywords = /* @__PURE__ */ new Set([
536
+ "if",
537
+ "for",
538
+ "while",
539
+ "switch",
540
+ "catch",
541
+ "function",
542
+ "class",
543
+ "return",
544
+ "typeof",
545
+ "import"
546
+ ]);
547
+ for (let index = 0; index < lines.length; index++) {
548
+ const stripped = stripCommentsAndStrings(lines[index] ?? "");
549
+ if (!stripped.trim()) continue;
550
+ const attributeMatches = [
551
+ ...stripped.matchAll(/\b([A-Za-z_$][\w$]*)\s*(?:\?\.|\.)\s*([A-Za-z_$][\w$]*)\s*\(/g),
552
+ ...stripped.matchAll(/\bthis\s*(?:\?\.|\.)\s*([A-Za-z_$][\w$]*)\s*\(/g)
553
+ ];
554
+ const attributeRanges = attributeMatches.map((match) => ({
555
+ start: match.index ?? -1,
556
+ end: (match.index ?? -1) + match[0].length
557
+ }));
558
+ for (const match of attributeMatches) {
559
+ const receiverName = match[2] ? match[1] : "this";
560
+ const calleeName = match[2] ?? match[1];
561
+ if (!receiverName || !calleeName) continue;
562
+ calls.push({
563
+ receiverName,
564
+ calleeName,
565
+ line: baseLine + index
566
+ });
567
+ }
568
+ for (const match of stripped.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)) {
569
+ const calleeName = match[1];
570
+ const start = match.index ?? -1;
571
+ if (!calleeName || start < 0) continue;
572
+ if (controlKeywords.has(calleeName)) continue;
573
+ if (attributeRanges.some((range) => start >= range.start && start < range.end)) continue;
574
+ const prefix = stripped.slice(0, start).trimEnd();
575
+ if (prefix.endsWith("function") || prefix.endsWith("class") || prefix.endsWith("new")) {
576
+ continue;
577
+ }
578
+ calls.push({
579
+ receiverName: null,
580
+ calleeName,
581
+ line: baseLine + index
582
+ });
583
+ }
584
+ }
585
+ return calls;
586
+ }
587
+ function parsePythonConstructorBindings(lines) {
588
+ const bindings = /* @__PURE__ */ new Map();
589
+ for (const rawLine of lines) {
590
+ const stripped = stripCommentsAndStrings(rawLine);
591
+ const constructorMatch = stripped.match(/\b([A-Za-z_][\w]*)\s*=\s*([A-Z][\w]*)\s*\(/);
592
+ if (constructorMatch?.[1] && constructorMatch[2]) {
593
+ bindings.set(constructorMatch[1], constructorMatch[2]);
594
+ }
595
+ }
596
+ return [...bindings.entries()].map(([localName, typeName]) => ({ localName, typeName }));
597
+ }
598
+ function parseJavaScriptConstructorBindings(lines) {
599
+ const bindings = /* @__PURE__ */ new Map();
600
+ for (const rawLine of lines) {
601
+ const stripped = stripCommentsAndStrings(rawLine);
602
+ for (const match of stripped.matchAll(/\b([A-Za-z_$][\w$]*)\s*:\s*([A-Z][A-Za-z0-9_$]*)\b/g)) {
603
+ const localName = match[1];
604
+ const typeName = match[2];
605
+ if (localName && typeName) {
606
+ bindings.set(localName, typeName);
607
+ }
608
+ }
609
+ const constructorMatch = stripped.match(/\b(?:const|let|var)?\s*([A-Za-z_$][\w$]*)\s*(?::\s*[A-Z][A-Za-z0-9_$<> ,]*)?\s*=\s*new\s+([A-Z][A-Za-z0-9_$]*)\s*\(/);
610
+ if (constructorMatch?.[1] && constructorMatch[2]) {
611
+ bindings.set(constructorMatch[1], constructorMatch[2]);
612
+ }
613
+ }
614
+ return [...bindings.entries()].map(([localName, typeName]) => ({ localName, typeName }));
615
+ }
616
+ function parsePythonImports(db, importerPath, source) {
617
+ return collectPythonImportStatements(source).flatMap(
618
+ (statement) => parsePythonImportStatement(db, importerPath, statement, source)
619
+ );
620
+ }
621
+ function collectPythonImportStatements(source) {
622
+ const lines = source.split("\n");
623
+ const statements = [];
624
+ let offset = 0;
625
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
626
+ const line = lines[lineIndex];
627
+ const trimmed = line.trimStart();
628
+ const lineStart = offset;
629
+ offset += line.length + 1;
630
+ if (!trimmed.startsWith("import ") && !trimmed.startsWith("from ")) {
631
+ continue;
632
+ }
633
+ let statement = line;
634
+ let statementEnd = lineStart + line.length;
635
+ let balance = pythonParenBalance(line);
636
+ while (lineIndex + 1 < lines.length && (balance > 0 || statement.trimEnd().endsWith("\\"))) {
637
+ lineIndex++;
638
+ const nextLine = lines[lineIndex];
639
+ statement += `
640
+ ${nextLine}`;
641
+ statementEnd += 1 + nextLine.length;
642
+ balance += pythonParenBalance(nextLine);
643
+ offset += nextLine.length + 1;
644
+ }
645
+ const parsed = parsePythonStatementHeader(statement);
646
+ if (parsed) {
647
+ statements.push({
648
+ ...parsed,
649
+ start: lineStart,
650
+ end: statementEnd
651
+ });
652
+ }
653
+ }
654
+ return statements;
655
+ }
656
+ function parsePythonStatementHeader(statement) {
657
+ const normalized = statement.replace(/\\\s*\n/g, " ").trim();
658
+ if (normalized.startsWith("import ")) {
659
+ return {
660
+ kind: "import",
661
+ module: null,
662
+ clause: normalized.slice("import ".length).trim()
663
+ };
664
+ }
665
+ const fromMatch = normalized.match(/^from\s+([.\w]+)\s+import\s+([\s\S]+)$/);
666
+ if (!fromMatch) {
667
+ return null;
668
+ }
669
+ let clause = fromMatch[2].trim();
670
+ if (clause.startsWith("(") && clause.endsWith(")")) {
671
+ clause = clause.slice(1, -1).trim();
672
+ }
673
+ return {
674
+ kind: "from",
675
+ module: fromMatch[1],
676
+ clause
677
+ };
678
+ }
679
+ function parsePythonImportStatement(db, importerPath, statement, source) {
680
+ const body = buildUsageBody(source, statement.start, statement.end);
681
+ const normalizedClause = statement.clause.replace(/\n/g, " ").trim();
682
+ if (statement.kind === "import") {
683
+ return splitTopLevel(normalizedClause).flatMap((entry) => {
684
+ const cleaned = entry.trim().replace(/,$/, "");
685
+ if (!cleaned) return [];
686
+ const [moduleName, alias] = cleaned.split(/\s+as\s+/);
687
+ const importedName = moduleName.trim();
688
+ const localName = (alias ?? importedName.split(".")[0] ?? importedName).trim();
689
+ const sourcePath2 = resolvePythonImportPath(db, importerPath, importedName);
690
+ const usedMembers = collectNamespaceMembers(body, localName);
691
+ return [{
692
+ importedName,
693
+ localName,
694
+ sourcePath: sourcePath2,
695
+ kind: "namespace",
696
+ used: hasIdentifierUsage(body, localName) || usedMembers.length > 0,
697
+ usedMembers
698
+ }];
699
+ });
700
+ }
701
+ const sourcePath = statement.module ? resolvePythonImportPath(db, importerPath, statement.module) : null;
702
+ const results = [];
703
+ for (const entry of splitTopLevel(normalizedClause)) {
704
+ const cleaned = entry.trim().replace(/,$/, "");
705
+ if (!cleaned) continue;
706
+ if (cleaned === "*") {
707
+ results.push({
708
+ importedName: "*",
709
+ localName: null,
710
+ sourcePath,
711
+ kind: "side-effect",
712
+ used: true,
713
+ usedMembers: []
714
+ });
715
+ continue;
716
+ }
717
+ const [importedName, alias] = cleaned.split(/\s+as\s+/);
718
+ const localName = (alias ?? importedName).trim();
719
+ results.push({
720
+ importedName: importedName.trim(),
721
+ localName,
722
+ sourcePath,
723
+ kind: "named",
724
+ used: hasIdentifierUsage(body, localName),
725
+ usedMembers: []
726
+ });
727
+ }
728
+ return results;
729
+ }
730
+ function parseImportClause(clause) {
731
+ const trimmed = clause.trim().replace(/^type\s+/, "");
732
+ const [first, second] = splitImportClause(trimmed);
733
+ const entries = [];
734
+ if (first) {
735
+ entries.push(...parseImportBinding(first));
736
+ }
737
+ if (second) {
738
+ entries.push(...parseImportBinding(second));
739
+ }
740
+ return entries;
741
+ }
742
+ function parseImportBinding(binding) {
743
+ const trimmed = binding.trim();
744
+ if (!trimmed) return [];
745
+ if (trimmed.startsWith("{")) {
746
+ const inner = trimmed.slice(1, -1).trim();
747
+ if (!inner) return [];
748
+ return splitTopLevel(inner).map((entry) => {
749
+ const cleaned = entry.trim().replace(/^type\s+/, "");
750
+ const [importedName, alias] = cleaned.split(/\s+as\s+/);
751
+ return {
752
+ importedName: importedName.trim(),
753
+ localName: (alias ?? importedName).trim(),
754
+ kind: "named"
755
+ };
756
+ });
757
+ }
758
+ if (trimmed.startsWith("* as ")) {
759
+ return [{
760
+ importedName: "*",
761
+ localName: trimmed.slice(5).trim(),
762
+ kind: "namespace"
763
+ }];
764
+ }
765
+ return [{
766
+ importedName: "default",
767
+ localName: trimmed,
768
+ kind: "default"
769
+ }];
770
+ }
771
+ function splitImportClause(clause) {
772
+ let depth = 0;
773
+ for (let i = 0; i < clause.length; i++) {
774
+ const char = clause[i];
775
+ if (char === "{") depth++;
776
+ if (char === "}") depth--;
777
+ if (char === "," && depth === 0) {
778
+ return [clause.slice(0, i).trim(), clause.slice(i + 1).trim()];
779
+ }
780
+ }
781
+ return [clause.trim(), null];
782
+ }
783
+ function splitTopLevel(input) {
784
+ const parts = [];
785
+ let depth = 0;
786
+ let start = 0;
787
+ for (let i = 0; i < input.length; i++) {
788
+ const char = input[i];
789
+ if (char === "{" || char === "[" || char === "(") depth++;
790
+ if (char === "}" || char === "]" || char === ")") depth--;
791
+ if (char === "," && depth === 0) {
792
+ parts.push(input.slice(start, i));
793
+ start = i + 1;
794
+ }
795
+ }
796
+ parts.push(input.slice(start));
797
+ return parts;
798
+ }
799
+ function buildUsageBody(source, start, end) {
800
+ const masked = `${source.slice(0, start)}${" ".repeat(end - start)}${source.slice(end)}`;
801
+ return stripCommentsAndStrings(masked);
802
+ }
803
+ function stripCommentsAndStrings(source) {
804
+ return source.replace(/'''[\s\S]*?'''/g, maskPreservingLines).replace(/"""[\s\S]*?"""/g, maskPreservingLines).replace(/#.*$/gm, maskPreservingLines).replace(/\/\/.*$/gm, maskPreservingLines).replace(/\/\*[\s\S]*?\*\//g, maskPreservingLines).replace(/`(?:\\[\s\S]|[^`])*`/g, maskPreservingLines).replace(/'(?:\\.|[^'\\\r\n])*'/g, maskPreservingLines).replace(/"(?:\\.|[^"\\\r\n])*"/g, maskPreservingLines);
805
+ }
806
+ function maskPreservingLines(segment) {
807
+ return segment.replace(/[^\r\n]/g, " ");
808
+ }
809
+ function hasIdentifierUsage(body, identifier) {
810
+ return new RegExp(`\\b${escapeRegex(identifier)}\\b`, "m").test(body);
811
+ }
812
+ function collectNamespaceMembers(body, namespaceName) {
813
+ const members = /* @__PURE__ */ new Set();
814
+ const regex = new RegExp(`\\b${escapeRegex(namespaceName)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`, "g");
815
+ for (const match of body.matchAll(regex)) {
816
+ const member = match[1];
817
+ if (member) {
818
+ members.add(member);
819
+ }
820
+ }
821
+ return [...members];
822
+ }
823
+ function resolveImportPath(db, importerPath, specifier) {
824
+ if (isPythonSourcePath(importerPath)) {
825
+ return resolvePythonImportPath(db, importerPath, specifier);
826
+ }
827
+ if (isRustSourcePath(importerPath)) {
828
+ return resolveRustImportPath(db, importerPath, specifier);
829
+ }
830
+ if (isRubySourcePath(importerPath)) {
831
+ return resolveRubyImportPath(db, importerPath, specifier);
832
+ }
833
+ if (isCLikeSourcePath(importerPath)) {
834
+ return resolveCLikeImportPath(db, importerPath, specifier);
835
+ }
836
+ if (isJvmSourcePath(importerPath) || isDotNetSourcePath(importerPath) || isPhpSourcePath(importerPath)) {
837
+ return resolveQualifiedImportPath(db, specifier.replace(/\\/g, "."), extensionFamilyFor(importerPath));
838
+ }
839
+ if (isDartSourcePath(importerPath)) {
840
+ return resolveDartImportPath(db, importerPath, specifier);
841
+ }
842
+ return resolveJavaScriptImportPath(db, importerPath, specifier);
843
+ }
844
+ function resolveJavaScriptImportPath(db, importerPath, specifier) {
845
+ if (!specifier.startsWith(".") && !specifier.startsWith("/")) {
846
+ return null;
847
+ }
848
+ const importerDir = dirname(join(db.config.projectRoot, importerPath));
849
+ const absolute = resolve(importerDir, specifier);
850
+ const indexedPaths = getIndexedPaths(db);
851
+ for (const candidate of candidateImportPaths(absolute)) {
852
+ const relativeCandidate = normalizePath(relative(db.config.projectRoot, candidate));
853
+ if (indexedPaths.has(relativeCandidate) || existsSync(candidate)) {
854
+ return relativeCandidate;
855
+ }
856
+ }
857
+ return normalizePath(relative(db.config.projectRoot, absolute));
858
+ }
859
+ function resolvePythonImportPath(db, importerPath, specifier) {
860
+ const indexedPaths = getIndexedPaths(db);
861
+ let basePath;
862
+ if (specifier.startsWith(".")) {
863
+ const match = specifier.match(/^(\.+)(.*)$/);
864
+ if (!match) return null;
865
+ const dots = match[1].length;
866
+ const remainder = match[2].replace(/^\./, "");
867
+ let baseDir = dirname(join(db.config.projectRoot, importerPath));
868
+ for (let i = 1; i < dots; i++) {
869
+ baseDir = dirname(baseDir);
870
+ }
871
+ basePath = remainder ? resolve(baseDir, remainder.replace(/\./g, "/")) : baseDir;
872
+ } else {
873
+ basePath = resolve(db.config.projectRoot, specifier.replace(/\./g, "/"));
874
+ }
875
+ for (const candidate of pythonCandidateImportPaths(basePath)) {
876
+ const relativeCandidate = normalizePath(relative(db.config.projectRoot, candidate));
877
+ if (indexedPaths.has(relativeCandidate) || existsSync(candidate)) {
878
+ return relativeCandidate;
879
+ }
880
+ }
881
+ return null;
882
+ }
883
+ function resolveRustImportPath(db, importerPath, specifier) {
884
+ if (!specifier) return null;
885
+ const normalizedSpecifier = specifier.replace(/\s+as\s+.+$/, "").trim();
886
+ if (!normalizedSpecifier.startsWith("crate::") && !normalizedSpecifier.startsWith("self::") && !normalizedSpecifier.startsWith("super::")) {
887
+ return null;
888
+ }
889
+ const importerDir = dirname(join(db.config.projectRoot, importerPath));
890
+ let basePath;
891
+ if (normalizedSpecifier.startsWith("crate::")) {
892
+ basePath = resolve(db.config.projectRoot, "src", normalizedSpecifier.slice("crate::".length).replace(/::/g, "/"));
893
+ } else if (normalizedSpecifier.startsWith("self::")) {
894
+ basePath = resolve(importerDir, normalizedSpecifier.slice("self::".length).replace(/::/g, "/"));
895
+ } else {
896
+ basePath = resolve(dirname(importerDir), normalizedSpecifier.slice("super::".length).replace(/::/g, "/"));
897
+ }
898
+ for (const candidate of rustCandidateImportPaths(basePath)) {
899
+ const relativeCandidate = normalizePath(relative(db.config.projectRoot, candidate));
900
+ if (getIndexedPaths(db).has(relativeCandidate) || existsSync(candidate)) {
901
+ return relativeCandidate;
902
+ }
903
+ }
904
+ return null;
905
+ }
906
+ function resolveRubyImportPath(db, importerPath, specifier) {
907
+ const importerDir = dirname(join(db.config.projectRoot, importerPath));
908
+ const absolute = resolve(importerDir, specifier);
909
+ for (const candidate of rubyCandidateImportPaths(absolute)) {
910
+ const relativeCandidate = normalizePath(relative(db.config.projectRoot, candidate));
911
+ if (getIndexedPaths(db).has(relativeCandidate) || existsSync(candidate)) {
912
+ return relativeCandidate;
913
+ }
914
+ }
915
+ return null;
916
+ }
917
+ function resolveCLikeImportPath(db, importerPath, specifier) {
918
+ const indexedPaths = getIndexedPaths(db);
919
+ const importerDir = dirname(join(db.config.projectRoot, importerPath));
920
+ const candidates = [
921
+ resolve(importerDir, specifier),
922
+ resolve(db.config.projectRoot, specifier),
923
+ resolve(db.config.projectRoot, "include", specifier),
924
+ resolve(db.config.projectRoot, "src", specifier)
925
+ ];
926
+ for (const candidate of candidates) {
927
+ const relativeCandidate = normalizePath(relative(db.config.projectRoot, candidate));
928
+ if (indexedPaths.has(relativeCandidate) || existsSync(candidate)) {
929
+ return relativeCandidate;
930
+ }
931
+ }
932
+ return null;
933
+ }
934
+ function resolveQualifiedImportPath(db, specifier, extensions) {
935
+ const indexedPaths = getIndexedPaths(db);
936
+ const normalized = specifier.replace(/\\/g, ".").replace(/::/g, ".").replace(/^global::/, "");
937
+ const pathified = normalized.replace(/\./g, "/");
938
+ const basenameOnly = normalized.split(".").pop() ?? normalized;
939
+ for (const ext of extensions) {
940
+ const exactSuffix = `${pathified}${ext}`;
941
+ const exact = [...indexedPaths].find((relativePath) => relativePath.endsWith(exactSuffix));
942
+ if (exact) return exact;
943
+ }
944
+ for (const ext of extensions) {
945
+ const basenameMatch = [...indexedPaths].find((relativePath) => basename(relativePath) === `${basenameOnly}${ext}`);
946
+ if (basenameMatch) return basenameMatch;
947
+ }
948
+ const folderMatches = [...indexedPaths].filter((relativePath) => extensions.includes(extname(relativePath).toLowerCase())).filter((relativePath) => relativePath.includes(`/${pathified}/`) || relativePath.includes(`/${basenameOnly}/`)).sort((left, right) => left.localeCompare(right));
949
+ if (folderMatches.length === 1) {
950
+ return folderMatches[0];
951
+ }
952
+ return null;
953
+ }
954
+ function resolveDartImportPath(db, importerPath, specifier) {
955
+ const indexedPaths = getIndexedPaths(db);
956
+ if (specifier.startsWith("package:")) {
957
+ const withoutScheme = specifier.slice("package:".length);
958
+ const slashIndex = withoutScheme.indexOf("/");
959
+ if (slashIndex < 0) return null;
960
+ const packageRelative = withoutScheme.slice(slashIndex + 1);
961
+ const candidate = normalizePath(packageRelative.startsWith("lib/") ? packageRelative : `lib/${packageRelative}`);
962
+ if (indexedPaths.has(candidate)) return candidate;
963
+ return null;
964
+ }
965
+ const importerDir = dirname(join(db.config.projectRoot, importerPath));
966
+ const absolute = resolve(importerDir, specifier);
967
+ for (const candidate of dartCandidateImportPaths(absolute)) {
968
+ const relativeCandidate = normalizePath(relative(db.config.projectRoot, candidate));
969
+ if (indexedPaths.has(relativeCandidate) || existsSync(candidate)) {
970
+ return relativeCandidate;
971
+ }
972
+ }
973
+ return null;
974
+ }
975
+ function pythonCandidateImportPaths(basePath) {
976
+ const ext = extname(basePath);
977
+ if (PYTHON_SOURCE_EXTENSIONS.includes(ext)) {
978
+ return [basePath];
979
+ }
980
+ return [
981
+ `${basePath}.py`,
982
+ `${basePath}.pyi`,
983
+ join(basePath, "__init__.py"),
984
+ join(basePath, "__init__.pyi")
985
+ ];
986
+ }
987
+ function rustCandidateImportPaths(basePath) {
988
+ const ext = extname(basePath);
989
+ if (RUST_SOURCE_EXTENSIONS.includes(ext)) {
990
+ return [basePath];
991
+ }
992
+ return [
993
+ `${basePath}.rs`,
994
+ join(basePath, "mod.rs")
995
+ ];
996
+ }
997
+ function rubyCandidateImportPaths(basePath) {
998
+ const ext = extname(basePath);
999
+ if (RUBY_SOURCE_EXTENSIONS.includes(ext)) {
1000
+ return [basePath];
1001
+ }
1002
+ return [
1003
+ `${basePath}.rb`,
1004
+ join(basePath, "index.rb")
1005
+ ];
1006
+ }
1007
+ function dartCandidateImportPaths(basePath) {
1008
+ const ext = extname(basePath);
1009
+ if (DART_SOURCE_EXTENSIONS.includes(ext)) {
1010
+ return [basePath];
1011
+ }
1012
+ return [`${basePath}.dart`, basePath];
1013
+ }
1014
+ function candidateImportPaths(absolute) {
1015
+ const ext = extname(absolute);
1016
+ const candidates = /* @__PURE__ */ new Set();
1017
+ if (ext) {
1018
+ candidates.add(absolute);
1019
+ for (const sourceExt of SOURCE_EXTENSIONS) {
1020
+ candidates.add(absolute.slice(0, -ext.length) + sourceExt);
1021
+ }
1022
+ } else {
1023
+ for (const sourceExt of SOURCE_EXTENSIONS) {
1024
+ candidates.add(`${absolute}${sourceExt}`);
1025
+ candidates.add(join(absolute, `index${sourceExt}`));
1026
+ }
1027
+ }
1028
+ return [...candidates];
1029
+ }
1030
+ function getIndexedPaths(db) {
1031
+ const cached = INDEXED_PATH_CACHE.get(db);
1032
+ if (cached) {
1033
+ return cached;
1034
+ }
1035
+ const paths = new Set(
1036
+ db.all(
1037
+ `SELECT relative_path
1038
+ FROM documents
1039
+ WHERE 1 = 1
1040
+ ${db.pathExclusionsFor("documents")}`
1041
+ ).map((row) => normalizePath(row.relative_path)).filter((relativePath) => !db.isIgnored(relativePath))
1042
+ );
1043
+ INDEXED_PATH_CACHE.set(db, paths);
1044
+ return paths;
1045
+ }
1046
+ function getCachedMap(cache, db) {
1047
+ let map = cache.get(db);
1048
+ if (!map) {
1049
+ map = /* @__PURE__ */ new Map();
1050
+ cache.set(db, map);
1051
+ }
1052
+ return map;
1053
+ }
1054
+ function normalizePath(path) {
1055
+ return path.replace(/\\/g, "/");
1056
+ }
1057
+ function isJavaScriptSourcePath(relativePath) {
1058
+ return SOURCE_EXTENSIONS.includes(extname(relativePath).toLowerCase());
1059
+ }
1060
+ function isPythonSourcePath(relativePath) {
1061
+ return PYTHON_SOURCE_EXTENSIONS.includes(extname(relativePath).toLowerCase());
1062
+ }
1063
+ function isJvmSourcePath(relativePath) {
1064
+ return JVM_SOURCE_EXTENSIONS.includes(extname(relativePath).toLowerCase());
1065
+ }
1066
+ function isRustSourcePath(relativePath) {
1067
+ return RUST_SOURCE_EXTENSIONS.includes(extname(relativePath).toLowerCase());
1068
+ }
1069
+ function isRubySourcePath(relativePath) {
1070
+ return RUBY_SOURCE_EXTENSIONS.includes(extname(relativePath).toLowerCase());
1071
+ }
1072
+ function isCLikeSourcePath(relativePath) {
1073
+ return C_LIKE_SOURCE_EXTENSIONS.includes(extname(relativePath).toLowerCase());
1074
+ }
1075
+ function isDotNetSourcePath(relativePath) {
1076
+ return DOTNET_SOURCE_EXTENSIONS.includes(extname(relativePath).toLowerCase());
1077
+ }
1078
+ function isVisualBasicSourcePath(relativePath) {
1079
+ return extname(relativePath).toLowerCase() === ".vb";
1080
+ }
1081
+ function isDartSourcePath(relativePath) {
1082
+ return DART_SOURCE_EXTENSIONS.includes(extname(relativePath).toLowerCase());
1083
+ }
1084
+ function isPhpSourcePath(relativePath) {
1085
+ return PHP_SOURCE_EXTENSIONS.includes(extname(relativePath).toLowerCase());
1086
+ }
1087
+ function extensionFamilyFor(relativePath) {
1088
+ if (isJvmSourcePath(relativePath)) return JVM_SOURCE_EXTENSIONS;
1089
+ if (isDotNetSourcePath(relativePath)) return DOTNET_SOURCE_EXTENSIONS;
1090
+ if (isPhpSourcePath(relativePath)) return PHP_SOURCE_EXTENSIONS;
1091
+ if (isDartSourcePath(relativePath)) return DART_SOURCE_EXTENSIONS;
1092
+ if (isCLikeSourcePath(relativePath)) return C_LIKE_SOURCE_EXTENSIONS;
1093
+ if (isRustSourcePath(relativePath)) return RUST_SOURCE_EXTENSIONS;
1094
+ if (isRubySourcePath(relativePath)) return RUBY_SOURCE_EXTENSIONS;
1095
+ return SOURCE_EXTENSIONS;
1096
+ }
1097
+ function getSourceText(db, relativePath) {
1098
+ const cache = getCachedMap(SOURCE_TEXT_CACHE, db);
1099
+ const normalized = normalizePath(relativePath);
1100
+ const cached = cache.get(normalized);
1101
+ if (typeof cached === "string") {
1102
+ return cached;
1103
+ }
1104
+ const fullPath = join(db.config.projectRoot, normalized);
1105
+ if (!existsSync(fullPath)) {
1106
+ cache.set(normalized, "");
1107
+ return "";
1108
+ }
1109
+ const source = readFileSync(fullPath, "utf-8");
1110
+ cache.set(normalized, source);
1111
+ return source;
1112
+ }
1113
+ function pythonParenBalance(value) {
1114
+ let balance = 0;
1115
+ for (const char of value) {
1116
+ if (char === "(") balance++;
1117
+ if (char === ")") balance--;
1118
+ }
1119
+ return balance;
1120
+ }
1121
+ function escapeRegex(value) {
1122
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1123
+ }
1124
+
1125
+ // src/query-support.ts
1126
+ import { basename as basename2 } from "path";
1127
+ var FILE_DEFINITION_CACHE = /* @__PURE__ */ new WeakMap();
1128
+ var TEST_FILE_PATTERNS = [
1129
+ "%/__tests__/%",
1130
+ "%.test.%",
1131
+ "%.spec.%",
1132
+ "%/test/%",
1133
+ "%/tests/%",
1134
+ "%_test.%",
1135
+ "%_spec.%",
1136
+ "%/test_%.%",
1137
+ "%/spec_%.%"
1138
+ ];
1139
+ var TEST_SUPPORT_PATH_PATTERNS = [
1140
+ "%/test-utils/%"
1141
+ ];
1142
+ function testFileExclusionSql(alias, extraPatterns = []) {
1143
+ const patterns = uniquePatterns([...TEST_FILE_PATTERNS, ...extraPatterns]);
1144
+ return patterns.map((pattern) => `${alias}.relative_path NOT LIKE '${pattern}'`).join("\n AND ");
1145
+ }
1146
+ function buildFileDepGraph(db, scope) {
1147
+ const scopeFilter = scope ? `AND d1.relative_path LIKE '%${scope}%'` : "";
1148
+ const edges = db.all(
1149
+ `SELECT DISTINCT
1150
+ d1.relative_path AS from_file,
1151
+ d2.relative_path AS to_file
1152
+ FROM mentions m
1153
+ JOIN chunks c ON m.chunk_id = c.id
1154
+ JOIN documents d1 ON c.document_id = d1.id
1155
+ JOIN global_symbols gs ON m.symbol_id = gs.id
1156
+ JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
1157
+ JOIN documents d2 ON der.document_id = d2.id
1158
+ WHERE d1.id != d2.id
1159
+ AND m.role != 1
1160
+ ${db.pathExclusionsFor("d1", "d2")}
1161
+ ${scopeFilter}`
1162
+ );
1163
+ const graph = /* @__PURE__ */ new Map();
1164
+ const indexedFiles = new Set(
1165
+ db.all(
1166
+ `SELECT relative_path
1167
+ FROM documents
1168
+ WHERE 1 = 1
1169
+ ${db.pathExclusionsFor("documents")}
1170
+ ORDER BY relative_path`
1171
+ ).map((row) => row.relative_path).filter((relativePath) => !db.isIgnored(relativePath))
1172
+ );
1173
+ const addEdge = (fromFile, toFile) => {
1174
+ if (fromFile === toFile) return;
1175
+ if (db.isIgnored(fromFile) || db.isIgnored(toFile)) return;
1176
+ if (!indexedFiles.has(toFile)) return;
1177
+ if (!graph.has(fromFile)) graph.set(fromFile, /* @__PURE__ */ new Set());
1178
+ graph.get(fromFile).add(toFile);
1179
+ };
1180
+ for (const edge of edges) {
1181
+ addEdge(edge.from_file, edge.to_file);
1182
+ }
1183
+ for (const relativePath of indexedFiles) {
1184
+ if (scope && !relativePath.includes(scope)) continue;
1185
+ for (const entry of getSourceImports(db, relativePath)) {
1186
+ if (!entry.sourcePath) continue;
1187
+ addEdge(relativePath, entry.sourcePath);
1188
+ }
1189
+ }
1190
+ return graph;
1191
+ }
1192
+ function findFirstSymbolMatch(db, symbolPattern) {
1193
+ const exact = findExactSymbolMatch(db, symbolPattern.trim());
1194
+ if (exact) {
1195
+ return exact;
1196
+ }
1197
+ const fileLineMatch = symbolPattern.match(/^(.+):(\d+)-(\d+)$/);
1198
+ if (fileLineMatch) {
1199
+ const [, filePath, startStr, endStr] = fileLineMatch;
1200
+ let row = db.get(
1201
+ `SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path
1202
+ FROM global_symbols gs
1203
+ JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
1204
+ JOIN documents d ON der.document_id = d.id
1205
+ WHERE d.relative_path LIKE ?
1206
+ AND der.start_line <= ? AND der.end_line >= ?
1207
+ ${db.pathExclusionsFor("d")}
1208
+ ORDER BY (der.end_line - der.start_line) ASC
1209
+ LIMIT 1`,
1210
+ `%${filePath}%`,
1211
+ parseInt(startStr, 10),
1212
+ parseInt(endStr, 10)
1213
+ );
1214
+ if (!row) {
1215
+ row = db.get(
1216
+ `SELECT gs.id, gs.symbol, c.document_id, MIN(c.start_line) AS start_line, MAX(c.end_line) AS end_line, d.relative_path
1217
+ FROM global_symbols gs
1218
+ JOIN mentions m ON m.symbol_id = gs.id
1219
+ JOIN chunks c ON m.chunk_id = c.id
1220
+ JOIN documents d ON c.document_id = d.id
1221
+ WHERE m.role = 1
1222
+ AND d.relative_path LIKE ?
1223
+ AND c.start_line <= ? AND c.end_line >= ?
1224
+ ${db.pathExclusionsFor("d")}
1225
+ GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
1226
+ ORDER BY (MAX(c.end_line) - MIN(c.start_line)) ASC
1227
+ LIMIT 1`,
1228
+ `%${filePath}%`,
1229
+ parseInt(startStr, 10),
1230
+ parseInt(endStr, 10)
1231
+ );
1232
+ }
1233
+ if (row && !db.isIgnored(row.relative_path)) {
1234
+ return hydrateSymbolMatch(db, row);
1235
+ }
1236
+ }
1237
+ const cleaned = normalizeLookupPattern(symbolPattern);
1238
+ const tokens = lookupTokens(symbolPattern);
1239
+ const candidates = getSymbolLookupCandidates(db, tokens);
1240
+ const direct = findDirectSymbolCandidate(candidates, symbolPattern, cleaned);
1241
+ if (direct && !db.isIgnored(direct.relative_path)) {
1242
+ return hydrateSymbolMatch(db, direct);
1243
+ }
1244
+ let best = null;
1245
+ for (const row of candidates) {
1246
+ if (db.isIgnored(row.relative_path)) continue;
1247
+ const score = scoreSymbolCandidate(row, symbolPattern, cleaned, tokens);
1248
+ if (score <= 0) continue;
1249
+ if (!best || score > best.score) {
1250
+ best = { row, score };
1251
+ }
1252
+ }
1253
+ if (best) {
1254
+ return hydrateSymbolMatch(db, best.row);
1255
+ }
1256
+ return null;
1257
+ }
1258
+ function findExactSymbolMatch(db, symbol) {
1259
+ const row = db.get(
1260
+ `SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path
1261
+ FROM global_symbols gs
1262
+ JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
1263
+ JOIN documents d ON der.document_id = d.id
1264
+ WHERE gs.symbol = ?
1265
+ ${db.pathExclusionsFor("d")}
1266
+ ORDER BY d.relative_path, der.start_line
1267
+ LIMIT 1`,
1268
+ symbol
1269
+ );
1270
+ if (!row || db.isIgnored(row.relative_path)) {
1271
+ return null;
1272
+ }
1273
+ return hydrateSymbolMatch(db, row);
1274
+ }
1275
+ function resolveIndexedFile(db, filePattern) {
1276
+ return resolveDocumentCandidates(db, filePattern, { allowMultiple: false })[0]?.relativePath ?? null;
1277
+ }
1278
+ function resolveIndexedPaths(db, filePattern) {
1279
+ return resolveDocumentCandidates(db, filePattern, { allowMultiple: true }).map((candidate) => candidate.relativePath);
1280
+ }
1281
+ function normalizeLookupPattern(symbolPattern) {
1282
+ return symbolPattern.trim().replace(/\(\)$/, "").replace(/\(.*$/, "");
1283
+ }
1284
+ function lookupTokens(symbolPattern) {
1285
+ const cleaned = normalizeLookupPattern(symbolPattern);
1286
+ const tokens = cleaned.split(/[^A-Za-z0-9_]+/).map((token) => token.trim()).filter((token) => token.length > 0);
1287
+ return tokens.length > 0 ? [...new Set(tokens)] : [cleaned];
1288
+ }
1289
+ function getSymbolLookupCandidates(db, tokens) {
1290
+ const tokenClauses = tokens.map(
1291
+ () => `(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)`
1292
+ );
1293
+ const params = tokens.flatMap((token) => {
1294
+ const like = `%${token}%`;
1295
+ return [like, like, like];
1296
+ });
1297
+ const primary = db.all(
1298
+ `SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name
1299
+ FROM global_symbols gs
1300
+ JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
1301
+ JOIN documents d ON der.document_id = d.id
1302
+ WHERE ${tokenClauses.join("\n AND ")}
1303
+ ${db.pathExclusionsFor("d")}
1304
+ LIMIT 200`,
1305
+ ...params
1306
+ );
1307
+ if (primary.length > 0) {
1308
+ return primary;
1309
+ }
1310
+ return db.all(
1311
+ `SELECT
1312
+ gs.id,
1313
+ gs.symbol,
1314
+ c.document_id,
1315
+ MIN(c.start_line) AS start_line,
1316
+ MAX(c.end_line) AS end_line,
1317
+ d.relative_path,
1318
+ gs.display_name
1319
+ FROM global_symbols gs
1320
+ JOIN mentions m ON m.symbol_id = gs.id
1321
+ JOIN chunks c ON m.chunk_id = c.id
1322
+ JOIN documents d ON c.document_id = d.id
1323
+ WHERE m.role = 1
1324
+ AND ${tokenClauses.join("\n AND ")}
1325
+ ${db.pathExclusionsFor("d")}
1326
+ GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name
1327
+ LIMIT 200`,
1328
+ ...params
1329
+ );
1330
+ }
1331
+ function scoreSymbolCandidate(row, originalPattern, cleanedPattern, tokens) {
1332
+ const originalCase = originalPattern.trim();
1333
+ const cleanedCase = cleanedPattern;
1334
+ const noParensCase = cleanedCase.replace(/\(\)$/, "");
1335
+ const original = originalPattern.toLowerCase();
1336
+ const cleaned = cleanedPattern.toLowerCase();
1337
+ const noParens = cleaned.replace(/\(\)$/, "");
1338
+ const rawCase = row.symbol;
1339
+ const shortCase = shortenSymbol(row.symbol);
1340
+ const leafCase = leafName(row.symbol);
1341
+ const displayCase = row.display_name ?? "";
1342
+ const raw = row.symbol.toLowerCase();
1343
+ const short = shortCase.toLowerCase();
1344
+ const leaf = leafCase.toLowerCase();
1345
+ const display = displayCase.toLowerCase();
1346
+ const path = row.relative_path.toLowerCase();
1347
+ const looksPathLike = /[/:.]/.test(cleanedPattern);
1348
+ let score = 0;
1349
+ if (rawCase === originalCase || rawCase === cleanedCase) score += 1150;
1350
+ if (shortCase === originalCase || shortCase === cleanedCase) score += 1100;
1351
+ if (displayCase === noParensCase) score += 980;
1352
+ if (leafCase === noParensCase) score += 960;
1353
+ if (`${leafCase}()` === originalCase || `${leafCase}()` === cleanedCase) score += 955;
1354
+ if (raw === original || raw === cleaned) score += 1e3;
1355
+ if (short === original || short === cleaned) score += 950;
1356
+ if (path === original || path === cleaned) score += 925;
1357
+ if (path.endsWith(`/${cleaned}`) || path.endsWith(`/${original}`)) score += 875;
1358
+ if (display === noParens) score += 850;
1359
+ if (leaf === noParens) score += 825;
1360
+ if (`${leaf}()` === original || `${leaf}()` === cleaned) score += 820;
1361
+ if (short.endsWith(`:${cleaned}`) || short.endsWith(`:${noParens}`) || short.endsWith(`:${noParens}()`)) score += 800;
1362
+ if (raw.includes(cleaned)) score += 120;
1363
+ if (short.includes(cleaned)) score += 140;
1364
+ if (path.includes(cleaned)) score += 140;
1365
+ if (display.includes(cleaned)) score += 110;
1366
+ if (tokens.every((token) => {
1367
+ const lower = token.toLowerCase();
1368
+ return raw.includes(lower) || short.includes(lower) || path.includes(lower) || display.includes(lower);
1369
+ })) {
1370
+ score += 100 + tokens.length * 15;
1371
+ }
1372
+ if (isFunctionLikeSymbol(row.symbol) && leaf === noParens) {
1373
+ score += 60;
1374
+ }
1375
+ if (!looksPathLike && isModuleLikeSymbol(row.symbol)) {
1376
+ score -= 160;
1377
+ }
1378
+ score -= Math.min(50, Math.max(0, row.end_line - row.start_line));
1379
+ return score;
1380
+ }
1381
+ function getCalleeRowsForSymbol(db, symbol, opts = {}) {
1382
+ const mentions = db.all(
1383
+ `SELECT DISTINCT m.symbol_id, c.id AS chunk_id
1384
+ FROM mentions m
1385
+ JOIN chunks c ON m.chunk_id = c.id
1386
+ WHERE c.document_id = ?
1387
+ AND c.start_line >= ?
1388
+ AND c.end_line <= ?
1389
+ AND m.role != 1
1390
+ AND m.symbol_id != ?
1391
+ ${opts.limit ? "LIMIT ?" : ""}`,
1392
+ ...calleeQueryParams(symbol, opts.limit)
1393
+ );
1394
+ const primary = [];
1395
+ const directSeen = /* @__PURE__ */ new Set();
1396
+ for (const mention of mentions) {
1397
+ const callee = getFullSymbolMatch(db, {
1398
+ symbolId: mention.symbol_id,
1399
+ documentId: symbol.documentId,
1400
+ startLine: symbol.startLine,
1401
+ endLine: symbol.endLine
1402
+ });
1403
+ if (!callee || db.isIgnored(callee.relativePath)) continue;
1404
+ const key = `${callee.symbol}|${callee.relativePath}|${mention.chunk_id}`;
1405
+ if (directSeen.has(key)) continue;
1406
+ directSeen.add(key);
1407
+ primary.push({
1408
+ symbol: callee.symbol,
1409
+ file: callee.relativePath,
1410
+ chunkId: mention.chunk_id
1411
+ });
1412
+ }
1413
+ const sourceFallback = getSourceBackedCalleeRows(db, symbol, opts.limit);
1414
+ if (sourceFallback.length > 0) {
1415
+ return applyLimit(sourceFallback, opts.limit);
1416
+ }
1417
+ return primary;
1418
+ }
1419
+ function getCallerRowsForSymbol(db, symbol, opts = {}) {
1420
+ const match = getFullSymbolMatch(db, symbol);
1421
+ if (!match) {
1422
+ return [];
1423
+ }
1424
+ const primary = db.all(
1425
+ `SELECT DISTINCT ref_d.relative_path AS caller_file, c.start_line AS line
1426
+ FROM mentions m
1427
+ JOIN chunks c ON m.chunk_id = c.id
1428
+ JOIN documents ref_d ON c.document_id = ref_d.id
1429
+ WHERE m.symbol_id = ?
1430
+ AND m.role != 1
1431
+ ${db.pathExclusionsFor("ref_d")}
1432
+ ORDER BY ref_d.relative_path
1433
+ ${opts.limit ? "LIMIT ?" : ""}`,
1434
+ ...referenceQueryParams(match, opts.limit)
1435
+ ).filter((row) => !db.isIgnored(row.caller_file)).flatMap((row) => {
1436
+ const enclosing = findEnclosingDefinition(getDefinitionsForFile(db, row.caller_file), row.line);
1437
+ if (!enclosing || enclosing.symbolId === match.symbolId) {
1438
+ return [];
1439
+ }
1440
+ return [{
1441
+ symbol: enclosing.symbol,
1442
+ file: row.caller_file
1443
+ }];
1444
+ });
1445
+ const sourceFallback = dedupeCallerRows([
1446
+ ...getPythonSourceCallerRows(db, match, opts.limit),
1447
+ ...getGenericSourceCallerRows(db, match, opts.limit)
1448
+ ]);
1449
+ if (sourceFallback.length === 0) {
1450
+ return dedupeCallerRows(primary);
1451
+ }
1452
+ const merged = [...sourceFallback];
1453
+ const fallbackFiles = new Set(sourceFallback.map((row) => row.file));
1454
+ const seen = new Set(merged.map((row) => `${row.symbol}|${row.file}`));
1455
+ for (const row of primary) {
1456
+ if (fallbackFiles.has(row.file)) continue;
1457
+ const key = `${row.symbol}|${row.file}`;
1458
+ if (seen.has(key)) continue;
1459
+ if (isFunctionLikeSymbol(row.symbol) || merged.length === 0) {
1460
+ seen.add(key);
1461
+ merged.push(row);
1462
+ }
1463
+ }
1464
+ return applyLimit(merged, opts.limit);
1465
+ }
1466
+ function getGenericSourceCallerRows(db, symbol, limit) {
1467
+ return applyLimit(
1468
+ getSourceReferenceSites(db, symbol).filter((site) => site.enclosingSymbol && site.enclosingSymbol !== symbol.symbol).map((site) => ({
1469
+ symbol: site.enclosingSymbol,
1470
+ file: site.file
1471
+ })),
1472
+ limit
1473
+ );
1474
+ }
1475
+ function dedupeCallerRows(rows) {
1476
+ const seen = /* @__PURE__ */ new Set();
1477
+ const unique = [];
1478
+ for (const row of rows) {
1479
+ const key = `${row.symbol}|${row.file}`;
1480
+ if (seen.has(key)) continue;
1481
+ seen.add(key);
1482
+ unique.push(row);
1483
+ }
1484
+ return unique;
1485
+ }
1486
+ function getSourceReferenceSites(db, symbol) {
1487
+ const match = getFullSymbolMatch(db, symbol);
1488
+ if (!match) {
1489
+ return [];
1490
+ }
1491
+ const identifier = leafName(match.symbol);
1492
+ if (!identifier || !hasUniqueLeafDefinition(db, identifier, match.symbolId)) {
1493
+ return [];
1494
+ }
1495
+ const documents = db.all(
1496
+ `SELECT relative_path
1497
+ FROM documents
1498
+ WHERE 1 = 1
1499
+ ${db.pathExclusionsFor("documents")}
1500
+ ORDER BY relative_path`
1501
+ );
1502
+ const sites = [];
1503
+ const seen = /* @__PURE__ */ new Set();
1504
+ for (const document of documents) {
1505
+ if (db.isIgnored(document.relative_path)) continue;
1506
+ const lines = findIdentifierLines(db, document.relative_path, identifier, document.relative_path === match.relativePath ? { excludeStartLine: match.startLine, excludeEndLine: match.endLine } : {});
1507
+ const definitions = getDefinitionsForFile(db, document.relative_path);
1508
+ for (const line of lines) {
1509
+ const enclosing = findEnclosingDefinition(definitions, line);
1510
+ const key = `${document.relative_path}|${line}|${enclosing?.symbol ?? ""}`;
1511
+ if (seen.has(key)) continue;
1512
+ seen.add(key);
1513
+ sites.push({
1514
+ file: document.relative_path,
1515
+ line,
1516
+ enclosingSymbol: enclosing?.symbol ?? null
1517
+ });
1518
+ }
1519
+ }
1520
+ return sites;
1521
+ }
1522
+ function calleeQueryParams(symbol, limit) {
1523
+ const params = [
1524
+ symbol.documentId,
1525
+ symbol.startLine,
1526
+ symbol.endLine,
1527
+ symbol.symbolId
1528
+ ];
1529
+ if (typeof limit === "number") {
1530
+ params.push(limit);
1531
+ }
1532
+ return params;
1533
+ }
1534
+ function referenceQueryParams(symbol, limit) {
1535
+ const params = [symbol.symbolId];
1536
+ if (typeof limit === "number") {
1537
+ params.push(limit);
1538
+ }
1539
+ return params;
1540
+ }
1541
+ function findEnclosingDefinition(definitions, line) {
1542
+ let best = null;
1543
+ for (const definition of definitions) {
1544
+ if (definition.startLine > line || definition.endLine < line) continue;
1545
+ if (!best || definition.endLine - definition.startLine < best.endLine - best.startLine) {
1546
+ best = definition;
1547
+ }
1548
+ }
1549
+ return best;
1550
+ }
1551
+ function getPythonSourceCalleeRows(db, symbol, limit) {
1552
+ const match = getFullSymbolMatch(db, symbol);
1553
+ if (!match || !isPythonDocument(db, match.relativePath)) {
1554
+ return [];
1555
+ }
1556
+ const definitions = getDefinitionsForFile(db, match.relativePath);
1557
+ const current = definitions.find((definition) => definition.symbolId === match.symbolId);
1558
+ if (!current) {
1559
+ return [];
1560
+ }
1561
+ const imports = getSourceImports(db, match.relativePath);
1562
+ const bindings = new Map(
1563
+ getSourceConstructorBindings(db, match.relativePath, {
1564
+ startLine: match.startLine,
1565
+ endLine: match.endLine
1566
+ }).map((binding) => [binding.localName, binding.typeName])
1567
+ );
1568
+ const rows = [];
1569
+ const seen = /* @__PURE__ */ new Set();
1570
+ for (const call of getSourceCalls(db, match.relativePath, {
1571
+ startLine: match.startLine,
1572
+ endLine: match.endLine
1573
+ })) {
1574
+ const resolved = resolvePythonCallTarget(
1575
+ db,
1576
+ current,
1577
+ definitions,
1578
+ imports,
1579
+ bindings,
1580
+ call.receiverName,
1581
+ call.calleeName
1582
+ );
1583
+ if (!resolved || resolved.symbolId === match.symbolId || db.isIgnored(resolved.relativePath)) continue;
1584
+ const chunkId = 1e9 + call.line;
1585
+ const key = `${resolved.symbol}|${resolved.relativePath}|${chunkId}`;
1586
+ if (seen.has(key)) continue;
1587
+ seen.add(key);
1588
+ rows.push({
1589
+ symbol: resolved.symbol,
1590
+ file: resolved.relativePath,
1591
+ chunkId
1592
+ });
1593
+ }
1594
+ return applyLimit(rows, limit);
1595
+ }
1596
+ function getJavaScriptSourceCalleeRows(db, symbol, limit) {
1597
+ const match = getFullSymbolMatch(db, symbol);
1598
+ if (!match || !isJavaScriptDocument(db, match.relativePath)) {
1599
+ return [];
1600
+ }
1601
+ const definitions = getDefinitionsForFile(db, match.relativePath);
1602
+ const current = definitions.find((definition) => definition.symbolId === match.symbolId);
1603
+ if (!current) {
1604
+ return [];
1605
+ }
1606
+ const imports = getSourceImports(db, match.relativePath);
1607
+ const bindings = new Map(
1608
+ getSourceConstructorBindings(db, match.relativePath, {
1609
+ startLine: match.startLine,
1610
+ endLine: match.endLine
1611
+ }).map((binding) => [binding.localName, binding.typeName])
1612
+ );
1613
+ const rows = [];
1614
+ const seen = /* @__PURE__ */ new Set();
1615
+ for (const call of getSourceCalls(db, match.relativePath, {
1616
+ startLine: match.startLine,
1617
+ endLine: match.endLine
1618
+ })) {
1619
+ const resolved = resolveJavaScriptCallTarget(
1620
+ db,
1621
+ current,
1622
+ definitions,
1623
+ imports,
1624
+ bindings,
1625
+ call.receiverName,
1626
+ call.calleeName
1627
+ );
1628
+ if (!resolved || resolved.symbolId === match.symbolId || db.isIgnored(resolved.relativePath)) continue;
1629
+ const chunkId = 1e9 + call.line;
1630
+ const key = `${resolved.symbol}|${resolved.relativePath}|${chunkId}`;
1631
+ if (seen.has(key)) continue;
1632
+ seen.add(key);
1633
+ rows.push({
1634
+ symbol: resolved.symbol,
1635
+ file: resolved.relativePath,
1636
+ chunkId
1637
+ });
1638
+ }
1639
+ return applyLimit(rows, limit);
1640
+ }
1641
+ function getJavaSourceCalleeRows(db, symbol, limit) {
1642
+ const match = getFullSymbolMatch(db, symbol);
1643
+ if (!match || !isJavaDocument(db, match.relativePath)) {
1644
+ return [];
1645
+ }
1646
+ const calls = getSimpleSourceCalls(db, match.relativePath, match.startLine, match.endLine);
1647
+ const bindings = parseJavaFieldBindings(getSourceText(db, match.relativePath));
1648
+ return resolveSimpleSourceCallees(db, match, calls, bindings, limit);
1649
+ }
1650
+ function getKotlinSourceCalleeRows(db, symbol, limit) {
1651
+ const match = getFullSymbolMatch(db, symbol);
1652
+ if (!match || !isKotlinDocument(db, match.relativePath)) {
1653
+ return [];
1654
+ }
1655
+ const calls = getSimpleSourceCalls(db, match.relativePath, match.startLine, match.endLine);
1656
+ const bindings = parseKotlinFieldBindings(getSourceText(db, match.relativePath));
1657
+ return resolveSimpleSourceCallees(db, match, calls, bindings, limit);
1658
+ }
1659
+ function getScalaSourceCalleeRows(db, symbol, limit) {
1660
+ const match = getFullSymbolMatch(db, symbol);
1661
+ if (!match || !isScalaDocument(db, match.relativePath)) {
1662
+ return [];
1663
+ }
1664
+ const calls = getSimpleSourceCalls(db, match.relativePath, match.startLine, match.endLine);
1665
+ return resolveSimpleSourceCallees(db, match, calls, /* @__PURE__ */ new Map(), limit);
1666
+ }
1667
+ function getCSharpSourceCalleeRows(db, symbol, limit) {
1668
+ const match = getFullSymbolMatch(db, symbol);
1669
+ if (!match || !isCSharpDocument(db, match.relativePath)) {
1670
+ return [];
1671
+ }
1672
+ const calls = getSimpleSourceCalls(db, match.relativePath, match.startLine, match.endLine);
1673
+ return resolveSimpleSourceCallees(db, match, calls, /* @__PURE__ */ new Map(), limit);
1674
+ }
1675
+ function getVisualBasicSourceCalleeRows(db, symbol, limit) {
1676
+ const match = getFullSymbolMatch(db, symbol);
1677
+ if (!match || !isVisualBasicDocument(db, match.relativePath)) {
1678
+ return [];
1679
+ }
1680
+ const calls = getSimpleSourceCalls(db, match.relativePath, match.startLine, match.endLine);
1681
+ return resolveSimpleSourceCallees(db, match, calls, /* @__PURE__ */ new Map(), limit);
1682
+ }
1683
+ function getCppSourceCalleeRows(db, symbol, limit) {
1684
+ const match = getFullSymbolMatch(db, symbol);
1685
+ if (!match || !isCppDocument(db, match.relativePath)) {
1686
+ return [];
1687
+ }
1688
+ const calls = getSimpleSourceCalls(db, match.relativePath, match.startLine, match.endLine);
1689
+ const bindings = parseCppReceiverBindings(getSourceText(db, match.relativePath));
1690
+ return resolveSimpleSourceCallees(db, match, calls, bindings, limit);
1691
+ }
1692
+ function getRustSourceCalleeRows(db, symbol, limit) {
1693
+ const match = getFullSymbolMatch(db, symbol);
1694
+ if (!match || !isRustDocument(db, match.relativePath)) {
1695
+ return [];
1696
+ }
1697
+ const calls = getSimpleSourceCalls(db, match.relativePath, match.startLine, match.endLine);
1698
+ return resolveSimpleSourceCallees(db, match, calls, /* @__PURE__ */ new Map(), limit);
1699
+ }
1700
+ function getRubySourceCalleeRows(db, symbol, limit) {
1701
+ const match = getFullSymbolMatch(db, symbol);
1702
+ if (!match || !isRubyDocument(db, match.relativePath)) {
1703
+ return [];
1704
+ }
1705
+ const calls = getSimpleSourceCalls(db, match.relativePath, match.startLine, match.endLine, { allowInstanceVariables: true });
1706
+ const rubyCalls = getSimpleSourceCalls(db, match.relativePath, match.startLine, match.endLine, {
1707
+ allowInstanceVariables: true,
1708
+ allowBareMemberCalls: true
1709
+ });
1710
+ const bindings = parseRubyReceiverBindings(db, getSourceText(db, match.relativePath));
1711
+ return resolveSimpleSourceCallees(db, match, rubyCalls.length > 0 ? rubyCalls : calls, bindings, limit);
1712
+ }
1713
+ function getDartSourceCalleeRows(db, symbol, limit) {
1714
+ const match = getFullSymbolMatch(db, symbol);
1715
+ if (!match || !isDartDocument(db, match.relativePath)) {
1716
+ return [];
1717
+ }
1718
+ const calls = getSimpleSourceCalls(db, match.relativePath, match.startLine, match.endLine);
1719
+ return resolveSimpleSourceCallees(db, match, calls, /* @__PURE__ */ new Map(), limit);
1720
+ }
1721
+ function getPhpSourceCalleeRows(db, symbol, limit) {
1722
+ const match = getFullSymbolMatch(db, symbol);
1723
+ if (!match || !isPhpDocument(db, match.relativePath)) {
1724
+ return [];
1725
+ }
1726
+ const calls = getSimpleSourceCalls(db, match.relativePath, match.startLine, match.endLine);
1727
+ return resolveSimpleSourceCallees(db, match, calls, /* @__PURE__ */ new Map(), limit);
1728
+ }
1729
+ function getSourceBackedCalleeRows(db, symbol, limit) {
1730
+ const match = getFullSymbolMatch(db, symbol);
1731
+ if (!match) {
1732
+ return [];
1733
+ }
1734
+ if (isPythonDocument(db, match.relativePath)) {
1735
+ return getPythonSourceCalleeRows(db, match, limit);
1736
+ }
1737
+ if (isJavaScriptDocument(db, match.relativePath)) {
1738
+ return getJavaScriptSourceCalleeRows(db, match, limit);
1739
+ }
1740
+ if (isJavaDocument(db, match.relativePath)) {
1741
+ return getJavaSourceCalleeRows(db, match, limit);
1742
+ }
1743
+ if (isScalaDocument(db, match.relativePath)) {
1744
+ return getScalaSourceCalleeRows(db, match, limit);
1745
+ }
1746
+ if (isKotlinDocument(db, match.relativePath)) {
1747
+ return getKotlinSourceCalleeRows(db, match, limit);
1748
+ }
1749
+ if (isCSharpDocument(db, match.relativePath)) {
1750
+ return getCSharpSourceCalleeRows(db, match, limit);
1751
+ }
1752
+ if (isVisualBasicDocument(db, match.relativePath)) {
1753
+ return getVisualBasicSourceCalleeRows(db, match, limit);
1754
+ }
1755
+ if (isCppDocument(db, match.relativePath)) {
1756
+ return getCppSourceCalleeRows(db, match, limit);
1757
+ }
1758
+ if (isRustDocument(db, match.relativePath)) {
1759
+ return getRustSourceCalleeRows(db, match, limit);
1760
+ }
1761
+ if (isRubyDocument(db, match.relativePath)) {
1762
+ return getRubySourceCalleeRows(db, match, limit);
1763
+ }
1764
+ if (isDartDocument(db, match.relativePath)) {
1765
+ return getDartSourceCalleeRows(db, match, limit);
1766
+ }
1767
+ if (isPhpDocument(db, match.relativePath)) {
1768
+ return getPhpSourceCalleeRows(db, match, limit);
1769
+ }
1770
+ return [];
1771
+ }
1772
+ function getPythonSourceCallerRows(db, target, limit) {
1773
+ if (!isPythonDocument(db, target.relativePath)) {
1774
+ return [];
1775
+ }
1776
+ const rows = [];
1777
+ const seen = /* @__PURE__ */ new Set();
1778
+ for (const candidate of getAllFunctionLikeDefinitions(db)) {
1779
+ if (candidate.symbolId === target.symbolId) continue;
1780
+ const callees = getPythonSourceCalleeRows(db, candidate);
1781
+ if (!callees.some((callee) => callee.symbol === target.symbol)) continue;
1782
+ const key = `${candidate.symbol}|${candidate.relativePath}`;
1783
+ if (seen.has(key) || db.isIgnored(candidate.relativePath)) continue;
1784
+ seen.add(key);
1785
+ rows.push({
1786
+ symbol: candidate.symbol,
1787
+ file: candidate.relativePath
1788
+ });
1789
+ if (typeof limit === "number" && rows.length >= limit) {
1790
+ break;
1791
+ }
1792
+ }
1793
+ return rows;
1794
+ }
1795
+ function getDefinitionRowsForSymbolId(db, symbolId) {
1796
+ const primary = db.all(
1797
+ `SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name
1798
+ FROM global_symbols gs
1799
+ JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
1800
+ JOIN documents d ON der.document_id = d.id
1801
+ WHERE gs.id = ?
1802
+ ORDER BY der.start_line, der.end_line`,
1803
+ symbolId
1804
+ );
1805
+ if (primary.length > 0) {
1806
+ return primary;
1807
+ }
1808
+ return db.all(
1809
+ `SELECT
1810
+ gs.id,
1811
+ gs.symbol,
1812
+ c.document_id,
1813
+ MIN(c.start_line) AS start_line,
1814
+ MAX(c.end_line) AS end_line,
1815
+ d.relative_path,
1816
+ gs.display_name
1817
+ FROM global_symbols gs
1818
+ JOIN mentions m ON m.symbol_id = gs.id
1819
+ JOIN chunks c ON m.chunk_id = c.id
1820
+ JOIN documents d ON c.document_id = d.id
1821
+ WHERE gs.id = ?
1822
+ AND m.role = 1
1823
+ ${db.pathExclusionsFor("d")}
1824
+ GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name
1825
+ ORDER BY start_line, end_line`,
1826
+ symbolId
1827
+ );
1828
+ }
1829
+ function getFullSymbolMatch(db, symbol) {
1830
+ if ("symbol" in symbol && "relativePath" in symbol) {
1831
+ return symbol;
1832
+ }
1833
+ const row = getDefinitionRowsForSymbolId(db, symbol.symbolId)[0];
1834
+ if (!row) {
1835
+ return null;
1836
+ }
1837
+ return hydrateSymbolMatch(db, row);
1838
+ }
1839
+ function getDefinitionsForFile(db, relativePath) {
1840
+ let cache = FILE_DEFINITION_CACHE.get(db);
1841
+ if (!cache) {
1842
+ cache = /* @__PURE__ */ new Map();
1843
+ FILE_DEFINITION_CACHE.set(db, cache);
1844
+ }
1845
+ const cached = cache.get(relativePath);
1846
+ if (cached) {
1847
+ return cached;
1848
+ }
1849
+ const primary = db.all(
1850
+ `SELECT
1851
+ gs.id,
1852
+ gs.symbol,
1853
+ der.document_id,
1854
+ der.start_line,
1855
+ der.end_line,
1856
+ d.relative_path,
1857
+ gs.display_name,
1858
+ gs.kind,
1859
+ gs.documentation,
1860
+ gs.enclosing_symbol
1861
+ FROM global_symbols gs
1862
+ JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
1863
+ JOIN documents d ON der.document_id = d.id
1864
+ WHERE d.relative_path = ?
1865
+ ${db.symbolNoiseFor("gs")}
1866
+ ORDER BY der.start_line, der.end_line`,
1867
+ relativePath
1868
+ );
1869
+ const fallback = primary.length > 0 ? [] : db.all(
1870
+ `SELECT
1871
+ gs.id,
1872
+ gs.symbol,
1873
+ c.document_id,
1874
+ MIN(c.start_line) AS start_line,
1875
+ MAX(c.end_line) AS end_line,
1876
+ d.relative_path,
1877
+ gs.display_name,
1878
+ gs.kind,
1879
+ gs.documentation,
1880
+ gs.enclosing_symbol
1881
+ FROM global_symbols gs
1882
+ JOIN mentions m ON m.symbol_id = gs.id
1883
+ JOIN chunks c ON m.chunk_id = c.id
1884
+ JOIN documents d ON c.document_id = d.id
1885
+ WHERE d.relative_path = ?
1886
+ AND m.role = 1
1887
+ ${db.symbolNoiseFor("gs")}
1888
+ GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
1889
+ ORDER BY start_line, end_line`,
1890
+ relativePath
1891
+ );
1892
+ const definitions = correctDefinitionRangesFromSource(
1893
+ db,
1894
+ relativePath,
1895
+ (primary.length > 0 ? primary : fallback).map((row) => ({
1896
+ symbolId: row.id,
1897
+ symbol: row.symbol,
1898
+ documentId: row.document_id,
1899
+ startLine: row.start_line,
1900
+ endLine: row.end_line,
1901
+ relativePath: row.relative_path,
1902
+ leaf: leafName(row.symbol),
1903
+ parentTypeName: parentTypeName(row.symbol),
1904
+ isFunctionLike: isFunctionLikeSymbol(row.symbol),
1905
+ isTypeLike: leafSuffix(row.symbol) === "type",
1906
+ kind: row.kind ?? null,
1907
+ documentation: row.documentation ?? null,
1908
+ enclosingSymbol: row.enclosing_symbol ?? null
1909
+ }))
1910
+ );
1911
+ cache.set(relativePath, definitions);
1912
+ return definitions;
1913
+ }
1914
+ function hydrateSymbolMatch(db, row) {
1915
+ const corrected = getDefinitionsForFile(db, row.relative_path).find((definition) => definition.symbolId === row.id);
1916
+ if (corrected) {
1917
+ return {
1918
+ symbolId: corrected.symbolId,
1919
+ symbol: corrected.symbol,
1920
+ documentId: corrected.documentId,
1921
+ startLine: corrected.startLine,
1922
+ endLine: corrected.endLine,
1923
+ relativePath: corrected.relativePath
1924
+ };
1925
+ }
1926
+ return {
1927
+ symbolId: row.id,
1928
+ symbol: row.symbol,
1929
+ documentId: row.document_id,
1930
+ startLine: row.start_line,
1931
+ endLine: row.end_line,
1932
+ relativePath: row.relative_path
1933
+ };
1934
+ }
1935
+ function findDirectSymbolCandidate(candidates, symbolPattern, cleanedPattern) {
1936
+ const trimmed = symbolPattern.trim();
1937
+ const directMatches = candidates.filter((row) => {
1938
+ const short = shortenSymbol(row.symbol);
1939
+ const display = (row.display_name ?? "").trim();
1940
+ return row.symbol === trimmed || short === trimmed || short === cleanedPattern || display === trimmed || display === cleanedPattern || `${display}()` === trimmed || row.relative_path === trimmed;
1941
+ });
1942
+ if (directMatches.length === 0) {
1943
+ return null;
1944
+ }
1945
+ directMatches.sort(
1946
+ (left, right) => left.end_line - left.start_line - (right.end_line - right.start_line) || left.relative_path.localeCompare(right.relative_path) || left.symbol.localeCompare(right.symbol)
1947
+ );
1948
+ return directMatches[0] ?? null;
1949
+ }
1950
+ function correctDefinitionRangesFromSource(db, relativePath, definitions) {
1951
+ const source = getSourceText(db, relativePath);
1952
+ if (!source) {
1953
+ return definitions;
1954
+ }
1955
+ const lines = source.split(/\r?\n/);
1956
+ const correctedStarts = /* @__PURE__ */ new Map();
1957
+ for (const definition of definitions) {
1958
+ correctedStarts.set(
1959
+ definition.symbolId,
1960
+ resolveCallableDefinitionStartLine(lines, definition)
1961
+ );
1962
+ }
1963
+ const correctedRanges = /* @__PURE__ */ new Map();
1964
+ const callableDefinitions = definitions.filter((definition) => isCallableDefinition(definition.symbol)).map((definition) => ({
1965
+ definition,
1966
+ startLine: correctedStarts.get(definition.symbolId) ?? definition.startLine
1967
+ })).sort(
1968
+ (left, right) => left.startLine - right.startLine || left.definition.startLine - right.definition.startLine || left.definition.symbol.localeCompare(right.definition.symbol)
1969
+ );
1970
+ for (let index = 0; index < callableDefinitions.length; index += 1) {
1971
+ const current = callableDefinitions[index];
1972
+ const next = callableDefinitions[index + 1];
1973
+ const maxEndLine = next ? Math.max(current.startLine, next.startLine - 1) : lines.length - 1;
1974
+ correctedRanges.set(current.definition.symbolId, {
1975
+ startLine: current.startLine,
1976
+ endLine: resolveCallableDefinitionEndLine(
1977
+ lines,
1978
+ current.definition,
1979
+ current.startLine,
1980
+ maxEndLine
1981
+ )
1982
+ });
1983
+ }
1984
+ return definitions.map((definition) => {
1985
+ const corrected = correctedRanges.get(definition.symbolId);
1986
+ if (!corrected) {
1987
+ return definition;
1988
+ }
1989
+ return {
1990
+ ...definition,
1991
+ startLine: corrected.startLine,
1992
+ endLine: corrected.endLine
1993
+ };
1994
+ });
1995
+ }
1996
+ function resolveCallableDefinitionStartLine(lines, definition) {
1997
+ if (!isCallableDefinition(definition.symbol)) {
1998
+ return definition.startLine;
1999
+ }
2000
+ const escapedLeaf = escapeRegex2(definition.leaf);
2001
+ const strongPatterns = [
2002
+ new RegExp(`\\b(?:function|def|fn)\\s+${escapedLeaf}\\b`),
2003
+ new RegExp(`\\b${escapedLeaf}\\b\\s*[:=]\\s*(?:async\\s*)?(?:function\\b|\\()`)
2004
+ ];
2005
+ const fallbackPatterns = [
2006
+ new RegExp(`\\b${escapedLeaf}\\b\\s*\\(`)
2007
+ ];
2008
+ return findNearestMatchingLine(
2009
+ lines,
2010
+ [...strongPatterns, ...fallbackPatterns],
2011
+ definition.startLine,
2012
+ definition.endLine
2013
+ );
2014
+ }
2015
+ function findNearestMatchingLine(lines, patterns, preferredStartLine, preferredEndLine) {
2016
+ const windowStart = Math.max(0, preferredStartLine - 40);
2017
+ const windowEnd = Math.min(lines.length - 1, Math.max(preferredEndLine + 40, preferredStartLine + 5));
2018
+ const windowMatch = matchNearestLine(lines, patterns, preferredStartLine, windowStart, windowEnd);
2019
+ if (windowMatch !== null) {
2020
+ return windowMatch;
2021
+ }
2022
+ const fullMatch = matchNearestLine(lines, patterns, preferredStartLine, 0, lines.length - 1);
2023
+ return fullMatch ?? Math.max(0, Math.min(preferredStartLine, lines.length - 1));
2024
+ }
2025
+ function matchNearestLine(lines, patterns, preferredLine, startLine, endLine) {
2026
+ let best = null;
2027
+ for (let lineIndex = startLine; lineIndex <= endLine; lineIndex += 1) {
2028
+ const line = lines[lineIndex] ?? "";
2029
+ if (!patterns.some((pattern) => pattern.test(line))) continue;
2030
+ const distance = Math.abs(lineIndex - preferredLine);
2031
+ if (!best || distance < best.distance) {
2032
+ best = { line: lineIndex, distance };
2033
+ }
2034
+ }
2035
+ return best?.line ?? null;
2036
+ }
2037
+ function resolveCallableDefinitionEndLine(lines, definition, startLine, maxEndLine) {
2038
+ const boundedEndLine = Math.max(startLine, Math.min(lines.length - 1, maxEndLine));
2039
+ const fallbackEndLine = Math.max(startLine, Math.min(boundedEndLine, definition.endLine));
2040
+ let braceDepth = 0;
2041
+ let parenDepth = 0;
2042
+ let sawOpeningBrace = false;
2043
+ for (let lineIndex = startLine; lineIndex <= boundedEndLine; lineIndex += 1) {
2044
+ const masked = maskStructuralLine(lines[lineIndex] ?? "");
2045
+ for (const char of masked) {
2046
+ if (char === "{") {
2047
+ braceDepth += 1;
2048
+ sawOpeningBrace = true;
2049
+ } else if (char === "}") {
2050
+ braceDepth = Math.max(0, braceDepth - 1);
2051
+ } else if (char === "(") {
2052
+ parenDepth += 1;
2053
+ } else if (char === ")") {
2054
+ parenDepth = Math.max(0, parenDepth - 1);
2055
+ }
2056
+ }
2057
+ if (sawOpeningBrace && braceDepth === 0) {
2058
+ return lineIndex;
2059
+ }
2060
+ if (!sawOpeningBrace && parenDepth === 0 && lineIndex >= fallbackEndLine) {
2061
+ return lineIndex;
2062
+ }
2063
+ }
2064
+ return fallbackEndLine;
2065
+ }
2066
+ function maskStructuralLine(line) {
2067
+ let masked = "";
2068
+ let quote = null;
2069
+ let escaping = false;
2070
+ for (let index = 0; index < line.length; index += 1) {
2071
+ const char = line[index];
2072
+ const next = line[index + 1];
2073
+ if (!quote && char === "/" && next === "/") {
2074
+ masked += " ".repeat(line.length - index);
2075
+ break;
2076
+ }
2077
+ if (quote) {
2078
+ if (escaping) {
2079
+ escaping = false;
2080
+ masked += " ";
2081
+ continue;
2082
+ }
2083
+ if (char === "\\") {
2084
+ escaping = true;
2085
+ masked += " ";
2086
+ continue;
2087
+ }
2088
+ if (char === quote) {
2089
+ quote = null;
2090
+ }
2091
+ masked += " ";
2092
+ continue;
2093
+ }
2094
+ if (char === '"' || char === "'" || char === "`") {
2095
+ quote = char;
2096
+ masked += " ";
2097
+ continue;
2098
+ }
2099
+ masked += char;
2100
+ }
2101
+ return masked;
2102
+ }
2103
+ function isCallableDefinition(symbol) {
2104
+ return symbol.includes("().");
2105
+ }
2106
+ function escapeRegex2(value) {
2107
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2108
+ }
2109
+ function getAllDefinitions(db, opts = {}) {
2110
+ const { scope } = opts;
2111
+ const rows = db.all(
2112
+ `SELECT relative_path
2113
+ FROM documents
2114
+ WHERE 1 = 1
2115
+ ${db.pathExclusionsFor("documents")}
2116
+ ${scope ? "AND relative_path LIKE ?" : ""}
2117
+ ORDER BY relative_path`,
2118
+ ...scope ? [`%${scope}%`] : []
2119
+ );
2120
+ return rows.filter((row) => !db.isIgnored(row.relative_path)).flatMap((row) => getDefinitionsForFile(db, row.relative_path));
2121
+ }
2122
+ function getAllFunctionLikeDefinitions(db) {
2123
+ return getAllDefinitions(db).filter((definition) => definition.isFunctionLike);
2124
+ }
2125
+ function resolvePythonCallTarget(db, current, currentFileDefinitions, imports, constructorBindings, receiverName, calleeName) {
2126
+ if (receiverName === "self" || receiverName === "cls") {
2127
+ return findDefinitionByName(currentFileDefinitions, calleeName, current.parentTypeName, ["function"]);
2128
+ }
2129
+ if (receiverName) {
2130
+ const inferredType = constructorBindings.get(receiverName);
2131
+ if (inferredType) {
2132
+ const boundMethod = findDefinitionByName(currentFileDefinitions, calleeName, inferredType, ["function"]);
2133
+ if (boundMethod) {
2134
+ return boundMethod;
2135
+ }
2136
+ for (const entry of imports) {
2137
+ if (entry.localName !== inferredType || !entry.sourcePath) continue;
2138
+ const importedDefinitions = getDefinitionsForFile(db, entry.sourcePath);
2139
+ const importedMethod = findDefinitionByName(importedDefinitions, calleeName, entry.importedName, ["function"]);
2140
+ if (importedMethod) {
2141
+ return importedMethod;
2142
+ }
2143
+ }
2144
+ }
2145
+ const localClassMethod = findDefinitionByName(currentFileDefinitions, calleeName, receiverName, ["function"]);
2146
+ if (localClassMethod) {
2147
+ return localClassMethod;
2148
+ }
2149
+ const namespaceImport = imports.find((entry) => entry.localName === receiverName && entry.sourcePath);
2150
+ if (namespaceImport?.sourcePath) {
2151
+ const importedDefinitions = getDefinitionsForFile(db, namespaceImport.sourcePath);
2152
+ const importedTypeMethod = namespaceImport.kind === "named" ? findDefinitionByName(importedDefinitions, calleeName, namespaceImport.importedName, ["function"]) : null;
2153
+ if (importedTypeMethod) {
2154
+ return importedTypeMethod;
2155
+ }
2156
+ return findDefinitionByName(importedDefinitions, calleeName, null, ["function", "type"]);
2157
+ }
2158
+ return null;
2159
+ }
2160
+ const importedBinding = imports.find((entry) => entry.localName === calleeName && entry.sourcePath);
2161
+ if (importedBinding?.sourcePath) {
2162
+ const importedDefinitions = getDefinitionsForFile(db, importedBinding.sourcePath);
2163
+ const importedName = importedBinding.importedName === "*" ? calleeName : importedBinding.importedName;
2164
+ const importedDefinition = findDefinitionByName(importedDefinitions, importedName, null, ["function", "type"]);
2165
+ if (importedDefinition) {
2166
+ return importedDefinition;
2167
+ }
2168
+ }
2169
+ return findDefinitionByName(currentFileDefinitions, calleeName, null, ["function", "type"]);
2170
+ }
2171
+ function resolveJavaScriptCallTarget(db, current, currentFileDefinitions, imports, constructorBindings, receiverName, calleeName) {
2172
+ if (receiverName === "this") {
2173
+ return findDefinitionByName(currentFileDefinitions, calleeName, current.parentTypeName, ["function"]);
2174
+ }
2175
+ if (receiverName) {
2176
+ const inferredType = constructorBindings.get(receiverName);
2177
+ if (inferredType) {
2178
+ const boundMethod = findDefinitionByName(currentFileDefinitions, calleeName, inferredType, ["function"]);
2179
+ if (boundMethod) {
2180
+ return boundMethod;
2181
+ }
2182
+ for (const entry of imports) {
2183
+ if (entry.localName !== inferredType || !entry.sourcePath) continue;
2184
+ const importedDefinitions = getDefinitionsForFile(db, entry.sourcePath);
2185
+ const importedMethod = findDefinitionByName(importedDefinitions, calleeName, entry.importedName, ["function"]);
2186
+ if (importedMethod) {
2187
+ return importedMethod;
2188
+ }
2189
+ }
2190
+ }
2191
+ const localClassMethod = findDefinitionByName(currentFileDefinitions, calleeName, receiverName, ["function"]);
2192
+ if (localClassMethod) {
2193
+ return localClassMethod;
2194
+ }
2195
+ const namespaceImport = imports.find((entry) => entry.localName === receiverName && entry.sourcePath);
2196
+ if (namespaceImport?.sourcePath) {
2197
+ const importedDefinitions = getDefinitionsForFile(db, namespaceImport.sourcePath);
2198
+ if (namespaceImport.kind === "named" || namespaceImport.kind === "default") {
2199
+ const importedTypeMethod = findDefinitionByName(
2200
+ importedDefinitions,
2201
+ calleeName,
2202
+ namespaceImport.importedName,
2203
+ ["function"]
2204
+ );
2205
+ if (importedTypeMethod) {
2206
+ return importedTypeMethod;
2207
+ }
2208
+ }
2209
+ return findDefinitionByName(importedDefinitions, calleeName, null, ["function", "type"]);
2210
+ }
2211
+ return null;
2212
+ }
2213
+ const importedBinding = imports.find((entry) => entry.localName === calleeName && entry.sourcePath && entry.kind !== "namespace");
2214
+ if (importedBinding?.sourcePath) {
2215
+ const importedDefinitions = getDefinitionsForFile(db, importedBinding.sourcePath);
2216
+ const importedName = importedBinding.importedName === "default" ? importedBinding.localName ?? calleeName : importedBinding.importedName;
2217
+ const importedDefinition = findDefinitionByName(importedDefinitions, importedName, null, ["function", "type"]);
2218
+ if (importedDefinition) {
2219
+ return importedDefinition;
2220
+ }
2221
+ }
2222
+ return findDefinitionByName(currentFileDefinitions, calleeName, null, ["function", "type"]);
2223
+ }
2224
+ function resolveSimpleSourceCallees(db, current, calls, bindings, limit) {
2225
+ const currentFileDefinitions = getDefinitionsForFile(db, current.relativePath);
2226
+ const currentDefinition = currentFileDefinitions.find((definition) => definition.symbolId === current.symbolId);
2227
+ if (!currentDefinition) {
2228
+ return [];
2229
+ }
2230
+ const rows = [];
2231
+ const seen = /* @__PURE__ */ new Set();
2232
+ for (const call of calls) {
2233
+ const resolved = resolveSimpleSourceCallTarget(
2234
+ db,
2235
+ currentDefinition,
2236
+ currentFileDefinitions,
2237
+ bindings,
2238
+ call.receiverName,
2239
+ call.calleeName
2240
+ );
2241
+ if (!resolved || resolved.symbolId === current.symbolId || db.isIgnored(resolved.relativePath)) continue;
2242
+ const chunkId = 2e9 + call.line;
2243
+ const key = `${resolved.symbol}|${resolved.relativePath}|${chunkId}`;
2244
+ if (seen.has(key)) continue;
2245
+ seen.add(key);
2246
+ rows.push({
2247
+ symbol: resolved.symbol,
2248
+ file: resolved.relativePath,
2249
+ chunkId
2250
+ });
2251
+ }
2252
+ return applyLimit(rows, limit);
2253
+ }
2254
+ function resolveSimpleSourceCallTarget(db, current, currentFileDefinitions, bindings, receiverName, calleeName) {
2255
+ if (!receiverName) {
2256
+ const localMethod = findDefinitionByName(currentFileDefinitions, calleeName, current.parentTypeName, ["function"]);
2257
+ if (localMethod) {
2258
+ return localMethod;
2259
+ }
2260
+ if (current.parentTypeName) {
2261
+ return findProjectDefinitionByTypeAndLeaf(db, current.parentTypeName, calleeName);
2262
+ }
2263
+ return findDefinitionByName(currentFileDefinitions, calleeName, null, ["function", "type"]);
2264
+ }
2265
+ const normalizedReceiver = normalizeReceiverName(receiverName);
2266
+ const inferredType = bindings.get(normalizedReceiver) ?? inferTypeNameFromReceiver(db, normalizedReceiver);
2267
+ if (!inferredType) {
2268
+ return null;
2269
+ }
2270
+ return findProjectDefinitionByTypeAndLeaf(db, inferredType, calleeName);
2271
+ }
2272
+ function findProjectDefinitionByTypeAndLeaf(db, typeName, calleeName) {
2273
+ const definitions = getAllDefinitions(db).filter((definition) => definition.isFunctionLike || definition.symbol.endsWith("()."));
2274
+ const exact = definitions.find((definition) => definition.leaf === calleeName && (definition.parentTypeName === typeName || definition.symbol.includes(typeName)));
2275
+ if (exact) {
2276
+ return exact;
2277
+ }
2278
+ const normalizedType = normalizeLookupName(typeName);
2279
+ const normalizedMatch = definitions.find((definition) => definition.leaf === calleeName && normalizeLookupName(definition.parentTypeName ?? "").includes(normalizedType));
2280
+ if (normalizedMatch) {
2281
+ return normalizedMatch;
2282
+ }
2283
+ return findLooseProjectDefinitionByTypeAndLeaf(db, typeName, calleeName);
2284
+ }
2285
+ function inferTypeNameFromReceiver(db, receiverName) {
2286
+ const normalizedReceiver = normalizeLookupName(receiverName);
2287
+ if (!normalizedReceiver) {
2288
+ return null;
2289
+ }
2290
+ const candidates = getAllDefinitions(db).filter((definition) => definition.isTypeLike || definition.symbol.endsWith("#")).map((definition) => definition.leaf).filter((leaf) => leaf.length > 0);
2291
+ let best = null;
2292
+ for (const candidate of candidates) {
2293
+ const normalizedCandidate = normalizeLookupName(candidate);
2294
+ let score = 0;
2295
+ if (normalizedCandidate === normalizedReceiver) score += 100;
2296
+ if (normalizedCandidate.endsWith(normalizedReceiver)) score += 80;
2297
+ if (normalizedCandidate.includes(normalizedReceiver)) score += 40;
2298
+ if (normalizedReceiver.includes(normalizedCandidate)) score += 20;
2299
+ if (score > 0 && (!best || score > best.score || score === best.score && candidate.length < best.name.length)) {
2300
+ best = { name: candidate, score };
2301
+ }
2302
+ }
2303
+ return best?.name ?? null;
2304
+ }
2305
+ function getSimpleSourceCalls(db, relativePath, startLine, endLine, opts = {}) {
2306
+ const source = getSourceText(db, relativePath);
2307
+ if (!source) {
2308
+ return [];
2309
+ }
2310
+ const lines = source.split("\n");
2311
+ const scoped = lines.slice(startLine, endLine + 1);
2312
+ const calls = [];
2313
+ const seen = /* @__PURE__ */ new Set();
2314
+ const pattern = opts.allowInstanceVariables ? /(@?[A-Za-z_][\w]*)\s*(?:\.|::)\s*([A-Za-z_][\w!?=]*)\s*\(/g : /\b([A-Za-z_][\w]*)\s*(?:\.|::)\s*([A-Za-z_][\w]*)\s*\(/g;
2315
+ for (let index = 0; index < scoped.length; index++) {
2316
+ const rawLine = scoped[index] ?? "";
2317
+ for (const match of rawLine.matchAll(pattern)) {
2318
+ const receiverName = match[1];
2319
+ const calleeName = match[2];
2320
+ if (!receiverName || !calleeName) continue;
2321
+ const key = `${startLine + index}|${receiverName}|${calleeName}`;
2322
+ if (seen.has(key)) continue;
2323
+ seen.add(key);
2324
+ calls.push({
2325
+ receiverName,
2326
+ calleeName,
2327
+ line: startLine + index
2328
+ });
2329
+ }
2330
+ if (opts.allowBareMemberCalls) {
2331
+ for (const match of rawLine.matchAll(/(@?[A-Za-z_][\w]*)\s*\.\s*([A-Za-z_][\w!?=]*)\b(?!\s*[:=])/g)) {
2332
+ const receiverName = match[1];
2333
+ const calleeName = match[2];
2334
+ if (!receiverName || !calleeName) continue;
2335
+ const key = `${startLine + index}|${receiverName}|${calleeName}`;
2336
+ if (seen.has(key)) continue;
2337
+ seen.add(key);
2338
+ calls.push({
2339
+ receiverName,
2340
+ calleeName,
2341
+ line: startLine + index
2342
+ });
2343
+ }
2344
+ }
2345
+ for (const match of rawLine.matchAll(/\b([A-Za-z_][\w]*)\s*\(/g)) {
2346
+ const calleeName = match[1];
2347
+ const start = match.index ?? -1;
2348
+ if (!calleeName || start < 0) continue;
2349
+ const prefix = rawLine.slice(0, start).trimEnd();
2350
+ if (prefix.endsWith("def") || prefix.endsWith("fun") || prefix.endsWith("fn") || /\b(?:class|interface|trait|module|object)\s*$/.test(prefix)) {
2351
+ continue;
2352
+ }
2353
+ if (rawLine.slice(Math.max(0, start - 3), start).includes(".")) {
2354
+ continue;
2355
+ }
2356
+ calls.push({
2357
+ receiverName: null,
2358
+ calleeName,
2359
+ line: startLine + index
2360
+ });
2361
+ }
2362
+ }
2363
+ return calls;
2364
+ }
2365
+ function parseJavaFieldBindings(source) {
2366
+ const bindings = /* @__PURE__ */ new Map();
2367
+ for (const match of source.matchAll(/\b(?:private|protected|public)\s+(?:final\s+)?([A-Z][A-Za-z0-9_$<>?, ]*)\s+([A-Za-z_][\w$]*)\s*;/g)) {
2368
+ const typeName = stripGenericType(match[1]);
2369
+ const localName = match[2];
2370
+ if (typeName && localName) {
2371
+ bindings.set(localName, typeName);
2372
+ }
2373
+ }
2374
+ return bindings;
2375
+ }
2376
+ function parseKotlinFieldBindings(source) {
2377
+ const bindings = /* @__PURE__ */ new Map();
2378
+ for (const match of source.matchAll(/\b(?:private|protected|public)?\s*(?:val|var)\s+([A-Za-z_][\w]*)\s*:\s*([A-Z][A-Za-z0-9_.<>?]*)/g)) {
2379
+ const localName = match[1];
2380
+ const typeName = stripGenericType(match[2]);
2381
+ if (typeName && localName) {
2382
+ bindings.set(localName, typeName);
2383
+ }
2384
+ }
2385
+ return bindings;
2386
+ }
2387
+ function parseCppReceiverBindings(source) {
2388
+ const bindings = /* @__PURE__ */ new Map();
2389
+ const constructorMatch = source.match(/RunCoordinator::RunCoordinator\s*\(([\s\S]*?)\)\s*(?::\s*([\s\S]*?))?\s*\{/);
2390
+ if (!constructorMatch) {
2391
+ return bindings;
2392
+ }
2393
+ const params = constructorMatch[1] ?? "";
2394
+ const initializers = constructorMatch[2] ?? "";
2395
+ const parameterTypes = /* @__PURE__ */ new Map();
2396
+ for (const param of params.split(",")) {
2397
+ const trimmed = param.trim();
2398
+ const match = trimmed.match(/(.+?)\s+([A-Za-z_][\w]*)$/);
2399
+ if (!match) continue;
2400
+ const [, rawType, rawName] = match;
2401
+ if (!rawType || !rawName) continue;
2402
+ const typeName = stripGenericType(rawType.replace(/[&*]+/g, " ").replace(/\bconst\b/g, " ").trim());
2403
+ if (!typeName) continue;
2404
+ parameterTypes.set(normalizeReceiverName(rawName), typeName);
2405
+ }
2406
+ for (const initializer of initializers.split(",")) {
2407
+ const trimmed = initializer.trim();
2408
+ const match = trimmed.match(/([A-Za-z_][\w]*)\s*\(\s*([A-Za-z_][\w]*)\s*\)$/);
2409
+ if (!match) continue;
2410
+ const [, fieldName, sourceName] = match;
2411
+ if (!fieldName || !sourceName) continue;
2412
+ const typeName = parameterTypes.get(normalizeReceiverName(sourceName));
2413
+ if (!typeName) continue;
2414
+ bindings.set(normalizeReceiverName(fieldName), typeName);
2415
+ }
2416
+ return bindings;
2417
+ }
2418
+ function parseRubyReceiverBindings(db, source) {
2419
+ const bindings = /* @__PURE__ */ new Map();
2420
+ for (const match of source.matchAll(/@([A-Za-z_][\w]*)\s*=\s*([A-Za-z_][\w]*)/g)) {
2421
+ const ivarName = `@${match[1]}`;
2422
+ const localName = match[2];
2423
+ const typeName = inferTypeNameFromReceiver(db, localName ?? match[1] ?? "");
2424
+ if (typeName) {
2425
+ bindings.set(ivarName, typeName);
2426
+ bindings.set(match[1], typeName);
2427
+ }
2428
+ }
2429
+ return bindings;
2430
+ }
2431
+ function stripGenericType(typeName) {
2432
+ return (typeName ?? "").replace(/<.*$/, "").replace(/^.*\./, "").trim();
2433
+ }
2434
+ function normalizeReceiverName(receiverName) {
2435
+ return receiverName.replace(/^@/, "").replace(/^this(?:\.|->)/, "").replace(/^_+/, "").replace(/_+$/, "").trim();
2436
+ }
2437
+ function normalizeLookupName(value) {
2438
+ return value.replace(/[^A-Za-z0-9]+/g, "").toLowerCase();
2439
+ }
2440
+ function isLikelyTestPath(relativePath) {
2441
+ return /(^|\/)(tests?|__tests__)\//.test(relativePath) || /\.(?:spec|test)\./.test(relativePath) || /_test\./.test(relativePath);
2442
+ }
2443
+ function findDefinitionByName(definitions, leaf, parentType, preference) {
2444
+ const candidates = definitions.filter((definition) => definition.leaf === leaf && definition.parentTypeName === parentType);
2445
+ if (candidates.length === 0) {
2446
+ return null;
2447
+ }
2448
+ for (const preferred of preference) {
2449
+ const match = candidates.find((candidate) => preferred === "function" ? candidate.isFunctionLike : candidate.isTypeLike);
2450
+ if (match) {
2451
+ return match;
2452
+ }
2453
+ }
2454
+ return candidates[0] ?? null;
2455
+ }
2456
+ function findLooseProjectDefinitionByTypeAndLeaf(db, typeName, calleeName) {
2457
+ const rows = db.all(
2458
+ `SELECT
2459
+ gs.id,
2460
+ gs.symbol,
2461
+ c.document_id,
2462
+ MIN(c.start_line) AS start_line,
2463
+ MAX(c.end_line) AS end_line,
2464
+ d.relative_path,
2465
+ gs.kind,
2466
+ gs.documentation,
2467
+ gs.enclosing_symbol
2468
+ FROM global_symbols gs
2469
+ JOIN mentions m ON m.symbol_id = gs.id
2470
+ JOIN chunks c ON c.id = m.chunk_id
2471
+ JOIN documents d ON d.id = c.document_id
2472
+ WHERE gs.symbol LIKE ?
2473
+ AND gs.symbol LIKE ?
2474
+ ${db.pathExclusionsFor("d")}
2475
+ GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.kind, gs.documentation, gs.enclosing_symbol`,
2476
+ `%${typeName}%`,
2477
+ `%${calleeName}%`
2478
+ );
2479
+ const normalizedType = normalizeLookupName(typeName);
2480
+ const candidates = rows.filter((row2) => leafName(row2.symbol) === calleeName).filter((row2) => {
2481
+ const parentType = parentTypeName(row2.symbol);
2482
+ return parentType === typeName || row2.symbol.includes(typeName) || normalizeLookupName(parentType ?? "").includes(normalizedType);
2483
+ }).sort((left, right) => {
2484
+ const leftTest = isLikelyTestPath(left.relative_path) ? 1 : 0;
2485
+ const rightTest = isLikelyTestPath(right.relative_path) ? 1 : 0;
2486
+ return leftTest - rightTest || left.relative_path.localeCompare(right.relative_path) || left.start_line - right.start_line;
2487
+ });
2488
+ const row = candidates[0];
2489
+ if (!row) {
2490
+ return null;
2491
+ }
2492
+ return {
2493
+ symbolId: row.id,
2494
+ symbol: row.symbol,
2495
+ documentId: row.document_id,
2496
+ startLine: row.start_line,
2497
+ endLine: row.end_line,
2498
+ relativePath: row.relative_path,
2499
+ leaf: leafName(row.symbol),
2500
+ parentTypeName: parentTypeName(row.symbol),
2501
+ isFunctionLike: isFunctionLikeSymbol(row.symbol),
2502
+ isTypeLike: leafSuffix(row.symbol) === "type",
2503
+ kind: row.kind,
2504
+ documentation: row.documentation,
2505
+ enclosingSymbol: row.enclosing_symbol
2506
+ };
2507
+ }
2508
+ function hasUniqueLeafDefinition(db, leaf, symbolId) {
2509
+ const rows = db.all(
2510
+ `SELECT id, symbol
2511
+ FROM global_symbols
2512
+ WHERE symbol LIKE ?
2513
+ LIMIT 50`,
2514
+ `%${leaf}%`
2515
+ );
2516
+ let count = 0;
2517
+ for (const row of rows) {
2518
+ if (leafName(row.symbol) !== leaf) continue;
2519
+ count++;
2520
+ if (count > 1 && row.id !== symbolId) {
2521
+ return false;
2522
+ }
2523
+ }
2524
+ return count === 1;
2525
+ }
2526
+ function parentTypeName(rawSymbol) {
2527
+ const parsed = parseSymbol(rawSymbol);
2528
+ if ("kind" in parsed) {
2529
+ return null;
2530
+ }
2531
+ for (let index = parsed.descriptors.length - 2; index >= 0; index--) {
2532
+ const descriptor = parsed.descriptors[index];
2533
+ if (descriptor?.suffix === "type") {
2534
+ return descriptor.name;
2535
+ }
2536
+ }
2537
+ return null;
2538
+ }
2539
+ function isPythonDocument(db, relativePath) {
2540
+ const row = db.get(
2541
+ `SELECT language FROM documents WHERE relative_path = ? LIMIT 1`,
2542
+ relativePath
2543
+ );
2544
+ return row?.language === "python" || relativePath.endsWith(".py") || relativePath.endsWith(".pyi");
2545
+ }
2546
+ function isJavaScriptDocument(db, relativePath) {
2547
+ const row = db.get(
2548
+ `SELECT language FROM documents WHERE relative_path = ? LIMIT 1`,
2549
+ relativePath
2550
+ );
2551
+ return row?.language === "typescript" || row?.language === "javascript" || /\.(?:[cm]?[jt]sx?)$/.test(relativePath);
2552
+ }
2553
+ function isJavaDocument(db, relativePath) {
2554
+ const row = db.get(
2555
+ `SELECT language FROM documents WHERE relative_path = ? LIMIT 1`,
2556
+ relativePath
2557
+ );
2558
+ return row?.language === "java" || relativePath.endsWith(".java");
2559
+ }
2560
+ function isKotlinDocument(db, relativePath) {
2561
+ const row = db.get(
2562
+ `SELECT language FROM documents WHERE relative_path = ? LIMIT 1`,
2563
+ relativePath
2564
+ );
2565
+ return row?.language === "kotlin" || relativePath.endsWith(".kt") || relativePath.endsWith(".kts");
2566
+ }
2567
+ function isScalaDocument(db, relativePath) {
2568
+ const row = db.get(
2569
+ `SELECT language FROM documents WHERE relative_path = ? LIMIT 1`,
2570
+ relativePath
2571
+ );
2572
+ return row?.language === "scala" || relativePath.endsWith(".scala");
2573
+ }
2574
+ function isCSharpDocument(db, relativePath) {
2575
+ const row = db.get(
2576
+ `SELECT language FROM documents WHERE relative_path = ? LIMIT 1`,
2577
+ relativePath
2578
+ );
2579
+ return row?.language === "C#" || relativePath.endsWith(".cs");
2580
+ }
2581
+ function isVisualBasicDocument(db, relativePath) {
2582
+ const row = db.get(
2583
+ `SELECT language FROM documents WHERE relative_path = ? LIMIT 1`,
2584
+ relativePath
2585
+ );
2586
+ return row?.language === "Visual Basic" || relativePath.endsWith(".vb");
2587
+ }
2588
+ function isCppDocument(db, relativePath) {
2589
+ const row = db.get(
2590
+ `SELECT language FROM documents WHERE relative_path = ? LIMIT 1`,
2591
+ relativePath
2592
+ );
2593
+ return row?.language === "CPP" || /\.(?:cc|cpp|cxx|hpp|hh|hxx)$/.test(relativePath);
2594
+ }
2595
+ function isRustDocument(db, relativePath) {
2596
+ const row = db.get(
2597
+ `SELECT language FROM documents WHERE relative_path = ? LIMIT 1`,
2598
+ relativePath
2599
+ );
2600
+ return row?.language === "Rust" || relativePath.endsWith(".rs");
2601
+ }
2602
+ function isRubyDocument(db, relativePath) {
2603
+ const row = db.get(
2604
+ `SELECT language FROM documents WHERE relative_path = ? LIMIT 1`,
2605
+ relativePath
2606
+ );
2607
+ return row?.language === "ruby" || relativePath.endsWith(".rb");
2608
+ }
2609
+ function isDartDocument(db, relativePath) {
2610
+ const row = db.get(
2611
+ `SELECT language FROM documents WHERE relative_path = ? LIMIT 1`,
2612
+ relativePath
2613
+ );
2614
+ return row?.language === "Dart" || relativePath.endsWith(".dart");
2615
+ }
2616
+ function isPhpDocument(db, relativePath) {
2617
+ const row = db.get(
2618
+ `SELECT language FROM documents WHERE relative_path = ? LIMIT 1`,
2619
+ relativePath
2620
+ );
2621
+ return row?.language === "PHP" || relativePath.endsWith(".php");
2622
+ }
2623
+ function applyLimit(values, limit) {
2624
+ return typeof limit === "number" ? values.slice(0, limit) : values;
2625
+ }
2626
+ function resolveDocumentCandidates(db, filePattern, opts) {
2627
+ const normalizedPattern = normalizeLookupPath(filePattern);
2628
+ if (!normalizedPattern) {
2629
+ return [];
2630
+ }
2631
+ const rows = db.all(
2632
+ `SELECT relative_path
2633
+ FROM documents
2634
+ WHERE 1 = 1
2635
+ ${db.pathExclusionsFor("documents")}
2636
+ ORDER BY relative_path`
2637
+ );
2638
+ const scored = rows.filter((row) => !db.isIgnored(row.relative_path)).map((row) => ({
2639
+ relativePath: row.relative_path,
2640
+ score: scoreDocumentPath(row.relative_path, normalizedPattern)
2641
+ })).filter((row) => row.score > 0).sort((a, b) => b.score - a.score || a.relativePath.localeCompare(b.relativePath));
2642
+ if (scored.length === 0) {
2643
+ const symbolMatch = findFirstSymbolMatch(db, filePattern);
2644
+ if (!symbolMatch || db.isIgnored(symbolMatch.relativePath)) {
2645
+ return [];
2646
+ }
2647
+ return [{
2648
+ relativePath: symbolMatch.relativePath,
2649
+ score: 700
2650
+ }];
2651
+ }
2652
+ const exactish = scored.filter((row) => row.score >= 800);
2653
+ if (exactish.length > 0) {
2654
+ return opts.allowMultiple ? exactish : [exactish[0]];
2655
+ }
2656
+ return opts.allowMultiple ? scored : [scored[0]];
2657
+ }
2658
+ function scoreDocumentPath(relativePath, rawPattern) {
2659
+ const normalizedPath = normalizeLookupPath(relativePath);
2660
+ const pathBase = basename2(normalizedPath);
2661
+ const patternBase = basename2(rawPattern);
2662
+ let score = 0;
2663
+ if (normalizedPath === rawPattern) score += 1200;
2664
+ if (normalizedPath.endsWith(`/${rawPattern}`)) score += 1100;
2665
+ if (pathBase === patternBase) score += 900;
2666
+ if (normalizedPath.startsWith(`${rawPattern}/`)) score += 850;
2667
+ if (normalizedPath.includes(rawPattern)) score += 250;
2668
+ return score;
2669
+ }
2670
+ function normalizeLookupPath(filePattern) {
2671
+ return filePattern.trim().replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "").replace(/\/+$/, "");
2672
+ }
2673
+ function uniquePatterns(patterns) {
2674
+ return [...new Set(patterns)];
2675
+ }
2676
+
2677
+ export {
2678
+ getSourceImports,
2679
+ getSourceExports,
2680
+ getSourceText,
2681
+ TEST_FILE_PATTERNS,
2682
+ TEST_SUPPORT_PATH_PATTERNS,
2683
+ testFileExclusionSql,
2684
+ buildFileDepGraph,
2685
+ findFirstSymbolMatch,
2686
+ findExactSymbolMatch,
2687
+ resolveIndexedFile,
2688
+ resolveIndexedPaths,
2689
+ getCalleeRowsForSymbol,
2690
+ getCallerRowsForSymbol,
2691
+ getSourceReferenceSites,
2692
+ getDefinitionsForFile,
2693
+ getAllDefinitions
2694
+ };
2695
+ //# sourceMappingURL=chunk-ALUFWH3U.js.map