pi-lens 3.6.3 → 3.6.4

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 (206) hide show
  1. package/package.json +3 -3
  2. package/tsconfig.json +1 -1
  3. package/clients/__tests__/file-time.test.js +0 -216
  4. package/clients/__tests__/file-time.test.ts +0 -276
  5. package/clients/__tests__/format-service.test.js +0 -245
  6. package/clients/__tests__/format-service.test.ts +0 -339
  7. package/clients/__tests__/formatters.test.js +0 -271
  8. package/clients/__tests__/formatters.test.ts +0 -401
  9. package/clients/agent-behavior-client.js +0 -110
  10. package/clients/agent-behavior-client.test.js +0 -94
  11. package/clients/agent-behavior-client.test.ts +0 -116
  12. package/clients/amain-types.js +0 -164
  13. package/clients/architect-client.js +0 -291
  14. package/clients/ast-grep-client.js +0 -253
  15. package/clients/ast-grep-parser.js +0 -84
  16. package/clients/ast-grep-rule-manager.js +0 -89
  17. package/clients/ast-grep-types.js +0 -9
  18. package/clients/auto-loop.js +0 -131
  19. package/clients/biome-client.js +0 -420
  20. package/clients/biome-client.test.js +0 -144
  21. package/clients/biome-client.test.ts +0 -163
  22. package/clients/cache/rule-cache.js +0 -72
  23. package/clients/cache-manager.js +0 -245
  24. package/clients/cache-manager.test.js +0 -197
  25. package/clients/cache-manager.test.ts +0 -299
  26. package/clients/complexity-client.js +0 -675
  27. package/clients/complexity-client.test.js +0 -234
  28. package/clients/complexity-client.test.ts +0 -255
  29. package/clients/config-validator.js +0 -465
  30. package/clients/dependency-checker.js +0 -325
  31. package/clients/dependency-checker.test.js +0 -60
  32. package/clients/dependency-checker.test.ts +0 -71
  33. package/clients/dispatch/__tests__/autofix-integration.test.js +0 -245
  34. package/clients/dispatch/__tests__/autofix-integration.test.ts +0 -300
  35. package/clients/dispatch/__tests__/runner-registration.test.js +0 -234
  36. package/clients/dispatch/__tests__/runner-registration.test.ts +0 -286
  37. package/clients/dispatch/debug.log +0 -1
  38. package/clients/dispatch/dispatcher.edge.test.js +0 -82
  39. package/clients/dispatch/dispatcher.edge.test.ts +0 -100
  40. package/clients/dispatch/dispatcher.format.test.js +0 -46
  41. package/clients/dispatch/dispatcher.format.test.ts +0 -58
  42. package/clients/dispatch/dispatcher.inline.test.js +0 -74
  43. package/clients/dispatch/dispatcher.inline.test.ts +0 -93
  44. package/clients/dispatch/dispatcher.js +0 -381
  45. package/clients/dispatch/dispatcher.test.js +0 -116
  46. package/clients/dispatch/dispatcher.test.ts +0 -149
  47. package/clients/dispatch/integration.js +0 -108
  48. package/clients/dispatch/plan.js +0 -183
  49. package/clients/dispatch/runners/architect.js +0 -83
  50. package/clients/dispatch/runners/architect.test.js +0 -138
  51. package/clients/dispatch/runners/architect.test.ts +0 -162
  52. package/clients/dispatch/runners/ast-grep-napi.js +0 -405
  53. package/clients/dispatch/runners/ast-grep-napi.test.js +0 -107
  54. package/clients/dispatch/runners/ast-grep-napi.test.ts +0 -129
  55. package/clients/dispatch/runners/ast-grep.js +0 -157
  56. package/clients/dispatch/runners/biome.js +0 -55
  57. package/clients/dispatch/runners/config-validation.js +0 -67
  58. package/clients/dispatch/runners/go-vet.js +0 -48
  59. package/clients/dispatch/runners/index.js +0 -47
  60. package/clients/dispatch/runners/lsp.js +0 -102
  61. package/clients/dispatch/runners/oxlint.js +0 -67
  62. package/clients/dispatch/runners/oxlint.test.js +0 -230
  63. package/clients/dispatch/runners/oxlint.test.ts +0 -303
  64. package/clients/dispatch/runners/pyright.js +0 -100
  65. package/clients/dispatch/runners/pyright.test.js +0 -98
  66. package/clients/dispatch/runners/pyright.test.ts +0 -121
  67. package/clients/dispatch/runners/python-slop.js +0 -97
  68. package/clients/dispatch/runners/python-slop.test.js +0 -203
  69. package/clients/dispatch/runners/python-slop.test.ts +0 -298
  70. package/clients/dispatch/runners/ruff.js +0 -48
  71. package/clients/dispatch/runners/rust-clippy.js +0 -102
  72. package/clients/dispatch/runners/scan_codebase.test.js +0 -89
  73. package/clients/dispatch/runners/scan_codebase.test.ts +0 -105
  74. package/clients/dispatch/runners/shellcheck.js +0 -147
  75. package/clients/dispatch/runners/shellcheck.test.js +0 -98
  76. package/clients/dispatch/runners/shellcheck.test.ts +0 -129
  77. package/clients/dispatch/runners/similarity.js +0 -230
  78. package/clients/dispatch/runners/spellcheck.js +0 -106
  79. package/clients/dispatch/runners/spellcheck.test.js +0 -158
  80. package/clients/dispatch/runners/spellcheck.test.ts +0 -214
  81. package/clients/dispatch/runners/tree-sitter.js +0 -246
  82. package/clients/dispatch/runners/ts-lsp.js +0 -125
  83. package/clients/dispatch/runners/ts-slop.js +0 -113
  84. package/clients/dispatch/runners/type-safety.js +0 -142
  85. package/clients/dispatch/runners/utils/diagnostic-parsers.js +0 -134
  86. package/clients/dispatch/runners/utils/runner-helpers.js +0 -115
  87. package/clients/dispatch/runners/utils.js +0 -51
  88. package/clients/dispatch/runners/yaml-rule-parser.js +0 -360
  89. package/clients/dispatch/types.js +0 -16
  90. package/clients/dispatch/utils/format-utils.js +0 -44
  91. package/clients/dogfood.test.js +0 -201
  92. package/clients/dogfood.test.ts +0 -269
  93. package/clients/file-kinds.js +0 -177
  94. package/clients/file-kinds.test.js +0 -169
  95. package/clients/file-kinds.test.ts +0 -210
  96. package/clients/file-time.js +0 -152
  97. package/clients/file-utils.js +0 -40
  98. package/clients/fix-scanners.js +0 -204
  99. package/clients/format-service.js +0 -184
  100. package/clients/formatters.js +0 -488
  101. package/clients/go-client.js +0 -203
  102. package/clients/go-client.test.js +0 -127
  103. package/clients/go-client.test.ts +0 -143
  104. package/clients/installer/index.js +0 -403
  105. package/clients/interviewer-templates.js +0 -75
  106. package/clients/interviewer.js +0 -173
  107. package/clients/jscpd-client.js +0 -196
  108. package/clients/jscpd-client.test.js +0 -127
  109. package/clients/jscpd-client.test.ts +0 -145
  110. package/clients/knip-client.js +0 -239
  111. package/clients/knip-client.test.js +0 -112
  112. package/clients/knip-client.test.ts +0 -128
  113. package/clients/latency-logger.js +0 -40
  114. package/clients/lsp/__tests__/client.test.js +0 -310
  115. package/clients/lsp/__tests__/client.test.ts +0 -412
  116. package/clients/lsp/__tests__/config.test.js +0 -167
  117. package/clients/lsp/__tests__/config.test.ts +0 -217
  118. package/clients/lsp/__tests__/error-recovery.test.js +0 -213
  119. package/clients/lsp/__tests__/error-recovery.test.ts +0 -279
  120. package/clients/lsp/__tests__/integration.test.js +0 -127
  121. package/clients/lsp/__tests__/integration.test.ts +0 -160
  122. package/clients/lsp/__tests__/launch.test.js +0 -313
  123. package/clients/lsp/__tests__/launch.test.ts +0 -394
  124. package/clients/lsp/__tests__/server.test.js +0 -259
  125. package/clients/lsp/__tests__/server.test.ts +0 -332
  126. package/clients/lsp/__tests__/service.test.js +0 -438
  127. package/clients/lsp/__tests__/service.test.ts +0 -530
  128. package/clients/lsp/client.js +0 -350
  129. package/clients/lsp/config.js +0 -112
  130. package/clients/lsp/index.js +0 -318
  131. package/clients/lsp/installer/index.js +0 -391
  132. package/clients/lsp/interactive-install.js +0 -221
  133. package/clients/lsp/language.js +0 -170
  134. package/clients/lsp/launch.js +0 -329
  135. package/clients/lsp/lsp/launch.js +0 -116
  136. package/clients/lsp/lsp/server.js +0 -532
  137. package/clients/lsp/lsp-index.js +0 -10
  138. package/clients/lsp/path-utils.js +0 -5
  139. package/clients/lsp/server.js +0 -725
  140. package/clients/lsp/test-py-spawn/requirements.txt +0 -1
  141. package/clients/lsp/test-py-spawn/test.py +0 -3
  142. package/clients/lsp/test-py-svc/requirements.txt +0 -1
  143. package/clients/lsp/test-py-svc/test.py +0 -3
  144. package/clients/lsp/test-python-project/requirements.txt +0 -1
  145. package/clients/lsp/test-python-project/test.py +0 -5
  146. package/clients/metrics-client.js +0 -107
  147. package/clients/metrics-client.test.js +0 -128
  148. package/clients/metrics-client.test.ts +0 -163
  149. package/clients/metrics-history.js +0 -367
  150. package/clients/path-utils.js +0 -142
  151. package/clients/pipeline.js +0 -272
  152. package/clients/production-readiness.js +0 -522
  153. package/clients/project-index.js +0 -255
  154. package/clients/project-metadata.js +0 -531
  155. package/clients/ruff-client.js +0 -325
  156. package/clients/ruff-client.test.js +0 -132
  157. package/clients/ruff-client.test.ts +0 -153
  158. package/clients/rules-scanner.js +0 -97
  159. package/clients/runner-tracker.js +0 -152
  160. package/clients/rust-client.js +0 -205
  161. package/clients/rust-client.test.js +0 -108
  162. package/clients/rust-client.test.ts +0 -130
  163. package/clients/safe-spawn-async.js +0 -163
  164. package/clients/safe-spawn.js +0 -241
  165. package/clients/sanitize.js +0 -291
  166. package/clients/sanitize.test.js +0 -177
  167. package/clients/sanitize.test.ts +0 -223
  168. package/clients/scan-architectural-debt.js +0 -167
  169. package/clients/scan-utils.js +0 -83
  170. package/clients/secrets-scanner.js +0 -119
  171. package/clients/secrets-scanner.test.js +0 -100
  172. package/clients/secrets-scanner.test.ts +0 -113
  173. package/clients/sg-runner.js +0 -292
  174. package/clients/state-matrix.js +0 -160
  175. package/clients/subprocess-client.js +0 -65
  176. package/clients/symbol-types.js +0 -5
  177. package/clients/test-runner-client.js +0 -523
  178. package/clients/test-runner-client.test.js +0 -192
  179. package/clients/test-runner-client.test.ts +0 -253
  180. package/clients/test-utils.js +0 -27
  181. package/clients/test-utils.ts +0 -36
  182. package/clients/todo-scanner.js +0 -200
  183. package/clients/todo-scanner.test.js +0 -301
  184. package/clients/todo-scanner.test.ts +0 -352
  185. package/clients/tool-availability.js +0 -207
  186. package/clients/tree-sitter-client.js +0 -601
  187. package/clients/tree-sitter-query-loader.js +0 -355
  188. package/clients/tree-sitter-symbol-extractor.js +0 -289
  189. package/clients/ts-service.js +0 -129
  190. package/clients/type-coverage-client.js +0 -127
  191. package/clients/type-coverage-client.test.js +0 -105
  192. package/clients/type-coverage-client.test.ts +0 -125
  193. package/clients/type-safety-client.js +0 -138
  194. package/clients/types.js +0 -11
  195. package/clients/typescript-client.codefix.test.js +0 -157
  196. package/clients/typescript-client.codefix.test.ts +0 -186
  197. package/clients/typescript-client.js +0 -509
  198. package/clients/typescript-client.test.js +0 -105
  199. package/clients/typescript-client.test.ts +0 -126
  200. package/commands/booboo.js +0 -1007
  201. package/commands/fix-from-booboo.js +0 -398
  202. package/commands/fix-simplified.js +0 -618
  203. package/commands/rate.js +0 -281
  204. package/commands/rate.test.js +0 -119
  205. package/commands/rate.test.ts +0 -131
  206. package/commands/refactor.js +0 -130
@@ -1,601 +0,0 @@
1
- /**
2
- * Tree-sitter Structural Search Client for pi-lens
3
- *
4
- * Inspired by pi-lsp-extension's search-engine.ts and pattern-compiler.ts
5
- * Provides AST-aware structural search with metavariable capture.
6
- *
7
- * Uses web-tree-sitter (WASM) for parsing - no native compilation needed.
8
- *
9
- * Pattern syntax:
10
- * $NAME - Matches any single AST node, captures as NAME
11
- * $$$NAME - Matches zero or more sibling nodes (variadic)
12
- *
13
- * Example:
14
- * "console.log($MSG)" matches any console.log call, captures argument as MSG
15
- * "function $NAME($$$PARAMS) { $BODY }" matches function declarations
16
- */
17
- import * as fs from "node:fs";
18
- import * as path from "node:path";
19
- import { EXCLUDED_DIRS } from "./file-utils.js";
20
- import { TreeSitterQueryLoader, } from "./tree-sitter-query-loader.js";
21
- // biome-ignore lint/suspicious/noExplicitAny: Module type
22
- const _LanguageLoader = null;
23
- // --- WASM Grammar Mapping ---
24
- const LANGUAGE_TO_GRAMMAR = {
25
- typescript: "tree-sitter-typescript.wasm",
26
- tsx: "tree-sitter-tsx.wasm",
27
- javascript: "tree-sitter-javascript.wasm",
28
- python: "tree-sitter-python.wasm",
29
- rust: "tree-sitter-rust.wasm",
30
- go: "tree-sitter-go.wasm",
31
- java: "tree-sitter-java.wasm",
32
- c: "tree-sitter-c.wasm",
33
- cpp: "tree-sitter-cpp.wasm",
34
- ruby: "tree-sitter-ruby.wasm",
35
- };
36
- // --- Parser Manager ---
37
- export class TreeSitterClient {
38
- constructor(verbose = false) {
39
- this.initialized = false;
40
- this.languages = new Map();
41
- this.parsers = new Map();
42
- // biome-ignore lint/suspicious/noExplicitAny: Optional dependency loaded dynamically
43
- this.ParserClass = null;
44
- // biome-ignore lint/suspicious/noExplicitAny: Language loader from module
45
- this.LanguageLoader = null;
46
- // biome-ignore lint/suspicious/noExplicitAny: Compiled query cache by language+pattern hash
47
- this.queryCache = new Map();
48
- this.queryLoader = new TreeSitterQueryLoader();
49
- this.queriesLoaded = false;
50
- this.grammarsDir = this.findGrammarsDir();
51
- this.verbose = verbose;
52
- }
53
- /** Debug logging helper */
54
- dbg(msg) {
55
- if (this.verbose) {
56
- console.error(`[tree-sitter] ${msg}`);
57
- }
58
- }
59
- /** Find tree-sitter grammar directory */
60
- findGrammarsDir() {
61
- // Check for downloaded grammars in web-tree-sitter/grammars first
62
- const downloadedGrammars = [
63
- path.join(process.cwd(), "node_modules", "web-tree-sitter", "grammars"),
64
- ];
65
- // Add __dirname-based paths if __dirname is available (CommonJS)
66
- if (typeof __dirname !== "undefined") {
67
- downloadedGrammars.push(path.join(__dirname, "..", "..", "node_modules", "web-tree-sitter", "grammars"), path.join(__dirname, "..", "node_modules", "web-tree-sitter", "grammars"));
68
- }
69
- for (const dir of downloadedGrammars) {
70
- if (fs.existsSync(dir) &&
71
- fs.existsSync(path.join(dir, "tree-sitter-typescript.wasm"))) {
72
- return dir;
73
- }
74
- }
75
- // Fallback to legacy locations
76
- const candidates = [
77
- path.join(process.cwd(), "node_modules", "tree-sitter-wasms", "out"),
78
- ];
79
- if (typeof __dirname !== "undefined") {
80
- candidates.push(path.join(__dirname, "..", "..", "node_modules", "tree-sitter-wasms", "out"), path.join(__dirname, "..", "node_modules", "tree-sitter-wasms", "out"));
81
- }
82
- for (const dir of candidates) {
83
- if (fs.existsSync(dir))
84
- return dir;
85
- }
86
- // Default to web-tree-sitter/grammars (may need manual download)
87
- return downloadedGrammars[0];
88
- }
89
- /** Initialize tree-sitter WASM runtime */
90
- async init() {
91
- if (this.initialized)
92
- return true;
93
- try {
94
- const mod = await import("web-tree-sitter");
95
- // biome-ignore lint/suspicious/noExplicitAny: Dynamic import of optional dependency
96
- const ParserClass = mod.Parser || mod.default || mod;
97
- if (!ParserClass || typeof ParserClass.init !== "function") {
98
- this.dbg("Parser class not found or missing init method");
99
- return false;
100
- }
101
- // biome-ignore lint/suspicious/noExplicitAny: Parser class type
102
- this.ParserClass = ParserClass;
103
- // Store Language loader from module (not from Parser)
104
- this.LanguageLoader = mod.Language;
105
- // Log what we're trying to load
106
- const wasmPath = path.join(process.cwd(), "node_modules", "web-tree-sitter", "tree-sitter.wasm");
107
- this.dbg(`Looking for WASM at: ${wasmPath}, exists: ${fs.existsSync(wasmPath)}`);
108
- await ParserClass.init({
109
- locateFile: (scriptName) => {
110
- // Always return the full path to the WASM file
111
- const fullPath = path.join(process.cwd(), "node_modules", "web-tree-sitter", scriptName);
112
- this.dbg(`locateFile: ${scriptName} -> ${fullPath}`);
113
- return fullPath;
114
- },
115
- });
116
- // Load queries after initialization
117
- if (!this.queriesLoaded) {
118
- try {
119
- await this.queryLoader.loadQueries();
120
- this.queriesLoaded = true;
121
- this.dbg(`Queries loaded successfully`);
122
- }
123
- catch (err) {
124
- this.dbg(`Failed to load queries: ${err}`);
125
- // Continue anyway - fallbacks will work
126
- }
127
- }
128
- this.initialized = true;
129
- return true;
130
- }
131
- catch (err) {
132
- this.dbg(`Init error: ${err}`);
133
- return false;
134
- }
135
- }
136
- /** Load language grammar */
137
- async loadLanguage(languageId) {
138
- this.dbg(`Loading language: ${languageId}`);
139
- if (this.languages.has(languageId)) {
140
- this.dbg(`Language ${languageId} already loaded`);
141
- return this.languages.get(languageId);
142
- }
143
- if (!this.ParserClass) {
144
- this.dbg(`ParserClass not initialized`);
145
- return null;
146
- }
147
- const grammarFile = LANGUAGE_TO_GRAMMAR[languageId];
148
- if (!grammarFile) {
149
- this.dbg(`No grammar file for ${languageId}`);
150
- return null;
151
- }
152
- const grammarPath = path.join(this.grammarsDir, grammarFile);
153
- this.dbg(`Grammar path: ${grammarPath}, exists: ${fs.existsSync(grammarPath)}`);
154
- if (!fs.existsSync(grammarPath)) {
155
- this.dbg(`Grammar file not found: ${grammarPath}`);
156
- return null;
157
- }
158
- try {
159
- if (!this.LanguageLoader?.load) {
160
- this.dbg(`LanguageLoader.load not available`);
161
- return null;
162
- }
163
- this.dbg(`Calling Language.load...`);
164
- const language = await this.LanguageLoader.load(grammarPath);
165
- this.dbg(`Language loaded: ${language?.name || "unknown"}`);
166
- if (language) {
167
- this.languages.set(languageId, language);
168
- }
169
- return language;
170
- }
171
- catch (err) {
172
- this.dbg(`Language load error: ${err}`);
173
- return null;
174
- }
175
- }
176
- /** Get or create parser for a language */
177
- async getParser(languageId) {
178
- if (this.parsers.has(languageId)) {
179
- return this.parsers.get(languageId);
180
- }
181
- const language = await this.loadLanguage(languageId);
182
- if (!language || !this.ParserClass)
183
- return null;
184
- const parser = new this.ParserClass();
185
- parser.setLanguage(language);
186
- this.parsers.set(languageId, parser);
187
- return parser;
188
- }
189
- /** Parse a file and return the AST tree */
190
- async parseFile(filePath, languageId) {
191
- this.dbg(`Parsing ${filePath} with language ${languageId}`);
192
- const parser = await this.getParser(languageId);
193
- if (!parser) {
194
- this.dbg(`Failed to get parser for ${languageId}`);
195
- return null;
196
- }
197
- try {
198
- const content = fs.readFileSync(filePath, "utf-8");
199
- this.dbg(`File content length: ${content.length}`);
200
- const tree = parser.parse(content);
201
- this.dbg(`Parsed, root node type: ${tree.rootNode.type}`);
202
- return tree;
203
- }
204
- catch (err) {
205
- this.dbg(`Parse error: ${err}`);
206
- return null;
207
- }
208
- }
209
- /** Check if tree-sitter is available (grammars installed) */
210
- isAvailable() {
211
- return fs.existsSync(this.grammarsDir);
212
- }
213
- /** Check if specific language is supported */
214
- async isLanguageSupported(languageId) {
215
- if (!this.initialized)
216
- await this.init();
217
- const language = await this.loadLanguage(languageId);
218
- return language !== null;
219
- }
220
- /** Get loaded language for symbol extraction */
221
- getLanguage(languageId) {
222
- return this.languages.get(languageId) || null;
223
- }
224
- // --- Structural Search ---
225
- /**
226
- * Search for a structural pattern in files
227
- *
228
- * @param pattern - Pattern with metavariables (e.g., "console.log($MSG)")
229
- * @param languageId - Language ID (typescript, python, etc.)
230
- * @param rootDir - Directory to search
231
- * @param options - Search options
232
- * @returns Array of matches with captures
233
- */
234
- async structuralSearch(pattern, languageId, rootDir, options = {}) {
235
- if (!this.initialized) {
236
- const ok = await this.init();
237
- if (!ok)
238
- return [];
239
- }
240
- // Compile pattern into tree-sitter query
241
- this.dbg(`Compiling pattern: ${pattern.slice(0, 50)}...`);
242
- const compiled = await this.compileQuery(pattern, languageId);
243
- if (!compiled) {
244
- this.dbg(`Pattern compilation failed`);
245
- return [];
246
- }
247
- this.dbg(`Pattern compiled, metavars: ${compiled.metavars.join(", ")}`);
248
- // Collect source files
249
- const files = this.collectFiles(rootDir, languageId, options.fileFilter);
250
- this.dbg(`Scanning ${files.length} files...`);
251
- const matches = [];
252
- const maxResults = options.maxResults ?? 50;
253
- for (const file of files) {
254
- if (matches.length >= maxResults)
255
- break;
256
- const fileMatches = await this.searchFileWithQuery(file, compiled.query, compiled.metavars, languageId, pattern, compiled.postFilter, compiled.postFilterParams);
257
- matches.push(...fileMatches);
258
- }
259
- return matches.slice(0, maxResults);
260
- }
261
- /**
262
- * Convert pattern to tree-sitter query
263
- * First tries to load from query files, then falls back to inline patterns
264
- */
265
- patternToQuery(pattern, languageId) {
266
- // Try to find matching query from loaded files
267
- const loadedQuery = this.queryLoader.findMatchingQuery(pattern, languageId);
268
- if (loadedQuery) {
269
- this.dbg(`Using loaded query: ${loadedQuery.id}`);
270
- return {
271
- query: loadedQuery.query,
272
- metavars: loadedQuery.metavars,
273
- postFilter: loadedQuery.post_filter,
274
- postFilterParams: loadedQuery.post_filter_params,
275
- queryDef: loadedQuery,
276
- };
277
- }
278
- // Fallback to inline patterns
279
- return this.getInlinePattern(pattern);
280
- }
281
- /**
282
- * Inline patterns as fallback when no query file matches
283
- */
284
- getInlinePattern(pattern) {
285
- // Pattern: async function $NAME($$$PARAMS) { $BODY }
286
- if (pattern.includes("async function") && pattern.includes("$NAME")) {
287
- return {
288
- query: `(function_declaration
289
- "async"
290
- name: (identifier) @NAME
291
- parameters: (formal_parameters) @PARAMS
292
- body: (statement_block) @BODY)`,
293
- metavars: ["NAME", "PARAMS", "BODY"],
294
- };
295
- }
296
- // Pattern: console.$METHOD($MSG)
297
- if (pattern.includes("console")) {
298
- return {
299
- query: `(call_expression
300
- function: (member_expression
301
- object: (identifier) @OBJ (#eq? @OBJ "console")
302
- property: (property_identifier) @METHOD)
303
- arguments: (arguments) @ARGS)`,
304
- metavars: ["OBJ", "METHOD", "ARGS"],
305
- };
306
- }
307
- // Pattern: function $NAME($$$PARAMS) { $BODY } - match long parameter lists
308
- if (pattern.includes("function $NAME") && pattern.includes("PARAMS")) {
309
- return {
310
- query: `(function_declaration
311
- name: (identifier) @NAME
312
- parameters: (formal_parameters) @PARAMS
313
- body: (statement_block) @BODY)`,
314
- metavars: ["NAME", "PARAMS", "BODY"],
315
- postFilter: "count_params",
316
- postFilterParams: { min_params: 6 },
317
- };
318
- }
319
- // Pattern: promise chains with .then().catch().then() - 3+ levels
320
- if (pattern.includes(".then") && pattern.includes(".catch")) {
321
- return {
322
- query: `(call_expression
323
- function: (member_expression
324
- object: (call_expression
325
- function: (member_expression
326
- object: (call_expression
327
- function: (member_expression
328
- property: (property_identifier) @M1)
329
- arguments: (arguments))
330
- property: (property_identifier) @M2)
331
- arguments: (arguments))
332
- property: (property_identifier) @M3)
333
- arguments: (arguments))
334
- (#match? @M1 "^(then|catch)$")
335
- (#match? @M2 "^(then|catch)$")
336
- (#match? @M3 "^(then|catch)$")`,
337
- metavars: ["M1", "M2", "M3"],
338
- };
339
- }
340
- // Fallback: try to create a simple identifier capture
341
- const simpleMatch = pattern.match(/\$([A-Z_][A-Z0-9_]*)/);
342
- if (simpleMatch) {
343
- const name = simpleMatch[1];
344
- return {
345
- query: `(identifier) @${name}`,
346
- metavars: [name],
347
- };
348
- }
349
- // If we can't convert, return empty to trigger fallback
350
- return { query: "", metavars: [] };
351
- }
352
- /** Generate cache key for compiled query */
353
- getQueryCacheKey(pattern, languageId) {
354
- // Simple hash for the query string
355
- let hash = 0;
356
- for (let i = 0; i < pattern.length; i++) {
357
- const char = pattern.charCodeAt(i);
358
- hash = ((hash << 5) - hash + char) | 0;
359
- }
360
- return `${languageId}:${hash.toString(36)}`;
361
- }
362
- /** Compile a pattern into a tree-sitter Query with caching */
363
- async compileQuery(pattern, languageId) {
364
- const cacheKey = this.getQueryCacheKey(pattern, languageId);
365
- // Check cache first
366
- if (this.queryCache.has(cacheKey)) {
367
- this.dbg(`Query cache hit: ${cacheKey}`);
368
- return this.queryCache.get(cacheKey);
369
- }
370
- const language = await this.loadLanguage(languageId);
371
- if (!language) {
372
- this.dbg(`Could not load language ${languageId}`);
373
- return null;
374
- }
375
- const { query: queryStr, metavars, postFilter, postFilterParams, } = this.patternToQuery(pattern, languageId);
376
- this.dbg(`Query string: ${queryStr.slice(0, 100)}...`);
377
- try {
378
- // biome-ignore lint/suspicious/noExplicitAny: Query constructor
379
- const Query = (await import("web-tree-sitter")).Query;
380
- // biome-ignore lint/suspicious/noExplicitAny: Language type compatibility
381
- const query = new Query(language, queryStr);
382
- this.dbg(`Query compiled with ${query.patternCount} patterns`);
383
- const result = { query, metavars, postFilter, postFilterParams };
384
- // Cache the compiled query
385
- this.queryCache.set(cacheKey, result);
386
- return result;
387
- }
388
- catch (err) {
389
- this.dbg(`Query compilation failed: ${err}`);
390
- return null;
391
- }
392
- }
393
- /** Search a single file using tree-sitter Query */
394
- async searchFileWithQuery(filePath,
395
- // biome-ignore lint/suspicious/noExplicitAny: Query type from web-tree-sitter
396
- query, metavars, languageId, _originalPattern, postFilter,
397
- // biome-ignore lint/suspicious/noExplicitAny: Post filter params
398
- postFilterParams) {
399
- const tree = await this.parseFile(filePath, languageId);
400
- if (!tree)
401
- return [];
402
- const matches = [];
403
- try {
404
- // Use tree-sitter's native query matching
405
- const queryMatches = query.matches(tree.rootNode);
406
- for (const match of queryMatches) {
407
- const captures = {};
408
- // Extract captured metavariables (store nodes, not just text)
409
- for (const capture of match.captures) {
410
- const name = capture.name;
411
- const node = capture.node;
412
- if (metavars.includes(name)) {
413
- captures[name] = node;
414
- }
415
- }
416
- // Apply post-filters if specified
417
- if (postFilter === "count_params") {
418
- const paramsNode = captures.PARAMS;
419
- if (paramsNode) {
420
- // biome-ignore lint/suspicious/noExplicitAny: Count parameter nodes
421
- const paramCount = paramsNode.children.filter((c) => c.type === "required_parameter" ||
422
- c.type === "optional_parameter").length;
423
- const minParams = postFilterParams?.min_params || 6;
424
- if (paramCount < minParams)
425
- continue;
426
- }
427
- }
428
- if (postFilter === "empty_body") {
429
- const bodyNode = captures.BODY;
430
- if (bodyNode) {
431
- // Check if body has meaningful statements (not just comments/braces)
432
- // biome-ignore lint/suspicious/noExplicitAny: Check for meaningful statements
433
- const meaningfulStatements = bodyNode.children.filter((c) => c.isNamed &&
434
- c.type !== "comment" &&
435
- c.type !== "line_comment" &&
436
- c.type !== "block_comment");
437
- if (meaningfulStatements.length > 0)
438
- continue;
439
- }
440
- }
441
- if (postFilter === "bare_except_only") {
442
- const clauseNode = captures.CLAUSE;
443
- if (clauseNode) {
444
- // Check if this is a bare except (no identifier after except)
445
- // biome-ignore lint/suspicious/noExplicitAny: Check for identifier
446
- const hasIdentifier = clauseNode.children.some((c) => c.isNamed && c.type === "identifier");
447
- if (hasIdentifier)
448
- continue; // Skip if has identifier (not bare)
449
- }
450
- }
451
- if (postFilter === "has_mixed_async") {
452
- const bodyNode = captures.BODY;
453
- if (bodyNode) {
454
- const bodyText = bodyNode.text;
455
- // Check if body contains both await AND (.then() or .catch())
456
- const hasAwait = bodyText.includes("await");
457
- const hasPromiseChain = /\.\s*(then|catch)\s*\(/.test(bodyText);
458
- if (!hasAwait || !hasPromiseChain)
459
- continue; // Skip if not mixed
460
- }
461
- }
462
- if (postFilter === "not_dbg_method") {
463
- const methodNode = captures.METHOD;
464
- if (methodNode) {
465
- const methodName = methodNode.text;
466
- if (methodName === "dbg")
467
- continue; // Skip console.dbg()
468
- }
469
- }
470
- if (postFilter === "no_super_call") {
471
- const bodyNode = captures.BODY;
472
- if (bodyNode) {
473
- // Check if body contains actual super() call (not in comments)
474
- const bodyText = bodyNode.text;
475
- // Match super() or super.method() but not // super() in comments
476
- const superCallRegex = /(?<!\/\/.*)super\s*\(/;
477
- const hasSuperCall = superCallRegex.test(bodyText);
478
- if (hasSuperCall)
479
- continue; // Skip if has super() - this is the GOOD case
480
- }
481
- }
482
- // Use first capture for position info
483
- if (match.captures.length > 0) {
484
- const firstNode = match.captures[0].node;
485
- // Convert captures to text for the result
486
- const textCaptures = {};
487
- for (const [name, node] of Object.entries(captures)) {
488
- textCaptures[name] = node.text;
489
- }
490
- matches.push({
491
- file: filePath,
492
- line: firstNode.startPosition.row + 1,
493
- column: firstNode.startPosition.column + 1,
494
- matchedText: firstNode.text,
495
- captures: textCaptures,
496
- });
497
- }
498
- }
499
- if (matches.length > 0) {
500
- this.dbg(`Found ${matches.length} matches in ${path.basename(filePath)}`);
501
- }
502
- }
503
- catch (err) {
504
- this.dbg(`Query matching error: ${err}`);
505
- }
506
- return matches;
507
- }
508
- /** Collect source files for a language */
509
- collectFiles(dir, languageId, fileFilter) {
510
- const files = [];
511
- const extensions = this.getExtensionsForLanguage(languageId);
512
- const scan = (d) => {
513
- try {
514
- const entries = fs.readdirSync(d, { withFileTypes: true });
515
- for (const entry of entries) {
516
- const full = path.join(d, entry.name);
517
- if (entry.isDirectory()) {
518
- if (EXCLUDED_DIRS.includes(entry.name))
519
- continue;
520
- scan(full);
521
- }
522
- else if (extensions.some((ext) => entry.name.endsWith(ext))) {
523
- if (!fileFilter || fileFilter(full)) {
524
- files.push(full);
525
- }
526
- }
527
- }
528
- }
529
- catch { }
530
- };
531
- scan(dir);
532
- return files;
533
- }
534
- /** Get file extensions for a language */
535
- getExtensionsForLanguage(languageId) {
536
- const mapping = {
537
- typescript: [".ts", ".mts", ".cts"],
538
- tsx: [".tsx"],
539
- javascript: [".js", ".mjs", ".cjs"],
540
- python: [".py"],
541
- rust: [".rs"],
542
- go: [".go"],
543
- java: [".java"],
544
- c: [".c", ".h"],
545
- cpp: [".cpp", ".hpp", ".cc", ".hh"],
546
- ruby: [".rb"],
547
- };
548
- return mapping[languageId] || [];
549
- }
550
- }
551
- // --- Simplified Pattern Search (regex fallback) ---
552
- /**
553
- * Fallback structural search using regex when tree-sitter unavailable
554
- * Less accurate but works without WASM dependencies
555
- */
556
- export function regexStructuralSearch(pattern, files, options = {}) {
557
- const matches = [];
558
- const maxResults = options.maxResults ?? 50;
559
- // Extract pattern structure for regex
560
- // "console.log($MSG)" -> /console\.log\(([^)]+)\)/
561
- const regexPattern = pattern
562
- .replace(/\./g, "\\.")
563
- .replace(/\$\$\$[A-Z_][A-Z0-9_]*/g, "(.*?)") // variadic - non-greedy
564
- .replace(/\$[A-Z_][A-Z0-9_]*/g, "([^,)]+)"); // single - capture group
565
- try {
566
- const regex = new RegExp(regexPattern, "g");
567
- for (const file of files) {
568
- if (matches.length >= maxResults)
569
- break;
570
- try {
571
- const content = fs.readFileSync(file, "utf-8");
572
- const lines = content.split("\n");
573
- for (let i = 0; i < lines.length; i++) {
574
- regex.lastIndex = 0;
575
- const match = regex.exec(lines[i]);
576
- if (match) {
577
- const captures = {};
578
- // Extract captures
579
- for (let j = 1; j < match.length; j++) {
580
- captures[`$${j}`] = match[j];
581
- }
582
- matches.push({
583
- file,
584
- line: i + 1,
585
- column: match.index + 1,
586
- matchedText: match[0],
587
- captures,
588
- });
589
- if (matches.length >= maxResults)
590
- break;
591
- }
592
- }
593
- }
594
- catch { }
595
- }
596
- }
597
- catch {
598
- // Invalid regex
599
- }
600
- return matches;
601
- }