From 4bd76b662dd9e7c1939dc3adae054f267af86ff7 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 13 Apr 2024 23:55:44 -0700 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20run=20biome=20check=20on=20core?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- binary/biome.json | 15 ------ binary/src/index.ts | 2 +- binary/src/messenger.ts | 6 +-- biome.json | 4 ++ core/autocomplete/completionProvider.ts | 6 +-- core/autocomplete/lineStream.ts | 7 ++- core/autocomplete/ranking.ts | 36 +++++++------- core/autocomplete/templates.ts | 6 +-- core/autocomplete/util.ts | 2 +- core/commands/slash/draftIssue.ts | 2 +- core/commands/slash/edit.ts | 26 +++++----- core/commands/slash/review.ts | 2 +- core/config/load.ts | 25 +++++----- core/config/util.ts | 2 +- .../providers/DatabaseContextProvider.ts | 8 +-- .../providers/FileTreeContextProvider.ts | 8 +-- .../providers/GitHubIssuesContextProvider.ts | 2 +- .../GitLabMergeRequestContextProvider.ts | 22 ++++----- .../providers/GoogleContextProvider.ts | 8 +-- .../JiraIssuesContextProvider/JiraClient.ts | 22 ++++----- core/context/providers/LocalsProvider.ts | 4 +- core/context/providers/OSContextProvider.ts | 2 +- .../providers/PostgresContextProvider.ts | 18 ++----- .../providers/ProblemsContextProvider.ts | 2 +- core/context/rerankers/llm.ts | 12 ++--- core/diff/util.ts | 3 +- core/indexing/CodeSnippetsIndex.ts | 18 +++---- core/indexing/FullTextSearch.ts | 10 ++-- core/indexing/LanceDbIndex.ts | 6 +-- core/indexing/chunk/ChunkCodebaseIndex.ts | 12 ++--- core/indexing/chunk/basic.ts | 2 +- core/indexing/chunk/code.ts | 16 +++--- core/indexing/chunk/markdown.ts | 7 +-- core/indexing/docs/article.ts | 8 +-- core/indexing/docs/crawl.ts | 15 +++--- core/indexing/docs/db.ts | 6 +-- .../embeddings/FreeTrialEmbeddingsProvider.ts | 2 +- .../embeddings/OllamaEmbeddingsProvider.ts | 2 +- .../TransformersJsEmbeddingsProvider.ts | 11 +++-- .../embeddings/TransformersJsWorkerThread.js | 13 +++-- core/indexing/indexCodebase.ts | 2 +- core/indexing/refreshIndex.ts | 8 +-- core/llm/autodetect.ts | 2 +- core/llm/constructMessages.ts | 2 +- core/llm/countTokens.ts | 18 +++---- core/llm/llms/Anthropic.ts | 38 ++++++-------- core/llm/llms/Bedrock.ts | 49 +++++++++---------- core/llm/llms/Flowise.ts | 2 +- core/llm/llms/Gemini.ts | 4 +- core/llm/llms/Ollama.ts | 4 +- core/llm/llms/OpenAI.ts | 17 +++---- core/llm/llms/index.ts | 2 +- core/llm/stream.ts | 10 ++-- core/llm/templates/chat.ts | 2 +- core/util/devdata.ts | 2 +- core/util/devdataSqlite.ts | 4 +- core/util/fetchWithOptions.ts | 4 +- core/util/filesystem.ts | 2 +- core/util/history.ts | 9 ++-- core/util/index.ts | 2 +- core/util/merge.ts | 2 +- core/util/paths.ts | 11 ++--- core/util/posthog.ts | 2 +- core/util/treeSitter.ts | 2 +- extensions/vscode/biome.json | 15 ------ 65 files changed, 270 insertions(+), 325 deletions(-) delete mode 100644 binary/biome.json delete mode 100644 extensions/vscode/biome.json diff --git a/binary/biome.json b/binary/biome.json deleted file mode 100644 index 6308ce822..000000000 --- a/binary/biome.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "$schema": "https://biomejs.dev/schemas/1.6.4/schema.json", - "organizeImports": { - "enabled": true - }, - "linter": { - "enabled": true, - "rules": { - "recommended": true - } - }, - "formatter": { - "indentStyle": "space" - } -} diff --git a/binary/src/index.ts b/binary/src/index.ts index e78210ce1..59127b56d 100644 --- a/binary/src/index.ts +++ b/binary/src/index.ts @@ -1,5 +1,5 @@ process.env.IS_BINARY = "true"; -import fs from "fs"; +import fs from "node:fs"; import { Command } from "commander"; import { getCoreLogsPath } from "core/util/paths"; import { IpcIde } from "./IpcIde"; diff --git a/binary/src/messenger.ts b/binary/src/messenger.ts index 417a841f3..cfe44ac07 100644 --- a/binary/src/messenger.ts +++ b/binary/src/messenger.ts @@ -1,6 +1,6 @@ import { v4 as uuidv4 } from "uuid"; -import * as fs from "fs"; +import * as fs from "node:fs"; import { getCoreLogsPath } from "core/util/paths"; import type { Message } from "../../core/util/messenger"; import type { Protocol, ReverseProtocol } from "./protocol"; @@ -50,7 +50,7 @@ export class IpcMessenger { try { const msg: Message = JSON.parse(line); if (msg.messageType === undefined || msg.messageId === undefined) { - throw new Error("Invalid message sent: " + JSON.stringify(msg)); + throw new Error(`Invalid message sent: ${JSON.stringify(msg)}`); } // Call handler and respond with return value @@ -99,7 +99,7 @@ export class IpcMessenger { messageId, }; // process.send?.(data); - process.stdout?.write(JSON.stringify(data) + "\r\n"); + process.stdout?.write(`${JSON.stringify(data)}\r\n`); return messageId; } diff --git a/biome.json b/biome.json index 34018ee2d..3d76ea8f8 100644 --- a/biome.json +++ b/biome.json @@ -9,6 +9,10 @@ "recommended": true, "suspicious": { "noExplicitAny": "off" + }, + "style": { + "noUselessElse": "off", + "noNonNullAssertion": "off" } } }, diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index f64aa968d..5b8305a1c 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -69,11 +69,11 @@ function formatExternalSnippet( ) { const comment = language.comment; const lines = [ - comment + " Path: " + getBasename(filepath), + `${comment} Path: ${getBasename(filepath)}`, ...snippet .trim() .split("\n") - .map((line) => comment + " " + line), + .map((line) => `${comment} ${line}`), comment, ]; return lines.join("\n"); @@ -191,7 +191,7 @@ export async function getTabCompletion( ) .join("\n"); if (formattedSnippets.length > 0) { - prefix = formattedSnippets + "\n\n" + prefix; + prefix = `${formattedSnippets}\n\n${prefix}`; } prompt = compiledTemplate({ diff --git a/core/autocomplete/lineStream.ts b/core/autocomplete/lineStream.ts index 876e38d1e..dc3f5c4dc 100644 --- a/core/autocomplete/lineStream.ts +++ b/core/autocomplete/lineStream.ts @@ -8,7 +8,7 @@ export async function* noTopLevelKeywordsMidline( ): LineStream { for await (const line of lines) { for (const keyword of topLevelKeywords) { - const indexOf = line.indexOf(keyword + " "); + const indexOf = line.indexOf(`${keyword} `); if (indexOf >= 0 && line.slice(indexOf - 1, indexOf).trim() !== "") { yield line.slice(0, indexOf); break; @@ -26,7 +26,7 @@ export async function* avoidPathLine( // Sometimes the model with copy this pattern, which is unwanted for await (const line of stream) { // Also filter lines that are empty comments - if (line.startsWith(comment + " Path: ") || line.trim() === comment) { + if (line.startsWith(`${comment} Path: `) || line.trim() === comment) { continue; } yield line; @@ -112,9 +112,8 @@ export async function* filterCodeBlockLines(rawLines: LineStream): LineStream { if (!seenValidLine) { if (shouldRemoveLineBeforeStart(line)) { continue; - } else { - seenValidLine = true; } + seenValidLine = true; } // Filter out ending ``` diff --git a/core/autocomplete/ranking.ts b/core/autocomplete/ranking.ts index 175a28f29..007793134 100644 --- a/core/autocomplete/ranking.ts +++ b/core/autocomplete/ranking.ts @@ -114,7 +114,7 @@ function mergeOverlappingRangeContents( ): string { const firstLines = first.contents.split("\n"); const numOverlapping = first.range.end.line - second.range.start.line; - return firstLines.slice(-numOverlapping).join("\n") + "\n" + second.contents; + return `${firstLines.slice(-numOverlapping).join("\n")}\n${second.contents}`; } /** @@ -134,7 +134,6 @@ export function fillPromptWithSnippets( tokensRemaining -= tokenCount; keptSnippets.push(snippet); } else { - continue; } } @@ -146,18 +145,17 @@ function rangeIntersectionByLines(a: Range, b: Range): Range | null { const endLine = Math.min(a.end.line, b.end.line); if (startLine >= endLine) { return null; - } else { - return { - start: { - line: startLine, - character: 0, - }, - end: { - line: endLine, - character: 0, - }, - }; } + return { + start: { + line: startLine, + character: 0, + }, + end: { + line: endLine, + character: 0, + }, + }; } /** @@ -170,7 +168,8 @@ function rangeDifferenceByLines(orig: Range, remove: Range): Range[] { ) { // / | | / return []; - } else if ( + } + if ( orig.start.line <= remove.start.line && orig.end.line >= remove.end.line ) { @@ -186,7 +185,8 @@ function rangeDifferenceByLines(orig: Range, remove: Range): Range[] { end: orig.end, }, ]; - } else if ( + } + if ( orig.start.line >= remove.start.line && orig.end.line >= remove.end.line ) { @@ -197,7 +197,8 @@ function rangeDifferenceByLines(orig: Range, remove: Range): Range[] { end: orig.end, }, ]; - } else if ( + } + if ( orig.start.line <= remove.start.line && orig.end.line <= remove.end.line ) { @@ -208,9 +209,8 @@ function rangeDifferenceByLines(orig: Range, remove: Range): Range[] { end: remove.start, }, ]; - } else { - return [orig]; } + return [orig]; } export function removeRangeFromSnippets( diff --git a/core/autocomplete/templates.ts b/core/autocomplete/templates.ts index 626a2f80b..b7d60ebef 100644 --- a/core/autocomplete/templates.ts +++ b/core/autocomplete/templates.ts @@ -51,14 +51,12 @@ const starcoder2FimTemplate: AutocompleteTemplate = { const otherFiles = snippets.length === 0 ? "" - : "" + - snippets + : `${snippets .map((snippet) => { return snippet.contents; // return `${getBasename(snippet.filepath)}\n${snippet.contents}`; }) - .join("") + - ""; + .join("")}`; const prompt = `${otherFiles}${prefix}${suffix}`; return prompt; diff --git a/core/autocomplete/util.ts b/core/autocomplete/util.ts index a1bde8d4e..2a30b67c4 100644 --- a/core/autocomplete/util.ts +++ b/core/autocomplete/util.ts @@ -117,7 +117,7 @@ export class GeneratorReuseManager { } let alreadyTyped = prefix.slice(this.pendingGeneratorPrefix?.length) || ""; - for await (let chunk of this.currentGenerator!.tee()) { + for await (let chunk of this.currentGenerator?.tee()) { if (!chunk) { continue; } diff --git a/core/commands/slash/draftIssue.ts b/core/commands/slash/draftIssue.ts index be869fc02..a449c174b 100644 --- a/core/commands/slash/draftIssue.ts +++ b/core/commands/slash/draftIssue.ts @@ -31,7 +31,7 @@ const DraftIssueCommand: SlashCommand = { { maxTokens: 20 }, ); - title = removeQuotesAndEscapes(title.trim()) + "\n\n"; + title = `${removeQuotesAndEscapes(title.trim())}\n\n`; yield title; let body = ""; diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index 896c467bb..b956e8e0d 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -131,7 +131,7 @@ export async function getPromptParts( rif.contents = rif.contents.substring(1); } while (rif.contents.endsWith("\n")) { - fileSuffix = "\n" + fileSuffix; + fileSuffix = `\n${fileSuffix}`; rif.contents = rif.contents.substring(0, rif.contents.length - 1); } } @@ -144,7 +144,7 @@ function compilePrompt( fileSuffix: string, input: string, ): string { - if (contents.trim() == "") { + if (contents.trim() === "") { // Separate prompt for insertion at the cursor, the other tends to cause it to repeat whole file return `\ @@ -162,7 +162,7 @@ Please output the code to be inserted at the cursor in order to fulfill the user } let prompt = PROMPT; - if (filePrefix.trim() != "") { + if (filePrefix.trim() !== "") { prompt += ` ${filePrefix} @@ -173,7 +173,7 @@ ${filePrefix} ${contents} `; - if (fileSuffix.trim() != "") { + if (fileSuffix.trim() !== "") { prompt += ` ${fileSuffix} @@ -234,7 +234,7 @@ const EditSlashCommand: SlashCommand = { const content = history[history.length - 1].content; if (typeof content !== "string") { content.forEach((part) => { - if (part.text && part.text.startsWith("/edit")) { + if (part.text?.startsWith("/edit")) { part.text = part.text.replace("/edit", "").trimStart(); } }); @@ -301,13 +301,9 @@ const EditSlashCommand: SlashCommand = { linesToDisplay = contentsLines.slice(rewrittenLines); } - const newFileContents = - fullPrefixLines.join("\n") + - "\n" + - completion + - "\n" + - (linesToDisplay.length > 0 ? linesToDisplay.join("\n") + "\n" : "") + - fullSuffixLines.join("\n"); + const newFileContents = `${fullPrefixLines.join("\n")}\n${completion}\n${ + linesToDisplay.length > 0 ? `${linesToDisplay.join("\n")}\n` : "" + }${fullSuffixLines.join("\n")}`; const stepIndex = history.length - 1; @@ -532,11 +528,11 @@ const EditSlashCommand: SlashCommand = { break; } // Lines that should be ignored, like the <> tags - else if (lineToBeIgnored(chunkLines[i], completionLinesCovered === 0)) { + if (lineToBeIgnored(chunkLines[i], completionLinesCovered === 0)) { continue; // noice } // Check if we are currently just copying the prefix - else if ( + if ( (linesOfPrefixCopied > 0 || completionLinesCovered === 0) && linesOfPrefixCopied < filePrefix.split("\n").length && chunkLines[i] === fullPrefixLines[linesOfPrefixCopied] @@ -547,7 +543,7 @@ const EditSlashCommand: SlashCommand = { } // Because really short lines might be expected to be repeated, this is only a !heuristic! // Stop when it starts copying the fileSuffix - else if ( + if ( chunkLines[i].trim() === lineBelowHighlightedRange.trim() && chunkLines[i].trim().length > 4 && !( diff --git a/core/commands/slash/review.ts b/core/commands/slash/review.ts index c6551e496..ced5c7b59 100644 --- a/core/commands/slash/review.ts +++ b/core/commands/slash/review.ts @@ -18,7 +18,7 @@ function getLastUserHistory(history: ChatMessage[]): string { if (!lastUserHistory) return ""; - if (lastUserHistory.content instanceof Array) { + if (Array.isArray(lastUserHistory.content)) { return lastUserHistory.content.reduce( (acc: string, current: { type: string; text?: string }) => { return current.type === "text" && current.text diff --git a/core/config/load.ts b/core/config/load.ts index 9feb2098f..b38058728 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -1,5 +1,5 @@ -import * as fs from "fs"; -import path from "path"; +import * as fs from "node:fs"; +import path from "node:path"; import type { BrowserSerializedContinueConfig, Config, @@ -42,7 +42,7 @@ import { getContinueDotEnv, migrate, } from "../util/paths"; -const { execSync } = require("child_process"); +const { execSync } = require("node:child_process"); function resolveSerializedConfig(filepath: string): SerializedContinueConfig { let content = fs.readFileSync(filepath, "utf8"); @@ -201,7 +201,7 @@ async function intermediateToFinalConfig( { ...desc, model: modelName, - title: llm.title + " - " + modelName, + title: `${llm.title} - ${modelName}`, }, readFile, copyOf(config.completionOptions), @@ -389,14 +389,13 @@ async function buildConfigTs() { try { if (process.env.IS_BINARY === "true") { execSync( - escapeSpacesInPath(path.dirname(process.execPath)) + - `/esbuild${ - getTarget().startsWith("win32") ? ".exe" : "" - } ${escapeSpacesInPath( - getConfigTsPath(), - )} --bundle --outfile=${escapeSpacesInPath( - getConfigJsPath(), - )} --platform=node --format=cjs --sourcemap --external:fetch --external:fs --external:path --external:os --external:child_process`, + `${escapeSpacesInPath(path.dirname(process.execPath))}/esbuild${ + getTarget().startsWith("win32") ? ".exe" : "" + } ${escapeSpacesInPath( + getConfigTsPath(), + )} --bundle --outfile=${escapeSpacesInPath( + getConfigJsPath(), + )} --platform=node --format=cjs --sourcemap --external:fetch --external:fs --external:path --external:os --external:child_process`, ); } else { // Dynamic import esbuild so potentially disastrous errors can be caught @@ -414,7 +413,7 @@ async function buildConfigTs() { } } catch (e) { console.log( - "Build error. Please check your ~/.continue/config.ts file: " + e, + `Build error. Please check your ~/.continue/config.ts file: ${e}`, ); return undefined; } diff --git a/core/config/util.ts b/core/config/util.ts index 3368e943d..d0dbf71ef 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -1,4 +1,4 @@ -import { readFileSync, writeFileSync } from "fs"; +import { readFileSync, writeFileSync } from "node:fs"; import type { ModelDescription } from ".."; import { editConfigJson, getConfigJsonPath } from "../util/paths"; diff --git a/core/context/providers/DatabaseContextProvider.ts b/core/context/providers/DatabaseContextProvider.ts index b11b62d7d..428ecfe7c 100644 --- a/core/context/providers/DatabaseContextProvider.ts +++ b/core/context/providers/DatabaseContextProvider.ts @@ -32,7 +32,7 @@ class DatabaseContextProvider extends BaseContextProvider { const getDatabaseAdapter = await require("dbinfoz"); for (const connection of connections) { - if (connection.name == connectionName) { + if (connection.name === connectionName) { const adapter = getDatabaseAdapter( connection.connection_type, connection.connection, @@ -47,7 +47,7 @@ class DatabaseContextProvider extends BaseContextProvider { const contextItem = { name: `${connectionName}-all-tables-schemas`, - description: `Schema for all tables.`, + description: "Schema for all tables.", content: prompt, }; @@ -101,7 +101,7 @@ class DatabaseContextProvider extends BaseContextProvider { const contextItem = { id: `${connection.name}.all`, title: `${connection.name} all table schemas`, - description: ``, + description: "", }; contextItems.push(contextItem); @@ -110,7 +110,7 @@ class DatabaseContextProvider extends BaseContextProvider { const contextItem = { id: `${connection.name}.${tableName}`, title: `${connection.name}.${tableName} schema`, - description: ``, + description: "", }; contextItems.push(contextItem); diff --git a/core/context/providers/FileTreeContextProvider.ts b/core/context/providers/FileTreeContextProvider.ts index f58c97f03..f8739db13 100644 --- a/core/context/providers/FileTreeContextProvider.ts +++ b/core/context/providers/FileTreeContextProvider.ts @@ -28,7 +28,7 @@ function formatFileTree(tree: Directory, indentation = ""): string { for (const directory of tree.directories) { result += `${indentation}${directory.name}/\n`; - result += formatFileTree(directory, indentation + " "); + result += formatFileTree(directory, `${indentation} `); } return result; @@ -82,9 +82,9 @@ class FileTreeContextProvider extends BaseContextProvider { return [ { - content: - "Here is a file tree of the current workspace:\n\n" + - trees.join("\n\n"), + content: `Here is a file tree of the current workspace:\n\n${trees.join( + "\n\n", + )}`, name: "File Tree", description: "File Tree", }, diff --git a/core/context/providers/GitHubIssuesContextProvider.ts b/core/context/providers/GitHubIssuesContextProvider.ts index 6a560bf62..1e50f36b3 100644 --- a/core/context/providers/GitHubIssuesContextProvider.ts +++ b/core/context/providers/GitHubIssuesContextProvider.ts @@ -46,7 +46,7 @@ class GitHubIssuesContextProvider extends BaseContextProvider { issue.data.body || "No description", ...comments.data.map((comment) => comment.body), ]; - content += "\n\n" + parts.join("\n\n---\n\n"); + content += `\n\n${parts.join("\n\n---\n\n")}`; return [ { diff --git a/core/context/providers/GitLabMergeRequestContextProvider.ts b/core/context/providers/GitLabMergeRequestContextProvider.ts index bc3c1ab11..7c17ca300 100644 --- a/core/context/providers/GitLabMergeRequestContextProvider.ts +++ b/core/context/providers/GitLabMergeRequestContextProvider.ts @@ -84,7 +84,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { const token = this.options.token; if (!token) { - throw new Error(`GitLab Private Token is required!`); + throw new Error("GitLab Private Token is required!"); } return Axios.create({ @@ -100,13 +100,13 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { ): Promise { const subprocess = await getSubprocess(extras); - const branchName = await subprocess(`git branch --show-current`); + const branchName = await subprocess("git branch --show-current"); const branchRemote = await subprocess( `git config branch.${branchName}.remote`, ); - const branchInfo = await subprocess(`git branch -vv`); + const branchInfo = await subprocess("git branch -vv"); const currentBranchInfo = branchInfo .split("\n") @@ -118,13 +118,13 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { console.dir({ remoteMatches }); - const remoteBranch = remoteMatches?.groups?.["remote_branch"] ?? null; + const remoteBranch = remoteMatches?.groups?.remote_branch ?? null; const remoteUrl = await subprocess(`git remote get-url ${branchRemote}`); const urlMatches = /:(?.*).git/.exec(remoteUrl); - const project = urlMatches?.groups?.["project"] ?? null; + const project = urlMatches?.groups?.project ?? null; return { branch: remoteBranch, @@ -162,7 +162,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { `# GitLab Merge Request\ntitle: "${ mergeRequest.title }"\ndescription: "${mergeRequest.description ?? "None"}"`, - `## Comments`, + "## Comments", ]; const comments = await api.get>( @@ -243,7 +243,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { if (filename !== "general") { parts.push(`### File ${filename}`); locationComments.sort( - (a, b) => a.position!.new_line - b.position!.new_line, + (a, b) => a.position?.new_line - b.position?.new_line, ); } else { parts.push("### General"); @@ -260,11 +260,11 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { result.push({ name: mergeRequest.title, content, - description: `Comments from the Merge Request for this branch.`, + description: "Comments from the Merge Request for this branch.", }); } } catch (ex) { - let content = `# GitLab Merge Request\n\nError getting merge request. `; + let content = "# GitLab Merge Request\n\nError getting merge request. "; if (ex instanceof AxiosError) { if (ex.response) { const errorMessage = ex.response?.data @@ -280,9 +280,9 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { } result.push({ - name: `GitLab Merge Request`, + name: "GitLab Merge Request", content, - description: `Error getting the Merge Request for this branch.`, + description: "Error getting the Merge Request for this branch.", }); } diff --git a/core/context/providers/GoogleContextProvider.ts b/core/context/providers/GoogleContextProvider.ts index 3fb9a6288..8479b86fc 100644 --- a/core/context/providers/GoogleContextProvider.ts +++ b/core/context/providers/GoogleContextProvider.ts @@ -42,14 +42,14 @@ class GoogleContextProvider extends BaseContextProvider { const jsonResults = JSON.parse(results); let content = `Google Search: ${query}\n\n`; - const answerBox = jsonResults["answerBox"]; + const answerBox = jsonResults.answerBox; if (answerBox) { - content += `Answer Box (${answerBox["title"]}): ${answerBox["answer"]}\n\n`; + content += `Answer Box (${answerBox.title}): ${answerBox.answer}\n\n`; } - for (const result of jsonResults["organic"]) { - content += `${result["title"]}\n${result["link"]}\n${result["snippet"]}\n\n`; + for (const result of jsonResults.organic) { + content += `${result.title}\n${result.link}\n${result.snippet}\n\n`; } return [ diff --git a/core/context/providers/JiraIssuesContextProvider/JiraClient.ts b/core/context/providers/JiraIssuesContextProvider/JiraClient.ts index ca051a2cf..5984c67e9 100644 --- a/core/context/providers/JiraIssuesContextProvider/JiraClient.ts +++ b/core/context/providers/JiraIssuesContextProvider/JiraClient.ts @@ -68,7 +68,8 @@ export class JiraClient { private authHeader; constructor(options: JiraClientOptions) { this.options = { - issueQuery: `assignee = currentUser() AND resolution = Unresolved order by updated DESC`, + issueQuery: + "assignee = currentUser() AND resolution = Unresolved order by updated DESC", apiVersion: "3", requestOptions: {}, ...options, @@ -76,9 +77,9 @@ export class JiraClient { this.baseUrl = `https://${this.options.domain}/rest/api/${this.options.apiVersion}`; this.authHeader = this.options.username ? { - Authorization: - "Basic " + - btoa(this.options.username + ":" + this.options.password), + Authorization: `Basic ${btoa( + `${this.options.username}:${this.options.password}`, + )}`, } : { Authorization: `Bearer ${this.options.password}`, @@ -90,7 +91,7 @@ export class JiraClient { const response = await fetchwithRequestOptions( new URL( - this.baseUrl + `/issue/${issueId}?fields=description,comment,summary`, + `${this.baseUrl}/issue/${issueId}?fields=description,comment,summary`, ), { method: "GET", @@ -136,11 +137,10 @@ export class JiraClient { async listIssues(): Promise> { const response = await fetchwithRequestOptions( new URL( - this.baseUrl + - `/search?fields=summary&jql=${ - this.options.issueQuery ?? - `assignee = currentUser() AND resolution = Unresolved order by updated DESC` - }`, + `${this.baseUrl}/search?fields=summary&jql=${ + this.options.issueQuery ?? + "assignee = currentUser() AND resolution = Unresolved order by updated DESC" + }`, ), { method: "GET", @@ -152,7 +152,7 @@ export class JiraClient { this.options.requestOptions, ); - if (response.status != 200) { + if (response.status !== 200) { console.warn( "Unable to get jira tickets. Response code from API is", response.status, diff --git a/core/context/providers/LocalsProvider.ts b/core/context/providers/LocalsProvider.ts index 119c7ed77..9d6fa15ae 100644 --- a/core/context/providers/LocalsProvider.ts +++ b/core/context/providers/LocalsProvider.ts @@ -23,7 +23,7 @@ class LocalsProvider extends BaseContextProvider { const localVariables = await extras.ide.getDebugLocals(Number(query)); const threadIndex = Number(query); const thread = (await extras.ide.getAvailableThreads()).find( - (thread) => thread.id == threadIndex, + (thread) => thread.id === threadIndex, ); const callStacksSources = await extras.ide.getTopLevelCallStackSources( threadIndex, @@ -31,7 +31,7 @@ class LocalsProvider extends BaseContextProvider { ); const callStackContents = callStacksSources.reduce( (acc, source, index) => - acc + `\n\ncall stack ${index}\n` + "```\n" + source + "\n```", + `${acc}\n\ncall stack ${index}\n\`\`\`\n${source}\n`\`\``, "", ); return [ diff --git a/core/context/providers/OSContextProvider.ts b/core/context/providers/OSContextProvider.ts index abcbd4c55..bbc0c4705 100644 --- a/core/context/providers/OSContextProvider.ts +++ b/core/context/providers/OSContextProvider.ts @@ -1,7 +1,7 @@ //os.platform() //os.arch() -import os from "os"; +import os from "node:os"; import { BaseContextProvider } from ".."; import type { ContextItem, diff --git a/core/context/providers/PostgresContextProvider.ts b/core/context/providers/PostgresContextProvider.ts index 4e1cd56c7..088fd9551 100644 --- a/core/context/providers/PostgresContextProvider.ts +++ b/core/context/providers/PostgresContextProvider.ts @@ -18,18 +18,6 @@ class PostgresContextProvider extends BaseContextProvider { static ALL_TABLES = "__all_tables"; static DEFAULT_SAMPLE_ROWS = 3; - constructor(options: { - host: string; - port: number; - user: string; - password: string; - database: string; - schema?: string; - sampleRows?: number; - }) { - super(options); - } - private async getPool() { const pg = await require("pg"); return new pg.Pool({ @@ -43,7 +31,7 @@ class PostgresContextProvider extends BaseContextProvider { private async getTableNames(pool: any): Promise { const schema = this.options.schema ?? "public"; - var tablesInfoQuery = ` + let tablesInfoQuery = ` SELECT table_schema, table_name FROM information_schema.tables`; if (schema != null) { @@ -78,7 +66,7 @@ FROM information_schema.tables`; `Table name must be in format schema.table_name, got ${tableName}`, ); } - var schemaQuery = ` + const schemaQuery = ` SELECT column_name, data_type, character_maximum_length FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = '${tableName.split(".")[0]}' @@ -96,7 +84,7 @@ FROM ${tableName} LIMIT ${sampleRows}`); // Create prompt from the table schema and sample rows - var prompt = `Postgres schema for database ${this.options.database} table ${tableName}:\n`; + let prompt = `Postgres schema for database ${this.options.database} table ${tableName}:\n`; prompt += `${JSON.stringify(tableSchema, null, 2)}\n\n`; prompt += `Sample rows: ${JSON.stringify(sampleRowResults, null, 2)}`; diff --git a/core/context/providers/ProblemsContextProvider.ts b/core/context/providers/ProblemsContextProvider.ts index 11bde4563..be437f6d7 100644 --- a/core/context/providers/ProblemsContextProvider.ts +++ b/core/context/providers/ProblemsContextProvider.ts @@ -46,7 +46,7 @@ class ProblemsContextProvider extends BaseContextProvider { ? [ { description: "Problems in current file", - content: `There are no problems found in the open file.`, + content: "There are no problems found in the open file.", name: "No problems found", }, ] diff --git a/core/context/rerankers/llm.ts b/core/context/rerankers/llm.ts index d8137107c..153e86b70 100644 --- a/core/context/rerankers/llm.ts +++ b/core/context/rerankers/llm.ts @@ -68,14 +68,14 @@ export class LLMReranker implements Reranker { if (answer === "yes") { return 1.0; - } else if (answer === "no") { - return 0.0; - } else { - console.warn( - `Unexpected response from single token reranker: "${answer}". Expected "yes" or "no".`, - ); + } + if (answer === "no") { return 0.0; } + console.warn( + `Unexpected response from single token reranker: "${answer}". Expected "yes" or "no".`, + ); + return 0.0; } async rerank(query: string, chunks: Chunk[]): Promise { diff --git a/core/diff/util.ts b/core/diff/util.ts index d8817c875..8f61bf0c0 100644 --- a/core/diff/util.ts +++ b/core/diff/util.ts @@ -49,7 +49,8 @@ export function matchLine( if (linesMatchPerfectly(newLine, oldLines[i])) { return [i, true, newLine]; - } else if (linesMatch(newLine, oldLines[i], i)) { + } + if (linesMatch(newLine, oldLines[i], i)) { // This is a way to fix indentation, but only for sufficiently long lines to avoid matching whitespace or short lines if ( newLine.trimStart() === oldLines[i].trimStart() && diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 9968570a8..d7216d8b2 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -1,5 +1,5 @@ -import fs from "fs"; -import path from "path"; +import fs from "node:fs"; +import path from "node:path"; import type { ChunkWithoutID, ContextItem, @@ -112,7 +112,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { // Add snippets to sqlite for (const snippet of snippets) { const { lastID } = await db.run( - `INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)`, + "INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)", [ compute.path, compute.cacheKey, @@ -124,7 +124,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { ); await db.run( - `INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)`, + "INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)", [lastID, tagString], ); } @@ -139,10 +139,10 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { for (let i = 0; i < results.del.length; i++) { const del = results.del[i]; const deleted = await db.run( - `DELETE FROM code_snippets WHERE path = ? AND cacheKey = ?`, + "DELETE FROM code_snippets WHERE path = ? AND cacheKey = ?", [del.path, del.cacheKey], ); - await db.run(`DELETE FROM code_snippets_tags WHERE snippetId = ?`, [ + await db.run("DELETE FROM code_snippets_tags WHERE snippetId = ?", [ deleted.lastID, ]); markComplete([del], IndexResultType.Delete); @@ -150,13 +150,13 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { for (let i = 0; i < results.addTag.length; i++) { const snippetsWithPath = await db.all( - `SELECT * FROM code_snippets WHERE cacheKey = ?`, + "SELECT * FROM code_snippets WHERE cacheKey = ?", [results.addTag[i].cacheKey], ); for (const snippet of snippetsWithPath) { await db.run( - `INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)`, + "INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)", [snippet.id, tagString], ); } @@ -183,7 +183,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { static async getForId(id: number): Promise { const db = await SqliteDb.get(); - const row = await db.get(`SELECT * FROM code_snippets WHERE id = ?`, [id]); + const row = await db.get("SELECT * FROM code_snippets WHERE id = ?", [id]); return { name: row.title, diff --git a/core/indexing/FullTextSearch.ts b/core/indexing/FullTextSearch.ts index 5b691c3c7..1f594265e 100644 --- a/core/indexing/FullTextSearch.ts +++ b/core/indexing/FullTextSearch.ts @@ -43,17 +43,17 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { // Insert chunks const chunks = await db.all( - `SELECT * FROM chunks WHERE path = ? AND cacheKey = ?`, + "SELECT * FROM chunks WHERE path = ? AND cacheKey = ?", [item.path, item.cacheKey], ); for (const chunk of chunks) { const { lastID } = await db.run( - `INSERT INTO fts (path, content) VALUES (?, ?)`, + "INSERT INTO fts (path, content) VALUES (?, ?)", [item.path, chunk.content], ); await db.run( - `INSERT INTO fts_metadata (id, path, cacheKey, chunkId) VALUES (?, ?, ?, ?)`, + "INSERT INTO fts_metadata (id, path, cacheKey, chunkId) VALUES (?, ?, ?, ?)", [lastID, item.path, item.cacheKey, chunk.id], ); } @@ -78,10 +78,10 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { // Delete for (const item of results.del) { const { lastID } = await db.run( - `DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?`, + "DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [item.path, item.cacheKey], ); - await db.run(`DELETE FROM fts WHERE rowid = ?`, [lastID]); + await db.run("DELETE FROM fts WHERE rowid = ?", [lastID]); markComplete([item], IndexResultType.Delete); } diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 65b118989..309c85034 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -32,7 +32,7 @@ interface LanceDbRow { export class LanceDbIndex implements CodebaseIndex { get artifactId(): string { - return "vectordb::" + this.embeddingsProvider.id; + return `vectordb::${this.embeddingsProvider.id}`; } static MAX_CHUNK_SIZE = MAX_CHUNK_SIZE; @@ -276,7 +276,7 @@ export class LanceDbIndex implements CodebaseIndex { table = await db.createTable(tableName, lanceRows); needToCreateTable = false; } else if (lanceRows.length > 0) { - await table!.add(lanceRows); + await table?.add(lanceRows); } markComplete([{ path, cacheKey }], IndexResultType.AddTag); @@ -286,7 +286,7 @@ export class LanceDbIndex implements CodebaseIndex { if (!needToCreateTable) { for (const { path, cacheKey } of [...results.removeTag, ...results.del]) { // This is where the aforementioned lowercase conversion problem shows - await table!.delete(`cachekey = '${cacheKey}' AND path = '${path}'`); + await table?.delete(`cachekey = '${cacheKey}' AND path = '${path}'`); } } markComplete(results.removeTag, IndexResultType.RemoveTag); diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index 550b4692c..c762da100 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -57,7 +57,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex { async function handleChunk(chunk: Chunk) { const { lastID } = await db.run( - `INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)`, + "INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)", [ chunk.digest, chunk.filepath, @@ -68,7 +68,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex { ], ); - await db.run(`INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)`, [ + await db.run("INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)", [ lastID, tagString, ]); @@ -124,12 +124,12 @@ export class ChunkCodebaseIndex implements CodebaseIndex { // Add tag for (const item of results.addTag) { const chunksWithPath = await db.all( - `SELECT * FROM chunks WHERE cacheKey = ?`, + "SELECT * FROM chunks WHERE cacheKey = ?", [item.cacheKey], ); for (const chunk of chunksWithPath) { - await db.run(`INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)`, [ + await db.run("INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)", [ chunk.id, tagString, ]); @@ -156,12 +156,12 @@ export class ChunkCodebaseIndex implements CodebaseIndex { // Delete for (const item of results.del) { - const deleted = await db.run(`DELETE FROM chunks WHERE cacheKey = ?`, [ + const deleted = await db.run("DELETE FROM chunks WHERE cacheKey = ?", [ item.cacheKey, ]); // Delete from chunk_tags - await db.run(`DELETE FROM chunk_tags WHERE chunkId = ?`, [ + await db.run("DELETE FROM chunk_tags WHERE chunkId = ?", [ deleted.lastID, ]); diff --git a/core/indexing/chunk/basic.ts b/core/indexing/chunk/basic.ts index 185cec1d3..8c3563b9e 100644 --- a/core/indexing/chunk/basic.ts +++ b/core/indexing/chunk/basic.ts @@ -20,7 +20,7 @@ export function* basicChunker( } if (lineTokens < maxChunkSize) { - chunkContent += line + "\n"; + chunkContent += `${line}\n`; chunkTokens += lineTokens + 1; } diff --git a/core/indexing/chunk/code.ts b/core/indexing/chunk/code.ts index c78f56784..0ddf79eef 100644 --- a/core/indexing/chunk/code.ts +++ b/core/indexing/chunk/code.ts @@ -6,9 +6,8 @@ import { getParserForFile } from "../../util/treeSitter"; function collapsedReplacement(node: SyntaxNode): string { if (node.type === "statement_block") { return "{ ... }"; - } else { - return "..."; } + return "..."; } function firstChild( @@ -19,9 +18,8 @@ function firstChild( return ( node.children.find((child) => grammarName.includes(child.type)) || null ); - } else { - return node.children.find((child) => child.type === grammarName) || null; } + return node.children.find((child) => child.type === grammarName) || null; } function collapseChildren( @@ -130,12 +128,10 @@ function constructFunctionDefinitionChunk( // If inside a class, include the class header const classNode = node.parent.parent; const classBlock = node.parent; - return ( - code.slice(classNode.startIndex, classBlock.startIndex) + - "...\n\n" + - " ".repeat(node.startPosition.column) + // ... - funcText - ); + return `${code.slice( + classNode.startIndex, + classBlock.startIndex, + )}...\n\n${" ".repeat(node.startPosition.column)}${funcText}`; } return funcText; } diff --git a/core/indexing/chunk/markdown.ts b/core/indexing/chunk/markdown.ts index cab3dea64..1bc9b5fb8 100644 --- a/core/indexing/chunk/markdown.ts +++ b/core/indexing/chunk/markdown.ts @@ -74,7 +74,8 @@ export async function* markdownChunker( }, }; return; - } else if (hLevel > 4) { + } + if (hLevel > 4) { const header = findHeader(content.split("\n")); for (const chunk of basicChunker(content, maxChunkSize)) { @@ -89,7 +90,7 @@ export async function* markdownChunker( return; } - const h = "#".repeat(hLevel + 1) + " "; + const h = `${"#".repeat(hLevel + 1)} `; const lines = content.split("\n"); const sections = []; @@ -131,7 +132,7 @@ export async function* markdownChunker( hLevel + 1, )) { yield { - content: section.header + "\n" + chunk.content, + content: `${section.header}\n${chunk.content}`, startLine: section.startLine + chunk.startLine, endLine: section.startLine + chunk.endLine, otherMetadata: { diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index 5529ae591..0702337a4 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -33,7 +33,7 @@ function breakdownArticleComponent( for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (content.length + line.length <= MAX_CHUNK_SIZE) { - content += line + "\n"; + content += `${line}\n`; endLine = i; } else { chunks.push({ @@ -45,12 +45,12 @@ function breakdownArticleComponent( }, index: index, filepath: new URL( - subpath + `#${cleanFragment(article.title)}`, + `${subpath}#${cleanFragment(article.title)}`, url, ).toString(), digest: subpath, }); - content = line + "\n"; + content = `${line}\n`; startLine = i; endLine = i; index += 1; @@ -68,7 +68,7 @@ function breakdownArticleComponent( }, index: index, filepath: new URL( - subpath + `#${cleanFragment(article.title)}`, + `${subpath}#${cleanFragment(article.title)}`, url, ).toString(), digest: subpath, diff --git a/core/indexing/docs/crawl.ts b/core/indexing/docs/crawl.ts index a545100c4..c45e92fd9 100644 --- a/core/indexing/docs/crawl.ts +++ b/core/indexing/docs/crawl.ts @@ -1,4 +1,4 @@ -import { URL } from "url"; +import { URL } from "node:url"; import { Octokit } from "@octokit/rest"; import cheerio from "cheerio"; import fetch from "node-fetch"; @@ -45,7 +45,7 @@ async function crawlGithubRepo(baseUrl: URL) { const paths = tree.data.tree .filter((file) => file.type === "blob" && file.path?.endsWith(".md")) - .map((file) => baseUrl.pathname + "/tree/main/" + file.path); + .map((file) => `${baseUrl.pathname}/tree/main/${file.path}`); return paths; } @@ -63,13 +63,12 @@ async function getLinksFromUrl(url: string, path: string) { html: "", links: [], }; - } else { - console.error(error); - return { - html: "", - links: [], - }; } + console.error(error); + return { + html: "", + links: [], + }; } const html = await response.text(); diff --git a/core/indexing/docs/db.ts b/core/indexing/docs/db.ts index 087d60b30..8de1c4ec0 100644 --- a/core/indexing/docs/db.ts +++ b/core/indexing/docs/db.ts @@ -128,7 +128,7 @@ export async function addDocs( // Only after add it to SQLite const db = await getDBDocs(); await db.run( - `INSERT INTO docs (title, baseUrl) VALUES (?, ?)`, + "INSERT INTO docs (title, baseUrl) VALUES (?, ?)", title, baseUrl.toString(), ); @@ -138,12 +138,12 @@ export async function listDocs(): Promise< { title: string; baseUrl: string }[] > { const db = await getDBDocs(); - const docs = db.all(`SELECT title, baseUrl FROM docs`); + const docs = db.all("SELECT title, baseUrl FROM docs"); return docs; } export async function hasDoc(baseUrl: string) { const db = await getDBDocs(); - const doc = await db.get(`SELECT title FROM docs WHERE baseUrl =?`, baseUrl); + const doc = await db.get("SELECT title FROM docs WHERE baseUrl =?", baseUrl); return !!doc; } diff --git a/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts b/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts index 3de3913d6..258fc15f5 100644 --- a/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts +++ b/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts @@ -12,7 +12,7 @@ class FreeTrialEmbeddingsProvider extends BaseEmbeddingsProvider { }; get id(): string { - return FreeTrialEmbeddingsProvider.defaultOptions!.model!; + return FreeTrialEmbeddingsProvider.defaultOptions?.model!; } async embed(chunks: string[]) { diff --git a/core/indexing/embeddings/OllamaEmbeddingsProvider.ts b/core/indexing/embeddings/OllamaEmbeddingsProvider.ts index 532bf62ae..cb6946ad2 100644 --- a/core/indexing/embeddings/OllamaEmbeddingsProvider.ts +++ b/core/indexing/embeddings/OllamaEmbeddingsProvider.ts @@ -15,7 +15,7 @@ async function embedOne(chunk: string, options: EmbedOptions) { ); const resp = await fetchWithBackoff(); if (!resp.ok) { - throw new Error("Failed to embed chunk: " + (await resp.text())); + throw new Error(`Failed to embed chunk: ${await resp.text()}`); } return (await resp.json()).embedding; diff --git a/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts b/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts index a267fde98..3b7d9b0ac 100644 --- a/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts +++ b/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts @@ -4,7 +4,7 @@ import { pipeline, } from "../../vendor/node_modules/@xenova/transformers"; -import path from "path"; +import path from "node:path"; import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider"; env.allowLocalModels = true; @@ -20,11 +20,14 @@ class EmbeddingsPipeline { static instance: any | null = null; static async getInstance() { - if (this.instance === null) { - this.instance = await pipeline(this.task, this.model); + if (EmbeddingsPipeline.instance === null) { + EmbeddingsPipeline.instance = await pipeline( + EmbeddingsPipeline.task, + EmbeddingsPipeline.model, + ); } - return this.instance; + return EmbeddingsPipeline.instance; } } diff --git a/core/indexing/embeddings/TransformersJsWorkerThread.js b/core/indexing/embeddings/TransformersJsWorkerThread.js index 7e6c37e9d..b11f02c74 100644 --- a/core/indexing/embeddings/TransformersJsWorkerThread.js +++ b/core/indexing/embeddings/TransformersJsWorkerThread.js @@ -1,10 +1,10 @@ -import path from "path"; +import path from "node:path"; import { env, pipeline, } from "../../vendor/node_modules/@xenova/transformers/types/transformers"; import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider"; -const { parentPort } = require("worker_threads"); +const { parentPort } = require("node:worker_threads"); env.allowLocalModels = true; env.allowRemoteModels = false; @@ -19,11 +19,14 @@ class EmbeddingsPipeline { static instance = null; static async getInstance() { - if (this.instance === null) { - this.instance = await pipeline(this.task, this.model); + if (EmbeddingsPipeline.instance === null) { + EmbeddingsPipeline.instance = await pipeline( + EmbeddingsPipeline.task, + EmbeddingsPipeline.model, + ); } - return this.instance; + return EmbeddingsPipeline.instance; } } diff --git a/core/indexing/indexCodebase.ts b/core/indexing/indexCodebase.ts index 7a93e1a11..e21b9e4df 100644 --- a/core/indexing/indexCodebase.ts +++ b/core/indexing/indexCodebase.ts @@ -132,7 +132,7 @@ export class CodebaseIndexer { progress: (completedDirs + completedIndexes / indexesToBuild.length) / workspaceDirs.length, - desc: "Completed indexing " + codebaseIndex.artifactId, + desc: `Completed indexing ${codebaseIndex.artifactId}`, }; } } catch (e) { diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index 7708b62f3..b58e71589 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -1,5 +1,5 @@ -import crypto from "crypto"; -import * as fs from "fs"; +import crypto from "node:crypto"; +import * as fs from "node:fs"; import { type Database, open } from "sqlite"; import sqlite3 from "sqlite3"; import type { IndexTag, IndexingProgressUpdate } from ".."; @@ -157,7 +157,7 @@ async function getAddRemoveForTag( switch (resultType) { case AddRemoveResultType.Add: await db.run( - `INSERT INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)`, + "INSERT INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)", path, cacheKey, newLastUpdatedTimestamp, @@ -243,7 +243,7 @@ async function getTagsFromGlobalCache( ): Promise { const db = await SqliteDb.get(); const stmt = await db.prepare( - `SELECT dir, branch, artifactId FROM global_cache WHERE cacheKey = ? AND artifactId = ?`, + "SELECT dir, branch, artifactId FROM global_cache WHERE cacheKey = ? AND artifactId = ?", ); const rows = await stmt.all(cacheKey, artifactId); return rows; diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 5f4b64bb2..8101e791b 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -282,7 +282,7 @@ function autodetectPromptTemplates( } if (editTemplate !== null) { - templates["edit"] = editTemplate; + templates.edit = editTemplate; } return templates; diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index b133f0a33..d23f247dc 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -11,7 +11,7 @@ export function constructMessages(history: ChatHistory): ChatMessage[] { : [{ type: "text", text: historyItem.message.content } as MessagePart]; const ctxItems = historyItem.contextItems.map((ctxItem) => { - return { type: "text", text: ctxItem.content + "\n" } as MessagePart; + return { type: "text", text: `${ctxItem.content}\n` } as MessagePart; }); content = [...ctxItems, ...content]; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 891cdfba2..dbb189493 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -32,9 +32,8 @@ function encodingForModel(modelName: string): Encoding { function countImageTokens(content: MessagePart): number { if (content.type === "imageUrl") { return 85; - } else { - throw new Error("Non-image content type"); } + throw new Error("Non-image content type"); } function countTokens( @@ -49,9 +48,8 @@ function countTokens( ? countImageTokens(part) : encoding.encode(part.text ?? "", "all", []).length; }, 0); - } else { - return encoding.encode(content, "all", []).length; } + return encoding.encode(content, "all", []).length; } function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { @@ -62,7 +60,7 @@ function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { flattened.length > 0 && flattened[flattened.length - 1].role === msg.role ) { - flattened[flattened.length - 1].content += "\n\n" + (msg.content || ""); + flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`; } else { flattened.push(msg); } @@ -76,9 +74,8 @@ export function stripImages(content: MessageContent): string { .filter((part) => part.type === "text") .map((part) => part.text) .join("\n"); - } else { - return content; } + return content; } function countChatMessageTokens( @@ -174,10 +171,9 @@ function pruneRawPromptFromBottom( function summarize(message: MessageContent): string { if (Array.isArray(message)) { - return stripImages(message).substring(0, 100) + "..."; - } else { - return message.substring(0, 100) + "..."; + return `${stripImages(message).substring(0, 100)}...`; } + return `${message.substring(0, 100)}...`; } function pruneChatHistory( @@ -276,7 +272,7 @@ function pruneChatHistory( function compileChatMessages( modelName: string, - msgs: ChatMessage[] | undefined = undefined, + msgs: ChatMessage[] | undefined, contextLength: number, maxTokens: number, supportsImages: boolean, diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index e31e5938e..ec7b29adc 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -20,10 +20,6 @@ class Anthropic extends BaseLLM { apiBase: "https://api.anthropic.com/v1/", }; - constructor(options: LLMOptions) { - super(options); - } - private _convertArgs(options: CompletionOptions) { const finalOptions = { top_k: options.topK, @@ -44,25 +40,23 @@ class Anthropic extends BaseLLM { .map((message) => { if (typeof message.content === "string") { return message; - } else { - return { - ...message, - content: message.content.map((part) => { - if (part.type === "text") { - return part; - } else { - return { - type: "image", - source: { - type: "base64", - media_type: "image/jpeg", - data: part.imageUrl?.url.split(",")[1], - }, - }; - } - }), - }; } + return { + ...message, + content: message.content.map((part) => { + if (part.type === "text") { + return part; + } + return { + type: "image", + source: { + type: "base64", + media_type: "image/jpeg", + data: part.imageUrl?.url.split(",")[1], + }, + }; + }), + }; }); return messages; } diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 556f3027a..2871a8e07 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -1,6 +1,6 @@ -import * as fs from "fs"; -import { join as joinPath } from "path"; -import { promisify } from "util"; +import * as fs from "node:fs"; +import { join as joinPath } from "node:path"; +import { promisify } from "node:util"; import { BaseLLM } from ".."; import type { ChatMessage, @@ -64,25 +64,23 @@ class Bedrock extends BaseLLM { .map((message) => { if (typeof message.content === "string") { return message; - } else { - return { - ...message, - content: message.content.map((part) => { - if (part.type === "text") { - return part; - } else { - return { - type: "image", - source: { - type: "base64", - media_type: "image/jpeg", - data: part.imageUrl?.url.split(",")[1], - }, - }; - } - }), - }; } + return { + ...message, + content: message.content.map((part) => { + if (part.type === "text") { + return part; + } + return { + type: "image", + source: { + type: "base64", + media_type: "image/jpeg", + data: part.imageUrl?.url.split(",")[1], + }, + }; + }), + }; }); return messages; } @@ -139,7 +137,9 @@ class Bedrock extends BaseLLM { region: this.region, }; - let accessKeyId: string, secretAccessKey: string, sessionToken: string; + let accessKeyId: string; + let secretAccessKey: string; + let sessionToken: string; try { const data = await readFile( @@ -156,9 +156,8 @@ class Bedrock extends BaseLLM { } return await this.fetch(new URL(`${this.apiBase}${path}`), { method: "POST", - headers: aws4.sign(opts, { accessKeyId, secretAccessKey, sessionToken })[ - "headers" - ], + headers: aws4.sign(opts, { accessKeyId, secretAccessKey, sessionToken }) + .headers, body: body, }); } diff --git a/core/llm/llms/Flowise.ts b/core/llm/llms/Flowise.ts index fd2c0e207..1d9692db4 100644 --- a/core/llm/llms/Flowise.ts +++ b/core/llm/llms/Flowise.ts @@ -92,7 +92,7 @@ class Flowise extends BaseLLM { }; if (this.apiKey) { - headers["Authorization"] = `Bearer ${this.apiKey}`; + headers.Authorization = `Bearer ${this.apiKey}`; } for (const additionalHeader of this.additionalHeaders) { diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index e52b7b0a2..a3edd1608 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -33,7 +33,7 @@ class Gemini extends BaseLLM { const msgs = [...messages]; if (msgs[0]?.role === "system") { - const sysMsg = msgs.shift()!.content; + const sysMsg = msgs.shift()?.content; // @ts-ignore if (msgs[0]?.role === "user") { msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`; @@ -139,7 +139,7 @@ class Gemini extends BaseLLM { const wordsToYield = Math.min(3, words.length); yield { role: "assistant", - content: words.splice(0, wordsToYield).join(" ") + " ", + content: `${words.splice(0, wordsToYield).join(" ")} `, }; await delay(delaySeconds); } diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 81ce82cc9..b853f1e6b 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -173,9 +173,9 @@ class Ollama extends BaseLLM { try { const j = JSON.parse(chunk); if ("response" in j) { - yield j["response"]; + yield j.response; } else if ("error" in j) { - throw new Error(j["error"]); + throw new Error(j.error); } } catch (e) { throw new Error(`Error parsing Ollama response: ${e} ${chunk}`); diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index f043a6918..62fbcb00f 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -120,15 +120,14 @@ class OpenAI extends BaseLLM { `openai/deployments/${this.engine}/${endpoint}?api-version=${this.apiVersion}`, this.apiBase, ); - } else { - if (!this.apiBase) { - throw new Error( - "No API base URL provided. Please set the 'apiBase' option in config.json", - ); - } - - return new URL(endpoint, this.apiBase); } + if (!this.apiBase) { + throw new Error( + "No API base URL provided. Please set the 'apiBase' option in config.json", + ); + } + + return new URL(endpoint, this.apiBase); } protected async *_streamComplete( @@ -149,7 +148,7 @@ class OpenAI extends BaseLLM { ): AsyncGenerator { const args: any = this._convertArgs(options, []); args.prompt = prompt; - delete args.messages; + args.messages = undefined; const response = await this.fetch(this._getEndpoint("completions"), { method: "POST", diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 9aaa3f3e7..cbcf42e97 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -49,7 +49,7 @@ const getHandlebarsVars = ( const letter = convertToLetter(keyIndex); keysToFilepath[letter] = (ast.body[i] as any).path.original; value = value.replace( - new RegExp("{{\\s*" + (ast.body[i] as any).path.original + "\\s*}}"), + new RegExp(`{{\\s*${(ast.body[i] as any).path.original}\\s*}}`), `{{${letter}}}`, ); keyIndex++; diff --git a/core/llm/stream.ts b/core/llm/stream.ts index 302ee82ed..2a13f8445 100644 --- a/core/llm/stream.ts +++ b/core/llm/stream.ts @@ -6,7 +6,7 @@ export async function* streamResponse( } if (!response.body) { - throw new Error(`No response body returned.`); + throw new Error("No response body returned."); } const stream = response.body as any; @@ -38,9 +38,11 @@ function parseDataLine(line: string): any { function parseSseLine(line: string): { done: boolean; data: any } { if (line.startsWith("data: [DONE]")) { return { done: true, data: undefined }; - } else if (line.startsWith("data:")) { + } + if (line.startsWith("data:")) { return { done: false, data: parseDataLine(line) }; - } else if (line.startsWith(": ping")) { + } + if (line.startsWith(": ping")) { return { done: true, data: undefined }; } return { done: false, data: undefined }; @@ -51,7 +53,7 @@ export async function* streamSse(response: Response): AsyncGenerator { for await (const value of streamResponse(response)) { buffer += value; - let position; + let position: number; while ((position = buffer.indexOf("\n")) >= 0) { const line = buffer.slice(0, position); buffer = buffer.slice(position + 1); diff --git a/core/llm/templates/chat.ts b/core/llm/templates/chat.ts index 5a59b4f6f..561384432 100644 --- a/core/llm/templates/chat.ts +++ b/core/llm/templates/chat.ts @@ -166,7 +166,7 @@ function deepseekTemplateMessages(msgs: ChatMessage[]): string { prompt += msg.role === "user" ? "### Instruction:\n" : "### Response:\n"; if (system && msg.role === "user" && i === msgs.length - 1) { - prompt += system + "\n"; + prompt += `${system}\n`; } prompt += `${msg.content}`; diff --git a/core/util/devdata.ts b/core/util/devdata.ts index bb98b2527..c9df0d53e 100644 --- a/core/util/devdata.ts +++ b/core/util/devdata.ts @@ -1,4 +1,4 @@ -import { writeFileSync } from "fs"; +import { writeFileSync } from "node:fs"; import { getDevDataFilePath } from "./paths"; export function logDevData(tableName: string, data: any) { diff --git a/core/util/devdataSqlite.ts b/core/util/devdataSqlite.ts index 678c96b0f..08f6b00e3 100644 --- a/core/util/devdataSqlite.ts +++ b/core/util/devdataSqlite.ts @@ -1,4 +1,4 @@ -import fs from "fs"; +import fs from "node:fs"; import type { DatabaseConnection } from "../indexing/refreshIndex"; import { getDevDataSqlitePath } from "./paths"; @@ -24,7 +24,7 @@ export class DevDataSqliteDb { ) { const db = await DevDataSqliteDb.get(); await db?.run( - `INSERT INTO tokens_generated (model, provider, tokens_generated) VALUES (?, ?, ?)`, + "INSERT INTO tokens_generated (model, provider, tokens_generated) VALUES (?, ?, ?)", [model, provider, tokens], ); } diff --git a/core/util/fetchWithOptions.ts b/core/util/fetchWithOptions.ts index 102093dd3..67e1aef0f 100644 --- a/core/util/fetchWithOptions.ts +++ b/core/util/fetchWithOptions.ts @@ -1,5 +1,5 @@ -import * as fs from "fs"; -import tls from "tls"; +import * as fs from "node:fs"; +import tls from "node:tls"; import { http, https } from "follow-redirects"; import { HttpProxyAgent } from "http-proxy-agent"; import { HttpsProxyAgent } from "https-proxy-agent"; diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index b6d7b399c..a71a71a4b 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -1,4 +1,4 @@ -import * as fs from "fs"; +import * as fs from "node:fs"; import type { ContinueRcJson, IDE, diff --git a/core/util/history.ts b/core/util/history.ts index 2bd6d71d8..c03416ae7 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -1,4 +1,4 @@ -import * as fs from "fs"; +import * as fs from "node:fs"; import type { PersistedSessionInfo, SessionInfo } from ".."; import { getSessionFilePath, getSessionsListPath } from "./paths"; @@ -116,11 +116,10 @@ class HistoryManager { throw new Error( `It looks like there is a JSON formatting error in your sessions.json file (${sessionsListFilePath}). Please fix this before creating a new session.`, ); - } else { - throw new Error( - `It looks like there is a validation error in your sessions.json file (${sessionsListFilePath}). Please fix this before creating a new session. Error: ${error}`, - ); } + throw new Error( + `It looks like there is a validation error in your sessions.json file (${sessionsListFilePath}). Please fix this before creating a new session. Error: ${error}`, + ); } } } diff --git a/core/util/index.ts b/core/util/index.ts index 31bf54c33..5924a0304 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -72,7 +72,7 @@ export function dedentAndGetCommonWhitespace(s: string): [string, string] { // Iterate through the leading whitespace characters of the current line for (let j = 0; j < lcp.length; j++) { // If it doesn't have the same whitespace as lcp, then update lcp - if (j >= lines[i].length || lcp[j] != lines[i][j]) { + if (j >= lines[i].length || lcp[j] !== lines[i][j]) { lcp = lcp.slice(0, j); if (lcp === "") { return [s, ""]; diff --git a/core/util/merge.ts b/core/util/merge.ts index 2f8681371..32be931e0 100644 --- a/core/util/merge.ts +++ b/core/util/merge.ts @@ -11,7 +11,7 @@ export function mergeJson( const copyOfFirst = JSON.parse(JSON.stringify(first)); try { - for (var key in second) { + for (const key in second) { const secondValue = second[key]; if (!(key in copyOfFirst) || mergeBehavior === "overwrite") { diff --git a/core/util/paths.ts b/core/util/paths.ts index 071eafa6d..18499a2f9 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -1,6 +1,6 @@ -import * as fs from "fs"; -import * as os from "os"; -import * as path from "path"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; import dotenv from "dotenv"; import type { IdeType, SerializedContinueConfig } from ".."; import { defaultConfig, defaultConfigJetBrains } from "../config/default"; @@ -143,7 +143,7 @@ export function getDevDataSqlitePath(): string { } export function getDevDataFilePath(fileName: string): string { - return path.join(devDataPath(), fileName + ".jsonl"); + return path.join(devDataPath(), `${fileName}.jsonl`); } export function editConfigJson( @@ -220,9 +220,8 @@ export function getContinueDotEnv(): { [key: string]: string } { const filepath = path.join(getContinueGlobalPath(), ".env"); if (fs.existsSync(filepath)) { return dotenv.parse(fs.readFileSync(filepath)); - } else { - return {}; } + return {}; } export function getCoreLogsPath(): string { diff --git a/core/util/posthog.ts b/core/util/posthog.ts index 6949efc40..182758edc 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -1,4 +1,4 @@ -import os from "os"; +import os from "node:os"; export class Telemetry { // Set to undefined whenever telemetry is disabled diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 2c6be73c6..594e38069 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -1,4 +1,4 @@ -import * as path from "path"; +import * as path from "node:path"; import type { Language } from "web-tree-sitter"; const Parser = require("web-tree-sitter"); diff --git a/extensions/vscode/biome.json b/extensions/vscode/biome.json deleted file mode 100644 index 6308ce822..000000000 --- a/extensions/vscode/biome.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "$schema": "https://biomejs.dev/schemas/1.6.4/schema.json", - "organizeImports": { - "enabled": true - }, - "linter": { - "enabled": true, - "rules": { - "recommended": true - } - }, - "formatter": { - "indentStyle": "space" - } -}