Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 | 1x 7x 7x 5x 5x 7x 12x 11x 11x 11x 11x 10x 10x 9x 7x 5x 5x 1x 25x 19x 19x 19x 10x 10x 10x 20x 19x 11x 11x 11x 11x 19x 37x 37x 19x 19x 37x 26x 26x 26x 26x 26x 38x 37x 26x 9x 2x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 1x 7x 7x 7x 10x 9x 9x 9x 9x 8x 8x 8x 7x 7x 7x 23x 23x 23x 25x 3x 1x 2x 1x 1x 1x 4x 4x 3x 1x 1x 1x 2x 3x 2x 2x 1x 20x 20x 20x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 6x 6x 6x 2x 2x 2x 2x 2x 2x 1x | #!/usr/bin/env node
/**
* AST-aware structural code search powered by @ast-grep/napi.
*
* Usage:
* node scripts/ast-search.js --pattern 'console.log($$$ARGS)' --root ./src
* node scripts/ast-search.js --preset empty-catch --root ./packages
* node scripts/ast-search.js --kind function_declaration --root ./src --json
*/
import fs from 'node:fs';
import path from 'node:path';
import { js as astJs, ts as astTs, tsx as astTsx } from '@ast-grep/napi';
import { ALLOWED_EXTS } from './types.js';
import type { NapiConfig, SgNode, SgRoot } from '@ast-grep/napi';
// ─── Types ──────────────────────────────────────────────────────────────────
export interface AstSearchOptions {
root: string;
pattern: string | null;
kind: string | null;
preset: string | null;
rule: NapiConfig | null;
json: boolean;
limit: number;
includeTests: boolean;
ignoreDirs: Set<string>;
context: number;
}
export interface AstMatch {
file: string;
kind: string;
text: string;
lineStart: number;
lineEnd: number;
columnStart: number;
columnEnd: number;
metaVariables?: Record<string, string>;
}
export interface AstSearchResult {
query: string;
queryType: 'pattern' | 'kind' | 'preset' | 'rule';
totalMatches: number;
totalFiles: number;
matches: AstMatch[];
/** Source lines keyed by relative file path — only populated when context > 0 */
_sourceByFile?: Map<string, string[]>;
}
// ─── Presets ────────────────────────────────────────────────────────────────
type PresetRule = NapiConfig & { description: string };
export const PRESETS: Record<string, PresetRule> = {
'empty-catch': {
rule: {
kind: 'catch_clause',
has: {
kind: 'statement_block',
regex: '^\\{\\s*\\}$',
},
},
description: 'Empty catch blocks that silently swallow errors',
},
'console-log': {
rule: {
pattern: 'console.log($$$ARGS)',
},
description: 'console.log calls left in production code',
},
'console-any': {
rule: {
pattern: 'console.$METHOD($$$ARGS)',
},
description: 'Any console method call (log, warn, error, debug, etc.)',
},
'debugger': {
rule: {
kind: 'debugger_statement',
},
description: 'Debugger statements left in code',
},
'todo-fixme': {
rule: {
kind: 'comment',
regex: '(?i)(TODO|FIXME|HACK|XXX|BUG)',
},
description: 'TODO, FIXME, HACK, XXX, BUG comments',
},
'any-type': {
rule: {
kind: 'predefined_type',
regex: '^any$',
},
description: 'Explicit `any` type annotations',
},
'type-assertion': {
rule: {
kind: 'as_expression',
},
description: 'TypeScript type assertions (as X)',
},
'non-null-assertion': {
rule: {
kind: 'non_null_expression',
},
description: 'Non-null assertions (x!)',
},
'fat-arrow-body': {
rule: {
kind: 'arrow_function',
has: {
kind: 'statement_block',
},
},
description: 'Arrow functions with statement block bodies (could be expression)',
},
'nested-ternary': {
rule: {
kind: 'ternary_expression',
has: {
kind: 'ternary_expression',
stopBy: 'end',
},
},
description: 'Nested ternary expressions (hard to read)',
},
'throw-string': {
rule: {
kind: 'throw_statement',
has: {
kind: 'string',
},
},
description: 'Throwing string literals instead of Error objects',
},
'switch-no-default': {
rule: {
kind: 'switch_statement',
not: {
has: {
kind: 'switch_default',
stopBy: 'end',
},
},
},
description: 'Switch statements without a default case',
},
'class-declaration': {
rule: {
kind: 'class_declaration',
},
description: 'All class declarations',
},
'async-function': {
rule: {
kind: 'function_declaration',
regex: '^async ',
},
description: 'Async function declarations',
},
'export-default': {
rule: {
kind: 'export_statement',
has: {
field: 'default',
},
},
description: 'Default exports',
},
'import-star': {
rule: {
kind: 'import_statement',
has: {
kind: 'namespace_import',
},
},
description: 'Namespace imports (import * as X)',
},
};
// ─── File Collection ────────────────────────────────────────────────────────
function isTestFile(filePath: string): boolean {
const base = path.basename(filePath);
return /\.(test|spec)\.(ts|tsx|js|jsx|mjs|cjs)$/.test(base)
|| base.startsWith('test_')
|| filePath.includes('__tests__');
}
export function collectSearchFiles(root: string, opts: Pick<AstSearchOptions, 'includeTests' | 'ignoreDirs'>): string[] {
const files: string[] = [];
const walk = (dir: string): void => {
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
entries.sort((a, b) => a.name.localeCompare(b.name));
for (const entry of entries) {
if (opts.ignoreDirs.has(entry.name)) continue;
Iif (entry.isSymbolicLink()) continue;
const next = path.join(dir, entry.name);
if (entry.isDirectory()) { walk(next); continue; }
Iif (!entry.isFile()) continue;
if (entry.name.endsWith('.d.ts')) continue;
const ext = path.extname(entry.name);
if (!ALLOWED_EXTS.has(ext)) continue;
if (!opts.includeTests && isTestFile(next)) continue;
files.push(next);
}
};
walk(root);
return files;
}
// ─── Parser Selection ───────────────────────────────────────────────────────
type AstParser = { parse(src: string): SgRoot };
function parserForExt(ext: string): AstParser {
switch (ext) {
case '.tsx':
return astTsx;
case '.jsx':
return astJs;
case '.js':
case '.mjs':
case '.cjs':
return astJs;
case '.ts':
default:
return astTs;
}
}
// ─── Core Search ────────────────────────────────────────────────────────────
function extractMetaVars(node: SgNode, pattern: string): Record<string, string> {
const vars: Record<string, string> = {};
let match: RegExpExecArray | null;
const triplePattern = /\$\$\$([A-Z_][A-Z0-9_]*)/g;
const triplNames = new Set<string>();
while ((match = triplePattern.exec(pattern)) !== null) {
const name = match[1];
triplNames.add(name);
const multiMatch = node.getMultipleMatches(name);
if (multiMatch.length > 0) {
vars[`$$$${name}`] = multiMatch.map(n => n.text()).join(', ');
}
}
const singlePattern = /(?<!\$)\$([A-Z_][A-Z0-9_]*)(?!\$)/g;
while ((match = singlePattern.exec(pattern)) !== null) {
const name = match[1];
Iif (triplNames.has(name)) continue;
const matchNode = node.getMatch(name);
Eif (matchNode) vars[`$${name}`] = matchNode.text();
}
return vars;
}
function nodeToMatch(node: SgNode, file: string, pattern: string | null): AstMatch {
const range = node.range();
const result: AstMatch = {
file,
kind: String(node.kind()),
text: node.text(),
lineStart: range.start.line + 1,
lineEnd: range.end.line + 1,
columnStart: range.start.column,
columnEnd: range.end.column,
};
if (pattern) {
const vars = extractMetaVars(node, pattern);
Eif (Object.keys(vars).length > 0) result.metaVariables = vars;
}
return result;
}
export function searchFile(
filePath: string,
source: string,
matcher: string | number | NapiConfig,
patternStr: string | null,
limit: number,
): AstMatch[] {
const ext = path.extname(filePath);
const parser = parserForExt(ext);
let nodes: SgNode[];
try {
const root = parser.parse(source).root();
nodes = root.findAll(matcher);
} catch {
return [];
}
const matches: AstMatch[] = [];
for (const node of nodes) {
if (matches.length >= limit) break;
matches.push(nodeToMatch(node, filePath, patternStr));
}
return matches;
}
export function runSearch(files: string[], opts: AstSearchOptions, root: string): AstSearchResult {
let matcher: string | NapiConfig;
let queryLabel: string;
let queryType: AstSearchResult['queryType'];
let patternStr: string | null = null;
if (opts.preset) {
const preset = PRESETS[opts.preset];
if (!preset) {
const available = Object.keys(PRESETS).join(', ');
throw new Error(`Unknown preset: "${opts.preset}". Available: ${available}`);
}
matcher = preset;
queryLabel = `preset:${opts.preset} — ${preset.description}`;
queryType = 'preset';
} else if (opts.rule) {
matcher = opts.rule;
queryLabel = `rule:${JSON.stringify(opts.rule)}`;
queryType = 'rule';
} else if (opts.kind) {
matcher = { rule: { kind: opts.kind } } as NapiConfig;
queryLabel = `kind:${opts.kind}`;
queryType = 'kind';
} else if (opts.pattern) {
matcher = opts.pattern;
patternStr = opts.pattern;
queryLabel = `pattern:${opts.pattern}`;
queryType = 'pattern';
} else {
throw new Error('Must provide --pattern, --kind, --preset, or --rule');
}
const allMatches: AstMatch[] = [];
const filesWithMatches = new Set<string>();
const sourceByFile = opts.context > 0 ? new Map<string, string[]>() : undefined;
for (const filePath of files) {
if (allMatches.length >= opts.limit) break;
let source: string;
try {
source = fs.readFileSync(filePath, 'utf8');
} catch {
continue;
}
const relFile = path.relative(root, filePath);
const remaining = opts.limit - allMatches.length;
const fileMatches = searchFile(relFile, source, matcher, patternStr, remaining);
if (fileMatches.length > 0) {
filesWithMatches.add(relFile);
allMatches.push(...fileMatches);
if (sourceByFile) sourceByFile.set(relFile, source.split('\n'));
}
}
const result: AstSearchResult = {
query: queryLabel,
queryType,
totalMatches: allMatches.length,
totalFiles: filesWithMatches.size,
matches: allMatches,
};
if (sourceByFile) result._sourceByFile = sourceByFile;
return result;
}
// ─── CLI ────────────────────────────────────────────────────────────────────
interface ParsedSearchArgs {
opts: AstSearchOptions;
listPresets: boolean;
}
export function parseSearchArgs(argv: string[]): ParsedSearchArgs {
const opts: AstSearchOptions = {
root: process.cwd(),
pattern: null,
kind: null,
preset: null,
rule: null,
json: false,
limit: 500,
includeTests: false,
ignoreDirs: new Set([
'.git', '.next', '.yarn', '.cache', '.octocode',
'node_modules', 'dist', 'coverage', 'out',
]),
context: 0,
};
let listPresets = false;
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--pattern' || arg === '-p') { opts.pattern = argv[++i]; continue; }
if (arg.startsWith('--pattern=')) { opts.pattern = arg.slice('--pattern='.length); continue; }
if (arg === '--kind' || arg === '-k') { opts.kind = argv[++i]; continue; }
if (arg.startsWith('--kind=')) { opts.kind = arg.slice('--kind='.length); continue; }
if (arg === '--preset') { opts.preset = argv[++i]; continue; }
if (arg.startsWith('--preset=')) { opts.preset = arg.slice('--preset='.length); continue; }
if (arg === '--rule') {
const raw = argv[++i];
try { opts.rule = JSON.parse(raw) as NapiConfig; } catch {
throw new Error(`Invalid --rule JSON: ${raw?.slice(0, 100) ?? '(empty)'}`);
}
continue;
}
if (arg === '--root') { opts.root = path.resolve(argv[++i]); continue; }
if (arg.startsWith('--root=')) { opts.root = path.resolve(arg.slice('--root='.length)); continue; }
if (arg === '--json') { opts.json = true; continue; }
if (arg === '--limit') { opts.limit = parseInt(argv[++i], 10); continue; }
if (arg === '--include-tests') { opts.includeTests = true; continue; }
if (arg === '--context' || arg === '-C') { opts.context = parseInt(argv[++i], 10); continue; }
if (arg === '--list-presets') { listPresets = true; continue; }
if (arg === '--help' || arg === '-h') { printSearchHelp(); process.exit(0); }
}
if (Number.isNaN(opts.limit)) opts.limit = 500;
Iif (Number.isNaN(opts.context)) opts.context = 0;
return { opts, listPresets };
}
function printSearchHelp(): void {
console.log(`
ast-search — Structural code search powered by ast-grep
Usage:
node scripts/ast-search.js [options]
Search modes (pick one):
--pattern, -p <code> Match code structurally (e.g. 'console.log($$$ARGS)')
--kind, -k <kind> Match AST node kind (e.g. 'function_declaration')
--preset <name> Use a built-in search preset (e.g. 'empty-catch')
--rule <json> Raw ast-grep rule object as JSON
Options:
--root <path> Search root directory (default: cwd)
--json Output as JSON
--limit N Max matches (default: 500)
--include-tests Include test files
--context, -C N Lines of context around matches (text output only)
--list-presets Show available presets and exit
--help, -h Show this message
Pattern wildcards:
$NAME Match any single AST node
$$$NAME Match zero or more nodes (variadic)
Examples:
node scripts/ast-search.js -p 'console.log($$$ARGS)' --root ./src
node scripts/ast-search.js --preset empty-catch --root ./packages
node scripts/ast-search.js -k function_declaration --json --limit 20
node scripts/ast-search.js --preset todo-fixme --include-tests
node scripts/ast-search.js -p 'if ($COND) { return $VAL }' --root ./src
node scripts/ast-search.js --rule '{"rule":{"kind":"catch_clause"}}' --root ./src
Presets:
${Object.entries(PRESETS).map(([name, p]) => ` ${name.padEnd(22)} ${p.description}`).join('\n')}
`);
}
export function formatTextOutput(result: AstSearchResult, opts: AstSearchOptions, _root: string): string {
const lines: string[] = [];
lines.push(`\n🔍 ${result.query}`);
lines.push(` ${result.totalMatches} matches across ${result.totalFiles} files\n`);
const ctx = opts.context;
const sourceMap = result._sourceByFile;
let currentFile = '';
for (const m of result.matches) {
if (m.file !== currentFile) {
currentFile = m.file;
lines.push(`\n── ${currentFile} ──`);
}
if (ctx > 0 && sourceMap) {
const srcLines = sourceMap.get(m.file);
if (srcLines) {
const start = Math.max(0, m.lineStart - 1 - ctx);
const end = Math.min(srcLines.length, m.lineEnd + ctx);
for (let i = start; i < end; i++) {
const lineNum = i + 1;
const marker = (lineNum >= m.lineStart && lineNum <= m.lineEnd) ? '>' : ' ';
lines.push(` ${marker} ${String(lineNum).padStart(4)} | ${srcLines[i]}`);
}
lines.push('');
continue;
}
}
const truncatedText = m.text.length > 200
? m.text.slice(0, 200) + '…'
: m.text;
const singleLine = truncatedText.replace(/\n/g, '↵').replace(/\s+/g, ' ');
lines.push(` L${m.lineStart}:${m.columnStart} [${m.kind}] ${singleLine}`);
if (m.metaVariables && Object.keys(m.metaVariables).length > 0) {
for (const [k, v] of Object.entries(m.metaVariables)) {
const truncV = v.length > 80 ? v.slice(0, 80) + '…' : v;
lines.push(` ${k} = ${truncV}`);
}
}
}
lines.push('');
return lines.join('\n');
}
async function main(): Promise<void> {
const { opts, listPresets } = parseSearchArgs(process.argv.slice(2));
if (listPresets) {
if (opts.json) {
console.log(JSON.stringify(PRESETS, null, 2));
} else {
console.log('\nAvailable presets:\n');
for (const [name, preset] of Object.entries(PRESETS)) {
console.log(` ${name.padEnd(22)} ${preset.description}`);
}
console.log('');
}
return;
}
if (!opts.pattern && !opts.kind && !opts.preset && !opts.rule) {
console.error('Error: Must provide --pattern, --kind, --preset, or --rule');
console.error('Run with --help for usage information.');
process.exit(1);
}
const files = collectSearchFiles(opts.root, opts);
if (files.length === 0) {
console.error(`No files found in ${opts.root}`);
process.exit(1);
}
const result = runSearch(files, opts, opts.root);
if (opts.json) {
console.log(JSON.stringify(result, null, 2));
} else {
console.log(formatTextOutput(result, opts, opts.root));
}
}
const isDirectRun = process.argv[1] && (
import.meta.url.endsWith(process.argv[1].replace(/\\/g, '/'))
|| import.meta.url.endsWith('/scripts/ast-search.js')
);
if (isDirectRun) {
main().catch((error: unknown) => {
console.error(error);
process.exit(1);
});
}
|