| 1 | import { RangeInFileWithContents, SymbolWithRange } from "core"; |
| 2 | |
| 3 | const terminalLanguages = ["bash", "sh"]; |
| 4 | const commonTerminalCommands = [ |
| 5 | "npm", |
| 6 | "pnpm", |
| 7 | "yarn", |
| 8 | "bun", |
| 9 | "deno", |
| 10 | "npx", |
| 11 | "cd", |
| 12 | "ls", |
| 13 | "pwd", |
| 14 | "pip", |
| 15 | "python", |
| 16 | "node", |
| 17 | "git", |
| 18 | "curl", |
| 19 | "wget", |
| 20 | "rbenv", |
| 21 | "gem", |
| 22 | "ruby", |
| 23 | "bundle", |
| 24 | ]; |
| 25 | |
| 26 | export function isTerminalCodeBlock( |
| 27 | language: string | undefined | null, |
| 28 | text: string, |
| 29 | ) { |
| 30 | return ( |
| 31 | (language && terminalLanguages.includes(language)) || |
| 32 | ((!language || language?.length === 0) && |
| 33 | (text.trim().split("\n").length === 1 || |
| 34 | commonTerminalCommands.some((c) => text.trim().startsWith(c)))) |
| 35 | ); |
| 36 | } |
| 37 | |
| 38 | function childToText(child: any): string { |
| 39 | if (typeof child === "string") { |
| 40 | return child; |
| 41 | } else if (child?.props) { |
| 42 | return childToText(child.props?.children); |
| 43 | } else if (Array.isArray(child)) { |
| 44 | return childrenToText(child); |
| 45 | } else { |
| 46 | return ""; |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | export function childrenToText(children: any) { |
| 51 | return children.map((child: any) => childToText(child)).join(""); |
| 52 | } |
| 53 | |
| 54 | export function matchCodeToSymbolOrFile( |
| 55 | content: string, |
| 56 | symbols: SymbolWithRange[], |
| 57 | rifs: RangeInFileWithContents[], |
| 58 | ): SymbolWithRange | RangeInFileWithContents | undefined { |
| 59 | // Insert file links for matching previous context items |
| 60 | // With some reasonable limitations on what might be a filename |
| 61 | if (rifs.length && content.includes(".") && content.length > 2) { |
| 62 | const match = rifs.find( |
| 63 | (rif) => rif.filepath.split("/").pop() === content, // Exact match for last segment of URI |
| 64 | ); |
| 65 | |
| 66 | if (match) { |
| 67 | return match; |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | // Insert symbols for exact matches |
| 72 | const exactSymbol = symbols.find((s) => s.name === content); |
| 73 | if (exactSymbol) { |
| 74 | return exactSymbol; |
| 75 | } |
| 76 | |
| 77 | // Partial matches - this is the case where the llm returns e.g. `subtract(number)` instead of `subtract` |
| 78 | const partialSymbol = symbols.find((s) => content.startsWith(s.name)); |
| 79 | if (partialSymbol) { |
| 80 | return partialSymbol; |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | export function isSymbolNotRif( |
| 85 | item: SymbolWithRange | RangeInFileWithContents, |
| 86 | ): item is SymbolWithRange { |
| 87 | return (item as SymbolWithRange).type !== undefined; |
| 88 | } |