Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222import { createRequire } from "node:module";import { extname } from "node:path";import { truncateHead } from "@earendil-works/pi-coding-agent";import { countTokens } from "gpt-tokenizer/encoding/o200k_base";import { Language, Parser, type Node, type Tree } from "web-tree-sitter";
type SourceLanguage = "typescript" | "tsx" | "go" | "rust" | "python" | "c" | "lua" | "bash";
const require = createRequire(import.meta.url);const grammars = new Map<SourceLanguage, string>([ ["typescript", "tree-sitter-typescript/tree-sitter-typescript.wasm"], ["tsx", "tree-sitter-typescript/tree-sitter-tsx.wasm"], ["go", "tree-sitter-go/tree-sitter-go.wasm"], ["rust", "tree-sitter-rust/tree-sitter-rust.wasm"], ["python", "tree-sitter-python/tree-sitter-python.wasm"], ["c", "tree-sitter-c/tree-sitter-c.wasm"], ["lua", "@tree-sitter-grammars/tree-sitter-lua/tree-sitter-lua.wasm"], ["bash", "tree-sitter-bash/tree-sitter-bash.wasm"],]);const extensions = new Map<string, SourceLanguage>([ [".ts", "typescript"], [".mts", "typescript"], [".cts", "typescript"], [".tsx", "tsx"], [".go", "go"], [".rs", "rust"], [".py", "python"], [".pyi", "python"], [".c", "c"], [".h", "c"], [".lua", "lua"], [".sh", "bash"], [".bash", "bash"],]);const callableKinds = new Set([ "function_declaration", "function_expression", "generator_function_declaration", "generator_function", "method_definition", "arrow_function", "method_declaration", "func_literal", "function_item", "closure_expression", "function_definition", "lambda",]);let runtime: Promise<void> | undefined;const parsers = new Map<SourceLanguage, Promise<Parser>>();
export interface Declaration { kind: string; startLine: number; endLine: number; text: string;}
export interface OutlineResult { declarations: Declaration[]; mode: "raw" | "outline"; output: string; reason?: string; error?: string; omittedBodies: number;}
function range(node: Node): string { return `[${node.startPosition.row + 1}-${node.endPosition.row + 1}]`;}
export function referenceTokens(source: string): number { return countTokens(source, { disallowedSpecial: new Set() });}
export function languageForPath(path: string): SourceLanguage | undefined { return extensions.get(extname(path).toLowerCase());}
export async function outline( path: string, source: string, signal?: AbortSignal,): Promise<OutlineResult> { signal?.throwIfAborted(); const language = languageForPath(path); const result: OutlineResult = { mode: "raw", output: source, declarations: [], omittedBodies: 0, }; if (!language) { result.reason = "unsupported"; return result; } if (truncateHead(source).truncated) { result.reason = "oversized"; return result; } if (source.includes("\0")) { result.reason = "binary"; return result; }
let tree: Tree | null = null; try { let pending = parsers.get(language); if (!pending) { pending = (async () => { runtime ??= Parser.init({ locateFile: () => require.resolve("web-tree-sitter/web-tree-sitter.wasm"), }); await runtime; const grammarPath = grammars.get(language)!; const grammar = await Language.load(require.resolve(grammarPath)); const parser = new Parser(); parser.setLanguage(grammar); return parser; })(); parsers.set(language, pending); } const parser = await pending; signal?.throwIfAborted(); const parseStart = performance.now(); tree = parser.parse(source, null, { progressCallback: () => signal?.aborted || performance.now() - parseStart > 100, }); if (!tree) { parser.reset(); signal?.throwIfAborted(); result.reason = "timeout"; return result; } if (tree.rootNode.hasError) { result.reason = "syntax-error"; return result; }
let previousEnd = 0; const declarations: Declaration[] = []; const snippets = tree.rootNode.namedChildren.map((statement) => { const gap = source.slice(previousEnd, statement.startIndex); previousEnd = statement.endIndex; const cuts: Node[] = []; function visit(node: Node): void { const body = callableKinds.has(node.type) ? node.childForFieldName("body") : null; if (body) { cuts.push(body); return; } for (const child of node.namedChildren) { visit(child); } } visit(statement); let cursor = statement.startIndex; const pieces: string[] = []; for (const body of cuts) { pieces.push(source.slice(cursor, body.startIndex)); const label = `… ${range(body.parent!)}`; pieces.push( body.type === "compound_statement" && body.firstChild?.type === "((" ? `(( ${label} ))` : body.type === "compound_statement" || body.type === "statement_block" || (body.type === "block" && language !== "python" && language !== "lua") ? `{ ${label} }` : body.type === "subshell" ? `( ${label} )` : label, ); cursor = body.endIndex; } pieces.push(source.slice(cursor, statement.endIndex)); result.omittedBodies += cuts.length; const text = pieces.join(""); declarations.push({ kind: statement.type, startLine: statement.startPosition.row + 1, endLine: statement.endPosition.row + 1, text, }); return `${gap}${range(statement)} ${text}`; }); const output = "SOURCE OUTLINE — function bodies omitted; ranges refer to original lines. Read original ranges before edits or behavior claims.\n" + snippets.join("") + source.slice(previousEnd); if (!result.omittedBodies || Buffer.byteLength(output) >= Buffer.byteLength(source)) { result.reason = result.omittedBodies ? "no-reduction" : "no-bodies"; return result; } const reducesTokens = referenceTokens(output) < referenceTokens(source); if (!reducesTokens) { result.reason = "no-token-reduction"; return result; } result.mode = "outline"; result.output = output; result.declarations = declarations; return result; } catch (error) { signal?.throwIfAborted(); result.reason = "parser-error"; result.error = String(error); return result; } finally { tree?.delete(); }}
export async function closeParsers(): Promise<void> { const loaded = await Promise.allSettled(parsers.values()); for (const entry of loaded) { if (entry.status === "fulfilled") { entry.value.delete(); } } parsers.clear();}