| 1 | import { distance } from "fastest-levenshtein"; |
| 2 | |
| 3 | import { ChatMessage } from "../index.js"; |
| 4 | import { renderChatMessage } from "../util/messageContent.js"; |
| 5 | |
| 6 | export type LineStream = AsyncGenerator<string>; |
| 7 | |
| 8 | export type MatchLineResult = { |
| 9 | /** |
| 10 | * -1 if it's a new line, otherwise the index of the first match |
| 11 | * in the old lines. |
| 12 | */ |
| 13 | matchIndex: number; |
| 14 | isPerfectMatch: boolean; |
| 15 | newLine: string; |
| 16 | }; |
| 17 | |
| 18 | function linesMatchPerfectly(lineA: string, lineB: string): boolean { |
| 19 | return lineA === lineB && lineA !== ""; |
| 20 | } |
| 21 | |
| 22 | const END_BRACKETS = ["}", "});", "})"]; |
| 23 | |
| 24 | function linesMatch(lineA: string, lineB: string, linesBetween = 0): boolean { |
| 25 | // Require a perfect (without padding) match for these lines |
| 26 | // Otherwise they are edit distance 1 from empty lines and other single char lines (e.g. each other) |
| 27 | if (["}", "*", "});", "})"].includes(lineA.trim())) { |
| 28 | return lineA.trim() === lineB.trim(); |
| 29 | } |
| 30 | |
| 31 | const d = distance(lineA, lineB); |
| 32 | |
| 33 | return ( |
| 34 | // Should be more unlikely for lines to fuzzy match if they are further away |
| 35 | (d / Math.max(lineA.length, lineB.length) <= |
| 36 | Math.max(0, 0.48 - linesBetween * 0.06) || |
| 37 | lineA.trim() === lineB.trim()) && |
| 38 | lineA.trim() !== "" |
| 39 | ); |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Used to find a match for a new line in an array of old lines. |
| 44 | * |
| 45 | * Return the index of the first match and whether it is a perfect match |
| 46 | * Also return a version of the line with correct indentation if needs fixing |
| 47 | */ |
| 48 | export function matchLine( |
| 49 | newLine: string, |
| 50 | oldLines: string[], |
| 51 | permissiveAboutIndentation = false, |
| 52 | ): MatchLineResult { |
| 53 | // Only match empty lines if it's the next one: |
| 54 | if (newLine.trim() === "" && oldLines[0]?.trim() === "") { |
| 55 | return { |
| 56 | matchIndex: 0, |
| 57 | isPerfectMatch: true, |
| 58 | newLine: newLine.trim(), |
| 59 | }; |
| 60 | } |
| 61 | |
| 62 | const isEndBracket = END_BRACKETS.includes(newLine.trim()); |
| 63 | |
| 64 | for (let i = 0; i < oldLines.length; i++) { |
| 65 | // trims trailing whitespaces from the lines before comparison |
| 66 | //this ensures trailing spaces don't affect matching. |
| 67 | const oldLineTrimmed = oldLines[i].trimEnd(); |
| 68 | const newLineTrimmed = newLine.trimEnd(); |
| 69 | |
| 70 | // Don't match end bracket lines if too far away |
| 71 | if (i > 4 && isEndBracket) { |
| 72 | return { matchIndex: -1, isPerfectMatch: false, newLine }; |
| 73 | } |
| 74 | |
| 75 | if (linesMatchPerfectly(newLineTrimmed, oldLineTrimmed)) { |
| 76 | return { matchIndex: i, isPerfectMatch: true, newLine }; |
| 77 | } |
| 78 | if (linesMatch(newLineTrimmed, oldLineTrimmed, i)) { |
| 79 | // This is a way to fix indentation, but only for sufficiently long lines to avoid matching whitespace or short lines |
| 80 | if ( |
| 81 | newLineTrimmed.trimStart() === oldLineTrimmed.trimStart() && |
| 82 | (permissiveAboutIndentation || newLine.trim().length > 8) |
| 83 | ) { |
| 84 | return { |
| 85 | matchIndex: i, |
| 86 | isPerfectMatch: true, |
| 87 | newLine: oldLines[i], |
| 88 | }; |
| 89 | } |
| 90 | return { matchIndex: i, isPerfectMatch: false, newLine }; |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | return { matchIndex: -1, isPerfectMatch: false, newLine }; |
| 95 | } |
| 96 | |
| 97 | /** |
| 98 | * Convert a stream of arbitrary chunks to a stream of lines |
| 99 | */ |
| 100 | export async function* streamLines( |
| 101 | streamCompletion: AsyncGenerator<string | ChatMessage>, |
| 102 | log: boolean = false, |
| 103 | ): LineStream { |
| 104 | let allLines = []; |
| 105 | |
| 106 | let buffer = ""; |
| 107 | |
| 108 | try { |
| 109 | for await (const update of streamCompletion) { |
| 110 | const chunk = |
| 111 | typeof update === "string" ? update : renderChatMessage(update); |
| 112 | buffer += chunk; |
| 113 | const lines = buffer.split("\n"); |
| 114 | buffer = lines.pop() ?? ""; |
| 115 | for (const line of lines) { |
| 116 | yield line; |
| 117 | allLines.push(line); |
| 118 | } |
| 119 | |
| 120 | // if (buffer === "" && chunk.endsWith("\n")) { |
| 121 | // yield ""; |
| 122 | // allLines.push(""); |
| 123 | // } |
| 124 | } |
| 125 | if (buffer.length > 0) { |
| 126 | yield buffer; |
| 127 | allLines.push(buffer); |
| 128 | } |
| 129 | } finally { |
| 130 | if (log) { |
| 131 | console.log("Streamed lines: ", allLines.join("\n")); |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | export async function* generateLines<T>(lines: T[]): AsyncGenerator<T> { |
| 137 | for (const line of lines) { |
| 138 | yield line; |
| 139 | // await new Promise((resolve, reject) => setTimeout(() => resolve(null), 50)); |
| 140 | } |
| 141 | } |