From 16e8756115db3073a0a49a45561c0d8d3ec713c3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 13 Jun 2025 02:07:49 -0700 Subject: [PATCH 001/100] support for ports, case insensitivity, and removing empty gs strings --- packages/fetch/src/fetch.ts | 4 +- packages/fetch/src/util.ts | 92 +++++++++++++++++++++++++++++-------- 2 files changed, 74 insertions(+), 22 deletions(-) diff --git a/packages/fetch/src/fetch.ts b/packages/fetch/src/fetch.ts index 3b145012f..b5b461647 100644 --- a/packages/fetch/src/fetch.ts +++ b/packages/fetch/src/fetch.ts @@ -98,9 +98,7 @@ export async function fetchwithRequestOptions( } // Check if should bypass proxy based on requestOptions or NO_PROXY env var - const shouldBypass = - requestOptions?.noProxy?.includes(url.hostname) || - shouldBypassProxy(url.hostname); + const shouldBypass = shouldBypassProxy(url.hostname, requestOptions); // Create agent const protocol = url.protocol === "https:" ? https : http; diff --git a/packages/fetch/src/util.ts b/packages/fetch/src/util.ts index 20e3c1181..19fba2ba3 100644 --- a/packages/fetch/src/util.ts +++ b/packages/fetch/src/util.ts @@ -1,3 +1,5 @@ +import { RequestOptions } from "@continuedev/config-types"; + /** * Gets the proxy settings from environment variables * @param protocol The URL protocol (http: or https:) @@ -16,28 +18,80 @@ export function getProxyFromEnv(protocol: string): string | undefined { } } +export function getEnvNoProxyPatterns(): string[] { + const envValue = process.env.NO_PROXY || process.env.no_proxy; + if (envValue) { + return envValue + .split(",") + .map((item) => item.trim().toLowerCase()) + .filter((i) => !!i); + } else { + return []; + } +} + +export function getReqOptionsNoProxyPatterns( + options: RequestOptions | undefined, +): string[] { + return ( + options?.noProxy?.map((i) => i.trim().toLowerCase()).filter((i) => !!i) ?? + [] + ); +} + +export function patternMatchesHostname(hostname: string, pattern: string) { + // Split hostname and pattern to separate hostname and port + const [hostnameWithoutPort, hostnamePort] = hostname.split(":"); + const [patternWithoutPort, patternPort] = pattern.split(":"); + + // If pattern specifies a port but hostname doesn't match it, no match + if (patternPort && (!hostnamePort || hostnamePort !== patternPort)) { + return false; + } + + // Now compare just the hostname parts + + // exact match + if (patternWithoutPort === hostnameWithoutPort) { + return true; + } + // wildcard domain match (*.example.com) + if ( + patternWithoutPort.startsWith("*.") && + hostnameWithoutPort.endsWith(patternWithoutPort.substring(1)) + ) { + return true; + } + // Domain suffix match (.example.com) + if ( + patternWithoutPort.startsWith(".") && + hostnameWithoutPort.endsWith(patternWithoutPort.slice(1)) + ) { + return true; + } + + // TODO IP address ranges + + // TODO CIDR notation + + return false; +} + /** * Checks if a hostname should bypass proxy based on NO_PROXY environment variable * @param hostname The hostname to check * @returns True if the hostname should bypass proxy */ -export function shouldBypassProxy(hostname: string): boolean { - const noProxy = process.env.NO_PROXY || process.env.no_proxy; - if (!noProxy) return false; - - const noProxyItems = noProxy.split(",").map((item) => item.trim()); - - return noProxyItems.some((item) => { - // Exact match - if (item === hostname) return true; - - // Wildcard domain match (*.example.com) - if (item.startsWith("*.") && hostname.endsWith(item.substring(1))) - return true; - - // Domain suffix match (.example.com) - if (item.startsWith(".") && hostname.endsWith(item.slice(1))) return true; - - return false; - }); +export function shouldBypassProxy( + hostname: string, + requestOptions: RequestOptions | undefined, +): boolean { + const ignores = [ + ...getEnvNoProxyPatterns(), + ...getReqOptionsNoProxyPatterns(requestOptions), + ]; + const hostLowerCase = hostname.toLowerCase(); + return ignores.some((ignore) => + patternMatchesHostname(hostLowerCase, ignore), + ); } From bfe8199fe33efa17d122fa3b7d9c7554956e85f0 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 13 Jun 2025 02:07:54 -0700 Subject: [PATCH 002/100] unit tests --- packages/fetch/src/util.test.ts | 148 ++++++++++++++++++++++++++++---- 1 file changed, 130 insertions(+), 18 deletions(-) diff --git a/packages/fetch/src/util.test.ts b/packages/fetch/src/util.test.ts index 934f1a735..35c079b01 100644 --- a/packages/fetch/src/util.test.ts +++ b/packages/fetch/src/util.test.ts @@ -1,5 +1,9 @@ import { afterEach, expect, test, vi } from "vitest"; -import { getProxyFromEnv, shouldBypassProxy } from "./util.js"; +import { + getProxyFromEnv, + patternMatchesHostname, + shouldBypassProxy, +} from "./util.js"; // Reset environment variables after each test afterEach(() => { @@ -52,51 +56,159 @@ test("getProxyFromEnv prefers HTTPS_PROXY over other env vars for https protocol expect(getProxyFromEnv("https:")).toBe("https://preferred.example.com"); }); +// Tests for patternMatchesHostname +test("patternMatchesHostname with exact hostname match", () => { + expect(patternMatchesHostname("example.com", "example.com")).toBe(true); + expect(patternMatchesHostname("example.com", "different.com")).toBe(false); +}); + +test("patternMatchesHostname with wildcard domains", () => { + expect(patternMatchesHostname("sub.example.com", "*.example.com")).toBe(true); + expect(patternMatchesHostname("sub.sub.example.com", "*.example.com")).toBe( + true, + ); + expect(patternMatchesHostname("example.com", "*.example.com")).toBe(false); + expect(patternMatchesHostname("sub.different.com", "*.example.com")).toBe( + false, + ); +}); + +test("patternMatchesHostname with domain suffix", () => { + expect(patternMatchesHostname("sub.example.com", ".example.com")).toBe(true); + expect(patternMatchesHostname("example.com", ".example.com")).toBe(true); + expect(patternMatchesHostname("different.com", ".example.com")).toBe(false); +}); + +test("patternMatchesHostname with case insensitivity", () => { + expect(patternMatchesHostname("EXAMPLE.com", "example.COM")).toBe(true); + expect(patternMatchesHostname("sub.EXAMPLE.com", "*.example.COM")).toBe(true); +}); + +// Port handling tests +test("patternMatchesHostname with exact port match", () => { + expect(patternMatchesHostname("example.com:8080", "example.com:8080")).toBe( + true, + ); + expect(patternMatchesHostname("example.com:8080", "example.com:9090")).toBe( + false, + ); +}); + +test("patternMatchesHostname with port in pattern but not in hostname", () => { + expect(patternMatchesHostname("example.com", "example.com:8080")).toBe(false); +}); + +test("patternMatchesHostname with port in hostname but not in pattern", () => { + expect(patternMatchesHostname("example.com:8080", "example.com")).toBe(true); +}); + +test("patternMatchesHostname with wildcard domains and ports", () => { + expect( + patternMatchesHostname("sub.example.com:8080", "*.example.com:8080"), + ).toBe(true); + expect( + patternMatchesHostname("sub.example.com:9090", "*.example.com:8080"), + ).toBe(false); + expect(patternMatchesHostname("sub.example.com", "*.example.com:8080")).toBe( + false, + ); +}); + +test("patternMatchesHostname with domain suffix and ports", () => { + expect( + patternMatchesHostname("sub.example.com:8080", ".example.com:8080"), + ).toBe(true); + expect(patternMatchesHostname("example.com:8080", ".example.com:8080")).toBe( + true, + ); + expect( + patternMatchesHostname("sub.example.com:9090", ".example.com:8080"), + ).toBe(false); +}); + // Tests for shouldBypassProxy test("shouldBypassProxy returns false when NO_PROXY is not set", () => { - expect(shouldBypassProxy("example.com")).toBe(false); + expect(shouldBypassProxy("example.com", undefined)).toBe(false); }); test("shouldBypassProxy returns true for exact hostname match", () => { process.env.NO_PROXY = "example.com,another.com"; - expect(shouldBypassProxy("example.com")).toBe(true); + expect(shouldBypassProxy("example.com", undefined)).toBe(true); }); test("shouldBypassProxy returns false when hostname doesn't match any NO_PROXY entry", () => { process.env.NO_PROXY = "example.com,another.com"; - expect(shouldBypassProxy("different.com")).toBe(false); + expect(shouldBypassProxy("different.com", undefined)).toBe(false); }); test("shouldBypassProxy handles lowercase no_proxy", () => { process.env.no_proxy = "example.com"; - expect(shouldBypassProxy("example.com")).toBe(true); + expect(shouldBypassProxy("example.com", undefined)).toBe(true); }); test("shouldBypassProxy works with wildcard domains", () => { process.env.NO_PROXY = "*.example.com"; - expect(shouldBypassProxy("sub.example.com")).toBe(true); - expect(shouldBypassProxy("example.com")).toBe(false); - expect(shouldBypassProxy("different.com")).toBe(false); + expect(shouldBypassProxy("sub.example.com", undefined)).toBe(true); + expect(shouldBypassProxy("example.com", undefined)).toBe(false); + expect(shouldBypassProxy("different.com", undefined)).toBe(false); }); test("shouldBypassProxy works with domain suffix", () => { process.env.NO_PROXY = ".example.com"; - expect(shouldBypassProxy("sub.example.com")).toBe(true); - expect(shouldBypassProxy("example.com")).toBe(true); - expect(shouldBypassProxy("different.com")).toBe(false); + expect(shouldBypassProxy("sub.example.com", undefined)).toBe(true); + expect(shouldBypassProxy("example.com", undefined)).toBe(true); + expect(shouldBypassProxy("different.com", undefined)).toBe(false); }); test("shouldBypassProxy handles multiple entries with different patterns", () => { process.env.NO_PROXY = "internal.local,*.example.com,.test.com"; - expect(shouldBypassProxy("internal.local")).toBe(true); - expect(shouldBypassProxy("sub.example.com")).toBe(true); - expect(shouldBypassProxy("sub.test.com")).toBe(true); - expect(shouldBypassProxy("test.com")).toBe(true); - expect(shouldBypassProxy("example.org")).toBe(false); + expect(shouldBypassProxy("internal.local", undefined)).toBe(true); + expect(shouldBypassProxy("sub.example.com", undefined)).toBe(true); + expect(shouldBypassProxy("sub.test.com", undefined)).toBe(true); + expect(shouldBypassProxy("test.com", undefined)).toBe(true); + expect(shouldBypassProxy("example.org", undefined)).toBe(false); }); test("shouldBypassProxy ignores whitespace in NO_PROXY", () => { process.env.NO_PROXY = " example.com , *.test.org "; - expect(shouldBypassProxy("example.com")).toBe(true); - expect(shouldBypassProxy("subdomain.test.org")).toBe(true); + expect(shouldBypassProxy("example.com", undefined)).toBe(true); + expect(shouldBypassProxy("subdomain.test.org", undefined)).toBe(true); +}); + +test("shouldBypassProxy with ports in NO_PROXY", () => { + process.env.NO_PROXY = "example.com:8080,*.test.org:443,.internal.net:8443"; + expect(shouldBypassProxy("example.com:8080", undefined)).toBe(true); + expect(shouldBypassProxy("example.com:9090", undefined)).toBe(false); + expect(shouldBypassProxy("sub.test.org:443", undefined)).toBe(true); + expect(shouldBypassProxy("sub.internal.net:8443", undefined)).toBe(true); + expect(shouldBypassProxy("internal.net:8443", undefined)).toBe(true); +}); + +test("shouldBypassProxy accepts options with noProxy patterns", () => { + const options = { noProxy: ["example.com:8080", "*.internal.net"] }; + expect(shouldBypassProxy("example.com:8080", options)).toBe(true); + expect(shouldBypassProxy("example.com", options)).toBe(false); + expect(shouldBypassProxy("server.internal.net", options)).toBe(true); +}); + +test("shouldBypassProxy combines environment and options noProxy patterns", () => { + process.env.NO_PROXY = "example.org,*.test.com"; + const options = { noProxy: ["example.com:8080", "*.internal.net"] }; + expect(shouldBypassProxy("example.org", options)).toBe(true); + expect(shouldBypassProxy("sub.test.com", options)).toBe(true); + expect(shouldBypassProxy("example.com:8080", options)).toBe(true); + expect(shouldBypassProxy("server.internal.net", options)).toBe(true); + expect(shouldBypassProxy("other.domain", options)).toBe(false); +}); + +test("shouldBypassProxy handles empty noProxy array in options", () => { + process.env.NO_PROXY = "example.org"; + const options = { noProxy: [] }; + expect(shouldBypassProxy("example.org", options)).toBe(true); + expect(shouldBypassProxy("different.com", options)).toBe(false); +}); + +test("shouldBypassProxy handles undefined options", () => { + process.env.NO_PROXY = "example.org"; + expect(shouldBypassProxy("example.org", undefined)).toBe(true); }); From b0cc911cf972923ee2c984a6a1c3cdb095adba3e Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 13 Jun 2025 11:33:57 -0700 Subject: [PATCH 003/100] clean up getProxy logic --- packages/fetch/src/fetch.ts | 7 ++----- packages/fetch/src/util.ts | 11 +++++++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/packages/fetch/src/fetch.ts b/packages/fetch/src/fetch.ts index b5b461647..fbf51f108 100644 --- a/packages/fetch/src/fetch.ts +++ b/packages/fetch/src/fetch.ts @@ -5,7 +5,7 @@ import { HttpsProxyAgent } from "https-proxy-agent"; import { BodyInit, RequestInit, Response } from "node-fetch"; import { getAgentOptions } from "./getAgentOptions.js"; import fetch from "./node-fetch-patch.js"; -import { getProxyFromEnv, shouldBypassProxy } from "./util.js"; +import { getProxy, shouldBypassProxy } from "./util.js"; const { http, https } = (followRedirects as any).default; @@ -92,10 +92,7 @@ export async function fetchwithRequestOptions( const agentOptions = getAgentOptions(requestOptions); // Get proxy from options or environment variables - let proxy = requestOptions?.proxy; - if (!proxy) { - proxy = getProxyFromEnv(url.protocol); - } + const proxy = getProxy(url.protocol, requestOptions); // Check if should bypass proxy based on requestOptions or NO_PROXY env var const shouldBypass = shouldBypassProxy(url.hostname, requestOptions); diff --git a/packages/fetch/src/util.ts b/packages/fetch/src/util.ts index 19fba2ba3..1a18d5b1e 100644 --- a/packages/fetch/src/util.ts +++ b/packages/fetch/src/util.ts @@ -18,6 +18,17 @@ export function getProxyFromEnv(protocol: string): string | undefined { } } +// Note that request options proxy (per model) takes precedence over environment variables +export function getProxy( + protocol: string, + requestOptions?: RequestOptions, +): string | undefined { + if (requestOptions?.proxy) { + return requestOptions.proxy; + } + return getProxyFromEnv(protocol); +} + export function getEnvNoProxyPatterns(): string[] { const envValue = process.env.NO_PROXY || process.env.no_proxy; if (envValue) { From 05020b62a99f1416a2934904574a57583b43b72d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 13 Jun 2025 12:50:32 -0700 Subject: [PATCH 004/100] fix lowercase logic --- packages/fetch/src/util.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/fetch/src/util.ts b/packages/fetch/src/util.ts index 1a18d5b1e..dc302bf12 100644 --- a/packages/fetch/src/util.ts +++ b/packages/fetch/src/util.ts @@ -52,8 +52,8 @@ export function getReqOptionsNoProxyPatterns( export function patternMatchesHostname(hostname: string, pattern: string) { // Split hostname and pattern to separate hostname and port - const [hostnameWithoutPort, hostnamePort] = hostname.split(":"); - const [patternWithoutPort, patternPort] = pattern.split(":"); + const [hostnameWithoutPort, hostnamePort] = hostname.toLowerCase().split(":"); + const [patternWithoutPort, patternPort] = pattern.toLowerCase().split(":"); // If pattern specifies a port but hostname doesn't match it, no match if (patternPort && (!hostnamePort || hostnamePort !== patternPort)) { From 45b7069eb86dfbc6935c605f8490f2e6200f6fd0 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 13 Jun 2025 14:31:25 -0700 Subject: [PATCH 005/100] get agent options verbose fetch logging --- packages/fetch/src/getAgentOptions.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/packages/fetch/src/getAgentOptions.ts b/packages/fetch/src/getAgentOptions.ts index 20fc7641c..fd7200205 100644 --- a/packages/fetch/src/getAgentOptions.ts +++ b/packages/fetch/src/getAgentOptions.ts @@ -61,6 +61,19 @@ export function getAgentOptions(requestOptions?: RequestOptions): { keepAliveMsecs: timeout, }; + if (process.env.VERBOSE_FETCH) { + console.log("=== CERTIFICATE CONFIGURATION ==="); + console.log(`Number of CA certificates: ${ca.length}`); + console.log( + `Global agent CA certificates: ${globalAgent.options.ca ? "Present" : "Not present"}`, + ); + console.log( + `Custom certificates provided: ${customCerts?.length ? "Yes" : "No"}`, + ); + console.log(`rejectUnauthorized: ${agentOptions.rejectUnauthorized}`); + console.log("================================"); + } + // Handle ClientCertificateOptions if (requestOptions?.clientCertificate) { const { cert, key, passphrase } = requestOptions.clientCertificate; From e6ab397e1c61fe42cab2715f75a63da9809d8126 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 16 Jun 2025 13:28:34 -0700 Subject: [PATCH 006/100] call next edit provider --- .../src/autocomplete/completionProvider.ts | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 12eb8a881..9bc296416 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -215,12 +215,16 @@ export class ContinueCompletionProvider setupStatusBar(undefined, true); // TODO: revert back - const outcome = - await this.completionProvider.provideInlineCompletionItems( - input, - signal, - wasManuallyTriggered, - ); + // const outcome = + // await this.completionProvider.provideInlineCompletionItems( + // input, + // signal, + // wasManuallyTriggered, + // ); + const outcome = await this.nextEditProvider.provideInlineCompletionItems( + input, + signal, + ); if (!outcome || !outcome.completion) { return null; From 2f9e5ebcd89623f9008d8f255804cf44cbd8b1cc Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 16 Jun 2025 13:28:50 -0700 Subject: [PATCH 007/100] add recently opened file snippets --- core/autocomplete/snippets/getAllSnippets.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index bb3a9dbc3..671c52d3b 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -230,6 +230,7 @@ export const getAllSnippetsWithoutRace = async ({ ideSnippets, diffSnippets, clipboardSnippets, + recentlyOpenedFileSnippets ] = await Promise.all([ contextRetrievalService.getRootPathSnippets(helper), contextRetrievalService.getSnippetsFromImportDefinitions(helper), @@ -238,6 +239,7 @@ export const getAllSnippetsWithoutRace = async ({ : [], [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, getClipboardSnippets(ide), + getSnippetsFromRecentlyOpenedFiles(helper, ide) ]); return { @@ -248,5 +250,6 @@ export const getAllSnippetsWithoutRace = async ({ diffSnippets, clipboardSnippets, recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges, + recentlyOpenedFileSnippets }; }; From aafb95ae3b0e99a028c01e94f7da988ef5c15b6c Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 16 Jun 2025 13:29:22 -0700 Subject: [PATCH 008/100] pass in default abort controller signal --- core/nextEdit/NextEditProvider.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 5f43f14da..cc56c5ac5 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -254,8 +254,10 @@ export class NextEditProvider { // TODO: Do some zod schema validation here if needed. } else { - const testController = new AbortController(); - const msg: ChatMessage = await llm.chat(prompts, testController.signal); + // const testController = new AbortController(); + // const msg: ChatMessage = await llm.chat(prompts, testController.signal); + // const testToken = testController.signal; + const msg: ChatMessage = await llm.chat(prompts, token); if (typeof msg.content === "string") { const nextCompletion = msg.content; From 015c8fa1fe9fd4cf288584351353995b5db4116b Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 16 Jun 2025 14:38:56 -0700 Subject: [PATCH 009/100] render diff as ghost text (albeit by an entire line worth of diff) --- core/nextEdit/NextEditProvider.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index cc56c5ac5..cc5ec2dfe 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -18,6 +18,9 @@ import { AutocompleteInput, AutocompleteOutcome, } from "../autocomplete/util/types.js"; +import { myersDiff } from "../diff/myers.js"; +import { replaceEscapedCharacters } from "../util/text.js"; +import { getRenderableDiff } from "./diff/diff.js"; import { Prompt, renderDefaultSystemPrompt, @@ -259,11 +262,20 @@ export class NextEditProvider { // const testToken = testController.signal; const msg: ChatMessage = await llm.chat(prompts, token); if (typeof msg.content === "string") { - const nextCompletion = msg.content; + const nextCompletion = replaceEscapedCharacters( + msg.content + .split("<|editable_region_start|>\n")[1] + .slice(1) + .slice(0, -2), + ); + + const diffLines = myersDiff(helper.fileContents, nextCompletion); + + const diff = getRenderableDiff(diffLines); const outcomeNext: AutocompleteOutcome = { time: Date.now() - startTime, - completion: nextCompletion, + completion: diff, prefix: "", suffix: "", prompt: "", @@ -272,7 +284,7 @@ export class NextEditProvider { completionOptions: null, cacheHit: false, filepath: helper.filepath, - numLines: nextCompletion.split("\n").length, + numLines: diff.split("\n").length, completionId: helper.input.completionId, gitRepo: await this.ide.getRepoName(helper.filepath), uniqueId: await this.ide.getUniqueId(), From a6982b9e53330531353bce90dcf1dd2317ab5e43 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 16 Jun 2025 14:39:23 -0700 Subject: [PATCH 010/100] add a function to create a renderable diff given DiffLines --- core/nextEdit/diff/diff.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 core/nextEdit/diff/diff.ts diff --git a/core/nextEdit/diff/diff.ts b/core/nextEdit/diff/diff.ts new file mode 100644 index 000000000..c23a60620 --- /dev/null +++ b/core/nextEdit/diff/diff.ts @@ -0,0 +1,19 @@ +import { DiffLine } from "../.."; + +export function getRenderableDiff(diffLines: DiffLine[]) { + let diffLineNumberStart = -1; + const diff = diffLines + .reduce((acc, curr, i) => { + if (curr.type === "new") { + acc += `${curr.line}\n`; + + if (diffLineNumberStart === -1) { + diffLineNumberStart = i; + } + } + return acc; + }, "") + .slice(2); + + return diff; +} From d44c53329be71b038b9509824f7304c7f31998f2 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 16 Jun 2025 14:39:44 -0700 Subject: [PATCH 011/100] add a util function to replace all escaped characters --- core/util/text.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/core/util/text.ts b/core/util/text.ts index e4870dfa0..2e11fce05 100644 --- a/core/util/text.ts +++ b/core/util/text.ts @@ -4,3 +4,24 @@ export const capitalizeFirstLetter = (val: string) => { } return val[0].toUpperCase() + val.slice(1); }; + +export function replaceEscapedCharacters(str: string): string { + return str.replaceAll(/\\(n|t|r|\\|"|')/g, (match, p1) => { + switch (p1) { + case "n": + return "\n"; + case "t": + return "\t"; + case "r": + return "\r"; + case "\\": + return "\\"; + case '"': + return '"'; + case "'": + return "'"; + default: + return match; // NOTE: Handle unexpected escapes better than this. + } + }); +} From 69f3a5409777ee44487cb84ea9619911e8ff7dc6 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 16 Jun 2025 14:40:16 -0700 Subject: [PATCH 012/100] remove unnecessary slice --- core/nextEdit/diff/diff.ts | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/core/nextEdit/diff/diff.ts b/core/nextEdit/diff/diff.ts index c23a60620..156455f28 100644 --- a/core/nextEdit/diff/diff.ts +++ b/core/nextEdit/diff/diff.ts @@ -2,18 +2,16 @@ import { DiffLine } from "../.."; export function getRenderableDiff(diffLines: DiffLine[]) { let diffLineNumberStart = -1; - const diff = diffLines - .reduce((acc, curr, i) => { - if (curr.type === "new") { - acc += `${curr.line}\n`; + const diff = diffLines.reduce((acc, curr, i) => { + if (curr.type === "new") { + acc += `${curr.line}\n`; - if (diffLineNumberStart === -1) { - diffLineNumberStart = i; - } + if (diffLineNumberStart === -1) { + diffLineNumberStart = i; } - return acc; - }, "") - .slice(2); + } + return acc; + }, ""); return diff; } From 79f0729113c89c24b33f0679cef4c1eb8b1cc014 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 17 Jun 2025 02:27:12 -0700 Subject: [PATCH 013/100] read extra certs and use cert cache --- packages/fetch/src/certs.test.ts | 110 ++++++++++ packages/fetch/src/certs.ts | 129 +++++++++++ packages/fetch/src/fetch.test.ts | 173 --------------- packages/fetch/src/fetch.ts | 2 +- packages/fetch/src/getAgentOptions.test.ts | 237 +++++++++++++-------- packages/fetch/src/getAgentOptions.ts | 50 +---- 6 files changed, 398 insertions(+), 303 deletions(-) create mode 100644 packages/fetch/src/certs.test.ts create mode 100644 packages/fetch/src/certs.ts delete mode 100644 packages/fetch/src/fetch.test.ts diff --git a/packages/fetch/src/certs.test.ts b/packages/fetch/src/certs.test.ts new file mode 100644 index 000000000..bd7d405c4 --- /dev/null +++ b/packages/fetch/src/certs.test.ts @@ -0,0 +1,110 @@ +import * as fs from "node:fs"; +import { beforeEach, expect, test, vi } from "vitest"; +import { getCertificateContent } from "./certs.js"; + +// Mock fs module +vi.mock("node:fs", () => ({ + readFileSync: vi.fn(), +})); + +const mockReadFileSync = vi.mocked(fs.readFileSync); + +beforeEach(() => { + vi.clearAllMocks(); +}); + +test("getCertificateContent should decode base64 data URI correctly", () => { + const testCert = + "-----BEGIN CERTIFICATE-----\nMIIC...\n-----END CERTIFICATE-----"; + const base64Data = Buffer.from(testCert, "utf8").toString("base64"); + const dataUri = `data:application/x-pem-file;base64,${base64Data}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(testCert); +}); + +test("getCertificateContent should decode URL-encoded data URI correctly", () => { + const testCert = + "-----BEGIN CERTIFICATE-----\nMIIC...\n-----END CERTIFICATE-----"; + const encodedData = encodeURIComponent(testCert); + const dataUri = `data:text/plain,${encodedData}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(testCert); +}); + +test("getCertificateContent should handle plain text data URI correctly", () => { + const testCert = "simple-cert-content"; + const dataUri = `data:text/plain,${testCert}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(testCert); +}); + +test("getCertificateContent should read file when input is a file path", () => { + const filePath = "/path/to/cert.pem"; + const expectedContent = + "-----BEGIN CERTIFICATE-----\nfile content\n-----END CERTIFICATE-----"; + + mockReadFileSync.mockReturnValue(expectedContent); + + const result = getCertificateContent(filePath); + + expect(mockReadFileSync).toHaveBeenCalledWith(filePath, "utf8"); + expect(result).toBe(expectedContent); +}); + +test("getCertificateContent should handle data URI with different media types", () => { + const testData = "certificate-data"; + const base64Data = Buffer.from(testData, "utf8").toString("base64"); + const dataUri = `data:application/x-x509-ca-cert;base64,${base64Data}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(testData); +}); + +test("getCertificateContent should handle data URI without media type", () => { + const testData = "simple-data"; + const base64Data = Buffer.from(testData, "utf8").toString("base64"); + const dataUri = `data:;base64,${base64Data}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(testData); +}); + +test("getCertificateContent should handle data URI without media type or encoding", () => { + const testData = "simple-data"; + const base64Data = Buffer.from(testData, "utf8").toString("base64"); + const dataUri = `data:;base64,${base64Data}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(testData); +}); + +test("getCertificateContent should handle relative file paths", () => { + const filePath = "./certs/ca.pem"; + const expectedContent = "certificate from relative path"; + + mockReadFileSync.mockReturnValue(expectedContent); + + const result = getCertificateContent(filePath); + + expect(mockReadFileSync).toHaveBeenCalledWith(filePath, "utf8"); + expect(result).toBe(expectedContent); +}); + +test("getCertificateContent should handle data URI with special characters in URL encoding", () => { + const testCert = "cert with spaces and special chars: !@#$%"; + const encodedData = encodeURIComponent(testCert); + const dataUri = `data:text/plain,${encodedData}`; + + const result = getCertificateContent(dataUri); + + expect(result).toBe(testCert); +}); diff --git a/packages/fetch/src/certs.ts b/packages/fetch/src/certs.ts new file mode 100644 index 000000000..4793e36b7 --- /dev/null +++ b/packages/fetch/src/certs.ts @@ -0,0 +1,129 @@ +import { globalAgent } from "https"; +import * as fs from "node:fs"; +import tls from "node:tls"; + +/** + * Extracts content from either a file path or data URI + */ +export function getCertificateContent(input: string): string { + if (input.startsWith("data:")) { + // Parse data URI: data:[][;base64], + const [header, data] = input.split(","); + if (header.includes("base64")) { + return Buffer.from(data, "base64").toString("utf8"); + } else { + return decodeURIComponent(data); + } + } else { + // Assume it's a file path + return fs.readFileSync(input, "utf8"); + } +} + +export class CertsCache { + private static instance: CertsCache; + private _fixedCa: string[] = []; + private _initialized: boolean = false; + private _customCerts: Map = new Map(); + + private constructor() {} + + public static getInstance(): CertsCache { + if (!CertsCache.instance) { + CertsCache.instance = new CertsCache(); + } + return CertsCache.instance; + } + + get fixedCa(): string[] { + if (this._initialized) { + return this._fixedCa; + } + + const globalCerts: string[] = []; + if (Boolean(process.env.IS_BINARY)) { + if (Array.isArray(globalAgent.options.ca)) { + globalCerts.push( + ...globalAgent.options.ca.map((cert) => cert.toString()), + ); + } else if (typeof globalAgent.options.ca !== "undefined") { + globalCerts.push(globalAgent.options.ca.toString()); + } + } + + const extraCerts: string[] = []; + if (process.env.NODE_EXTRA_CA_CERTS) { + try { + const content = fs.readFileSync( + process.env.NODE_EXTRA_CA_CERTS, + "utf8", + ); + extraCerts.push(content); + } catch (error) { + if (process.env.VERBOSE_FETCH) { + console.error( + `Error reading NODE_EXTRA_CA_CERTS file: ${process.env.NODE_EXTRA_CA_CERTS}`, + error, + ); + } + } + } + + this._fixedCa = Array.from( + new Set([...tls.rootCertificates, ...globalCerts, ...extraCerts]), + ); + this._initialized = true; + return this._fixedCa; + } + + async getCachedCustomCert(path: string): Promise { + if (this._customCerts.has(path)) { + return this._customCerts.get(path); + } + const certContent = getCertificateContent(path); + this._customCerts.set(path, certContent); + return certContent; + } + + async getAllCachedCustomCerts( + caBundlePath: string[] | string, + ): Promise { + const paths = Array.isArray(caBundlePath) ? caBundlePath : [caBundlePath]; + const certs: string[] = []; + await Promise.all( + paths.map(async (path) => { + try { + const certContent = await this.getCachedCustomCert(path); + if (certContent) { + certs.push(certContent); + } else if (process.env.VERBOSE_FETCH) { + console.warn(`Empty certificate found at ${path}`); + } + } catch (error) { + if (process.env.VERBOSE_FETCH) { + console.error( + `Error loading custom certificate from ${path}:`, + error, + ); + } + } + }), + ); + return certs; + } + + async getCa(caBundlePath: undefined | string | string[]): Promise { + if (!caBundlePath) { + return this.fixedCa; + } + + const customCerts = await this.getAllCachedCustomCerts(caBundlePath); + return [...this.fixedCa, ...customCerts]; + } + + async clear(): Promise { + this._customCerts.clear(); + this._initialized = false; + this._fixedCa = []; + } +} diff --git a/packages/fetch/src/fetch.test.ts b/packages/fetch/src/fetch.test.ts deleted file mode 100644 index c11e0ed2c..000000000 --- a/packages/fetch/src/fetch.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { globalAgent } from "https"; -import * as fs from "node:fs"; -import * as os from "node:os"; -import * as path from "node:path"; -import { afterEach, beforeEach, expect, test } from "vitest"; -import { getAgentOptions } from "./getAgentOptions.js"; - -// Store original env -const originalEnv = process.env; -const originalGlobalAgentOptions = { ...globalAgent.options }; - -// Temporary directory for test certificate files -let tempDir: string; - -beforeEach(() => { - // Create a temporary directory for test files - tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "fetch-test-")); - - process.env = { ...originalEnv }; - - // Reset globalAgent for each test - globalAgent.options = { ...originalGlobalAgentOptions }; -}); - -afterEach(() => { - process.env = originalEnv; - globalAgent.options = originalGlobalAgentOptions; - - // Clean up temporary directory - try { - fs.rmSync(tempDir, { recursive: true, force: true }); - } catch (error) { - console.error(`Failed to remove temp directory: ${error}`); - } -}); - -// Helper function to create test certificate files -function createTestCertFile(filename: string, content: string): string { - const filePath = path.join(tempDir, filename); - fs.writeFileSync(filePath, content, "utf8"); - return filePath; -} - -test("getAgentOptions returns basic configuration with default values", () => { - const options = getAgentOptions(); - - // Check default timeout (7200 seconds = 2 hours = 7,200,000 ms) - expect(options.timeout).toBe(7200000); - expect(options.sessionTimeout).toBe(7200000); - expect(options.keepAliveMsecs).toBe(7200000); - expect(options.keepAlive).toBe(true); - - // Verify certificates array exists and contains items - expect(options.ca).toBeInstanceOf(Array); - expect(options.ca.length).toBeGreaterThan(0); - - // Verify at least one of the real TLS root certificates is included - // This assumes there's at least one certificate with "CERTIFICATE" in it - expect(options.ca.some((cert: any) => cert.includes("CERTIFICATE"))).toBe( - true, - ); -}); - -test("getAgentOptions respects custom timeout", () => { - const customTimeout = 300; // 5 minutes - const options = getAgentOptions({ timeout: customTimeout }); - - // Check timeout values (300 seconds = 300,000 ms) - expect(options.timeout).toBe(300000); - expect(options.sessionTimeout).toBe(300000); - expect(options.keepAliveMsecs).toBe(300000); -}); - -test("getAgentOptions uses verifySsl setting", () => { - // With verifySsl true - let options = getAgentOptions({ verifySsl: true }); - expect(options.rejectUnauthorized).toBe(true); - - // With verifySsl false - options = getAgentOptions({ verifySsl: false }); - expect(options.rejectUnauthorized).toBe(false); -}); - -test("getAgentOptions incorporates custom CA bundle paths", () => { - // Create a test CA bundle file - const caBundleContent = - "-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIJAMcuSp7chAYdMA==\n-----END CERTIFICATE-----"; - const caBundlePath = createTestCertFile("ca-bundle.pem", caBundleContent); - - // Single string path - let options = getAgentOptions({ caBundlePath }); - - // Verify that our test certificate is included in the CA list - expect(options.ca).toContain(caBundleContent); - - // Create multiple test CA bundle files - const caContent1 = - "-----BEGIN CERTIFICATE-----\nABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\n-----END CERTIFICATE-----"; - const caContent2 = - "-----BEGIN CERTIFICATE-----\n0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\n-----END CERTIFICATE-----"; - const caPath1 = createTestCertFile("ca1.pem", caContent1); - const caPath2 = createTestCertFile("ca2.pem", caContent2); - - // Array of paths - options = getAgentOptions({ - caBundlePath: [caPath1, caPath2], - }); - - // Verify that both test certificates are included in the CA list - expect(options.ca).toContain(caContent1); - expect(options.ca).toContain(caContent2); -}); - -test("getAgentOptions includes global certs when running as binary", () => { - // Set up test certs in globalAgent - globalAgent.options.ca = ["global-cert-1", "global-cert-2"]; - - // Set IS_BINARY environment variable - process.env.IS_BINARY = "true"; - - const options = getAgentOptions(); - - // Test for global certs - expect(options.ca).toContain("global-cert-1"); - expect(options.ca).toContain("global-cert-2"); -}); - -test("getAgentOptions handles client certificate configuration", () => { - // Create test certificate files - const clientCertContent = - "-----BEGIN CERTIFICATE-----\nCLIENTCERT\n-----END CERTIFICATE-----"; - const clientKeyContent = - "-----BEGIN PRIVATE KEY-----\nCLIENTKEY\n-----END PRIVATE KEY-----"; - const certPath = createTestCertFile("client.cert", clientCertContent); - const keyPath = createTestCertFile("client.key", clientKeyContent); - - const clientCertOptions = { - clientCertificate: { - cert: certPath, - key: keyPath, - passphrase: "secret-passphrase", - }, - }; - - const options = getAgentOptions(clientCertOptions); - - expect(options.cert).toBe(clientCertContent); - expect(options.key).toBe(clientKeyContent); - expect(options.passphrase).toBe("secret-passphrase"); -}); - -test("getAgentOptions handles client certificate without passphrase", () => { - // Create test certificate files - const clientCertContent = - "-----BEGIN CERTIFICATE-----\nCLIENTCERT2\n-----END CERTIFICATE-----"; - const clientKeyContent = - "-----BEGIN PRIVATE KEY-----\nCLIENTKEY2\n-----END PRIVATE KEY-----"; - const certPath = createTestCertFile("client2.cert", clientCertContent); - const keyPath = createTestCertFile("client2.key", clientKeyContent); - - const clientCertOptions = { - clientCertificate: { - cert: certPath, - key: keyPath, - }, - }; - - const options = getAgentOptions(clientCertOptions); - - expect(options.cert).toBe(clientCertContent); - expect(options.key).toBe(clientKeyContent); - expect(options.passphrase).toBeUndefined(); -}); diff --git a/packages/fetch/src/fetch.ts b/packages/fetch/src/fetch.ts index 3b145012f..c7b2b9db1 100644 --- a/packages/fetch/src/fetch.ts +++ b/packages/fetch/src/fetch.ts @@ -89,7 +89,7 @@ export async function fetchwithRequestOptions( url.host = "127.0.0.1"; } - const agentOptions = getAgentOptions(requestOptions); + const agentOptions = await getAgentOptions(requestOptions); // Get proxy from options or environment variables let proxy = requestOptions?.proxy; diff --git a/packages/fetch/src/getAgentOptions.test.ts b/packages/fetch/src/getAgentOptions.test.ts index 5b589ea85..e5e4dd549 100644 --- a/packages/fetch/src/getAgentOptions.test.ts +++ b/packages/fetch/src/getAgentOptions.test.ts @@ -1,122 +1,189 @@ +import { globalAgent } from "https"; import * as fs from "node:fs"; -import { expect, test, vi } from "vitest"; +import * as os from "node:os"; +import * as path from "node:path"; +import { afterEach, beforeEach, expect, test } from "vitest"; +import { CertsCache } from "./certs.js"; +import { getAgentOptions } from "./getAgentOptions.js"; -// Mock fs module -vi.mock("node:fs", () => ({ - readFileSync: vi.fn(), -})); +// Store original env +const originalEnv = process.env; +const originalGlobalAgentOptions = { ...globalAgent.options }; -const mockReadFileSync = vi.mocked(fs.readFileSync); +// Temporary directory for test certificate files +let tempDir: string; -// We need to access the private getCertificateContent function for testing -// Since it's not exported, we'll test it indirectly through scenarios or mock the module -const getCertificateContent = (input: string): string => { - if (input.startsWith("data:")) { - // Parse data URI: data:[][;base64], - const [header, data] = input.split(","); - if (header.includes("base64")) { - return Buffer.from(data, "base64").toString("utf8"); - } else { - return decodeURIComponent(data); - } - } else { - // Assume it's a file path - return fs.readFileSync(input, "utf8"); +beforeEach(() => { + // Create a temporary directory for test files + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "fetch-test-")); + + process.env = { ...originalEnv }; + + // Reset globalAgent for each test + globalAgent.options = { ...originalGlobalAgentOptions }; +}); + +afterEach(() => { + process.env = originalEnv; + globalAgent.options = originalGlobalAgentOptions; + + CertsCache.getInstance().clear(); + + // Clean up temporary directory + try { + fs.rmSync(tempDir, { recursive: true, force: true }); + } catch (error) { + console.error(`Failed to remove temp directory: ${error}`); } -}; - -test("getCertificateContent should decode base64 data URI correctly", () => { - const testCert = - "-----BEGIN CERTIFICATE-----\nMIIC...\n-----END CERTIFICATE-----"; - const base64Data = Buffer.from(testCert, "utf8").toString("base64"); - const dataUri = `data:application/x-pem-file;base64,${base64Data}`; - - const result = getCertificateContent(dataUri); - - expect(result).toBe(testCert); }); -test("getCertificateContent should decode URL-encoded data URI correctly", () => { - const testCert = - "-----BEGIN CERTIFICATE-----\nMIIC...\n-----END CERTIFICATE-----"; - const encodedData = encodeURIComponent(testCert); - const dataUri = `data:text/plain,${encodedData}`; +// Helper function to create test certificate files +function createTestCertFile(filename: string, content: string): string { + const filePath = path.join(tempDir, filename); + fs.writeFileSync(filePath, content, "utf8"); + return filePath; +} - const result = getCertificateContent(dataUri); +test("getAgentOptions returns basic configuration with default values", async () => { + const options = await getAgentOptions(); - expect(result).toBe(testCert); + // Check default timeout (7200 seconds = 2 hours = 7,200,000 ms) + expect(options.timeout).toBe(7200000); + expect(options.sessionTimeout).toBe(7200000); + expect(options.keepAliveMsecs).toBe(7200000); + expect(options.keepAlive).toBe(true); + + // Verify certificates array exists and contains items + expect(options.ca).toBeInstanceOf(Array); + expect(options.ca.length).toBeGreaterThan(0); + + // Verify at least one of the real TLS root certificates is included + // This assumes there's at least one certificate with "CERTIFICATE" in it + expect(options.ca.some((cert: any) => cert.includes("CERTIFICATE"))).toBe( + true, + ); }); -test("getCertificateContent should handle plain text data URI correctly", () => { - const testCert = "simple-cert-content"; - const dataUri = `data:text/plain,${testCert}`; +test("getAgentOptions respects custom timeout", async () => { + const customTimeout = 300; // 5 minutes + const options = await getAgentOptions({ timeout: customTimeout }); - const result = getCertificateContent(dataUri); - - expect(result).toBe(testCert); + // Check timeout values (300 seconds = 300,000 ms) + expect(options.timeout).toBe(300000); + expect(options.sessionTimeout).toBe(300000); + expect(options.keepAliveMsecs).toBe(300000); }); -test("getCertificateContent should read file when input is a file path", () => { - const filePath = "/path/to/cert.pem"; - const expectedContent = - "-----BEGIN CERTIFICATE-----\nfile content\n-----END CERTIFICATE-----"; +test("getAgentOptions uses verifySsl setting", async () => { + // With verifySsl true + let options = await getAgentOptions({ verifySsl: true }); + expect(options.rejectUnauthorized).toBe(true); - mockReadFileSync.mockReturnValue(expectedContent); - - const result = getCertificateContent(filePath); - - expect(mockReadFileSync).toHaveBeenCalledWith(filePath, "utf8"); - expect(result).toBe(expectedContent); + // With verifySsl false + options = await getAgentOptions({ verifySsl: false }); + expect(options.rejectUnauthorized).toBe(false); }); -test("getCertificateContent should handle data URI with different media types", () => { - const testData = "certificate-data"; - const base64Data = Buffer.from(testData, "utf8").toString("base64"); - const dataUri = `data:application/x-x509-ca-cert;base64,${base64Data}`; +test("getAgentOptions incorporates custom CA bundle paths", async () => { + // Create a test CA bundle file + const caBundleContent = + "-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIJAMcuSp7chAYdMA==\n-----END CERTIFICATE-----"; + const caBundlePath = createTestCertFile("ca-bundle.pem", caBundleContent); - const result = getCertificateContent(dataUri); + // Single string path + let options = await getAgentOptions({ caBundlePath }); - expect(result).toBe(testData); + // Verify that our test certificate is included in the CA list + expect(options.ca).toContain(caBundleContent); + + // Create multiple test CA bundle files + const caContent1 = + "-----BEGIN CERTIFICATE-----\nABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\n-----END CERTIFICATE-----"; + const caContent2 = + "-----BEGIN CERTIFICATE-----\n0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\n-----END CERTIFICATE-----"; + const caPath1 = createTestCertFile("ca1.pem", caContent1); + const caPath2 = createTestCertFile("ca2.pem", caContent2); + + // Array of paths + options = await getAgentOptions({ + caBundlePath: [caPath1, caPath2], + }); + + // Verify that both test certificates are included in the CA list + expect(options.ca).toContain(caContent1); + expect(options.ca).toContain(caContent2); }); -test("getCertificateContent should handle data URI without media type", () => { - const testData = "simple-data"; - const base64Data = Buffer.from(testData, "utf8").toString("base64"); - const dataUri = `data:;base64,${base64Data}`; +test("getAgentOptions includes global certs when running as binary", async () => { + // Set up test certs in globalAgent + globalAgent.options.ca = ["global-cert-1", "global-cert-2"]; - const result = getCertificateContent(dataUri); + // Set IS_BINARY environment variable + process.env.IS_BINARY = "true"; - expect(result).toBe(testData); + const options = await getAgentOptions(); + + // Test for global certs + expect(options.ca).toContain("global-cert-1"); + expect(options.ca).toContain("global-cert-2"); }); -test("getCertificateContent should handle data URI without media type or encoding", () => { - const testData = "simple-data"; - const base64Data = Buffer.from(testData, "utf8").toString("base64"); - const dataUri = `data:;base64,${base64Data}`; +test("getAgentOptions handles client certificate configuration", async () => { + // Create test certificate files + const clientCertContent = + "-----BEGIN CERTIFICATE-----\nCLIENTCERT\n-----END CERTIFICATE-----"; + const clientKeyContent = + "-----BEGIN PRIVATE KEY-----\nCLIENTKEY\n-----END PRIVATE KEY-----"; + const certPath = createTestCertFile("client.cert", clientCertContent); + const keyPath = createTestCertFile("client.key", clientKeyContent); - const result = getCertificateContent(dataUri); + const clientCertOptions = { + clientCertificate: { + cert: certPath, + key: keyPath, + passphrase: "secret-passphrase", + }, + }; - expect(result).toBe(testData); + const options = await getAgentOptions(clientCertOptions); + + expect(options.cert).toBe(clientCertContent); + expect(options.key).toBe(clientKeyContent); + expect(options.passphrase).toBe("secret-passphrase"); }); -test("getCertificateContent should handle relative file paths", () => { - const filePath = "./certs/ca.pem"; - const expectedContent = "certificate from relative path"; +test("getAgentOptions handles client certificate without passphrase", async () => { + // Create test certificate files + const clientCertContent = + "-----BEGIN CERTIFICATE-----\nCLIENTCERT2\n-----END CERTIFICATE-----"; + const clientKeyContent = + "-----BEGIN PRIVATE KEY-----\nCLIENTKEY2\n-----END PRIVATE KEY-----"; + const certPath = createTestCertFile("client2.cert", clientCertContent); + const keyPath = createTestCertFile("client2.key", clientKeyContent); - mockReadFileSync.mockReturnValue(expectedContent); + const clientCertOptions = { + clientCertificate: { + cert: certPath, + key: keyPath, + }, + }; - const result = getCertificateContent(filePath); + const options = await getAgentOptions(clientCertOptions); - expect(mockReadFileSync).toHaveBeenCalledWith(filePath, "utf8"); - expect(result).toBe(expectedContent); + expect(options.cert).toBe(clientCertContent); + expect(options.key).toBe(clientKeyContent); + expect(options.passphrase).toBeUndefined(); }); -test("getCertificateContent should handle data URI with special characters in URL encoding", () => { - const testCert = "cert with spaces and special chars: !@#$%"; - const encodedData = encodeURIComponent(testCert); - const dataUri = `data:text/plain,${encodedData}`; +test("getAgentOptions reads NODE_EXTRA_CA_CERTS", async () => { + const extraCertContent = + "-----BEGIN CERTIFICATE-----\nEXTRA_CERT\n-----END CERTIFICATE-----"; + const certPath = createTestCertFile("extra-cert.cert", extraCertContent); - const result = getCertificateContent(dataUri); + expect(CertsCache.getInstance().fixedCa).not.toContain(extraCertContent); - expect(result).toBe(testCert); + CertsCache.getInstance().clear(); + + process.env.NODE_EXTRA_CA_CERTS = certPath; + expect(CertsCache.getInstance().fixedCa).toContain(extraCertContent); }); diff --git a/packages/fetch/src/getAgentOptions.ts b/packages/fetch/src/getAgentOptions.ts index 20fc7641c..dec90b0ad 100644 --- a/packages/fetch/src/getAgentOptions.ts +++ b/packages/fetch/src/getAgentOptions.ts @@ -1,56 +1,18 @@ -import { globalAgent } from "https"; -import * as fs from "node:fs"; -import tls from "node:tls"; - import { RequestOptions } from "@continuedev/config-types"; - -/** - * Extracts content from either a file path or data URI - */ -function getCertificateContent(input: string): string { - if (input.startsWith("data:")) { - // Parse data URI: data:[][;base64], - const [header, data] = input.split(","); - if (header.includes("base64")) { - return Buffer.from(data, "base64").toString("utf8"); - } else { - return decodeURIComponent(data); - } - } else { - // Assume it's a file path - return fs.readFileSync(input, "utf8"); - } -} +import { CertsCache, getCertificateContent } from "./certs.js"; /** * Prepares agent options based on request options and certificates */ -export function getAgentOptions(requestOptions?: RequestOptions): { +export async function getAgentOptions( + requestOptions?: RequestOptions, +): Promise<{ [key: string]: any; -} { +}> { const TIMEOUT = 7200; // 7200 seconds = 2 hours const timeout = (requestOptions?.timeout ?? TIMEOUT) * 1000; // measured in ms - // Get root certificates - let globalCerts: string[] = []; - if (process.env.IS_BINARY) { - if (Array.isArray(globalAgent.options.ca)) { - globalCerts = [...globalAgent.options.ca.map((cert) => cert.toString())]; - } else if (typeof globalAgent.options.ca !== "undefined") { - globalCerts.push(globalAgent.options.ca.toString()); - } - } - - const ca = Array.from(new Set([...tls.rootCertificates, ...globalCerts])); - const customCerts = - typeof requestOptions?.caBundlePath === "string" - ? [requestOptions?.caBundlePath] - : requestOptions?.caBundlePath; - if (customCerts) { - ca.push( - ...customCerts.map((customCert) => getCertificateContent(customCert)), - ); - } + const ca = await CertsCache.getInstance().getCa(requestOptions?.caBundlePath); const agentOptions: { [key: string]: any } = { ca, From 3678a85dff26b31191bd97f96bb5461a2686c207 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 17 Jun 2025 02:30:04 -0700 Subject: [PATCH 014/100] add some cache functionality tests --- packages/fetch/src/certs.test.ts | 79 +++++++++++++++++++++++++++++++- 1 file changed, 78 insertions(+), 1 deletion(-) diff --git a/packages/fetch/src/certs.test.ts b/packages/fetch/src/certs.test.ts index bd7d405c4..04c30b0ed 100644 --- a/packages/fetch/src/certs.test.ts +++ b/packages/fetch/src/certs.test.ts @@ -1,6 +1,6 @@ import * as fs from "node:fs"; import { beforeEach, expect, test, vi } from "vitest"; -import { getCertificateContent } from "./certs.js"; +import { CertsCache, getCertificateContent } from "./certs.js"; // Mock fs module vi.mock("node:fs", () => ({ @@ -108,3 +108,80 @@ test("getCertificateContent should handle data URI with special characters in UR expect(result).toBe(testCert); }); + +test("CertsCache.getCachedCustomCert should cache and return certificate content", async () => { + const certsCache = CertsCache.getInstance(); + const filePath = "/path/to/custom/cert.pem"; + const expectedContent = "custom cert content"; + + mockReadFileSync.mockReturnValue(expectedContent); + + const cert1 = await certsCache.getCachedCustomCert(filePath); + expect(cert1).toBe(expectedContent); + expect(mockReadFileSync).toHaveBeenCalledTimes(1); + expect(mockReadFileSync).toHaveBeenCalledWith(filePath, "utf8"); + + // Call again to check if it's cached + const cert2 = await certsCache.getCachedCustomCert(filePath); + expect(cert2).toBe(expectedContent); + // readFileSync should not be called again + expect(mockReadFileSync).toHaveBeenCalledTimes(1); +}); + +test("CertsCache.getAllCachedCustomCerts should return all cached custom certs", async () => { + const certsCache = CertsCache.getInstance(); + const filePaths = ["/path/to/cert1.pem", "/path/to/cert2.pem"]; + const expectedContent1 = "content of cert1"; + const expectedContent2 = "content of cert2"; + + mockReadFileSync.mockReturnValueOnce(expectedContent1); + mockReadFileSync.mockReturnValueOnce(expectedContent2); + + const certs = await certsCache.getAllCachedCustomCerts(filePaths); + expect(certs).toEqual([expectedContent1, expectedContent2]); + expect(mockReadFileSync).toHaveBeenCalledTimes(2); +}); + +test("CertsCache.getCa should return combined CA when caBundlePath is provided", async () => { + const certsCache = CertsCache.getInstance(); + const fixedCa = ["fixed CA cert"]; + const customCertPath = "/path/to/custom/cert.pem"; + const customCertContent = "custom cert content"; + + // Directly set _fixedCa to avoid initializing it with real data + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + certsCache._fixedCa = fixedCa; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + certsCache._initialized = true; + mockReadFileSync.mockReturnValue(customCertContent); + + const ca = await certsCache.getCa(customCertPath); + expect(ca).toEqual([...fixedCa, customCertContent]); +}); + +test("CertsCache.clear should clear custom certs and reset initialized flag", () => { + const certsCache = CertsCache.getInstance(); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + certsCache._customCerts.set("key", "value"); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + certsCache._initialized = true; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + certsCache._fixedCa = ["test"]; + + certsCache.clear(); + + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + expect(certsCache._customCerts.size).toBe(0); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + expect(certsCache._initialized).toBe(false); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + expect(certsCache._fixedCa).toEqual([]); +}); From c1d4c558a6e5f884979d136ab320bdb546e843c4 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 17 Jun 2025 02:44:05 -0700 Subject: [PATCH 015/100] bump fetch --- packages/fetch/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/fetch/package.json b/packages/fetch/package.json index f17bcfc69..c6850ee54 100644 --- a/packages/fetch/package.json +++ b/packages/fetch/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/fetch", - "version": "1.0.13", + "version": "1.0.14", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", From 0d37e9b977d541f3a5edd1956c6b7a4e57db2131 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 17 Jun 2025 09:02:49 -0700 Subject: [PATCH 016/100] initialize next edit window manager on vscode extension activate --- extensions/vscode/src/activation/activate.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index d364dc7b0..ea4b1918e 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -10,6 +10,7 @@ import { getExtensionVersion } from "../util/util"; import { VsCodeContinueApi } from "./api"; import setupInlineTips from "./InlineTipManager"; +import setupNextEditWindowManager from "./NextEditWindowManager"; export async function activateExtension(context: vscode.ExtensionContext) { // Add necessary files @@ -19,6 +20,7 @@ export async function activateExtension(context: vscode.ExtensionContext) { // Register commands and providers registerQuickFixProvider(); setupInlineTips(context); + setupNextEditWindowManager(context); const vscodeExtension = new VsCodeExtension(context); From 6dfe33d5d1c5ab5b719764ba52632a42d633fd13 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 17 Jun 2025 09:03:34 -0700 Subject: [PATCH 017/100] return undefined for next edit --- extensions/vscode/src/autocomplete/completionProvider.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 9bc296416..9194c909d 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -15,6 +15,7 @@ import { handleLLMError } from "../util/errorHandling"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { NextEditWindowManager } from "../activation/NextEditWindowManager"; import { getDefinitionsFromLsp } from "./lsp"; import { RecentlyEditedTracker } from "./recentlyEdited"; import { RecentlyVisitedRangesService } from "./RecentlyVisitedRangesService"; @@ -329,7 +330,13 @@ export class ContinueCompletionProvider ); (completionItem as any).completeBracketPairs = true; - return [completionItem]; + // return [completionItem]; + const editor = vscode.window.activeTextEditor; + if (editor) { + NextEditWindowManager.getInstance().showTooltip(editor, completionText); + } + // return [completionItem]; + return undefined; } finally { stopStatusBarLoading(); } From 00d850a80b34f5aabf6ec6a204863bbab78548b7 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 17 Jun 2025 09:04:18 -0700 Subject: [PATCH 018/100] create a next edit window manager singleton --- .../src/activation/NextEditWindowManager.ts | 366 ++++++++++++++++++ 1 file changed, 366 insertions(+) create mode 100644 extensions/vscode/src/activation/NextEditWindowManager.ts diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts new file mode 100644 index 000000000..dac4a0388 --- /dev/null +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -0,0 +1,366 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +import { EXTENSION_NAME } from "core/control-plane/env"; +// @ts-ignore +import svgBuilder from "svg-builder"; +import * as vscode from "vscode"; + +import { getTheme } from "../util/getTheme"; + +// Fallback theme colors +const FALLBACK_THEME = { + colors: { + "editor.foreground": "#333333", + "editor.background": "#FFFFFF", + }, +}; + +const SVG_CONFIG = { + stroke: "#999998", + strokeWidth: 1, + textColor: "#999998", + filter: "drop-shadow(0 2px 2px rgba(0,0,0,0.2))", + radius: 3, + leftMargin: 40, + defaultText: "", + lineSpacing: 1.2, // Line spacing multiplier + cursorOffset: 4, // Spaces to offset from cursor + + get fontSize() { + return Math.ceil( + (vscode.workspace.getConfiguration("editor").get("fontSize") ?? + 14) * 0.8, + ); + }, + get fontFamily() { + return ( + vscode.workspace.getConfiguration("editor").get("fontFamily") || + "helvetica" + ); + }, + get paddingX() { + return Math.ceil(this.getEstimatedTextWidth(" ")); + }, + get paddingY() { + return Math.ceil(this.fontSize * 0.3); + }, + get lineHeight() { + return Math.ceil(this.fontSize * this.lineSpacing); + }, + getEstimatedTextWidth(text: string): number { + return text.length * this.fontSize * 0.6; + }, + getTipWidth(text: string): number { + // Find the longest line + const lines = text.split("\n"); + const longestLine = lines.reduce( + (longest, line) => (line.length > longest.length ? line : longest), + "", + ); + + return this.getEstimatedTextWidth(longestLine) + this.paddingX * 2; + }, + getTipHeight(text: string): number { + // Count the number of lines + const lineCount = text.split("\n").length; + return this.lineHeight * lineCount + this.paddingY * 2; + }, +} as const; + +// Command ID - can be used in package.json +export const HIDE_TOOLTIP_COMMAND = "nextEditWindow.hideTooltips"; + +export class NextEditWindowManager { + private static instance: NextEditWindowManager; + + private readonly excludedURIPrefixes = ["output:", "vscode://inline-chat"]; + private readonly hideCommand = "continue.hideNextEditWindow"; + private theme = getTheme() || FALLBACK_THEME; + + // Current active decoration + private currentDecoration: vscode.TextEditorDecorationType | null = null; + // Track which editor has the active decoration + private activeEditor: vscode.TextEditor | null = null; + + // Disposables + private disposables: vscode.Disposable[] = []; + + public static getInstance(): NextEditWindowManager { + if (!NextEditWindowManager.instance) { + NextEditWindowManager.instance = new NextEditWindowManager(); + } + return NextEditWindowManager.instance; + } + + private constructor() { + console.log( + "Theme initialized:", + this.theme ? "Theme exists" : "Theme is undefined", + ); + this.setupListeners(); + } + + public setupNextEditWindowManager(context: vscode.ExtensionContext) { + // Register the command to hide tooltips + const hideTooltipsCommand = vscode.commands.registerCommand( + HIDE_TOOLTIP_COMMAND, + () => { + this.hideAllTooltips(); + }, + ); + context.subscriptions.push(hideTooltipsCommand); + + // Add this class to context disposables + context.subscriptions.push(this); + } + + /** + * Show a tooltip with the given text at the current cursor position + * @param editor The active text editor + * @param text Text to display in the tooltip + */ + public showTooltip(editor: vscode.TextEditor, text: string) { + if (!text || !this.shouldRenderTip(editor.document.uri)) { + return; + } + + // Clear any existing decorations first (very important to prevent overlapping) + this.hideAllTooltips(); + + // Get cursor position + const position = editor.selection.active; + + // Create and apply decoration with the text + this.renderTooltip(editor, position, text); + } + + /** + * Hide all tooltips in all editors + */ + public hideAllTooltips() { + if (this.currentDecoration) { + // Remove decoration from all editors to be extra safe + vscode.window.visibleTextEditors.forEach((editor) => { + editor.setDecorations(this.currentDecoration!, []); + }); + + // If we know which editor had the decoration, clear it specifically + if (this.activeEditor) { + this.activeEditor.setDecorations(this.currentDecoration, []); + this.activeEditor = null; + } + + // Dispose the decoration + this.currentDecoration.dispose(); + this.currentDecoration = null; + } + } + + public dispose() { + // Dispose current decoration + if (this.currentDecoration) { + this.currentDecoration.dispose(); + this.currentDecoration = null; + } + + // Dispose all other disposables + this.disposables.forEach((d) => d.dispose()); + this.disposables = []; + } + + private setupListeners() { + // Theme change listener + const themeListener = vscode.workspace.onDidChangeConfiguration((e) => { + if ( + e.affectsConfiguration("workbench.colorTheme") || + e.affectsConfiguration("editor.fontSize") || + e.affectsConfiguration("editor.fontFamily") + ) { + const newTheme = getTheme(); + this.theme = newTheme || FALLBACK_THEME; + console.log( + "Theme updated:", + this.theme ? "Theme exists" : "Theme is undefined", + ); + } + }); + this.disposables.push(themeListener); + + // Listen for editor changes to clean up decorations when editor closes + const editorCloseListener = vscode.window.onDidChangeVisibleTextEditors( + () => { + // If our active editor is no longer visible, clear decorations + if ( + this.activeEditor && + !vscode.window.visibleTextEditors.includes(this.activeEditor) + ) { + this.hideAllTooltips(); + } + }, + ); + this.disposables.push(editorCloseListener); + + // Listen for selection changes to hide tooltip when cursor moves + const selectionListener = vscode.window.onDidChangeTextEditorSelection( + (e) => { + // If the selection changed in our active editor, hide the tooltip + if (this.activeEditor && e.textEditor === this.activeEditor) { + this.hideAllTooltips(); + } + }, + ); + this.disposables.push(selectionListener); + } + + private shouldRenderTip(uri: vscode.Uri): boolean { + const isAllowedUri = + !this.excludedURIPrefixes.some((prefix) => + uri.toString().startsWith(prefix), + ) && uri.scheme !== "comment"; + + const isEnabled = + !!vscode.workspace + .getConfiguration(EXTENSION_NAME) + .get("showInlineTip") === true; + + return isAllowedUri && isEnabled; + } + + /** + * Create an SVG with the given text, supporting multiple lines + */ + private createSvgTooltip(text: string): vscode.Uri | undefined { + const baseTextConfig = { + "font-family": SVG_CONFIG.fontFamily, + "font-size": SVG_CONFIG.fontSize, + fill: this.theme.colors["editor.foreground"], + }; + + try { + const tipWidth = SVG_CONFIG.getTipWidth(text); + const tipHeight = SVG_CONFIG.getTipHeight(text); + + // Split text into lines + const lines = text.split("\n"); + + // Create SVG builder + let svg = svgBuilder.width(tipWidth).height(tipHeight); + + // Add each line as a separate text element + lines.forEach((line, index) => { + const y = + SVG_CONFIG.paddingY + + SVG_CONFIG.fontSize + + index * SVG_CONFIG.lineHeight; + + svg = svg.text( + { + ...baseTextConfig, + x: SVG_CONFIG.paddingX, + y: y, + }, + line, + ); + }); + + // Render the SVG + const svgContent = svg.render(); + + const dataUri = `data:image/svg+xml;base64,${Buffer.from(svgContent).toString("base64")}`; + return vscode.Uri.parse(dataUri); + } catch (error) { + console.error("Error creating SVG tooltip:", error); + return undefined; + } + } + + /** + * Create a decoration type with SVG content + */ + private createSvgDecoration( + text: string, + ): vscode.TextEditorDecorationType | undefined { + const svgUri = this.createSvgTooltip(text); + if (!svgUri) { + return undefined; + } + + // Use theme or fallback + const backgroundColour = this.theme.colors["editor.background"]; + const tipWidth = SVG_CONFIG.getTipWidth(text); + const tipHeight = SVG_CONFIG.getTipHeight(text); + + // Use renderOptions.before instead of after to prevent text displacement + return vscode.window.createTextEditorDecorationType({ + after: { + contentIconPath: svgUri, + border: `;box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${tipHeight}px ${backgroundColour}; + border-radius: ${SVG_CONFIG.radius}px; + filter: ${SVG_CONFIG.filter}`, + width: `${tipWidth}px`, + height: `${tipHeight}px`, + }, + // Set a negative margin to make the decoration float rather than displace text + // Also use absolute positioning + rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed, + }); + } + + private buildHideTooltipHoverMsg() { + const hoverMarkdown = new vscode.MarkdownString( + `[Dismiss](command:${HIDE_TOOLTIP_COMMAND})`, + ); + + hoverMarkdown.isTrusted = true; + hoverMarkdown.supportHtml = true; + return hoverMarkdown; + } + + /** + * Calculate a position to the right of the cursor with the specified offset + */ + private getOffsetPosition( + editor: vscode.TextEditor, + position: vscode.Position, + ): vscode.Position { + // Create a position that's offset spaces to the right of the cursor + const offsetChar = position.character + SVG_CONFIG.cursorOffset; + return new vscode.Position(position.line, offsetChar); + } + + /** + * Render a tooltip with the given text at the specified position + */ + private renderTooltip( + editor: vscode.TextEditor, + position: vscode.Position, + text: string, + ) { + // Create a new decoration with the text + const decoration = this.createSvgDecoration(text); + if (!decoration) { + console.error("Failed to create decoration for text:", text); + return; + } + + // Store the decoration and editor + this.currentDecoration = decoration; + this.activeEditor = editor; + + // Get the position with offset + const offsetPosition = this.getOffsetPosition(editor, position); + + // Apply the decoration at the offset position + editor.setDecorations(decoration, [ + { + range: new vscode.Range(offsetPosition, offsetPosition), + hoverMessage: [this.buildHideTooltipHoverMsg()], + }, + ]); + } +} + +export default function setupNextEditWindowManager( + context: vscode.ExtensionContext, +) { + NextEditWindowManager.getInstance().setupNextEditWindowManager(context); +} From bcc8c2d043e356bb2ab7f74b76368154caae4a47 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 17 Jun 2025 09:12:01 -0700 Subject: [PATCH 019/100] add ctrl+space esc to hide next edit window --- extensions/vscode/package.json | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index c635e4641..b1753e2e1 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -334,6 +334,10 @@ "category": "Continue", "title": "Enter Enterprise License Key", "group": "Continue" + }, + { + "command": "nextEditWindow.hideTooltips", + "title": "Hide Tooltip Window" } ], "keybindings": [ @@ -426,6 +430,11 @@ "command": "continue.applyCodeFromChat", "mac": "alt+a", "key": "alt+a" + }, + { + "command": "nextEditWindow.hideTooltips", + "key": "ctrl+space escape", + "when": "editorTextFocus" } ], "submenus": [ From 985233a2aa455bc2b098d05f2205e11d28f63746 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 17 Jun 2025 11:03:15 -0700 Subject: [PATCH 020/100] fix margins --- .../src/activation/NextEditWindowManager.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index dac4a0388..8bf3c209c 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -289,13 +289,20 @@ export class NextEditWindowManager { const tipWidth = SVG_CONFIG.getTipWidth(text); const tipHeight = SVG_CONFIG.getTipHeight(text); - // Use renderOptions.before instead of after to prevent text displacement return vscode.window.createTextEditorDecorationType({ after: { contentIconPath: svgUri, - border: `;box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${tipHeight}px ${backgroundColour}; - border-radius: ${SVG_CONFIG.radius}px; - filter: ${SVG_CONFIG.filter}`, + // border: `;box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${tipHeight}px ${backgroundColour}; + // border-radius: ${SVG_CONFIG.radius}px; + // filter: ${SVG_CONFIG.filter}`, + // width: `${tipWidth}px`, + // height: `${tipHeight}px`, + border: `transparent; position: absolute; z-index: 1000; + box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, + inset 0 0 0 ${tipHeight}px ${backgroundColour}; + border-radius: ${SVG_CONFIG.radius}px; + filter: ${SVG_CONFIG.filter}; + margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`, width: `${tipWidth}px`, height: `${tipHeight}px`, }, From deca888900df145e55d86910d00d07e848e2b602 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 17 Jun 2025 11:28:31 -0700 Subject: [PATCH 021/100] better agent fetch logging --- packages/fetch/src/getAgentOptions.ts | 32 +++++++++++++++------------ 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/packages/fetch/src/getAgentOptions.ts b/packages/fetch/src/getAgentOptions.ts index e2176e8ec..d7a915cad 100644 --- a/packages/fetch/src/getAgentOptions.ts +++ b/packages/fetch/src/getAgentOptions.ts @@ -12,7 +12,8 @@ export async function getAgentOptions( const TIMEOUT = 7200; // 7200 seconds = 2 hours const timeout = (requestOptions?.timeout ?? TIMEOUT) * 1000; // measured in ms - const ca = await CertsCache.getInstance().getCa(requestOptions?.caBundlePath); + const certsCache = CertsCache.getInstance(); + const ca = await certsCache.getCa(requestOptions?.caBundlePath); const agentOptions: { [key: string]: any } = { ca, @@ -23,19 +24,6 @@ export async function getAgentOptions( keepAliveMsecs: timeout, }; - if (process.env.VERBOSE_FETCH) { - console.log("=== CERTIFICATE CONFIGURATION ==="); - console.log(`Number of CA certificates: ${ca.length}`); - console.log( - `Global agent CA certificates: ${globalAgent.options.ca ? "Present" : "Not present"}`, - ); - console.log( - `Custom certificates provided: ${customCerts?.length ? "Yes" : "No"}`, - ); - console.log(`rejectUnauthorized: ${agentOptions.rejectUnauthorized}`); - console.log("================================"); - } - // Handle ClientCertificateOptions if (requestOptions?.clientCertificate) { const { cert, key, passphrase } = requestOptions.clientCertificate; @@ -48,5 +36,21 @@ export async function getAgentOptions( } } + if (process.env.VERBOSE_FETCH) { + console.log( + `Fetch agent: rejectUnauthorized/verifySsl: ${agentOptions.rejectUnauthorized ?? "not set (defaulting to true)"}`, + ); + console.log(`Fetch agent options:`); + console.log( + `\tTimeout (sessionTimeout/keepAliveMsecs): ${agentOptions.timeout}`, + ); + console.log(`\tTotal CA certs: ${ca.length}`); + console.log(`\tGlobal/Root CA certs: ${certsCache.fixedCa.length}`); + console.log(`\tCustom CA certs: ${ca.length - certsCache.fixedCa.length}`); + console.log( + `\tClient certificate: ${requestOptions?.clientCertificate ? "Yes" : "No"}`, + ); + } + return agentOptions; } From 46f991029d01b94b9a2025a550f66c4d9212970a Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 17 Jun 2025 11:29:24 -0700 Subject: [PATCH 022/100] rearrange logging --- packages/fetch/src/getAgentOptions.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/fetch/src/getAgentOptions.ts b/packages/fetch/src/getAgentOptions.ts index d7a915cad..2cdc1dbae 100644 --- a/packages/fetch/src/getAgentOptions.ts +++ b/packages/fetch/src/getAgentOptions.ts @@ -37,9 +37,6 @@ export async function getAgentOptions( } if (process.env.VERBOSE_FETCH) { - console.log( - `Fetch agent: rejectUnauthorized/verifySsl: ${agentOptions.rejectUnauthorized ?? "not set (defaulting to true)"}`, - ); console.log(`Fetch agent options:`); console.log( `\tTimeout (sessionTimeout/keepAliveMsecs): ${agentOptions.timeout}`, @@ -50,6 +47,9 @@ export async function getAgentOptions( console.log( `\tClient certificate: ${requestOptions?.clientCertificate ? "Yes" : "No"}`, ); + console.log( + `\trejectUnauthorized/verifySsl: ${agentOptions.rejectUnauthorized ?? "not set (defaults to true)"}`, + ); } return agentOptions; From 8030843c8c04469ec417767db541f927ab491161 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 17 Jun 2025 15:01:15 -0700 Subject: [PATCH 023/100] render leading whitespaces --- .../src/activation/NextEditWindowManager.ts | 40 ++++++++++++++----- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 8bf3c209c..bf640a1d7 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -125,6 +125,7 @@ export class NextEditWindowManager { // Clear any existing decorations first (very important to prevent overlapping) this.hideAllTooltips(); + // this.dispose(); // Get cursor position const position = editor.selection.active; @@ -137,6 +138,7 @@ export class NextEditWindowManager { * Hide all tooltips in all editors */ public hideAllTooltips() { + console.log("hideAllTooltips"); if (this.currentDecoration) { // Remove decoration from all editors to be extra safe vscode.window.visibleTextEditors.forEach((editor) => { @@ -153,6 +155,7 @@ export class NextEditWindowManager { this.currentDecoration.dispose(); this.currentDecoration = null; } + this.dispose(); } public dispose() { @@ -229,6 +232,7 @@ export class NextEditWindowManager { * Create an SVG with the given text, supporting multiple lines */ private createSvgTooltip(text: string): vscode.Uri | undefined { + console.log("createSvgTooltip"); const baseTextConfig = { "font-family": SVG_CONFIG.fontFamily, "font-size": SVG_CONFIG.fontSize, @@ -239,31 +243,44 @@ export class NextEditWindowManager { const tipWidth = SVG_CONFIG.getTipWidth(text); const tipHeight = SVG_CONFIG.getTipHeight(text); - // Split text into lines const lines = text.split("\n"); + const globalIndent = + lines.length > 0 ? (lines[0].match(/^[ \t]*/) || [""])[0].length : 0; - // Create SVG builder - let svg = svgBuilder.width(tipWidth).height(tipHeight); + // Create a fresh SVG builder instance each time. + // This ensures we don't have state accumulation between calls. + const svg = svgBuilder.newInstance().width(tipWidth).height(tipHeight); - // Add each line as a separate text element + // Add each line as a separate text element. lines.forEach((line, index) => { const y = SVG_CONFIG.paddingY + SVG_CONFIG.fontSize + index * SVG_CONFIG.lineHeight; - svg = svg.text( + svg.text( { ...baseTextConfig, x: SVG_CONFIG.paddingX, y: y, }, - line, + line.slice(globalIndent), ); }); - // Render the SVG - const svgContent = svg.render(); + // Render the SVG. + let svgContent = svg.render(); + + // Manually add whitespace styling. + // svg-builder does not support styles. To be exact, + // there is a style function but it's broken and there are no docs. + if (!svgContent.includes('style="white-space: pre"')) { + svgContent = svgContent.replaceAll( + " Date: Tue, 17 Jun 2025 17:10:21 -0700 Subject: [PATCH 024/100] update colors to use css variables --- .../vscode/src/activation/NextEditWindowManager.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index bf640a1d7..0db1ef199 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -9,8 +9,10 @@ import { getTheme } from "../util/getTheme"; // Fallback theme colors const FALLBACK_THEME = { colors: { - "editor.foreground": "#333333", - "editor.background": "#FFFFFF", + // "editor.foreground": "#FFFFFF", + // "editor.background": "#333333", + "editor.foreground": "var(--vscode-editor-foreground)", + "editor.background": "var(--vscode-editor-background)", }, }; @@ -93,8 +95,10 @@ export class NextEditWindowManager { private constructor() { console.log( - "Theme initialized:", - this.theme ? "Theme exists" : "Theme is undefined", + "Next Edit Theme initialized:", + this.theme + ? `Theme exists: ${JSON.stringify(this.theme)}` + : "Theme is undefined", ); this.setupListeners(); } @@ -280,7 +284,6 @@ export class NextEditWindowManager { ' Date: Tue, 17 Jun 2025 17:32:56 -0700 Subject: [PATCH 025/100] revert back to hardcoded values --- extensions/vscode/src/activation/NextEditWindowManager.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 0db1ef199..a94f37921 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -9,10 +9,10 @@ import { getTheme } from "../util/getTheme"; // Fallback theme colors const FALLBACK_THEME = { colors: { - // "editor.foreground": "#FFFFFF", - // "editor.background": "#333333", - "editor.foreground": "var(--vscode-editor-foreground)", - "editor.background": "var(--vscode-editor-background)", + "editor.foreground": "#FFFFFF", + "editor.background": "#333333", + // "editor.foreground": "var(--vscode-editor-foreground)", + // "editor.background": "var(--vscode-editor-background)", }, }; From ec32afcc544218d176cca87caa3fd50803b6830d Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 18 Jun 2025 17:21:56 +0530 Subject: [PATCH 026/100] fix: show assistant loading on login --- .../modelSelection/platform/AssistantSelect.tsx | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index aebae2aa6..ac4a06553 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -32,6 +32,7 @@ import { import type { ProfileDescription } from "core/config/ConfigHandler"; import { useNavigate } from "react-router-dom"; +import { useWebviewListener } from "../../../hooks/useWebviewListener"; import { cn } from "../../../util/cn"; import { ROUTES } from "../../../util/navigation"; import { useLump } from "../../mainInput/Lump/LumpContext"; @@ -171,6 +172,11 @@ export default function AssistantSelect() { }); close(); } + async function refreshProfilesWithLoading() { + setLoading(true); + await refreshProfiles(); + setLoading(false); + } useEffect(() => { let lastToggleTime = 0; @@ -213,6 +219,8 @@ export default function AssistantSelect() { }; }, [currentOrg, selectedProfile]); + useWebviewListener("sessionUpdate", refreshProfilesWithLoading, []); + const cycleOrgs = () => { if (!session) { void login(false); @@ -294,10 +302,9 @@ export default function AssistantSelect() { className="flex cursor-pointer flex-row items-center gap-1 hover:brightness-125" onClick={async (e) => { e.stopPropagation(); - setLoading(true); - await refreshProfiles(); - setLoading(false); - buttonRef.current?.click(); + refreshProfilesWithLoading().then(() => + buttonRef.current?.click(), + ); }} > Date: Thu, 19 Jun 2025 10:12:24 +0530 Subject: [PATCH 027/100] show a loading indicator --- .../platform/AssistantSelect.tsx | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index ac4a06553..c33f4c707 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -279,14 +279,20 @@ export default function AssistantSelect() { style={{ fontSize: fontSize(-3) }} >
-
- -
- - {selectedProfile.title} - + {!loading ? ( + loading... + ) : ( + <> +
+ +
+ + {selectedProfile.title} + + + )}
{ e.stopPropagation(); - refreshProfilesWithLoading().then(() => + void refreshProfilesWithLoading().then(() => buttonRef.current?.click(), ); }} @@ -310,7 +316,7 @@ export default function AssistantSelect() { From afb36cdbfdbfdd0d4cc5e220252f90fc12d83490 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 19 Jun 2025 11:33:47 +0530 Subject: [PATCH 028/100] `configLoading` redux state on initial load, login and manual config refresh show the loading indicator --- .../platform/AssistantSelect.tsx | 22 +++++-------------- gui/src/context/Auth.tsx | 7 +++++- gui/src/hooks/ParallelListeners.tsx | 6 +++-- gui/src/redux/slices/configSlice.ts | 8 ++++++- 4 files changed, 23 insertions(+), 20 deletions(-) diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index c33f4c707..1a7c82c36 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -7,7 +7,7 @@ import { ExclamationTriangleIcon, PlusIcon, } from "@heroicons/react/24/outline"; -import { useContext, useEffect, useMemo, useRef, useState } from "react"; +import { useContext, useEffect, useMemo, useRef } from "react"; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { @@ -32,7 +32,6 @@ import { import type { ProfileDescription } from "core/config/ConfigHandler"; import { useNavigate } from "react-router-dom"; -import { useWebviewListener } from "../../../hooks/useWebviewListener"; import { cn } from "../../../util/cn"; import { ROUTES } from "../../../util/navigation"; import { useLump } from "../../mainInput/Lump/LumpContext"; @@ -156,7 +155,7 @@ export default function AssistantSelect() { const orgs = useAppSelector((store) => store.profiles.organizations); const ideMessenger = useContext(IdeMessengerContext); const { isToolbarExpanded } = useLump(); - const [loading, setLoading] = useState(false); + const configLoading = useAppSelector((store) => store.config.loading); const { profiles, session, login, selectedProfile, refreshProfiles } = useAuth(); @@ -172,11 +171,6 @@ export default function AssistantSelect() { }); close(); } - async function refreshProfilesWithLoading() { - setLoading(true); - await refreshProfiles(); - setLoading(false); - } useEffect(() => { let lastToggleTime = 0; @@ -219,8 +213,6 @@ export default function AssistantSelect() { }; }, [currentOrg, selectedProfile]); - useWebviewListener("sessionUpdate", refreshProfilesWithLoading, []); - const cycleOrgs = () => { if (!session) { void login(false); @@ -279,7 +271,7 @@ export default function AssistantSelect() { style={{ fontSize: fontSize(-3) }} >
- {!loading ? ( + {configLoading ? ( loading... ) : ( <> @@ -306,17 +298,15 @@ export default function AssistantSelect() { Assistants
{ + onClick={(e) => { e.stopPropagation(); - void refreshProfilesWithLoading().then(() => - buttonRef.current?.click(), - ); + void refreshProfiles().then(() => buttonRef.current?.click()); }} >
diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index 8c928630d..143f09f5f 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -19,6 +19,7 @@ import { setSelectedOrgId, } from "../redux/"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; +import { setConfigLoading } from "../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; import { IdeMessengerContext } from "./IdeMessenger"; @@ -53,7 +54,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ const login: AuthContextType["login"] = (useOnboarding: boolean) => { return new Promise((resolve) => { - ideMessenger + void ideMessenger .request("getControlPlaneSessionInfo", { silent: false, useOnboarding, @@ -113,17 +114,21 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ "sessionUpdate", async (data) => { setSession(data.sessionInfo); + void refreshProfiles(); }, [], ); const refreshProfiles = useCallback(async () => { try { + dispatch(setConfigLoading(true)); await ideMessenger.request("config/refreshProfiles", undefined); ideMessenger.post("showToast", ["info", "Config refreshed"]); } catch (e) { console.error("Failed to refresh profiles", e); ideMessenger.post("showToast", ["error", "Failed to refresh config"]); + } finally { + dispatch(setConfigLoading(false)); } }, [ideMessenger]); diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index 155b91e2c..0f3f56a62 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -12,7 +12,7 @@ import { } from "../redux"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall"; -import { setConfigResult } from "../redux/slices/configSlice"; +import { setConfigLoading, setConfigResult } from "../redux/slices/configSlice"; import { setLastNonEditSessionEmpty, updateEditStateApplyState, @@ -93,6 +93,7 @@ function ParallelListeners() { const initialLoadAuthAndConfig = useCallback( async (initial: boolean) => { + dispatch(setConfigLoading(true)); const result = await ideMessenger.request( "config/getSerializedProfileInfo", undefined, @@ -100,6 +101,7 @@ function ParallelListeners() { if (result.status === "success") { await handleConfigUpdate(initial, result.content); } + dispatch(setConfigLoading(false)); }, [ideMessenger, handleConfigUpdate], ); @@ -242,7 +244,7 @@ function ParallelListeners() { dispatch(updateEditStateApplyState(state)); if (state.status === "closed") { - dispatch(exitEdit({})); + void dispatch(exitEdit({})); } } else { // chat or agent diff --git a/gui/src/redux/slices/configSlice.ts b/gui/src/redux/slices/configSlice.ts index b26d596c8..8d48f7332 100644 --- a/gui/src/redux/slices/configSlice.ts +++ b/gui/src/redux/slices/configSlice.ts @@ -6,6 +6,7 @@ import { DEFAULT_MAX_TOKENS } from "core/llm/constants"; export type ConfigState = { configError: ConfigValidationError[] | undefined; config: BrowserSerializedContinueConfig; + loading: boolean; }; export const EMPTY_CONFIG: BrowserSerializedContinueConfig = { @@ -47,6 +48,7 @@ export const EMPTY_CONFIG: BrowserSerializedContinueConfig = { const initialState: ConfigState = { configError: undefined, config: EMPTY_CONFIG, + loading: false, }; export const configSlice = createSlice({ @@ -82,6 +84,9 @@ export const configSlice = createSlice({ ) => { state.config = config; }, + setConfigLoading: (state, { payload: loading }: PayloadAction) => { + state.loading = loading; + }, }, selectors: { selectSelectedChatModelContextLength: (state): number => { @@ -99,7 +104,8 @@ export const configSlice = createSlice({ }, }); -export const { updateConfig, setConfigResult } = configSlice.actions; +export const { updateConfig, setConfigResult, setConfigLoading } = + configSlice.actions; export const { selectSelectedChatModelContextLength, From 99d32fe12d203ed3b7b97ffac89ac674da6bf6df Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 19 Jun 2025 11:33:56 +0530 Subject: [PATCH 029/100] show loading in account selection --- gui/src/pages/config/AccountButton.tsx | 27 ++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/gui/src/pages/config/AccountButton.tsx b/gui/src/pages/config/AccountButton.tsx index 06c6beba0..a5c59f889 100644 --- a/gui/src/pages/config/AccountButton.tsx +++ b/gui/src/pages/config/AccountButton.tsx @@ -1,3 +1,4 @@ +import { ArrowPathIcon } from "@heroicons/react/24/outline"; import { UserCircleIcon } from "@heroicons/react/24/solid"; import { isOnPremSession } from "core/control-plane/AuthTypes"; import { @@ -10,11 +11,13 @@ import { Button } from "../../components/ui/Button"; import { useAuth } from "../../context/Auth"; import { selectCurrentOrg } from "../../redux"; import { useAppSelector } from "../../redux/hooks"; +import { cn } from "../../util/cn"; import { ScopeSelect } from "./ScopeSelect"; export function AccountButton() { - const { session, logout, login, organizations } = useAuth(); + const { session, logout, login, organizations, refreshProfiles } = useAuth(); const selectedOrg = useAppSelector(selectCurrentOrg); + const configLoading = useAppSelector((store) => store.config.loading); if (!session) { return ( @@ -58,9 +61,25 @@ export function AccountButton() { {organizations.length > 0 && (
- +
+ +
{ + e.stopPropagation(); + await refreshProfiles(); + }} + > + +
+
)} From 6fd8730e22f3ebb375f7eeb3ef36206d04758aa0 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 19 Jun 2025 14:27:07 -0700 Subject: [PATCH 030/100] add syntax highlighting, remove svg-builder --- .../src/activation/NextEditWindowManager.ts | 101 +++++++++--------- 1 file changed, 51 insertions(+), 50 deletions(-) diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index a94f37921..4b907004e 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -1,9 +1,9 @@ /* eslint-disable @typescript-eslint/naming-convention */ import { EXTENSION_NAME } from "core/control-plane/env"; // @ts-ignore -import svgBuilder from "svg-builder"; import * as vscode from "vscode"; +import { SyntaxHighlighter } from "core/syntaxHighlighting/SyntaxHighlighter"; import { getTheme } from "../util/getTheme"; // Fallback theme colors @@ -29,8 +29,7 @@ const SVG_CONFIG = { get fontSize() { return Math.ceil( - (vscode.workspace.getConfiguration("editor").get("fontSize") ?? - 14) * 0.8, + vscode.workspace.getConfiguration("editor").get("fontSize") ?? 14, ); }, get fontFamily() { @@ -122,7 +121,7 @@ export class NextEditWindowManager { * @param editor The active text editor * @param text Text to display in the tooltip */ - public showTooltip(editor: vscode.TextEditor, text: string) { + public async showTooltip(editor: vscode.TextEditor, text: string) { if (!text || !this.shouldRenderTip(editor.document.uri)) { return; } @@ -135,7 +134,7 @@ export class NextEditWindowManager { const position = editor.selection.active; // Create and apply decoration with the text - this.renderTooltip(editor, position, text); + await this.renderTooltip(editor, position, text); } /** @@ -235,7 +234,12 @@ export class NextEditWindowManager { /** * Create an SVG with the given text, supporting multiple lines */ - private createSvgTooltip(text: string): vscode.Uri | undefined { + private async createSvgTooltip( + text: string, + ): Promise< + | { uri: vscode.Uri; dimensions: { width: number; height: number } } + | undefined + > { console.log("createSvgTooltip"); const baseTextConfig = { "font-family": SVG_CONFIG.fontFamily, @@ -251,42 +255,25 @@ export class NextEditWindowManager { const globalIndent = lines.length > 0 ? (lines[0].match(/^[ \t]*/) || [""])[0].length : 0; - // Create a fresh SVG builder instance each time. - // This ensures we don't have state accumulation between calls. - const svg = svgBuilder.newInstance().width(tipWidth).height(tipHeight); - - // Add each line as a separate text element. - lines.forEach((line, index) => { - const y = - SVG_CONFIG.paddingY + - SVG_CONFIG.fontSize + - index * SVG_CONFIG.lineHeight; - - svg.text( - { - ...baseTextConfig, - x: SVG_CONFIG.paddingX, - y: y, - }, - line.slice(globalIndent), - ); + const syntaxHighlighter = SyntaxHighlighter.getInstance({ + theme: "one-dark-pro", }); - // Render the SVG. - let svgContent = svg.render(); + await syntaxHighlighter.init(); - // Manually add whitespace styling. - // svg-builder does not support styles. To be exact, - // there is a style function but it's broken and there are no docs. - if (!svgContent.includes('style="white-space: pre"')) { - svgContent = svgContent.replaceAll( - " { console.log("createSvgDecoration"); - const svgUri = this.createSvgTooltip(text); - if (!svgUri) { + const uriAndDimensions = await this.createSvgTooltip(text); + if (!uriAndDimensions) { return undefined; } + const { uri, dimensions } = uriAndDimensions; + // Use theme or fallback const backgroundColour = this.theme.colors["editor.background"]; - const tipWidth = SVG_CONFIG.getTipWidth(text); - const tipHeight = SVG_CONFIG.getTipHeight(text); + // const tipWidth = SVG_CONFIG.getTipWidth(text); + // const tipHeight = SVG_CONFIG.getTipHeight(text); + const tipWidth = dimensions.width; + const tipHeight = dimensions.height; return vscode.window.createTextEditorDecorationType({ after: { - contentIconPath: svgUri, + contentIconPath: uri, // border: `;box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${tipHeight}px ${backgroundColour}; // border-radius: ${SVG_CONFIG.radius}px; // filter: ${SVG_CONFIG.filter}`, // width: `${tipWidth}px`, // height: `${tipHeight}px`, + // border: `transparent; position: absolute; z-index: 1000; + // box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, + // inset 0 0 0 ${tipHeight}px ${backgroundColour}; + // border-radius: ${SVG_CONFIG.radius}px; + // filter: ${SVG_CONFIG.filter}; + // margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`, border: `transparent; position: absolute; z-index: 1000; - box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, - inset 0 0 0 ${tipHeight}px ${backgroundColour}; - border-radius: ${SVG_CONFIG.radius}px; - filter: ${SVG_CONFIG.filter}; margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`, + // border: `solid 1px white; position: absolute; z-index: 1000; + // margin-left: ${SVG_CONFIG.cursorOffset * 8}px; + // margin-top: 0em;`, + // border: `solid 1px white; position: absolute; z-index: 1000; + // margin: 0em; padding: 0em; + // margin-left: ${SVG_CONFIG.cursorOffset * 8}px; + // margin-top: 0em;`, width: `${tipWidth}px`, height: `${tipHeight}px`, + // textDecoration: `none; transform: translateY(-100%);`, }, // Set a negative margin to make the decoration float if it starts to displace text. // Also use absolute positioning. @@ -358,14 +359,14 @@ export class NextEditWindowManager { /** * Render a tooltip with the given text at the specified position */ - private renderTooltip( + private async renderTooltip( editor: vscode.TextEditor, position: vscode.Position, text: string, ) { console.log("renderTooltip"); // Create a new decoration with the text - const decoration = this.createSvgDecoration(text); + const decoration = await this.createSvgDecoration(text); if (!decoration) { console.error("Failed to create decoration for text:", text); return; From 87decd0d83928e2f5fd52b4518c6fbc573b5b13b Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 19 Jun 2025 14:28:28 -0700 Subject: [PATCH 031/100] create a syntax highlighting class --- core/syntaxHighlighting/SyntaxHighlighter.ts | 366 +++++++++++++++++++ 1 file changed, 366 insertions(+) create mode 100644 core/syntaxHighlighting/SyntaxHighlighter.ts diff --git a/core/syntaxHighlighting/SyntaxHighlighter.ts b/core/syntaxHighlighting/SyntaxHighlighter.ts new file mode 100644 index 000000000..7b00e7247 --- /dev/null +++ b/core/syntaxHighlighting/SyntaxHighlighter.ts @@ -0,0 +1,366 @@ +import * as fs from "fs/promises"; +import { JSDOM } from "jsdom"; +import path from "path"; +import puppeteer, { Browser, ScreenshotOptions } from "puppeteer"; +import { BundledTheme, codeToHtml } from "shiki"; +import { kebabOfStr } from "../util/text"; + +interface SyntaxHighlighterOptions { + themesDir?: string; + theme?: string; +} + +interface HTMLOptions { + theme?: string; + customCSS?: string; + containerClass?: string; +} + +interface ConversionOptions extends HTMLOptions { + transparent?: boolean; + screenshotOptions?: ScreenshotOptions; + imageType: "png" | "svg"; +} + +interface Dimensions { + width: number; + height: number; +} + +interface DataAndDimensions { + data: Buffer; + dimensions: Dimensions; +} + +interface DataUriAndDimensions { + uri: DataUri; + dimensions: Dimensions; +} + +type DataUri = PngUri | SvgUri; + +type PngUri = string; +type SvgUri = string; + +export class SyntaxHighlighter { + private themesDir: string = path.join(__dirname, "themes"); // We may need this in case we start supporting custom colors. + private currentTheme: string; + private browser: Browser | undefined = undefined; + private static instance: SyntaxHighlighter; + + private constructor(options: SyntaxHighlighterOptions = {}) { + this.currentTheme = options.theme || "dark-plus"; + } + + static getInstance(options?: SyntaxHighlighterOptions): SyntaxHighlighter { + if (!SyntaxHighlighter.instance) { + SyntaxHighlighter.instance = new SyntaxHighlighter(options); + } + return SyntaxHighlighter.instance; + } + + async init(): Promise { + if (!this.browser) { + this.browser = await puppeteer.launch(); + } + } + + async close(): Promise { + if (this.browser) { + await this.browser.close(); + this.browser = undefined; + } + } + + themeExists(themeNameKebab: string): themeNameKebab is BundledTheme { + const themeArray: BundledTheme[] = [ + "andromeeda", + "aurora-x", + "ayu-dark", + "catppuccin-frappe", + "catppuccin-latte", + "catppuccin-macchiato", + "catppuccin-mocha", + "dark-plus", + "dracula", + "dracula-soft", + "everforest-dark", + "everforest-light", + "github-dark", + "github-dark-default", + "github-dark-dimmed", + "github-dark-high-contrast", + "github-light", + "github-light-default", + "github-light-high-contrast", + "gruvbox-dark-hard", + "gruvbox-dark-medium", + "gruvbox-dark-soft", + "gruvbox-light-hard", + "gruvbox-light-medium", + "gruvbox-light-soft", + "houston", + "kanagawa-dragon", + "kanagawa-lotus", + "kanagawa-wave", + "laserwave", + "light-plus", + "material-theme", + "material-theme-darker", + "material-theme-lighter", + "material-theme-ocean", + "material-theme-palenight", + "min-dark", + "min-light", + "monokai", + "night-owl", + "nord", + "one-dark-pro", + "one-light", + "plastic", + "poimandres", + "red", + "rose-pine", + "rose-pine-dawn", + "rose-pine-moon", + "slack-dark", + "slack-ochin", + "snazzy-light", + "solarized-dark", + "solarized-light", + "synthwave-84", + "tokyo-night", + "vesper", + "vitesse-black", + "vitesse-dark", + "vitesse-light", + ]; + + return themeArray.includes(themeNameKebab as BundledTheme); + } + + async setTheme(themeName: string): Promise { + if (this.themeExists(kebabOfStr(themeName))) { + this.currentTheme = themeName; + } else { + this.currentTheme = "dark-plus"; + } + } + + async highlightCode( + code: string, + language: string = "javascript", + ): Promise { + return await codeToHtml(code, { + lang: language, + theme: this.currentTheme, + }); + } + + async convertToPNG( + code: string, + language: string = "javascript", + fontSize: number, + options: ConversionOptions, + ): Promise { + if (!this.browser) { + throw new Error("Browser not initialized. Call init() first."); + } + + const highlightedCodeHtml = await this.highlightCode(code, language); + + const page = await this.browser.newPage(); + await page.setContent(highlightedCodeHtml); + + const dimensions = await page.evaluate(() => { + const body = document.body; + return { + width: body.scrollWidth, + height: body.scrollHeight, + }; + }); + + await page.setViewport({ + width: 3840, + height: 2160, + deviceScaleFactor: 1, + }); + + const screenshot = await page.screenshot({ + type: "png", + omitBackground: true, + ...options.screenshotOptions, + }); + + await page.close(); + + return { data: screenshot, dimensions: dimensions }; + } + + async convertToSVG( + code: string, + language: string = "javascript", + fontSize: number, + options: ConversionOptions, + ): Promise { + if (!this.browser) { + throw new Error("Browser not initialized. Call init() first."); + } + + const highlightedCodeHtml = await this.highlightCode(code, language); + + console.log(code); + console.log(highlightedCodeHtml); + + const guts = this.convertShikiHtmlToSvgGut(highlightedCodeHtml, fontSize); + const backgroundColor = this.getBackgroundColor(highlightedCodeHtml); + const svg = ` + ${guts} +`; + + const tempPage = await this.browser.newPage(); + await tempPage.setContent(svg); + + const dimensions = await tempPage.evaluate(() => { + const svg = document.querySelector("svg"); + if (!svg) return { width: 0, height: 0 }; + const bbox = svg.getBBox(); + return { + width: Math.ceil(bbox.width), + height: Math.ceil(bbox.height), + }; + }); + + await tempPage.close(); + + const finalSvg = ` + ${guts} +`; + + console.log(finalSvg); + return { data: Buffer.from(finalSvg, "utf8"), dimensions: dimensions }; + } + + convertShikiHtmlToSvgGut(shikiHtml: string, fontSize: number): string { + const dom = new JSDOM(shikiHtml); + const document = dom.window.document; + + const lines = Array.from(document.querySelectorAll(".line")); + const svgLines = lines.map((line, index) => { + const spans = Array.from(line.childNodes) + .map((node) => { + if (node.nodeType === 3) { + return `${node.textContent}`; + } + + const el = node as HTMLElement; + const style = el.getAttribute("style") || ""; + const colorMatch = style.match(/color:\s*(#[0-9a-fA-F]{6})/); + const fill = colorMatch ? ` fill="${colorMatch[1]}"` : ""; + const content = el.textContent || ""; + return `${content}`; + }) + .join(""); + + const y = index * 20 + fontSize; // 20px line height + return `${spans}`; + }); + + return ` + ${svgLines.join("\n")} + `.trim(); + } + + getBackgroundColor(shikiHtml: string): string { + const dom = new JSDOM(shikiHtml); + const document = dom.window.document; + + const preElement = document.querySelector("pre"); + let backgroundColor = "#333333"; // Default white background + if (preElement) { + const style = preElement.getAttribute("style") || ""; + const bgColorMatch = style.match(/background-color:\s*(#[0-9a-fA-F]{6})/); + if (bgColorMatch) { + backgroundColor = bgColorMatch[1]; + } + } + + return backgroundColor; + } + + async getDataUri( + code: string, + language: string = "javascript", + fontSize: number, + options: ConversionOptions, + ): Promise { + switch (options.imageType) { + case "png": + const pngBuffer = await this.convertToPNG( + code, + language, + fontSize, + options, + ); + return `data:image/png;base64,${pngBuffer.data.toString("base64")}`; + case "svg": + const svgBuffer = await this.convertToSVG( + code, + language, + fontSize, + options, + ); + return `data:image/svg+xml;base64,${svgBuffer.data.toString("base64")}`; + } + } + + async getDataUriAndDimensions( + code: string, + language: string = "javascript", + fontSize: number, + options: ConversionOptions, + ): Promise { + const converters: { + [Key in "png" | "svg"]: ( + code: string, + language: string, + fontSize: number, + options: ConversionOptions, + ) => Promise; + } = { + png: this.convertToPNG.bind(this), + svg: this.convertToSVG.bind(this), + }; + + const mimetypes: { + [Key in "png" | "svg"]: string; + } = { + png: "image/png", + svg: "image/svg+xml", + }; + + const { data, dimensions } = await converters[options.imageType]( + code, + language, + fontSize, + options, + ); + + return { + uri: `data:${mimetypes[options.imageType]};base64,${data.toString("base64")}`, + dimensions: dimensions, + }; + } + + // Utility method to list available themes + async getAvailableThemes(): Promise { + try { + const files = await fs.readdir(this.themesDir); + return files + .filter((file) => file.endsWith(".css")) + .map((file) => file.replace(".css", "")); + } catch (error) { + return []; + } + } +} From 16719466686999ed2386988887d3de1787ef8a98 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 19 Jun 2025 14:30:03 -0700 Subject: [PATCH 032/100] create a helper function to get kebab cases of differenly cased strings --- core/util/text.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/core/util/text.ts b/core/util/text.ts index 2e11fce05..7b0aa22e8 100644 --- a/core/util/text.ts +++ b/core/util/text.ts @@ -25,3 +25,10 @@ export function replaceEscapedCharacters(str: string): string { } }); } + +export function kebabOfStr(str: string): string { + return str + .replace(/([a-z])([A-Z])/g, "$1-$2") // handle camelCase and PascalCase + .replace(/[\s_]+/g, "-") // replace spaces and underscores with hyphens + .toLowerCase(); +} From 585ad1b125884d9bf8abd875fb5667984b6779e2 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 19 Jun 2025 14:30:33 -0700 Subject: [PATCH 033/100] asyncify --- extensions/vscode/src/autocomplete/completionProvider.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 8a2605a95..45fb4a044 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -333,7 +333,10 @@ export class ContinueCompletionProvider // return [completionItem]; const editor = vscode.window.activeTextEditor; if (editor) { - NextEditWindowManager.getInstance().showTooltip(editor, completionText); + await NextEditWindowManager.getInstance().showTooltip( + editor, + completionText, + ); } // return [completionItem]; return undefined; From 2d3d76de5b0863468c79940696f6ab3fee8f897b Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 19 Jun 2025 15:25:56 -0700 Subject: [PATCH 034/100] deprecate support for png, remove puppeteer dependency --- core/syntaxHighlighting/SyntaxHighlighter.ts | 206 ++++++++----------- 1 file changed, 86 insertions(+), 120 deletions(-) diff --git a/core/syntaxHighlighting/SyntaxHighlighter.ts b/core/syntaxHighlighting/SyntaxHighlighter.ts index 7b00e7247..c0886f078 100644 --- a/core/syntaxHighlighting/SyntaxHighlighter.ts +++ b/core/syntaxHighlighting/SyntaxHighlighter.ts @@ -1,7 +1,7 @@ import * as fs from "fs/promises"; import { JSDOM } from "jsdom"; import path from "path"; -import puppeteer, { Browser, ScreenshotOptions } from "puppeteer"; +// import puppeteer, { Browser, ScreenshotOptions } from "puppeteer"; import { BundledTheme, codeToHtml } from "shiki"; import { kebabOfStr } from "../util/text"; @@ -18,8 +18,7 @@ interface HTMLOptions { interface ConversionOptions extends HTMLOptions { transparent?: boolean; - screenshotOptions?: ScreenshotOptions; - imageType: "png" | "svg"; + imageType: "svg"; } interface Dimensions { @@ -45,7 +44,6 @@ type SvgUri = string; export class SyntaxHighlighter { private themesDir: string = path.join(__dirname, "themes"); // We may need this in case we start supporting custom colors. private currentTheme: string; - private browser: Browser | undefined = undefined; private static instance: SyntaxHighlighter; private constructor(options: SyntaxHighlighterOptions = {}) { @@ -59,18 +57,9 @@ export class SyntaxHighlighter { return SyntaxHighlighter.instance; } - async init(): Promise { - if (!this.browser) { - this.browser = await puppeteer.launch(); - } - } + async init(): Promise {} - async close(): Promise { - if (this.browser) { - await this.browser.close(); - this.browser = undefined; - } - } + async close(): Promise {} themeExists(themeNameKebab: string): themeNameKebab is BundledTheme { const themeArray: BundledTheme[] = [ @@ -157,91 +146,99 @@ export class SyntaxHighlighter { }); } - async convertToPNG( - code: string, - language: string = "javascript", - fontSize: number, - options: ConversionOptions, - ): Promise { - if (!this.browser) { - throw new Error("Browser not initialized. Call init() first."); - } + // async convertToPNG( + // code: string, + // language: string = "javascript", + // fontSize: number, + // dimensions: Dimensions, + // lineHeight: number, + // options: ConversionOptions, + // ): Promise { + // if (!this.browser) { + // throw new Error("Browser not initialized. Call init() first."); + // } - const highlightedCodeHtml = await this.highlightCode(code, language); + // const highlightedCodeHtml = await this.highlightCode(code, language); - const page = await this.browser.newPage(); - await page.setContent(highlightedCodeHtml); + // const page = await this.browser.newPage(); + // await page.setContent(highlightedCodeHtml); - const dimensions = await page.evaluate(() => { - const body = document.body; - return { - width: body.scrollWidth, - height: body.scrollHeight, - }; - }); + // const dims = await page.evaluate(() => { + // const body = document.body; + // return { + // width: body.scrollWidth, + // height: body.scrollHeight, + // }; + // }); - await page.setViewport({ - width: 3840, - height: 2160, - deviceScaleFactor: 1, - }); + // await page.setViewport({ + // width: 3840, + // height: 2160, + // deviceScaleFactor: 1, + // }); - const screenshot = await page.screenshot({ - type: "png", - omitBackground: true, - ...options.screenshotOptions, - }); + // const screenshot = await page.screenshot({ + // type: "png", + // omitBackground: true, + // ...options.screenshotOptions, + // }); - await page.close(); + // await page.close(); - return { data: screenshot, dimensions: dimensions }; - } + // return { data: screenshot, dimensions: dims }; + // } async convertToSVG( code: string, language: string = "javascript", fontSize: number, + dimensions: Dimensions, + lineHeight: number, options: ConversionOptions, - ): Promise { - if (!this.browser) { - throw new Error("Browser not initialized. Call init() first."); - } - + ): Promise { const highlightedCodeHtml = await this.highlightCode(code, language); console.log(code); console.log(highlightedCodeHtml); - const guts = this.convertShikiHtmlToSvgGut(highlightedCodeHtml, fontSize); + const guts = this.convertShikiHtmlToSvgGut( + highlightedCodeHtml, + fontSize, + lineHeight, + ); const backgroundColor = this.getBackgroundColor(highlightedCodeHtml); - const svg = ` - ${guts} -`; + // const svg = ` + // ${guts} + // `; - const tempPage = await this.browser.newPage(); - await tempPage.setContent(svg); + // const tempPage = await this.browser.newPage(); + // await tempPage.setContent(svg); - const dimensions = await tempPage.evaluate(() => { - const svg = document.querySelector("svg"); - if (!svg) return { width: 0, height: 0 }; - const bbox = svg.getBBox(); - return { - width: Math.ceil(bbox.width), - height: Math.ceil(bbox.height), - }; - }); + // const dimensions = await tempPage.evaluate(() => { + // const svg = document.querySelector("svg"); + // if (!svg) return { width: 0, height: 0 }; + // const bbox = svg.getBBox(); + // return { + // width: Math.ceil(bbox.width), + // height: Math.ceil(bbox.height), + // }; + // }); - await tempPage.close(); + // await tempPage.close(); - const finalSvg = ` + const svg = ` ${guts} `; - console.log(finalSvg); - return { data: Buffer.from(finalSvg, "utf8"), dimensions: dimensions }; + console.log(svg); + return Buffer.from(svg, "utf8"); } - convertShikiHtmlToSvgGut(shikiHtml: string, fontSize: number): string { + convertShikiHtmlToSvgGut( + shikiHtml: string, + fontSize: number, + lineHeight: number, + ): string { const dom = new JSDOM(shikiHtml); const document = dom.window.document; @@ -262,7 +259,8 @@ export class SyntaxHighlighter { }) .join(""); - const y = index * 20 + fontSize; // 20px line height + const y = (index + 1) * lineHeight; + // const y = index * lineHeight; return `${spans}`; }); @@ -292,66 +290,34 @@ export class SyntaxHighlighter { code: string, language: string = "javascript", fontSize: number, + dimensions: Dimensions, + lineHeight: number, options: ConversionOptions, ): Promise { switch (options.imageType) { - case "png": - const pngBuffer = await this.convertToPNG( - code, - language, - fontSize, - options, - ); - return `data:image/png;base64,${pngBuffer.data.toString("base64")}`; + // case "png": + // const pngBuffer = await this.convertToPNG( + // code, + // language, + // fontSize, + // dimensions, + // lineHeight, + // options, + // ); + // return `data:image/png;base64,${pngBuffer.data.toString("base64")}`; case "svg": const svgBuffer = await this.convertToSVG( code, language, fontSize, + dimensions, + lineHeight, options, ); - return `data:image/svg+xml;base64,${svgBuffer.data.toString("base64")}`; + return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`; } } - async getDataUriAndDimensions( - code: string, - language: string = "javascript", - fontSize: number, - options: ConversionOptions, - ): Promise { - const converters: { - [Key in "png" | "svg"]: ( - code: string, - language: string, - fontSize: number, - options: ConversionOptions, - ) => Promise; - } = { - png: this.convertToPNG.bind(this), - svg: this.convertToSVG.bind(this), - }; - - const mimetypes: { - [Key in "png" | "svg"]: string; - } = { - png: "image/png", - svg: "image/svg+xml", - }; - - const { data, dimensions } = await converters[options.imageType]( - code, - language, - fontSize, - options, - ); - - return { - uri: `data:${mimetypes[options.imageType]};base64,${data.toString("base64")}`, - dimensions: dimensions, - }; - } - // Utility method to list available themes async getAvailableThemes(): Promise { try { From 976865eece0b468f3d765c7609307e3fc298a1b4 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 19 Jun 2025 15:35:51 -0700 Subject: [PATCH 035/100] dimension calculation is now done inside the window manager --- .../src/activation/NextEditWindowManager.ts | 31 +++++++++++-------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 4b907004e..3053b806a 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -250,10 +250,11 @@ export class NextEditWindowManager { try { const tipWidth = SVG_CONFIG.getTipWidth(text); const tipHeight = SVG_CONFIG.getTipHeight(text); + const dimensions = { width: tipWidth, height: tipHeight }; - const lines = text.split("\n"); - const globalIndent = - lines.length > 0 ? (lines[0].match(/^[ \t]*/) || [""])[0].length : 0; + // const lines = text.split("\n"); + // const globalIndent = + // lines.length > 0 ? (lines[0].match(/^[ \t]*/) || [""])[0].length : 0; const syntaxHighlighter = SyntaxHighlighter.getInstance({ theme: "one-dark-pro", @@ -261,19 +262,23 @@ export class NextEditWindowManager { await syntaxHighlighter.init(); - const { uri, dimensions } = - await syntaxHighlighter.getDataUriAndDimensions( - text, - "typescript", - SVG_CONFIG.fontSize, - { - imageType: "svg", - }, - ); + const uri = await syntaxHighlighter.getDataUri( + text, + "typescript", + SVG_CONFIG.fontSize, + dimensions, + SVG_CONFIG.lineHeight, + { + imageType: "svg", + }, + ); console.log(dimensions); - return { uri: vscode.Uri.parse(uri), dimensions: dimensions }; + return { + uri: vscode.Uri.parse(uri), + dimensions, + }; } catch (error) { console.error("Error creating SVG tooltip:", error); return undefined; From 531b0064a94ec63d3e52d964e95081f530922132 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 20 Jun 2025 11:21:10 +0530 Subject: [PATCH 036/100] ollama streaming for tool calls --- core/llm/llms/Ollama.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 16d0e9542..106f99e1b 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -405,7 +405,6 @@ class Ollama extends BaseLLM implements ModelInstaller { parameters: tool.function.parameters, }, })); - chatOptions.stream = false; // Cannot set stream = true for tools calls } const headers: Record = { "Content-Type": "application/json", From 133242aaeb5680ecd2cf90cca600593fc0c2136e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 20 Jun 2025 13:26:18 -0700 Subject: [PATCH 037/100] add methods to generate blank svgs and svgs using satori --- core/syntaxHighlighting/SyntaxHighlighter.ts | 103 ++++++++++++++++++- 1 file changed, 100 insertions(+), 3 deletions(-) diff --git a/core/syntaxHighlighting/SyntaxHighlighter.ts b/core/syntaxHighlighting/SyntaxHighlighter.ts index c0886f078..d826984f7 100644 --- a/core/syntaxHighlighting/SyntaxHighlighter.ts +++ b/core/syntaxHighlighting/SyntaxHighlighter.ts @@ -1,6 +1,7 @@ import * as fs from "fs/promises"; import { JSDOM } from "jsdom"; import path from "path"; +import satori from "satori"; // import puppeteer, { Browser, ScreenshotOptions } from "puppeteer"; import { BundledTheme, codeToHtml } from "shiki"; import { kebabOfStr } from "../util/text"; @@ -188,6 +189,37 @@ export class SyntaxHighlighter { // return { data: screenshot, dimensions: dims }; // } + async convertToBlankSVG( + dimensions: Dimensions, + options: ConversionOptions, + ): Promise { + // const svg = ` + // ${guts} + // `; + + // const tempPage = await this.browser.newPage(); + // await tempPage.setContent(svg); + + // const dimensions = await tempPage.evaluate(() => { + // const svg = document.querySelector("svg"); + // if (!svg) return { width: 0, height: 0 }; + // const bbox = svg.getBBox(); + // return { + // width: Math.ceil(bbox.width), + // height: Math.ceil(bbox.height), + // }; + // }); + + // await tempPage.close(); + + const svg = ` + TEST TEXT THIS IS +`; + + console.log(svg); + return Buffer.from(svg, "utf8"); + } + async convertToSVG( code: string, language: string = "javascript", @@ -198,8 +230,8 @@ export class SyntaxHighlighter { ): Promise { const highlightedCodeHtml = await this.highlightCode(code, language); - console.log(code); - console.log(highlightedCodeHtml); + // console.log(code); + // console.log(highlightedCodeHtml); const guts = this.convertShikiHtmlToSvgGut( highlightedCodeHtml, @@ -227,13 +259,57 @@ export class SyntaxHighlighter { // await tempPage.close(); const svg = ` - ${guts} + ${guts} `; console.log(svg); return Buffer.from(svg, "utf8"); } + async convertToSVGWithSatori( + code: string, + language: string = "javascript", + fontSize: number, + dimensions: Dimensions, + lineHeight: number, + options: ConversionOptions, + ): Promise { + const highlightedCodeHtml = await this.highlightCode(code, language); + + console.log(code); + console.log(highlightedCodeHtml); + + // Convert to SVG using Satori + const fontData = await this.loadFont(); + const svg = await satori(highlightedCodeHtml, { + width: dimensions.width, // You'll need to determine appropriate width + height: dimensions.height, // Dynamic height based on content + fonts: [ + { + name: "YourMonospaceFontName", + data: fontData, + style: "normal", + }, + ], + }); + + console.log(svg); + return Buffer.from(svg, "utf8"); + } + + // Function to load your font + async loadFont(): Promise { + // Option 1: If running in Node.js, you can load from the filesystem + console.log(process.cwd()); + return Buffer.from( + await fs.readFile( + "/home/jacob/continue/continue/fonts/Cascadia_Mono/static/CascadiaMono-Regular.ttf", + "binary", + ), + "binary", + ); + } + convertShikiHtmlToSvgGut( shikiHtml: string, fontSize: number, @@ -318,6 +394,27 @@ export class SyntaxHighlighter { } } + async getBlankDataUri( + dimensions: Dimensions, + options: ConversionOptions, + ): Promise { + switch (options.imageType) { + // case "png": + // const pngBuffer = await this.convertToPNG( + // code, + // language, + // fontSize, + // dimensions, + // lineHeight, + // options, + // ); + // return `data:image/png;base64,${pngBuffer.data.toString("base64")}`; + case "svg": + const svgBuffer = await this.convertToBlankSVG(dimensions, options); + return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`; + } + } + // Utility method to list available themes async getAvailableThemes(): Promise { try { From d3e64842eb6851fcf3e6da851a81fd9a33b0455c Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 20 Jun 2025 13:26:54 -0700 Subject: [PATCH 038/100] make syntax highlighter a class attribute, WIP debug some svgs not rendering --- .../src/activation/NextEditWindowManager.ts | 137 ++++++++++++++++-- 1 file changed, 123 insertions(+), 14 deletions(-) diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 3053b806a..08777072c 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -76,6 +76,7 @@ export class NextEditWindowManager { private readonly excludedURIPrefixes = ["output:", "vscode://inline-chat"]; private readonly hideCommand = "continue.hideNextEditWindow"; private theme = getTheme() || FALLBACK_THEME; + private syntaxHighlighter: SyntaxHighlighter; // Current active decoration private currentDecoration: vscode.TextEditorDecorationType | null = null; @@ -100,6 +101,9 @@ export class NextEditWindowManager { : "Theme is undefined", ); this.setupListeners(); + this.syntaxHighlighter = SyntaxHighlighter.getInstance({ + theme: "one-dark-pro", + }); } public setupNextEditWindowManager(context: vscode.ExtensionContext) { @@ -157,8 +161,11 @@ export class NextEditWindowManager { // Dispose the decoration this.currentDecoration.dispose(); this.currentDecoration = null; + + this.disposables.forEach((d) => d.dispose()); + this.disposables = []; } - this.dispose(); + // this.dispose(); } public dispose() { @@ -250,19 +257,22 @@ export class NextEditWindowManager { try { const tipWidth = SVG_CONFIG.getTipWidth(text); const tipHeight = SVG_CONFIG.getTipHeight(text); - const dimensions = { width: tipWidth, height: tipHeight }; + const dimensions = { + width: Math.floor(tipWidth), + height: Math.floor(tipHeight), + }; // const lines = text.split("\n"); // const globalIndent = // lines.length > 0 ? (lines[0].match(/^[ \t]*/) || [""])[0].length : 0; - const syntaxHighlighter = SyntaxHighlighter.getInstance({ - theme: "one-dark-pro", - }); + // const syntaxHighlighter = SyntaxHighlighter.getInstance({ + // theme: "one-dark-pro", + // }); - await syntaxHighlighter.init(); + // await syntaxHighlighter.init(); - const uri = await syntaxHighlighter.getDataUri( + const uri = await this.syntaxHighlighter.getDataUri( text, "typescript", SVG_CONFIG.fontSize, @@ -273,7 +283,7 @@ export class NextEditWindowManager { }, ); - console.log(dimensions); + // console.log(dimensions); return { uri: vscode.Uri.parse(uri), @@ -299,6 +309,10 @@ export class NextEditWindowManager { const { uri, dimensions } = uriAndDimensions; + const blankUri = await this.syntaxHighlighter.getBlankDataUri(dimensions, { + imageType: "svg", + }); + // Use theme or fallback const backgroundColour = this.theme.colors["editor.background"]; // const tipWidth = SVG_CONFIG.getTipWidth(text); @@ -320,7 +334,7 @@ export class NextEditWindowManager { // border-radius: ${SVG_CONFIG.radius}px; // filter: ${SVG_CONFIG.filter}; // margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`, - border: `transparent; position: absolute; z-index: 1000; + border: `solid 1px white; position: absolute; z-index: 1000; margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`, // border: `solid 1px white; position: absolute; z-index: 1000; // margin-left: ${SVG_CONFIG.cursorOffset * 8}px; @@ -329,8 +343,8 @@ export class NextEditWindowManager { // margin: 0em; padding: 0em; // margin-left: ${SVG_CONFIG.cursorOffset * 8}px; // margin-top: 0em;`, - width: `${tipWidth}px`, - height: `${tipHeight}px`, + width: `${Math.floor(tipWidth)}px`, + height: `${Math.floor(tipHeight)}px`, // textDecoration: `none; transform: translateY(-100%);`, }, // Set a negative margin to make the decoration float if it starts to displace text. @@ -349,6 +363,63 @@ export class NextEditWindowManager { return hoverMarkdown; } + private isValidRange( + editor: vscode.TextEditor, + range: vscode.Range, + ): boolean { + const doc = editor.document; + + // Check if line numbers are valid + if (range.start.line < 0 || range.start.line >= doc.lineCount) { + console.log( + "Invalid start line:", + range.start.line, + "doc lines:", + doc.lineCount, + ); + return false; + } + + if (range.end.line < 0 || range.end.line >= doc.lineCount) { + console.log( + "Invalid end line:", + range.end.line, + "doc lines:", + doc.lineCount, + ); + return false; + } + + // Check if character positions are valid + const startLine = doc.lineAt(range.start.line); + const endLine = doc.lineAt(range.end.line); + + if ( + range.start.character < 0 || + range.start.character > startLine.text.length + ) { + console.log( + "Invalid start character:", + range.start.character, + "line length:", + startLine.text.length, + ); + return false; + } + + if (range.end.character < 0 || range.end.character > endLine.text.length) { + console.log( + "Invalid end character:", + range.end.character, + "line length:", + endLine.text.length, + ); + return false; + } + + return true; + } + /** * Calculate a position to the right of the cursor with the specified offset */ @@ -357,7 +428,14 @@ export class NextEditWindowManager { position: vscode.Position, ): vscode.Position { // Create a position that's offset spaces to the right of the cursor - const offsetChar = position.character + SVG_CONFIG.cursorOffset; + // const offsetChar = position.character + SVG_CONFIG.cursorOffset; + // return new vscode.Position(position.line, offsetChar); + + const line = editor.document.lineAt(position.line); + const offsetChar = Math.min( + position.character + SVG_CONFIG.cursorOffset, + line.text.length, + ); return new vscode.Position(position.line, offsetChar); } @@ -370,6 +448,9 @@ export class NextEditWindowManager { text: string, ) { console.log("renderTooltip"); + // Capture document version to detect changes + const docVersion = editor.document.version; + // Create a new decoration with the text const decoration = await this.createSvgDecoration(text); if (!decoration) { @@ -377,16 +458,44 @@ export class NextEditWindowManager { return; } + // Check if document changed during async operation + if (editor.document.version !== docVersion) { + console.log("Document changed during decoration creation, aborting"); + // decoration.dispose(); + // return; + } + // Store the decoration and editor + this.hideAllTooltips(); this.currentDecoration = decoration; this.activeEditor = editor; + // console.log(decoration); + // Get the position with offset const offsetPosition = this.getOffsetPosition(editor, position); + const line = editor.document.lineAt(offsetPosition.line); + const endPos = line.range.end; + const zeroPos = new vscode.Position(0, 0); + const onePos = new vscode.Position(0, 1); + console.log("Line info:", { + lineNumber: offsetPosition.line, + lineLength: line.text.length, + offsetChar: offsetPosition.character, + endPos: endPos.character, + }); + const range = new vscode.Range(offsetPosition, offsetPosition); + // Validate the range before applying + if (!this.isValidRange(editor, range)) { + console.error("Invalid range detected, skipping decoration"); + // return; + } + + console.log("Applying decoration at range:", range.start, "to", range.end); // Apply the decoration at the offset position - editor.setDecorations(decoration, []); - editor.setDecorations(decoration, [ + // editor.setDecorations(decoration, []); + editor.setDecorations(this.currentDecoration, [ { range: new vscode.Range(offsetPosition, offsetPosition), hoverMessage: [this.buildHideTooltipHoverMsg()], From 85dd9db5977948556bfc4d1cd4c9abf2e14a4410 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 20 Jun 2025 13:48:52 -0700 Subject: [PATCH 039/100] make the class a singleton, save user diff --- core/nextEdit/NextEditProvider.ts | 40 ++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index cc5ec2dfe..5bf121f53 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -40,6 +40,8 @@ const ERRORS_TO_IGNORE = [ ]; export class NextEditProvider { + private static instance: NextEditProvider | null = null; + private autocompleteCache = AutocompleteLruCache.get(); public errorsShown: Set = new Set(); private bracketMatchingService = new BracketMatchingService(); @@ -48,8 +50,9 @@ export class NextEditProvider { private loggingService = new AutocompleteLoggingService(); private contextRetrievalService: ContextRetrievalService; private endpointType: "default" | "fineTuned"; + private diffContext: string = ""; - constructor( + private constructor( private readonly configHandler: ConfigHandler, private readonly ide: IDE, private readonly _injectedGetLlm: () => Promise, @@ -62,6 +65,40 @@ export class NextEditProvider { this.endpointType = endpointType; } + public static initialize( + configHandler: ConfigHandler, + ide: IDE, + injectedGetLlm: () => Promise, + onError: (e: any) => void, + getDefinitionsFromLsp: GetLspDefinitionsFunction, + endpointType: "default" | "fineTuned", + ): NextEditProvider { + if (!NextEditProvider.instance) { + NextEditProvider.instance = new NextEditProvider( + configHandler, + ide, + injectedGetLlm, + onError, + getDefinitionsFromLsp, + endpointType, + ); + } + return NextEditProvider.instance; + } + + public static getInstance(): NextEditProvider { + if (!NextEditProvider.instance) { + throw new Error( + "NextEditProvider has not been initialized. Call initialize() first.", + ); + } + return NextEditProvider.instance; + } + + public addDiffToContext(diff: string): void { + this.diffContext = diff; + } + private async _prepareLlm(): Promise { const llm = await this._injectedGetLlm(); @@ -206,6 +243,7 @@ export class NextEditProvider { snippetPayload, this.ide, helper, + this.diffContext, ), ); } From 1c08d6804ad2f11f66d965280b699df9cf8e0ebe Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 20 Jun 2025 13:49:05 -0700 Subject: [PATCH 040/100] use unified diff as user edits --- core/nextEdit/templating/NextEditPromptEngine.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index ca71fed77..b3de49989 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -162,6 +162,7 @@ export async function renderFineTunedBasicUserPrompt( ide: IDE, // cursorPos: Position, helper: HelperVars, + diffContext: string, ): Promise { const ideInfo = await ide.getIdeInfo(); switch (ideInfo.ideType) { @@ -181,7 +182,7 @@ export async function renderFineTunedBasicUserPrompt( return { role: "user", - content: `### User Edits:\n\n${JSON.stringify(snippets)}\n\n### User Excerpts:\n\n\`\`\`${helper.lang.name}\n\<|editable_region_start|\>\n${JSON.stringify(editedCodeWithPins)}\n\<|editable_region_end|\>\n\`\`\``, + content: `### User Edits:\n\n${diffContext}\n\n### User Excerpts:\n\n\`\`\`${helper.lang.name}\n\<|editable_region_start|\>\n${JSON.stringify(editedCodeWithPins)}\n\<|editable_region_end|\>\n\`\`\``, }; case "jetbrains": From 64cf28905519a056ed4ec7bcb0610fff3d3ac94a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 20 Jun 2025 13:49:20 -0700 Subject: [PATCH 041/100] initialize instead of construcing --- .../vscode/src/autocomplete/completionProvider.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 45fb4a044..25fd9be91 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -83,7 +83,15 @@ export class ContinueCompletionProvider // NOTE: Only turn it on locally when testing (for review purposes). // TODO: revert back if (IS_NEXT_EDIT_ACTIVE || true) { - this.nextEditProvider = new NextEditProvider( + // this.nextEditProvider = new NextEditProvider( + // this.configHandler, + // this.ide, + // getAutocompleteModel, + // this.onError.bind(this), + // getDefinitionsFromLsp, + // "fineTuned", + // ); + this.nextEditProvider = NextEditProvider.initialize( this.configHandler, this.ide, getAutocompleteModel, From 767a95495198cee198be1b5fda6d79f89984ffa1 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 20 Jun 2025 13:49:37 -0700 Subject: [PATCH 042/100] add diff to context on files/smallEdit --- core/core.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/core.ts b/core/core.ts index 26c460fc8..d6aba4d8b 100644 --- a/core/core.ts +++ b/core/core.ts @@ -65,6 +65,7 @@ import { walkDirCache } from "./indexing/walkDir"; import { LLMLogger } from "./llm/logger"; import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants"; import { llmStreamChat } from "./llm/streamChat"; +import { NextEditProvider } from "./nextEdit/NextEditProvider"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { OnboardingModes } from "./protocol/core"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -701,6 +702,7 @@ export class Core { (diff: string) => { console.log(diff, "\n"); // TODO handle devData logging here + NextEditProvider.getInstance().addDiffToContext(diff); }, ); } From 4bfbced10be4b3f7f7503854efa0a906984b3ebf Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 20 Jun 2025 14:16:00 -0700 Subject: [PATCH 043/100] fix a UI bug where completions won't render --- core/syntaxHighlighting/SyntaxHighlighter.ts | 8 ++++---- .../vscode/src/activation/NextEditWindowManager.ts | 14 +------------- 2 files changed, 5 insertions(+), 17 deletions(-) diff --git a/core/syntaxHighlighting/SyntaxHighlighter.ts b/core/syntaxHighlighting/SyntaxHighlighter.ts index d826984f7..3a3541d71 100644 --- a/core/syntaxHighlighting/SyntaxHighlighter.ts +++ b/core/syntaxHighlighting/SyntaxHighlighter.ts @@ -4,7 +4,7 @@ import path from "path"; import satori from "satori"; // import puppeteer, { Browser, ScreenshotOptions } from "puppeteer"; import { BundledTheme, codeToHtml } from "shiki"; -import { kebabOfStr } from "../util/text"; +import { escapeForSVG, kebabOfStr } from "../util/text"; interface SyntaxHighlighterOptions { themesDir?: string; @@ -259,7 +259,7 @@ export class SyntaxHighlighter { // await tempPage.close(); const svg = ` - ${guts} + ${guts} `; console.log(svg); @@ -323,7 +323,7 @@ export class SyntaxHighlighter { const spans = Array.from(line.childNodes) .map((node) => { if (node.nodeType === 3) { - return `${node.textContent}`; + return `${escapeForSVG(node.textContent ?? "")}`; } const el = node as HTMLElement; @@ -331,7 +331,7 @@ export class SyntaxHighlighter { const colorMatch = style.match(/color:\s*(#[0-9a-fA-F]{6})/); const fill = colorMatch ? ` fill="${colorMatch[1]}"` : ""; const content = el.textContent || ""; - return `${content}`; + return `${escapeForSVG(content)}`; }) .join(""); diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 08777072c..abf186738 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -474,27 +474,15 @@ export class NextEditWindowManager { // Get the position with offset const offsetPosition = this.getOffsetPosition(editor, position); - const line = editor.document.lineAt(offsetPosition.line); - const endPos = line.range.end; - const zeroPos = new vscode.Position(0, 0); - const onePos = new vscode.Position(0, 1); - console.log("Line info:", { - lineNumber: offsetPosition.line, - lineLength: line.text.length, - offsetChar: offsetPosition.character, - endPos: endPos.character, - }); const range = new vscode.Range(offsetPosition, offsetPosition); // Validate the range before applying if (!this.isValidRange(editor, range)) { console.error("Invalid range detected, skipping decoration"); - // return; + return; } - console.log("Applying decoration at range:", range.start, "to", range.end); // Apply the decoration at the offset position - // editor.setDecorations(decoration, []); editor.setDecorations(this.currentDecoration, [ { range: new vscode.Range(offsetPosition, offsetPosition), From f720b44b329af25eb3960183cf1d148b04db32cd Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 20 Jun 2025 16:13:09 -0700 Subject: [PATCH 044/100] accept next edit contents on ctrl+space tab --- .../src/activation/NextEditWindowManager.ts | 60 ++++++++++++++++--- 1 file changed, 53 insertions(+), 7 deletions(-) diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index abf186738..9cb6ce98c 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -69,6 +69,7 @@ const SVG_CONFIG = { // Command ID - can be used in package.json export const HIDE_TOOLTIP_COMMAND = "nextEditWindow.hideTooltips"; +export const ACCEPT_NEXT_EDIT_COMMAND = "nextEditWindow.acceptNextEdit"; export class NextEditWindowManager { private static instance: NextEditWindowManager; @@ -82,6 +83,8 @@ export class NextEditWindowManager { private currentDecoration: vscode.TextEditorDecorationType | null = null; // Track which editor has the active decoration private activeEditor: vscode.TextEditor | null = null; + // Store the current tooltip text for accepting + private currentTooltipText: string | null = null; // Disposables private disposables: vscode.Disposable[] = []; @@ -116,10 +119,18 @@ export class NextEditWindowManager { ); context.subscriptions.push(hideTooltipsCommand); + // Register the command to accept next edit + const acceptNextEditCommand = vscode.commands.registerCommand( + ACCEPT_NEXT_EDIT_COMMAND, + () => { + this.acceptNextEdit(); + }, + ); + context.subscriptions.push(acceptNextEditCommand); + // Add this class to context disposables context.subscriptions.push(this); } - /** * Show a tooltip with the given text at the current cursor position * @param editor The active text editor @@ -134,6 +145,9 @@ export class NextEditWindowManager { this.hideAllTooltips(); // this.dispose(); + // Store the current tooltip text for accepting later + this.currentTooltipText = text; + // Get cursor position const position = editor.selection.active; @@ -164,10 +178,38 @@ export class NextEditWindowManager { this.disposables.forEach((d) => d.dispose()); this.disposables = []; + + // Clear the current tooltip text + this.currentTooltipText = null; } // this.dispose(); } + /** + * Accept the current next edit suggestion by inserting it at cursor position + */ + private acceptNextEdit() { + if (!this.activeEditor || !this.currentTooltipText) { + return; + } + + const editor = this.activeEditor; + const text = this.currentTooltipText; + const position = editor.selection.active; + + // Insert the text at the current cursor position + editor + .edit((editBuilder) => { + editBuilder.insert(position, text); + }) + .then((success) => { + if (success) { + // Hide the tooltip after inserting + this.hideAllTooltips(); + } + }); + } + public dispose() { // Dispose current decoration if (this.currentDecoration) { @@ -258,8 +300,8 @@ export class NextEditWindowManager { const tipWidth = SVG_CONFIG.getTipWidth(text); const tipHeight = SVG_CONFIG.getTipHeight(text); const dimensions = { - width: Math.floor(tipWidth), - height: Math.floor(tipHeight), + width: tipWidth, + height: tipHeight, }; // const lines = text.split("\n"); @@ -302,6 +344,7 @@ export class NextEditWindowManager { text: string, ): Promise { console.log("createSvgDecoration"); + console.log(text); const uriAndDimensions = await this.createSvgTooltip(text); if (!uriAndDimensions) { return undefined; @@ -334,7 +377,10 @@ export class NextEditWindowManager { // border-radius: ${SVG_CONFIG.radius}px; // filter: ${SVG_CONFIG.filter}; // margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`, - border: `solid 1px white; position: absolute; z-index: 1000; + border: `transparent; position: absolute; z-index: 1000; + box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${tipHeight}px ${backgroundColour}; + filter: ${SVG_CONFIG.filter}; + border-radius: ${SVG_CONFIG.radius}px; margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`, // border: `solid 1px white; position: absolute; z-index: 1000; // margin-left: ${SVG_CONFIG.cursorOffset * 8}px; @@ -343,8 +389,8 @@ export class NextEditWindowManager { // margin: 0em; padding: 0em; // margin-left: ${SVG_CONFIG.cursorOffset * 8}px; // margin-top: 0em;`, - width: `${Math.floor(tipWidth)}px`, - height: `${Math.floor(tipHeight)}px`, + width: `${tipWidth}px`, + height: `${tipHeight}px`, // textDecoration: `none; transform: translateY(-100%);`, }, // Set a negative margin to make the decoration float if it starts to displace text. @@ -355,7 +401,7 @@ export class NextEditWindowManager { private buildHideTooltipHoverMsg() { const hoverMarkdown = new vscode.MarkdownString( - `[Dismiss](command:${HIDE_TOOLTIP_COMMAND})`, + `[Dismiss](command:${HIDE_TOOLTIP_COMMAND}) | [Accept (Ctrl+Space, Tab)](command:${ACCEPT_NEXT_EDIT_COMMAND})`, ); hoverMarkdown.isTrusted = true; From 09fbbecaa334a6904e4e16d4f69387c14f327fec Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 20 Jun 2025 16:13:28 -0700 Subject: [PATCH 045/100] insert editable regions pins at selected locations --- .../templating/NextEditPromptEngine.ts | 85 ++++++++++++++----- 1 file changed, 63 insertions(+), 22 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index b3de49989..3eac64f19 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -102,14 +102,14 @@ export async function renderFineTunedUserPrompt( // helper.filepath, // ); - const editedCodeWithPins = insertCursorPin( - helper.fileContents, + const editedCodeWithPins = insertPins( + helper.fileContents.split("\n"), helper.pos, ); return { role: "user", - content: `### User Edits:\n\n${snippets.diffSnippets}\n\n### User Excerpts:\n\n\`\`\`${helper.lang.name}\n\<|editable_region_start|\>\n${JSON.stringify(editedCodeWithPins)}\n\<|editable_region_end|\>\n\`\`\``, + content: `### User Edits:\n\n${snippets.diffSnippets}\n\n### User Excerpts:\n\n\`\`\`${helper.lang.name}\n${editedCodeWithPins}\`\`\``, }; case "jetbrains": @@ -137,14 +137,14 @@ export async function renderDefaultBasicUserPrompt( // helper.filepath, // ); - const editedCodeWithPins = insertCursorPin( - helper.fileContents, + const editedCodeWithPins = insertPins( + helper.fileContents.split("\n"), helper.pos, ); return { role: "user", - content: `### User Edits:\n\n${JSON.stringify(snippets)}\n\n### User Excerpts:\n\n\`\`\`${helper.lang.name}\n\<|editable_region_start|\>\n${JSON.stringify(editedCodeWithPins)}\n\<|editable_region_end|\>\n\`\`\``, + content: `### User Edits:\n\n${JSON.stringify(snippets)}\n\n### User Excerpts:\n\n\`\`\`${helper.lang.name}\n${editedCodeWithPins}\`\`\``, }; case "jetbrains": @@ -167,22 +167,14 @@ export async function renderFineTunedBasicUserPrompt( const ideInfo = await ide.getIdeInfo(); switch (ideInfo.ideType) { case "vscode": - // const diffs = await compareAndReturnDiff( - // originalCode, - // editedCode, - // helper.filepath, - // ); + const lines = helper.fileContents.split("\n"); + const editedCodeWithPins = insertPins(lines, helper.pos); - const editedCodeWithPins = insertCursorPin( - helper.fileContents, - helper.pos, - ); - - console.log(snippets); + // console.log(snippets); return { role: "user", - content: `### User Edits:\n\n${diffContext}\n\n### User Excerpts:\n\n\`\`\`${helper.lang.name}\n\<|editable_region_start|\>\n${JSON.stringify(editedCodeWithPins)}\n\<|editable_region_end|\>\n\`\`\``, + content: `### User Edits:\n\n${diffContext}\n\n### User Excerpts:\n\n\`\`\`${helper.lang.name}\n${editedCodeWithPins}\`\`\``, }; case "jetbrains": @@ -193,11 +185,15 @@ export async function renderFineTunedBasicUserPrompt( } } -function insertCursorPin(fileContents: string, cursorPos: Position) { - const lines = fileContents.split("\n"); +function insertPins(lines: string[], cursorPos: Position) { + const a = insertCursorPin(lines, cursorPos); + const b = insertEditableRegionPinsWithStaticRange(a, cursorPos, 5, 5); + return b.join("\n"); +} +function insertCursorPin(lines: string[], cursorPos: Position) { if (cursorPos.line < 0 || cursorPos.line >= lines.length) { - return fileContents; + return lines; } // Ensure character position is within bounds or at the end of the line. @@ -209,5 +205,50 @@ function insertCursorPin(fileContents: string, cursorPos: Position) { "<|user_cursor_is_here|>" + lines[cursorPos.line].slice(charPos); - return lines.join("\n"); + return lines; +} + +function insertEditableRegionPinsWithStaticRange( + lines: string[], + cursorPos: Position, + marginTop: number, + marginBottom: number, +) { + if (cursorPos.line < 0 || cursorPos.line >= lines.length) { + return lines; + } + + // Ensure editable regions are within bounds. + const editableRegionStart = Math.max(cursorPos.line - marginTop, 0); + const editableRegionEnd = Math.min( + cursorPos.line + marginBottom, + lines.length - 1, + ); + + const instrumentedLines = [ + ...lines.slice(0, editableRegionStart), + "<|editable_region_start|>", + ...lines.slice(editableRegionStart, editableRegionEnd), + "<|editable_region_end|>", + ...lines.slice(editableRegionEnd), + ]; + + return instrumentedLines; +} + +function insertEditableRegionPinsWithAst(lines: string[], cursorPos: Position) { + if (cursorPos.line < 0 || cursorPos.line >= lines.length) { + return lines; + } + + // Ensure character position is within bounds or at the end of the line. + const lineLength = lines[cursorPos.line].length; + const charPos = Math.min(Math.max(0, cursorPos.character), lineLength); + + lines[cursorPos.line] = + lines[cursorPos.line].slice(0, charPos) + + "<|user_cursor_is_here|>" + + lines[cursorPos.line].slice(charPos); + + return lines; } From a1df08c6e81c024ddefd11c1fab86a3a0c2dd485 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 20 Jun 2025 16:13:50 -0700 Subject: [PATCH 046/100] small cleanup --- core/syntaxHighlighting/SyntaxHighlighter.ts | 49 ++------------------ 1 file changed, 5 insertions(+), 44 deletions(-) diff --git a/core/syntaxHighlighting/SyntaxHighlighter.ts b/core/syntaxHighlighting/SyntaxHighlighter.ts index 3a3541d71..b05092913 100644 --- a/core/syntaxHighlighting/SyntaxHighlighter.ts +++ b/core/syntaxHighlighting/SyntaxHighlighter.ts @@ -193,30 +193,10 @@ export class SyntaxHighlighter { dimensions: Dimensions, options: ConversionOptions, ): Promise { - // const svg = ` - // ${guts} - // `; - - // const tempPage = await this.browser.newPage(); - // await tempPage.setContent(svg); - - // const dimensions = await tempPage.evaluate(() => { - // const svg = document.querySelector("svg"); - // if (!svg) return { width: 0, height: 0 }; - // const bbox = svg.getBBox(); - // return { - // width: Math.ceil(bbox.width), - // height: Math.ceil(bbox.height), - // }; - // }); - - // await tempPage.close(); - const svg = ` TEST TEXT THIS IS `; - console.log(svg); return Buffer.from(svg, "utf8"); } @@ -230,39 +210,20 @@ export class SyntaxHighlighter { ): Promise { const highlightedCodeHtml = await this.highlightCode(code, language); - // console.log(code); - // console.log(highlightedCodeHtml); - const guts = this.convertShikiHtmlToSvgGut( highlightedCodeHtml, fontSize, lineHeight, ); const backgroundColor = this.getBackgroundColor(highlightedCodeHtml); - // const svg = ` - // ${guts} - // `; - - // const tempPage = await this.browser.newPage(); - // await tempPage.setContent(svg); - - // const dimensions = await tempPage.evaluate(() => { - // const svg = document.querySelector("svg"); - // if (!svg) return { width: 0, height: 0 }; - // const bbox = svg.getBBox(); - // return { - // width: Math.ceil(bbox.width), - // height: Math.ceil(bbox.height), - // }; - // }); - - // await tempPage.close(); const svg = ` - ${guts} + + + ${guts} + `; - console.log(svg); return Buffer.from(svg, "utf8"); } @@ -303,6 +264,7 @@ export class SyntaxHighlighter { console.log(process.cwd()); return Buffer.from( await fs.readFile( + // TODO: fix this to actually resolve to path "/home/jacob/continue/continue/fonts/Cascadia_Mono/static/CascadiaMono-Regular.ttf", "binary", ), @@ -336,7 +298,6 @@ export class SyntaxHighlighter { .join(""); const y = (index + 1) * lineHeight; - // const y = index * lineHeight; return `${spans}`; }); From 8b4501b5a8c3b0ad73ccb7a09f96ce26fcd0ae0a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 20 Jun 2025 16:14:08 -0700 Subject: [PATCH 047/100] escape reserved characters for SVG --- core/util/text.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/core/util/text.ts b/core/util/text.ts index 7b0aa22e8..9e948f415 100644 --- a/core/util/text.ts +++ b/core/util/text.ts @@ -26,6 +26,15 @@ export function replaceEscapedCharacters(str: string): string { }); } +export function escapeForSVG(text: string): string { + return text + .replace(/&/g, "&") // must be first + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + export function kebabOfStr(str: string): string { return str .replace(/([a-z])([A-Z])/g, "$1-$2") // handle camelCase and PascalCase From 08de67f3690d645209d46ad6102246358812322e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 20 Jun 2025 16:14:35 -0700 Subject: [PATCH 048/100] add a function to get renderable diffs with +, - gutter annotations --- core/nextEdit/diff/diff.ts | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/core/nextEdit/diff/diff.ts b/core/nextEdit/diff/diff.ts index 156455f28..476e1c8b5 100644 --- a/core/nextEdit/diff/diff.ts +++ b/core/nextEdit/diff/diff.ts @@ -1,14 +1,28 @@ import { DiffLine } from "../.."; export function getRenderableDiff(diffLines: DiffLine[]) { - let diffLineNumberStart = -1; const diff = diffLines.reduce((acc, curr, i) => { if (curr.type === "new") { acc += `${curr.line}\n`; - - if (diffLineNumberStart === -1) { - diffLineNumberStart = i; - } + // } else if (curr.type === "old") { + // acc += `${curr.line}\n`; + // } else if (curr.type == "same") { + // acc += `${curr.line}\n`; + } + return acc; + }, ""); + + return diff; +} + +export function getRenderableDiffWithGutterAnnotations(diffLines: DiffLine[]) { + const diff = diffLines.reduce((acc, curr, i) => { + if (curr.type === "new") { + acc += `+ ${curr.line}\n`; + // } else if (curr.type === "old") { + // acc += `- ${curr.line}\n`; + // } else if (curr.type == "same") { + // acc += ` ${curr.line}\n`; } return acc; }, ""); From 09ad19b1428e2622902d8184aa5a2d62576ca361 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sun, 22 Jun 2025 13:23:59 -0700 Subject: [PATCH 049/100] add shiki and satori as deps --- core/package-lock.json | 747 ++++++++++++++++++++++++++++++++++++++++- core/package.json | 2 + 2 files changed, 748 insertions(+), 1 deletion(-) diff --git a/core/package-lock.json b/core/package-lock.json index 81c23f4f1..16e96ecfe 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -62,6 +62,7 @@ "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", + "satori": "^0.15.2", "socket.io-client": "^4.7.3", "sqlite": "^5.1.1", "sqlite3": "^5.1.7", @@ -105,6 +106,7 @@ "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", + "shiki": "^3.6.0", "ts-jest": "^29.1.1", "typescript": "^5.6.3", "vitest": "^3.1.4" @@ -139,7 +141,7 @@ }, "../packages/config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.0.88", + "version": "1.0.92", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -4745,6 +4747,96 @@ "integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==", "peer": true }, + "node_modules/@shikijs/core": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-3.6.0.tgz", + "integrity": "sha512-9By7Xb3olEX0o6UeJyPLI1PE1scC4d3wcVepvtv2xbuN9/IThYN4Wcwh24rcFeASzPam11MCq8yQpwwzCgSBRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.6.0", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4", + "hast-util-to-html": "^9.0.5" + } + }, + "node_modules/@shikijs/engine-javascript": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-3.6.0.tgz", + "integrity": "sha512-7YnLhZG/TU05IHMG14QaLvTW/9WiK8SEYafceccHUSXs2Qr5vJibUwsDfXDLmRi0zHdzsxrGKpSX6hnqe0k8nA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.6.0", + "@shikijs/vscode-textmate": "^10.0.2", + "oniguruma-to-es": "^4.3.3" + } + }, + "node_modules/@shikijs/engine-oniguruma": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-3.6.0.tgz", + "integrity": "sha512-nmOhIZ9yT3Grd+2plmW/d8+vZ2pcQmo/UnVwXMUXAKTXdi+LK0S08Ancrz5tQQPkxvjBalpMW2aKvwXfelauvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.6.0", + "@shikijs/vscode-textmate": "^10.0.2" + } + }, + "node_modules/@shikijs/langs": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-3.6.0.tgz", + "integrity": "sha512-IdZkQJaLBu1LCYCwkr30hNuSDfllOT8RWYVZK1tD2J03DkiagYKRxj/pDSl8Didml3xxuyzUjgtioInwEQM/TA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.6.0" + } + }, + "node_modules/@shikijs/themes": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-3.6.0.tgz", + "integrity": "sha512-Fq2j4nWr1DF4drvmhqKq8x5vVQ27VncF8XZMBuHuQMZvUSS3NBgpqfwz/FoGe36+W6PvniZ1yDlg2d4kmYDU6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.6.0" + } + }, + "node_modules/@shikijs/types": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-3.6.0.tgz", + "integrity": "sha512-cLWFiToxYu0aAzJqhXTQsFiJRTFDAGl93IrMSBNaGSzs7ixkLfdG6pH11HipuWFGW5vyx4X47W8HDQ7eSrmBUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4" + } + }, + "node_modules/@shikijs/vscode-textmate": { + "version": "10.0.2", + "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz", + "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@shuding/opentype.js": { + "version": "1.4.0-beta.0", + "resolved": "https://registry.npmjs.org/@shuding/opentype.js/-/opentype.js-1.4.0-beta.0.tgz", + "integrity": "sha512-3NgmNyH3l/Hv6EvsWJbsvpcpUba6R8IREQ83nH83cyakCw7uM1arZKNfHwv1Wz6jgqrF/j4x5ELvR6PnK9nTcA==", + "license": "MIT", + "dependencies": { + "fflate": "^0.7.3", + "string.prototype.codepointat": "^0.2.1" + }, + "bin": { + "ot": "bin/ot" + }, + "engines": { + "node": ">= 8.0.0" + } + }, "node_modules/@sinclair/typebox": { "version": "0.27.8", "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", @@ -5475,6 +5567,16 @@ "@types/node": "*" } }, + "node_modules/@types/hast": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", + "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, "node_modules/@types/istanbul-lib-coverage": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", @@ -5546,6 +5648,16 @@ "resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.2.tgz", "integrity": "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==" }, + "node_modules/@types/mdast": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", + "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, "node_modules/@types/mozilla-readability": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/@types/mozilla-readability/-/mozilla-readability-0.2.1.tgz", @@ -5682,6 +5794,13 @@ "resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz", "integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==" }, + "node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/uuid": { "version": "9.0.8", "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.8.tgz", @@ -7174,6 +7293,15 @@ "node": ">=6" } }, + "node_modules/camelize": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/camelize/-/camelize-1.0.1.tgz", + "integrity": "sha512-dU+Tx2fsypxTgtLoE36npi3UqcjSSMNYfkqgmoEhtZrraP5VWq0K7FkWVTYa8eMPtnU/G2txVsfdCJTn9uzpuQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/caniuse-lite": { "version": "1.0.30001687", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001687.tgz", @@ -7199,6 +7327,17 @@ "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==" }, + "node_modules/ccount": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", + "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/chai": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/chai/-/chai-5.2.0.tgz", @@ -7255,6 +7394,28 @@ "node": ">=10" } }, + "node_modules/character-entities-html4": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", + "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-legacy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", + "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/check-error": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.1.tgz", @@ -7480,6 +7641,17 @@ "node": ">= 0.8" } }, + "node_modules/comma-separated-tokens": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", + "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/command-line-args": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.2.1.tgz", @@ -7714,6 +7886,36 @@ "node": ">= 8" } }, + "node_modules/css-background-parser": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/css-background-parser/-/css-background-parser-0.1.0.tgz", + "integrity": "sha512-2EZLisiZQ+7m4wwur/qiYJRniHX4K5Tc9w93MT3AS0WS1u5kaZ4FKXlOTBhOjc+CgEgPiGY+fX1yWD8UwpEqUA==", + "license": "MIT" + }, + "node_modules/css-box-shadow": { + "version": "1.0.0-3", + "resolved": "https://registry.npmjs.org/css-box-shadow/-/css-box-shadow-1.0.0-3.tgz", + "integrity": "sha512-9jaqR6e7Ohds+aWwmhe6wILJ99xYQbfmK9QQB9CcMjDbTxPZjwEmUQpU91OG05Xgm8BahT5fW+svbsQGjS/zPg==", + "license": "MIT" + }, + "node_modules/css-color-keywords": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/css-color-keywords/-/css-color-keywords-1.0.0.tgz", + "integrity": "sha512-FyyrDHZKEjXDpNJYvVsV960FiqQyXc/LlYmsxl2BcdMb2WPx0OGRVgTg55rPSyLSNMqP52R9r8geSp7apN3Ofg==", + "license": "ISC", + "engines": { + "node": ">=4" + } + }, + "node_modules/css-gradient-parser": { + "version": "0.0.16", + "resolved": "https://registry.npmjs.org/css-gradient-parser/-/css-gradient-parser-0.0.16.tgz", + "integrity": "sha512-3O5QdqgFRUbXvK1x5INf1YkBz1UKSWqrd63vWsum8MNHDBYD5urm3QtxZbKU259OrEXNM26lP/MPY3d1IGkBgA==", + "license": "MIT", + "engines": { + "node": ">=16" + } + }, "node_modules/css-select": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.1.0.tgz", @@ -7729,6 +7931,17 @@ "url": "https://github.com/sponsors/fb55" } }, + "node_modules/css-to-react-native": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/css-to-react-native/-/css-to-react-native-3.2.0.tgz", + "integrity": "sha512-e8RKaLXMOFii+02mOlqwjbD00KSEKqblnpO9e++1aXS1fPQOpS1YoqdVHBqPjHNoxeF2mimzVqawm2KCbEdtHQ==", + "license": "MIT", + "dependencies": { + "camelize": "^1.0.0", + "css-color-keywords": "^1.0.0", + "postcss-value-parser": "^4.0.2" + } + }, "node_modules/css-what": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.1.0.tgz", @@ -8019,6 +8232,16 @@ "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", "integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==" }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/detect-libc": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz", @@ -8036,6 +8259,20 @@ "node": ">=8" } }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", + "dev": true, + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/devtools-protocol": { "version": "0.0.1312386", "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1312386.tgz", @@ -8243,6 +8480,15 @@ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" }, + "node_modules/emoji-regex-xs": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/emoji-regex-xs/-/emoji-regex-xs-2.0.1.tgz", + "integrity": "sha512-1QFuh8l7LqUcKe24LsPUNzjrzJQ7pgRwp1QMcZ5MX6mFplk2zQ08NVCM84++1cveaUUYtcCYHmeFEuNg16sU4g==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/enabled": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz", @@ -9672,6 +9918,12 @@ "node": "^12.20 || >= 14.13" } }, + "node_modules/fflate": { + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.7.4.tgz", + "integrity": "sha512-5u2V/CDW15QM1XbbgS+0DfPxVB+jUKhWEKuuFuHncbk3tEEqzmoXL+2KyOFuKGqOnmdIy0/davWF1CkuwtibCw==", + "license": "MIT" + }, "node_modules/file-entry-cache": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", @@ -10582,6 +10834,44 @@ "node": ">= 0.4" } }, + "node_modules/hast-util-to-html": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz", + "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "comma-separated-tokens": "^2.0.0", + "hast-util-whitespace": "^3.0.0", + "html-void-elements": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "stringify-entities": "^4.0.0", + "zwitch": "^2.0.4" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-whitespace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", + "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/he": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", @@ -10590,6 +10880,18 @@ "he": "bin/he" } }, + "node_modules/hex-rgb": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/hex-rgb/-/hex-rgb-4.3.0.tgz", + "integrity": "sha512-Ox1pJVrDCyGHMG9CFg1tmrRUMRPRsAWYc/PinY0XzJU4K7y7vjNoLKIQ7BR5UJMCxNN8EM1MNDmHWA/B3aZUuw==", + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/html-encoding-sniffer": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", @@ -10607,6 +10909,17 @@ "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", "dev": true }, + "node_modules/html-void-elements": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz", + "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/htmlparser2": { "version": "9.1.0", "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-9.1.0.tgz", @@ -12657,6 +12970,25 @@ "node": ">= 0.8.0" } }, + "node_modules/linebreak": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz", + "integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==", + "license": "MIT", + "dependencies": { + "base64-js": "0.0.8", + "unicode-trie": "^2.0.0" + } + }, + "node_modules/linebreak/node_modules/base64-js": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz", + "integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/lines-and-columns": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", @@ -13003,6 +13335,28 @@ "node": ">= 0.4" } }, + "node_modules/mdast-util-to-hast": { + "version": "13.2.0", + "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.0.tgz", + "integrity": "sha512-QGYKEuUsYT9ykKBCMOEDLsU5JRObWQusAolFMeko/tYPufNkRffBAQjIE+99jbA87xv6FgmjLtwjh9wBWajwAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@ungap/structured-clone": "^1.0.0", + "devlop": "^1.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "trim-lines": "^3.0.0", + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/media-typer": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", @@ -13036,6 +13390,100 @@ "node": ">= 8" } }, + "node_modules/micromark-util-character": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", + "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-encode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", + "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-sanitize-uri": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", + "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-symbol": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", + "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-types": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz", + "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, "node_modules/micromatch": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", @@ -13878,6 +14326,25 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/oniguruma-parser": { + "version": "0.12.1", + "resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.1.tgz", + "integrity": "sha512-8Unqkvk1RYc6yq2WBYRj4hdnsAxVze8i7iPfQr8e4uSP3tRv0rpZcbGUDvxfQQcdwHt/e9PrMvGCsa8OqG9X3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/oniguruma-to-es": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-4.3.3.tgz", + "integrity": "sha512-rPiZhzC3wXwE59YQMRDodUwwT9FZ9nNBwQQfsd1wfdtlKEyCdRV0avrTcSZ5xlIvGRVPd/cx6ZN45ECmS39xvg==", + "dev": true, + "license": "MIT", + "dependencies": { + "oniguruma-parser": "^0.12.1", + "regex": "^6.0.1", + "regex-recursion": "^6.0.2" + } + }, "node_modules/onnx-proto": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/onnx-proto/-/onnx-proto-4.0.4.tgz", @@ -14154,6 +14621,12 @@ "node": ">=0.10.0" } }, + "node_modules/pako": { + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz", + "integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==", + "license": "MIT" + }, "node_modules/parent-module": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", @@ -14165,6 +14638,16 @@ "node": ">=6" } }, + "node_modules/parse-css-color": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/parse-css-color/-/parse-css-color-0.2.1.tgz", + "integrity": "sha512-bwS/GGIFV3b6KS4uwpzCFj4w297Yl3uqnSgIPsoQkx7GMLROXfMnWvxfNkL0oh8HVhZA4hvJoEoEIqonfJ3BWg==", + "license": "MIT", + "dependencies": { + "color-name": "^1.1.4", + "hex-rgb": "^4.1.0" + } + }, "node_modules/parse-json": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", @@ -14633,6 +15116,12 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "license": "MIT" + }, "node_modules/postgres-array": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-3.0.2.tgz", @@ -14875,6 +15364,17 @@ "node": ">= 6" } }, + "node_modules/property-information": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz", + "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/protobufjs": { "version": "6.11.4", "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-6.11.4.tgz", @@ -15279,6 +15779,33 @@ "@babel/runtime": "^7.8.4" } }, + "node_modules/regex": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/regex/-/regex-6.0.1.tgz", + "integrity": "sha512-uorlqlzAKjKQZ5P+kTJr3eeJGSVroLKoHmquUj4zHWuR+hEyNqlXsSKlYYF5F4NI6nl7tWCs0apKJ0lmfsXAPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-recursion": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz", + "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==", + "dev": true, + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-utilities": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz", + "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==", + "dev": true, + "license": "MIT" + }, "node_modules/regexp.prototype.flags": { "version": "1.5.3", "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.3.tgz", @@ -15678,6 +16205,28 @@ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, + "node_modules/satori": { + "version": "0.15.2", + "resolved": "https://registry.npmjs.org/satori/-/satori-0.15.2.tgz", + "integrity": "sha512-vu/49vdc8MzV5jUchs3TIRDCOkOvMc1iJ11MrZvhg9tE4ziKIEIBjBZvies6a9sfM2vQ2gc3dXeu6rCK7AztHA==", + "license": "MPL-2.0", + "dependencies": { + "@shuding/opentype.js": "1.4.0-beta.0", + "css-background-parser": "^0.1.0", + "css-box-shadow": "1.0.0-3", + "css-gradient-parser": "^0.0.16", + "css-to-react-native": "^3.0.0", + "emoji-regex-xs": "^2.0.1", + "escape-html": "^1.0.3", + "linebreak": "^1.1.0", + "parse-css-color": "^0.2.1", + "postcss-value-parser": "^4.2.0", + "yoga-wasm-web": "^0.3.3" + }, + "engines": { + "node": ">=16" + } + }, "node_modules/saxes": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", @@ -15850,6 +16399,23 @@ "node": ">=8" } }, + "node_modules/shiki": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-3.6.0.tgz", + "integrity": "sha512-tKn/Y0MGBTffQoklaATXmTqDU02zx8NYBGQ+F6gy87/YjKbizcLd+Cybh/0ZtOBX9r1NEnAy/GTRDKtOsc1L9w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/core": "3.6.0", + "@shikijs/engine-javascript": "3.6.0", + "@shikijs/engine-oniguruma": "3.6.0", + "@shikijs/langs": "3.6.0", + "@shikijs/themes": "3.6.0", + "@shikijs/types": "3.6.0", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4" + } + }, "node_modules/side-channel": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", @@ -16130,6 +16696,17 @@ "source-map": "^0.6.0" } }, + "node_modules/space-separated-tokens": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", + "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/split": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/split/-/split-1.0.1.tgz", @@ -16402,6 +16979,12 @@ "node": ">=8" } }, + "node_modules/string.prototype.codepointat": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/string.prototype.codepointat/-/string.prototype.codepointat-0.2.1.tgz", + "integrity": "sha512-2cBVCj6I4IOvEnjgO/hWqXjqBGsY+zwPmHl12Srk9IXSZ56Jwwmy+66XO5Iut/oQVR7t5ihYdLB0GMa4alEUcg==", + "license": "MIT" + }, "node_modules/string.prototype.trim": { "version": "1.2.9", "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.9.tgz", @@ -16451,6 +17034,21 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/stringify-entities": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", + "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", + "dev": true, + "license": "MIT", + "dependencies": { + "character-entities-html4": "^2.0.0", + "character-entities-legacy": "^3.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -16794,6 +17392,12 @@ "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==" }, + "node_modules/tiny-inflate": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz", + "integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==", + "license": "MIT" + }, "node_modules/tinybench": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", @@ -16941,6 +17545,17 @@ "tree-sitter-wasms": "^0.1.11" } }, + "node_modules/trim-lines": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", + "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/triple-beam": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz", @@ -17351,6 +17966,16 @@ "node": ">=4" } }, + "node_modules/unicode-trie": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz", + "integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==", + "license": "MIT", + "dependencies": { + "pako": "^0.2.5", + "tiny-inflate": "^1.0.0" + } + }, "node_modules/unique-filename": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-1.1.1.tgz", @@ -17369,6 +17994,79 @@ "imurmurhash": "^0.1.4" } }, + "node_modules/unist-util-is": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.0.tgz", + "integrity": "sha512-2qCTHimwdxLfz+YzdGfkqNlH0tLi9xjTnHddPmJwtIG9MGsdbutfTc4P+haPD7l7Cjxf/WZj+we5qfVPvvxfYw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-position": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", + "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-stringify-position": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", + "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.0.0.tgz", + "integrity": "sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit-parents": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.1.tgz", + "integrity": "sha512-L/PqWzfTP9lzzEa6CKs0k2nARxTdZduw3zyh8d2NVBnsyvHjSX4TWse388YrrQKbvI8w20fGjGlhgT96WwKykw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/universal-user-agent": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz", @@ -17528,6 +18226,36 @@ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", "integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==" }, + "node_modules/vfile": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", + "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-message": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.2.tgz", + "integrity": "sha512-jRDZ1IMLttGj41KcZvlrYAaI3CfqpLpfpf+Mfig13viT6NKvRzWZ+lXz0Y5D60w6uJIBAOGq9mSHf0gktF0duw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/vite": { "version": "6.3.5", "resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz", @@ -18332,6 +19060,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/yoga-wasm-web": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/yoga-wasm-web/-/yoga-wasm-web-0.3.3.tgz", + "integrity": "sha512-N+d4UJSJbt/R3wqY7Coqs5pcV0aUj2j9IaQ3rNj9bVCLld8tTGKRa2USARjnvZJWVx1NDmQev8EknoczaOQDOA==", + "license": "MIT" + }, "node_modules/zod": { "version": "3.24.2", "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.2.tgz", @@ -18339,6 +19073,17 @@ "funding": { "url": "https://github.com/sponsors/colinhacks" } + }, + "node_modules/zwitch": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", + "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } } } } diff --git a/core/package.json b/core/package.json index d2a639ea7..679dc03cc 100644 --- a/core/package.json +++ b/core/package.json @@ -41,6 +41,7 @@ "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", + "shiki": "^3.6.0", "ts-jest": "^29.1.1", "typescript": "^5.6.3", "vitest": "^3.1.4" @@ -99,6 +100,7 @@ "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", + "satori": "^0.15.2", "socket.io-client": "^4.7.3", "sqlite": "^5.1.1", "sqlite3": "^5.1.7", From dec1ff4e3ef436ed7fb3b1dba5062bc6a59faf1f Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sun, 22 Jun 2025 13:24:29 -0700 Subject: [PATCH 050/100] add accept next edit command and keymap --- extensions/vscode/package.json | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 8b8cac8b0..7192e32f7 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -338,6 +338,10 @@ { "command": "nextEditWindow.hideTooltips", "title": "Hide Tooltip Window" + }, + { + "command": "nextEditWindow.acceptNextEdit", + "title": "Accept Next Edit Suggestion" } ], "keybindings": [ @@ -435,6 +439,11 @@ "command": "nextEditWindow.hideTooltips", "key": "ctrl+space escape", "when": "editorTextFocus" + }, + { + "command": "nextEditWindow.acceptNextEdit", + "key": "ctrl+space tab", + "when": "editorTextFocus" } ], "submenus": [ From 8f6e2ab6840251bb184f4f7980e140711f256560 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sun, 22 Jun 2025 13:25:28 -0700 Subject: [PATCH 051/100] add satori and shiki as deps --- extensions/vscode/package-lock.json | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 199c669c7..023117fdd 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.48", + "version": "1.1.49", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.48", + "version": "1.1.49", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -156,6 +156,7 @@ "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", + "satori": "^0.15.2", "socket.io-client": "^4.7.3", "sqlite": "^5.1.1", "sqlite3": "^5.1.7", @@ -199,6 +200,7 @@ "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", + "shiki": "^3.6.0", "ts-jest": "^29.1.1", "typescript": "^5.6.3", "vitest": "^3.1.4" From b3aded6af5b4e074bb66cee5e24e47b08160920e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sun, 22 Jun 2025 13:27:04 -0700 Subject: [PATCH 052/100] add satori and shiki as deps, remove prismjs --- gui/package-lock.json | 3 ++- gui/package.json | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/package-lock.json b/gui/package-lock.json index 045ee07cb..eb09ae7bb 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -36,7 +36,6 @@ "minisearch": "^7.0.2", "mustache": "^4.2.0", "posthog-js": "^1.130.1", - "prismjs": "^1.29.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-error-boundary": "^4.0.11", @@ -161,6 +160,7 @@ "quick-lru": "^7.0.0", "replicate": "^0.26.0", "request": "^2.88.2", + "satori": "^0.15.2", "socket.io-client": "^4.7.3", "sqlite": "^5.1.1", "sqlite3": "^5.1.7", @@ -204,6 +204,7 @@ "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", + "shiki": "^3.6.0", "ts-jest": "^29.1.1", "typescript": "^5.6.3", "vitest": "^3.1.4" diff --git a/gui/package.json b/gui/package.json index 1f137f19b..fd6b06034 100644 --- a/gui/package.json +++ b/gui/package.json @@ -45,7 +45,6 @@ "minisearch": "^7.0.2", "mustache": "^4.2.0", "posthog-js": "^1.130.1", - "prismjs": "^1.29.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-error-boundary": "^4.0.11", From 684a4e9765d1e5d92f87bad8fadadf6424c842a8 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Sun, 22 Jun 2025 13:27:31 -0700 Subject: [PATCH 053/100] add jsdom as deps --- package-lock.json | 465 +++++++++++++++++++++++++++++++++++++++++++++- package.json | 3 + 2 files changed, 464 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index b4289d422..d95241923 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,6 +4,9 @@ "requires": true, "packages": { "": { + "dependencies": { + "jsdom": "^26.1.0" + }, "devDependencies": { "@typescript-eslint/parser": "^7.8.0", "concurrently": "^9.1.2", @@ -13,6 +16,129 @@ "typescript": "^5.6.3" } }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.0.2.tgz", + "integrity": "sha512-JqWH1vsgdGcw2RR6VliXXdA0/59LttzlU8UlRT/iUUsEeWfYq8I+K0yhihEUTTHLRm1EXvpsCx3083EU15ecsA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.0.10", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.0.10.tgz", + "integrity": "sha512-TiJ5Ajr6WRd1r8HSiwJvZBiJOqtH86aHpUjq5aEKWHiII2Qfjqd/HCWKPOW8EP4vcspXbHnXrwIDlu5savQipg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.0.2", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@eslint-community/eslint-utils": { "version": "4.7.0", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.7.0.tgz", @@ -366,6 +492,15 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, + "node_modules/agent-base": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz", + "integrity": "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, "node_modules/ajv": { "version": "6.12.6", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", @@ -781,6 +916,32 @@ "node": ">= 8" } }, + "node_modules/cssstyle": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.4.0.tgz", + "integrity": "sha512-W0Y2HOXlPkb2yaKrCVRjinYKciu/qSLEmK0K9mcfDei3zwlnHFEHAs/Du3cIRwPqY+J4JsiBzUjoHyc8RsJ03A==", + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/data-view-buffer": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz", @@ -839,7 +1000,6 @@ "version": "4.4.1", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", - "dev": true, "license": "MIT", "dependencies": { "ms": "^2.1.3" @@ -853,6 +1013,12 @@ } } }, + "node_modules/decimal.js": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.5.0.tgz", + "integrity": "sha512-8vDa8Qxvr/+d94hSh5P3IJwI5t8/c0KsMp+g8bNw9cY2icONa5aPfvKeieW1WlG0WQYwwhJ7mjui2xtiePQSXw==", + "license": "MIT" + }, "node_modules/deep-is": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", @@ -946,6 +1112,18 @@ "dev": true, "license": "MIT" }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/es-abstract": { "version": "1.24.0", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.0.tgz", @@ -1941,6 +2119,56 @@ "node": ">= 0.4" } }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", @@ -2283,6 +2511,12 @@ "node": ">=8" } }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "license": "MIT" + }, "node_modules/is-regex": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", @@ -2457,6 +2691,45 @@ "js-yaml": "bin/js-yaml.js" } }, + "node_modules/jsdom": { + "version": "26.1.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz", + "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", + "license": "MIT", + "dependencies": { + "cssstyle": "^4.2.1", + "data-urls": "^5.0.0", + "decimal.js": "^10.5.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.16", + "parse5": "^7.2.1", + "rrweb-cssom": "^0.8.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.1.1", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.1.1", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, "node_modules/json-buffer": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", @@ -2552,6 +2825,12 @@ "license": "MIT", "peer": true }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "license": "ISC" + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -2616,7 +2895,6 @@ "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "dev": true, "license": "MIT" }, "node_modules/natural-compare": { @@ -2627,6 +2905,12 @@ "license": "MIT", "peer": true }, + "node_modules/nwsapi": { + "version": "2.2.20", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.20.tgz", + "integrity": "sha512-/ieB+mDe4MrrKMT8z+mQL8klXydZWGR5Dowt4RAGKbJ3kIGEx3X4ljUo+6V73IXtUPWgfOlU5B9MlGxFO5T+cA==", + "license": "MIT" + }, "node_modules/object-inspect": { "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", @@ -2820,6 +3104,18 @@ "node": ">=6" } }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -3003,9 +3299,7 @@ "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", - "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=6" } @@ -3146,6 +3440,12 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "license": "MIT" + }, "node_modules/run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", @@ -3235,6 +3535,24 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, "node_modules/semver": { "version": "7.7.2", "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", @@ -3575,6 +3893,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "license": "MIT" + }, "node_modules/text-table": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", @@ -3583,6 +3907,24 @@ "license": "MIT", "peer": true }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "license": "MIT" + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -3596,6 +3938,30 @@ "node": ">=8.0" } }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/tree-kill": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", @@ -3789,6 +4155,61 @@ "punycode": "^2.1.0" } }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -3932,6 +4353,42 @@ "license": "ISC", "peer": true }, + "node_modules/ws": { + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-DMricUmwGZUVr++AEAe2uiVM7UoO9MAVZMDu05UQOaUII0lp+zOzLLU4Xqh/JvTqklB1T4uELaaPBKyjE1r4fQ==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "license": "MIT" + }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", diff --git a/package.json b/package.json index 79e522af1..448796e65 100644 --- a/package.json +++ b/package.json @@ -15,5 +15,8 @@ "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8", "typescript": "^5.6.3" + }, + "dependencies": { + "jsdom": "^26.1.0" } } From af24a851e36348bd91326635cbbb5f87bcdd5576 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 22 Jun 2025 23:47:00 -0700 Subject: [PATCH 054/100] log whether tool calls fail or succeed --- gui/src/redux/thunks/callCurrentTool.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/gui/src/redux/thunks/callCurrentTool.ts b/gui/src/redux/thunks/callCurrentTool.ts index af8b4d4d9..02137d822 100644 --- a/gui/src/redux/thunks/callCurrentTool.ts +++ b/gui/src/redux/thunks/callCurrentTool.ts @@ -1,6 +1,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ContextItem } from "core"; import { CLIENT_TOOLS_IMPLS } from "core/tools/builtIn"; +import posthog from "posthog-js"; import { callClientTool } from "../../util/clientTools/callClientTool"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { selectSelectedChatModel } from "../slices/configSlice"; @@ -45,6 +46,9 @@ export const callCurrentTool = createAsyncThunk( let errorMessage: string | undefined = undefined; let streamResponse: boolean; + // Check if telemetry is enabled + const allowAnonymousTelemetry = state.config.config.allowAnonymousTelemetry; + // IMPORTANT: // Errors that occur while calling tool call implementations // Are caught and passed in output as context items @@ -110,6 +114,17 @@ export const callCurrentTool = createAsyncThunk( ); } + // Because we don't have access to use hooks, we check `allowAnonymousTelemetry` + // directly rather than using `CustomPostHogProvider` + if (allowAnonymousTelemetry) { + // Capture telemetry for tool calls + posthog.capture("gui_tool_call_outcome", { + succeeded: errorMessage === undefined, + toolName: toolCallState.toolCall.function.name, + errorMessage: errorMessage, + }); + } + if (streamResponse) { if (errorMessage) { dispatch( From f7bdae37e4dabf46aea2b46a9590e3cbbb303a51 Mon Sep 17 00:00:00 2001 From: Brian 'bdougie' Douglas Date: Mon, 23 Jun 2025 11:09:32 -0700 Subject: [PATCH 055/100] add llms.txt generation for docs --- docs/docusaurus.config.js | 9 +++++++++ docs/package-lock.json | 18 ++++++++++++++++++ docs/package.json | 1 + 3 files changed, 28 insertions(+) diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index 4e873f0db..7a3c3a8d9 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -211,6 +211,15 @@ const config = { enableInDevelopment: false, }, ], + [ + "docusaurus-plugin-llms-txt", + { + // Optional configuration + outputPath: "static/llms.txt", + includePatterns: ["docs/**"], + excludePatterns: ["**/node_modules/**"], + }, + ], [ "@docusaurus/plugin-client-redirects", { diff --git a/docs/package-lock.json b/docs/package-lock.json index f3a3ea446..684d04e98 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -14,6 +14,7 @@ "@docusaurus/preset-classic": "^3.7.0", "@mdx-js/react": "^3.0.0", "clsx": "^2.1.0", + "docusaurus-plugin-llms-txt": "^0.1.3", "posthog-docusaurus": "^2.0.4", "prism-react-renderer": "^2.3.1", "react": "^18.2.0", @@ -7604,6 +7605,23 @@ "node": ">=6" } }, + "node_modules/docusaurus-plugin-llms-txt": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/docusaurus-plugin-llms-txt/-/docusaurus-plugin-llms-txt-0.1.3.tgz", + "integrity": "sha512-X/Dqf1/soHFjvELWXtfa9C023498HsWWwNPdVZEu0OoznI2Gzf+VCB/4obwpBSV9OeDeI8D94/dK/ETq534k9A==", + "license": "MIT", + "dependencies": { + "fs-extra": "^11.2.0", + "gray-matter": "^4.0.3" + }, + "engines": { + "node": ">=16.14" + }, + "peerDependencies": { + "@docusaurus/core": ">=2.0.0", + "react": ">=16.8.0" + } + }, "node_modules/dom-converter": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/dom-converter/-/dom-converter-0.2.0.tgz", diff --git a/docs/package.json b/docs/package.json index 67b995070..af9538e94 100644 --- a/docs/package.json +++ b/docs/package.json @@ -22,6 +22,7 @@ "@docusaurus/preset-classic": "^3.7.0", "@mdx-js/react": "^3.0.0", "clsx": "^2.1.0", + "docusaurus-plugin-llms-txt": "^0.1.3", "posthog-docusaurus": "^2.0.4", "prism-react-renderer": "^2.3.1", "react": "^18.2.0", From a5a1b14d60ece5319ceb668331c7595865bb863e Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 23 Jun 2025 16:15:18 -0700 Subject: [PATCH 056/100] fix: local storage state for free trial exit --- gui/src/components/FreeTrialButton.tsx | 20 ++++++++++--------- .../LumpToolbar/BlockSettingsTopToolbar.tsx | 4 +++- gui/src/util/localStorage.ts | 2 ++ 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/gui/src/components/FreeTrialButton.tsx b/gui/src/components/FreeTrialButton.tsx index 1665b318d..c3373cf7b 100644 --- a/gui/src/components/FreeTrialButton.tsx +++ b/gui/src/components/FreeTrialButton.tsx @@ -4,6 +4,7 @@ import { useContext } from "react"; import { Button, SecondaryButton, vscButtonBackground } from "."; import { IdeMessengerContext } from "../context/IdeMessenger"; import { fontSize } from "../util"; +import { setLocalStorage } from "../util/localStorage"; import { Listbox, ListboxButton, ListboxOptions, Transition } from "./ui"; interface ProgressBarProps { @@ -79,6 +80,15 @@ export default function FreeTrialButton({ }: FreeTrialButtonProps) { const ideMessenger = useContext(IdeMessengerContext); + const onExitFreeTrial = async () => { + setLocalStorage("hasExitedFreeTrial", true); + + await ideMessenger.request("controlPlane/openUrl", { + path: "setup-models", + orgSlug: undefined, + }); + }; + return (
@@ -134,15 +144,7 @@ export default function FreeTrialButton({ )}
- { - await ideMessenger.request("controlPlane/openUrl", { - path: "setup-models", - orgSlug: undefined, - }); - }} - > + Exit trial + + ${ + user.status === "active" + ? `` + : `` + } +
+ + `; + }); + html += ""; + + container.innerHTML = html; + } catch (err: any) { + this.logger.log(`Failed to render users: ${err.message}`, "error"); + container.innerHTML = + "

Failed to load users. Please try again later.

"; + } + } + + private getStatusClass(status: UserStatus): string { + switch (status) { + case "active": + return "user-active"; + case "inactive": + return "user-inactive"; + case "suspended": + return "user-suspended"; + default: + return ""; + } + } + + populateEditForm(form: HTMLFormElement, user: User): void { + if (!form) return; + + (form.elements.namedItem("firstName") as HTMLInputElement).value = + user.firstName; + (form.elements.namedItem("lastName") as HTMLInputElement).value = + user.lastName; + (form.elements.namedItem("email") as HTMLInputElement).value = user.email; + (form.elements.namedItem("userId") as HTMLInputElement).value = String( + user.id, + ); + + // Scroll to form + form.scrollIntoView({ behavior: "smooth" }); + } + + resetForm(formId: string): void { + const form = document.getElementById(formId) as HTMLFormElement; + if (form) { + form.reset(); + (form.elements.namedItem("userId") as HTMLInputElement).value = ""; + } + } +} + +// User Controller - Handles UI interactions and coordinates services +class UserController { + private userRepository: UserRepository; + private userUIService: UserUIService; + private logger: Logger; + private lastOperation: string = ""; + + constructor( + userRepository: UserRepository, + userUIService: UserUIService, + logger: Logger, + ) { + this.userRepository = userRepository; + this.userUIService = userUIService; + this.logger = logger; + } + + async createUser(userData: User): Promise { + try { + await this.userRepository.createUser(userData); + this.lastOperation = "create"; + await this.userUIService.renderUserList("user-container"); + this.userUIService.resetForm("user-form"); + alert("User created successfully!"); + } catch (err: any) { + alert(`Failed to create user: ${err.message}`); + } + } + + async updateUser(userId: number, userData: User): Promise { + try { + await this.userRepository.updateUser(userId, userData); + this.lastOperation = "update"; + await this.userUIService.renderUserList("user-container"); + this.userUIService.resetForm("user-form"); + alert("User updated successfully!"); + } catch (err: any) { + alert(`Failed to update user: ${err.message}`); + } + } + + async editUser(userId: number): Promise { + try { + const users = await this.userRepository.getAllActiveUsers(); + const user = users.find((u) => u.id === userId); + + if (!user) { + this.logger.log(`User not found: ${userId}`, "error"); + return; + } + + const form = document.getElementById("user-form") as HTMLFormElement; + this.userUIService.populateEditForm(form, user); + this.lastOperation = "edit"; + } catch (err: any) { + this.logger.log(`Failed to edit user: ${err.message}`, "error"); + } + } + + async suspendUser(userId: number): Promise { + if (!confirm("Are you sure you want to suspend this user?")) { + return; + } + + try { + await this.userRepository.updateUserStatus(userId, "suspended"); + this.lastOperation = "suspend"; + await this.userUIService.renderUserList("user-container"); + alert("User suspended successfully!"); + } catch (err: any) { + alert(`Failed to suspend user: ${err.message}`); + } + } + + async activateUser(userId: number): Promise { + try { + await this.userRepository.updateUserStatus(userId, "active"); + this.lastOperation = "activate"; + await this.userUIService.renderUserList("user-container"); + alert("User activated successfully!"); + } catch (err: any) { + alert(`Failed to activate user: ${err.message}`); + } + } + + async deleteUser(userId: number): Promise { + if (!confirm("Are you sure you want to delete this user?")) { + return; + } + + try { + await this.userRepository.updateUserStatus(userId, "deleted"); + this.lastOperation = "delete"; + await this.userUIService.renderUserList("user-container"); + alert("User deleted successfully!"); + } catch (err: any) { + alert(`Failed to delete user: ${err.message}`); + } + } + + getLastOperation(): string { + return this.lastOperation; + } +} + +// Application class - Manages services and their lifecycle +class UserManagementApp { + private logger: Logger; + private db: Database; + private userRepository: UserRepository; + private userUIService: UserUIService; + private userController: UserController; + private authService: AuthService; + private configService: ConfigService; + private storageService: StorageService; + + constructor() { + // Initialize services + this.storageService = new LocalStorageService(); + const notificationService = new NotificationService(); + const baseLogger = new ConsoleLogger(notificationService); + this.logger = new PersistentLogger(baseLogger, this.storageService); + this.configService = new ConfigService(this.storageService, this.logger); + + // Initialize database + this.db = new DatabaseService(this.logger); + + // Initialize user repository + this.userRepository = new UserRepository(this.db, this.logger); + + // Initialize UI service + this.userUIService = new UserUIService(this.userRepository, this.logger); + + // Initialize controller + this.userController = new UserController( + this.userRepository, + this.userUIService, + this.logger, + ); + + // Initialize auth service + this.authService = new AuthService( + this.db, + this.logger, + this.storageService, + ); + + // Expose controller to global scope + (window as any).userController = this.userController; + + this.setupEventListeners(); + this.setupErrorHandlers(); + } + + private setupEventListeners(): void { + window.addEventListener("load", () => { + const userForm = document.getElementById("user-form"); + if (userForm) { + userForm.addEventListener( + "submit", + this.handleUserFormSubmit.bind(this), + ); + } + + // Initialize user list + this.userUIService.renderUserList("user-container"); + }); + } + + private setupErrorHandlers(): void { + window.onerror = (msg, url, line) => { + this.logger.log(`Global error: ${msg} at ${url}:${line}`, "error"); + return false; + }; + } + + private handleUserFormSubmit(event: Event): void { + event.preventDefault(); + const form = event.target as HTMLFormElement; + + const userData: User = { + firstName: (form.elements.namedItem("firstName") as HTMLInputElement) + .value, + lastName: (form.elements.namedItem("lastName") as HTMLInputElement).value, + email: (form.elements.namedItem("email") as HTMLInputElement).value, + }; + + const userId = (form.elements.namedItem("userId") as HTMLInputElement) + .value; + + if (userId) { + this.userController.updateUser(parseInt(userId), userData); + } else { + this.userController.createUser(userData); + } + } + + async login(email: string, password: string): Promise { + const success = await this.authService.login(email, password); + if (success) { + // Redirect to dashboard + window.location.href = "/dashboard.html"; + } else { + alert("Invalid email or password"); + } + return success; + } + + cleanup(): void { + this.logger.log("Cleaning up resources", "debug"); + this.db.close(); + } +} + +// Initialize the application +const app = new UserManagementApp(); + +/* +Code Smells in the Original Code + +Violation of Single Responsibility Principle: + +UserManager was a "God class" handling database connection, UI rendering, user CRUD operations, authentication, and logging +Logger mixed logging with email notifications +User operations contained both business logic and UI manipulation + +Violation of Open/Closed Principle: + +Hardcoded dependencies that couldn't be extended without modifying code +Direct UI manipulations embedded in business logic + +High Coupling: + +Direct references to the DOM throughout the codebase +Global state used across different operations +Direct database access from UI-related methods + +Code Duplication: + +Similar code repeated in suspendUser, activateUser, and deleteUser methods +Repetitive UI update logic + +Poor Security Practices: + +API tokens exposed in console logs +Weak password handling (just base64 encoding) +Direct SQL queries vulnerable to injection + + +Global Variables and Side Effects: + +Multiple global variables (currentUserID, loggedInUsers, etc.) +Global DOM event handlers + + +Improvements Made + +Applied Single Responsibility Principle: + +Created specialized classes for each concern: + +Logger and PersistentLogger for logging +NotificationService for alerts/notifications +DatabaseService for database operations +UserRepository for user data access +UserUIService for rendering UI +UserController for handling user actions +AuthService for authentication +ConfigService for configuration management + + +Applied Open/Closed Principle: + +Used interfaces (Logger, Database, StorageService) to define contracts +Implemented dependency injection to allow for extensions without modifications +Created the decorator pattern for logging (base logger + persistent storage) + + +Applied Interface Segregation Principle: + +Created focused interfaces (e.g., Logger only handles logging) +Split large interfaces into smaller, more specific ones + + +Applied Dependency Inversion Principle: + +High-level modules depend on abstractions, not concrete implementations +Dependencies are injected through constructors +Centralized service initialization in the UserManagementApp class + + +Applied Liskov Substitution Principle: + +Classes implementing interfaces fully satisfy their contracts +Derived classes (like PersistentLogger) maintain the behavior expected from the base interface + + +Reduced Duplication: + +Consolidated common user operations in the repository +Created reusable UI methods +Extracted common logic into shared methods + + +Improved Security: + +Removed sensitive information from console logs +Added proper encapsulation of sensitive data +Note: The password hashing is still weak (commented as such) but is separated for easy replacement + + +Better State Management: + +Eliminated global state +Encapsulated state within appropriate classes +Provided proper methods for state access + + +Improved Error Handling: + +Consistent error handling approach +Proper propagation of errors +Clear error messages + + +Proper Separation of Concerns: + +UI logic separated from business logic +Data access separated from business rules +Authentication separated from user management +*/ diff --git a/manual-testing-sandbox/next-edit/next-edit-8-4.ts b/manual-testing-sandbox/next-edit/next-edit-8-4.ts new file mode 100644 index 000000000..f162ba9d4 --- /dev/null +++ b/manual-testing-sandbox/next-edit/next-edit-8-4.ts @@ -0,0 +1,409 @@ +// User management system with mixed concerns and entangled logic +// Difficulty: 4/5 + +type UserStatus = "active" | "inactive" | "suspended" | "deleted"; +type LogLevel = "debug" | "info" | "warn" | "error"; + +// Global variables +let currentUserID: number | null = null; +let loggedInUsers: any[] = []; +let systemStatus = "online"; +let DEBUG_MODE = true; + +// Main user class that handles everything +class UserManager { + private users: any[] = []; + private db: any = null; + private logger: any = null; + private apiToken: string = "secret-token-1234"; + public lastOperation: string = ""; + + constructor() { + this.initializeSystem(); + // Connect to database directly in constructor + this.connectToDatabase(); + console.log("UserManager initialized!"); + } + + // Mixed responsibility - initialization, logging, and notification + private initializeSystem() { + // Set up logging + this.logger = { + log: function (message: string, level: LogLevel = "info") { + const timestamp = new Date().toISOString(); + console.log(`[${level.toUpperCase()}] ${timestamp}: ${message}`); + + // Store logs in localStorage too + const logs = JSON.parse(localStorage.getItem("system_logs") || "[]"); + logs.push({ timestamp, level, message }); + localStorage.setItem("system_logs", JSON.stringify(logs)); + + // If error, send notification + if (level === "error") { + // Send email notification + this.sendEmailAlert(message); + } + }, + + sendEmailAlert: function (message: string) { + console.log(`Sending email alert: ${message}`); + // Simulate email sending + setTimeout(() => { + console.log("Email sent!"); + }, 1000); + }, + }; + + // Load configuration + let config; + try { + config = JSON.parse(localStorage.getItem("user_system_config") || "{}"); + DEBUG_MODE = config.debugMode || DEBUG_MODE; + this.apiToken = config.apiToken || this.apiToken; + } catch (e) { + this.logger.log("Failed to load configuration", "error"); + } + } + + // Database connection hardcoded + private connectToDatabase() { + this.logger.log("Connecting to database...", "debug"); + + // Simulate database connection + this.db = { + query: function (sql: string, params: any[] = []) { + console.log(`Executing query: ${sql}`); + console.log("Params:", params); + return Promise.resolve({ rows: [], success: true }); + }, + + close: function () { + console.log("Closing database connection"); + }, + }; + + // Log connection info to console in plain text + console.log(`Connected to database with token: ${this.apiToken}`); + + // Save connection timestamp + localStorage.setItem("last_db_connection", new Date().toISOString()); + } + + // UI generation mixed with business logic + public renderUserList(containerId: string) { + const container = document.getElementById(containerId); + if (!container) { + this.logger.log(`Container ${containerId} not found`, "error"); + return; + } + + // Clear container + container.innerHTML = ""; + + // Get users - mixing data fetching and rendering + this.db + .query('SELECT * FROM users WHERE status != "deleted"') + .then((result: any) => { + this.users = result.rows; + + // Generate HTML - UI logic mixed with business logic + let html = '
    '; + this.users.forEach((user) => { + // User status determines CSS class + let statusClass = ""; + switch (user.status) { + case "active": + statusClass = "user-active"; + break; + case "inactive": + statusClass = "user-inactive"; + break; + case "suspended": + statusClass = "user-suspended"; + break; + } + + html += ` +
  • +
    ${user.firstName} ${user.lastName}
    +
    ${user.email}
    + +
  • + `; + }); + html += "
"; + + container.innerHTML = html; + }) + .catch((err: any) => { + this.logger.log(`Failed to fetch users: ${err.message}`, "error"); + container.innerHTML = + "

Failed to load users. Please try again later.

"; + }); + } + + // No validation, directly manipulating UI and data + public createUser(userData: any) { + // Directly create user without validation + this.db + .query( + "INSERT INTO users (firstName, lastName, email, status) VALUES (?, ?, ?, ?)", + [userData.firstName, userData.lastName, userData.email, "active"], + ) + .then((result: any) => { + this.logger.log(`User created: ${userData.email}`, "info"); + + // Update UI directly here + this.renderUserList("user-container"); + + // Update global state + this.lastOperation = "create"; + + // Clear form - direct DOM manipulation + document.getElementById("user-form")?.reset(); + + // Show success message + alert("User created successfully!"); + }) + .catch((err: any) => { + this.logger.log(`Failed to create user: ${err.message}`, "error"); + alert("Failed to create user! " + err.message); + }); + } + + // Logic duplicated for similar operations + public editUser(userId: number) { + // Directly edit UI elements based on user ID + const userElement = document.querySelector(`li[data-id="${userId}"]`); + if (!userElement) { + this.logger.log(`User element not found: ${userId}`, "error"); + return; + } + + // Find user data + const user = this.users.find((u) => u.id === userId); + if (!user) { + this.logger.log(`User not found: ${userId}`, "error"); + return; + } + + // Populate form - direct DOM manipulation + const form = document.getElementById("user-form") as HTMLFormElement; + if (form) { + (form.elements.namedItem("firstName") as HTMLInputElement).value = + user.firstName; + (form.elements.namedItem("lastName") as HTMLInputElement).value = + user.lastName; + (form.elements.namedItem("email") as HTMLInputElement).value = user.email; + (form.elements.namedItem("userId") as HTMLInputElement).value = + String(userId); + + // Scroll to form + form.scrollIntoView({ behavior: "smooth" }); + } + + // Update global state + currentUserID = userId; + this.lastOperation = "edit"; + } + + // Logic duplicated, similar to deleteUser + public suspendUser(userId: number) { + if (!confirm("Are you sure you want to suspend this user?")) { + return; + } + + this.db + .query("UPDATE users SET status = ? WHERE id = ?", ["suspended", userId]) + .then((result: any) => { + this.logger.log(`User suspended: ${userId}`, "info"); + + // Update UI directly + this.renderUserList("user-container"); + + // Update global state + this.lastOperation = "suspend"; + + // Show success message + alert("User suspended successfully!"); + }) + .catch((err: any) => { + this.logger.log(`Failed to suspend user: ${err.message}`, "error"); + alert("Failed to suspend user! " + err.message); + }); + } + + // Nearly identical to suspendUser + public activateUser(userId: number) { + this.db + .query("UPDATE users SET status = ? WHERE id = ?", ["active", userId]) + .then((result: any) => { + this.logger.log(`User activated: ${userId}`, "info"); + + // Update UI directly + this.renderUserList("user-container"); + + // Update global state + this.lastOperation = "activate"; + + // Show success message + alert("User activated successfully!"); + }) + .catch((err: any) => { + this.logger.log(`Failed to activate user: ${err.message}`, "error"); + alert("Failed to activate user! " + err.message); + }); + } + + // Logic duplicated again + public deleteUser(userId: number) { + if (!confirm("Are you sure you want to delete this user?")) { + return; + } + + // Actually just updating status to 'deleted' + this.db + .query("UPDATE users SET status = ? WHERE id = ?", ["deleted", userId]) + .then((result: any) => { + this.logger.log(`User deleted: ${userId}`, "info"); + + // Update UI directly + this.renderUserList("user-container"); + + // Update global state + this.lastOperation = "delete"; + + // Show success message + alert("User deleted successfully!"); + }) + .catch((err: any) => { + this.logger.log(`Failed to delete user: ${err.message}`, "error"); + alert("Failed to delete user! " + err.message); + }); + } + + // Authentication mixed with user management + public login(email: string, password: string) { + // Directly query with credentials + this.db + .query("SELECT * FROM users WHERE email = ? AND password_hash = ?", [ + email, + this.hashPassword(password), + ]) + .then((result: any) => { + if (result.rows.length === 0) { + this.logger.log(`Failed login attempt: ${email}`, "warn"); + alert("Invalid email or password"); + return; + } + + const user = result.rows[0]; + if (user.status !== "active") { + this.logger.log( + `Login attempt from inactive account: ${email}`, + "warn", + ); + alert("Your account is not active"); + return; + } + + // Update global state + currentUserID = user.id; + loggedInUsers.push(user); + this.lastOperation = "login"; + + // Store in localStorage + localStorage.setItem("current_user", JSON.stringify(user)); + + // Redirect to dashboard + window.location.href = "/dashboard.html"; + }) + .catch((err: any) => { + this.logger.log(`Login error: ${err.message}`, "error"); + alert("Login failed! " + err.message); + }); + } + + // Utility function with security implications + private hashPassword(password: string): string { + // Not a real hash, just base64 encoding + return btoa(password); + } + + // Cleanup that's never called + public cleanup() { + this.logger.log("Cleaning up resources", "debug"); + this.db.close(); + this.users = []; + currentUserID = null; + } +} + +// Instantiate globally +const userManager = new UserManager(); + +// Event handlers directly in global scope +function handleUserFormSubmit(event: Event) { + event.preventDefault(); + const form = event.target as HTMLFormElement; + + const userData = { + firstName: (form.elements.namedItem("firstName") as HTMLInputElement).value, + lastName: (form.elements.namedItem("lastName") as HTMLInputElement).value, + email: (form.elements.namedItem("email") as HTMLInputElement).value, + }; + + const userId = (form.elements.namedItem("userId") as HTMLInputElement).value; + + if (userId) { + // Should call an update method, but directly calls the database + userManager.db + .query( + "UPDATE users SET firstName = ?, lastName = ?, email = ? WHERE id = ?", + [userData.firstName, userData.lastName, userData.email, userId], + ) + .then(() => { + alert("User updated successfully!"); + userManager.renderUserList("user-container"); + form.reset(); + (form.elements.namedItem("userId") as HTMLInputElement).value = ""; + }) + .catch((err: any) => { + alert("Failed to update user: " + err.message); + }); + } else { + userManager.createUser(userData); + } +} + +// Global initialization +window.onload = function () { + console.log("Window loaded!"); + + // Set up event listeners + const userForm = document.getElementById("user-form"); + if (userForm) { + userForm.addEventListener("submit", handleUserFormSubmit); + } + + // Initialize user list + userManager.renderUserList("user-container"); + + // Set up some global error handlers + window.onerror = function (msg, url, line) { + userManager.logger.log(`Global error: ${msg} at ${url}:${line}`, "error"); + return false; + }; +}; + +// Global exports +(window as any).userManager = userManager; +(window as any).handleUserFormSubmit = handleUserFormSubmit; diff --git a/manual-testing-sandbox/next-edit/next-edit-9-5-sol.ts b/manual-testing-sandbox/next-edit/next-edit-9-5-sol.ts new file mode 100644 index 000000000..a81e7191a --- /dev/null +++ b/manual-testing-sandbox/next-edit/next-edit-9-5-sol.ts @@ -0,0 +1,654 @@ +// Clean implementation of e-commerce product management system +// Following SOLID principles + +// Types and Interfaces +type ProductStatus = + | "active" + | "inactive" + | "discontinued" + | "out_of_stock" + | "backorder"; +type UserRole = "admin" | "manager" | "staff" | "customer"; + +interface Product { + id: string; + name: string; + price: number; + description: string; + image: string; + category: string; + status: ProductStatus; + created: Date; + createdBy: string; + stock: number; + ratings: any[]; + tags: string[]; + lastModified: Date; + lastModifiedBy?: string; +} + +interface User { + id: string; + username: string; + role: UserRole; +} + +interface CartItem { + productId: string; + quantity: number; + price: number; + name: string; + addedAt: Date; +} + +interface Notification { + type: string; + message: string; + timestamp: Date; +} + +interface LogEntry { + timestamp: string; + action: string; + data: any; + user: string; +} + +interface SearchFilters { + category?: string; + minPrice?: number; + maxPrice?: number; + status?: ProductStatus; +} + +// Database abstraction - Single Responsibility for data persistence +class Database { + private products: Map = new Map(); + private users: Map = new Map(); + private cart: Map = new Map(); + private orders: any[] = []; + private logs: LogEntry[] = []; + private sessions: Map = new Map(); + private config = { taxRate: 0.08, discountThreshold: 1000 }; + + // Product repository methods + getProduct(id: string): Product | undefined { + return this.products.get(id); + } + + saveProduct(product: Product): void { + this.products.set(product.id, product); + } + + removeProduct(id: string): boolean { + return this.products.delete(id); + } + + getAllProducts(): Product[] { + return Array.from(this.products.values()); + } + + // Cart repository methods + getCart(userId: string): CartItem[] { + return this.cart.get(userId) || []; + } + + saveCart(userId: string, cart: CartItem[]): void { + this.cart.set(userId, cart); + } + + // Logging method + addLog(logEntry: LogEntry): void { + this.logs.push(logEntry); + } +} + +// Authentication service - Single Responsibility for user management +class AuthService { + private currentUser: User | null = null; + + constructor(private database: Database) {} + + getCurrentUser(): User | null { + return this.currentUser; + } + + setCurrentUser(user: User): void { + this.currentUser = user; + } + + logout(): void { + this.currentUser = null; + } + + hasPermission(allowedRoles: UserRole[]): boolean { + if (!this.currentUser) return false; + return allowedRoles.includes(this.currentUser.role); + } +} + +// Utility service - Single Responsibility for common functions +class UtilityService { + generateId(prefix: string): string { + return `${prefix}_${Math.random().toString(36).substring(2, 9)}`; + } +} + +// Logger service - Single Responsibility for logging +class LoggingService { + constructor( + private database: Database, + private authService: AuthService, + ) {} + + log(action: string, data: any): void { + const timestamp = new Date().toISOString(); + const logEntry: LogEntry = { + timestamp, + action, + data, + user: this.authService.getCurrentUser()?.username || "system", + }; + + this.database.addLog(logEntry); + console.log(`[${timestamp}] ${action}:`, data); + } +} + +// Notification service - Single Responsibility for notifications +class NotificationService { + private notifications: Notification[] = []; + + addNotification(type: string, message: string): void { + this.notifications.push({ + type, + message, + timestamp: new Date(), + }); + } + + getNotifications(): Notification[] { + return [...this.notifications]; + } +} + +// Email service - Single Responsibility for email communication +class EmailService { + sendEmailToSubscribers( + productName: string, + subject: string, + body: string, + ): void { + console.log(`Sending email about ${productName} to subscribers`); + // Actual email sending logic would go here + } +} + +// Product validation - Single Responsibility for product validation +class ProductValidator { + validate(name: string, price: number): boolean { + return name !== "" && price > 0; + } +} + +// Auth middleware interface - Open/Closed Principle +interface AuthorizationMiddleware { + checkAuthorization(operation: string): boolean; +} + +// Product authorization - Single Responsibility for product auth +class ProductAuthorizationMiddleware implements AuthorizationMiddleware { + constructor(private authService: AuthService) {} + + checkAuthorization(operation: string): boolean { + const currentUser = this.authService.getCurrentUser(); + if (!currentUser) return false; + + switch (operation) { + case "create": + case "update": + return this.authService.hasPermission(["admin", "manager"]); + case "delete": + return this.authService.hasPermission(["admin"]); + case "view": + return true; + default: + return false; + } + } +} + +// Product service - Core business logic with proper separation of concerns +class ProductService { + constructor( + private database: Database, + private utilityService: UtilityService, + private loggingService: LoggingService, + private notificationService: NotificationService, + private emailService: EmailService, + private validator: ProductValidator, + private authMiddleware: AuthorizationMiddleware, + ) {} + + createProduct( + name: string, + price: number, + description: string, + image: string, + category: string, + initialStock: number = 100, + ): string { + // Authorization check + if (!this.authMiddleware.checkAuthorization("create")) { + throw new Error("Unauthorized access"); + } + + // Validation + if (!this.validator.validate(name, price)) { + throw new Error("Invalid product data"); + } + + const currentUser = this.database.getUsers()[0]; // This is a placeholder - we'd use proper auth in a real app + const id = this.utilityService.generateId("prod"); + const tags = category.split(",").map((t) => t.trim()); + + // Create product object + const product: Product = { + id, + name, + price, + description, + image, + category, + status: "active" as ProductStatus, + created: new Date(), + createdBy: currentUser.id, + stock: initialStock, + ratings: [], + tags, + lastModified: new Date(), + }; + + // Save to database + this.database.saveProduct(product); + + // Logging + this.loggingService.log("product_added", { id, name, price }); + + // Notification + this.notificationService.addNotification( + "product_added", + `New product added: ${name}`, + ); + + return id; + } + + updateProduct(id: string, data: Partial): Product { + // Authorization check + if (!this.authMiddleware.checkAuthorization("update")) { + throw new Error("Unauthorized access"); + } + + const product = this.database.getProduct(id); + if (!product) { + throw new Error("Product not found"); + } + + // Create updated product - preventing modification of protected fields + const updatedProduct = { ...product }; + + Object.keys(data).forEach((key) => { + if (key !== "id" && key !== "created" && key !== "createdBy") { + updatedProduct[key as keyof Product] = data[ + key as keyof Product + ] as any; + } + }); + + const currentUser = this.database.getUsers()[0]; // Placeholder + updatedProduct.lastModified = new Date(); + updatedProduct.lastModifiedBy = currentUser.id; + + // Save to database + this.database.saveProduct(updatedProduct); + + // Logging + this.loggingService.log("product_updated", { id, changes: data }); + + // Notification + this.notificationService.addNotification( + "product_updated", + `Product updated: ${updatedProduct.name}`, + ); + + // Handle special status changes + if (data.status === "discontinued") { + this.emailService.sendEmailToSubscribers( + updatedProduct.name, + "Product Discontinued", + `The product ${updatedProduct.name} has been discontinued.`, + ); + } + + return updatedProduct; + } + + deleteProduct(id: string): boolean { + // Authorization check + if (!this.authMiddleware.checkAuthorization("delete")) { + throw new Error("Unauthorized access"); + } + + const product = this.database.getProduct(id); + if (!product) { + throw new Error("Product not found"); + } + + // Business rule validation + if (product.status === "active" && product.stock > 0) { + throw new Error("Cannot delete active product with stock"); + } + + // Delete from database + const result = this.database.removeProduct(id); + + // Logging + this.loggingService.log("product_deleted", { id, name: product.name }); + + // Notification + this.notificationService.addNotification( + "product_deleted", + `Product deleted: ${product.name}`, + ); + + return result; + } + + searchProducts(query: string, filters: SearchFilters = {}): Product[] { + const products = this.database.getAllProducts(); + const results = products.filter((product) => { + // Match text search + const matches = + product.name.toLowerCase().includes(query.toLowerCase()) || + product.description.toLowerCase().includes(query.toLowerCase()); + + if (!matches) return false; + + // Apply filters + if (filters.category && product.category !== filters.category) { + return false; + } + + if (filters.minPrice && product.price < filters.minPrice) { + return false; + } + + if (filters.maxPrice && product.price > filters.maxPrice) { + return false; + } + + if (filters.status && product.status !== filters.status) { + return false; + } + + return true; + }); + + // Log search results + this.loggingService.log("product_search", { + query, + filters, + resultCount: results.length, + }); + + return results; + } +} + +// Cart service - Single Responsibility for shopping cart functionality +class CartService { + constructor( + private database: Database, + private authService: AuthService, + private loggingService: LoggingService, + ) {} + + addToCart(productId: string, quantity: number = 1): CartItem[] { + const currentUser = this.authService.getCurrentUser(); + if (!currentUser) { + throw new Error("Must be logged in to add to cart"); + } + + const product = this.database.getProduct(productId); + if (!product) { + throw new Error("Product not found"); + } + + if (product.status !== "active") { + throw new Error("Product is not available"); + } + + if (product.stock < quantity) { + throw new Error("Not enough stock"); + } + + // Get current cart + const cart = this.database.getCart(currentUser.id); + + // Update or add item + const existingItemIndex = cart.findIndex( + (item) => item.productId === productId, + ); + + if (existingItemIndex >= 0) { + cart[existingItemIndex].quantity += quantity; + } else { + cart.push({ + productId, + quantity, + price: product.price, + name: product.name, + addedAt: new Date(), + }); + } + + // Update product stock + product.stock -= quantity; + this.database.saveProduct(product); + + // Save cart + this.database.saveCart(currentUser.id, cart); + + // Log action + this.loggingService.log("cart_add", { + productId, + quantity, + userId: currentUser.id, + }); + + return cart; + } +} + +// Service Factory - Creates and wires up the services +class ServiceFactory { + static createProductService(): ProductService { + const database = new Database(); + const authService = new AuthService(database); + const utilityService = new UtilityService(); + const loggingService = new LoggingService(database, authService); + const notificationService = new NotificationService(); + const emailService = new EmailService(); + const productValidator = new ProductValidator(); + const authMiddleware = new ProductAuthorizationMiddleware(authService); + + return new ProductService( + database, + utilityService, + loggingService, + notificationService, + emailService, + productValidator, + authMiddleware, + ); + } + + static createCartService(): CartService { + const database = new Database(); + const authService = new AuthService(database); + const loggingService = new LoggingService(database, authService); + + return new CartService(database, authService, loggingService); + } +} + +// Example usage: +/* +const productService = ServiceFactory.createProductService(); +const cartService = ServiceFactory.createCartService(); + +// Create a product +const productId = productService.createProduct( + 'Gaming Laptop', + 1299.99, + 'High performance gaming laptop', + 'laptop.jpg', + 'Electronics,Computers', + 100 +); + +// Add to cart +cartService.addToCart(productId, 2); +*/ + +/* +Original Code Smells: + +Violation of Single Responsibility Principle (SRP) + +ProductManager class handles product management, cart operations, email sending, UI updates, and analytics +Database operations, validation, logging, and notifications are all mixed together + + +Violation of Open/Closed Principle (OCP) + +Code is not structured to be easily extended without modification +Hard-coded business rules and functionality + + +Poor Encapsulation + +Global variables (DATABASE, CURRENT_USER, NOTIFICATIONS) +Direct manipulation of shared state + + +Tight Coupling + +Business logic directly depends on UI elements (document, window) +Authentication checks embedded in business methods + + +Singleton Anti-pattern Misuse + +Incorrect implementation of the Singleton pattern + + +Lack of Proper Interfaces and Abstraction + +No clear contracts between components +No separation between data access and business logic + + +Code Duplication + +Authentication checks duplicated across methods +Notification and logging logic repeated + + +Poor Error Handling + +Inconsistent error handling +Mixed validation with business operations + + +UI Manipulation in Business Logic + +Direct DOM manipulation in product methods + + +Hard-coded Values + +Default stock values +Business rules embedded in methods + + +Improvements Made: + +Applied Single Responsibility Principle (SRP) + +Created separate classes for distinct responsibilities: +Database for data storage +AuthService for authentication +LoggingService for logging +NotificationService for notifications +EmailService for email communication +ProductService for product business logic +CartService for cart operations +ProductValidator for validation +UtilityService for utility functions + + +Applied Open/Closed Principle (OCP) + +Used interfaces for extensibility (e.g., AuthorizationMiddleware) +Created classes that can be extended without modifying existing code + + +Applied Interface Segregation Principle (ISP) + +Created focused interfaces for different functionalities +Ensured clients only depend on methods they use + + +Applied Dependency Inversion Principle (DIP) + +High-level modules depend on abstractions +Used dependency injection to provide implementations + + +Proper Encapsulation + +Removed global variables +Encapsulated state within appropriate classes + + +Reduced Coupling + +Removed direct UI manipulation from business logic +Used dependency injection for loosely coupled components + + +Implemented Factory Pattern + +Added ServiceFactory to create and wire up services +Simplified client code by hiding implementation details + + +Added Type Safety + +Created proper interfaces for data structures +Used TypeScript types effectively + + +Improved Error Handling + +Consistent error checking across methods +Validation separated from business logic + + +Removed Code Duplication + +Centralized authentication checks +Reused code through proper abstraction +*/ diff --git a/manual-testing-sandbox/next-edit/next-edit-9-5.ts b/manual-testing-sandbox/next-edit/next-edit-9-5.ts new file mode 100644 index 000000000..9520b2c8e --- /dev/null +++ b/manual-testing-sandbox/next-edit/next-edit-9-5.ts @@ -0,0 +1,302 @@ +// A messy e-commerce product management system with tangled responsibilities +// Difficulty: 5/5 + +type ProductStatus = + | "active" + | "inactive" + | "discontinued" + | "out_of_stock" + | "backorder"; +type UserRole = "admin" | "manager" | "staff" | "customer"; +let DATABASE: any = { + products: new Map(), + users: new Map(), + cart: new Map(), + orders: [], + logs: [], + sessions: new Map(), + config: { taxRate: 0.08, discountThreshold: 1000 }, +}; +let CURRENT_USER: any = null; +let NOTIFICATIONS: any[] = []; + +// Global function to generate IDs (mixes concerns and not encapsulated) +function generateId(prefix: string) { + return `${prefix}_${Math.random().toString(36).substring(2, 9)}`; +} + +// Global function for logging (mixed with business logic) +function log(action: string, data: any) { + const timestamp = new Date().toISOString(); + DATABASE.logs.push({ + timestamp, + action, + data, + user: CURRENT_USER?.username || "system", + }); + console.log(`[${timestamp}] ${action}:`, data); +} + +class ProductManager { + // This class does way too much - violates SRP + static instance: ProductManager; + private constructor() {} + + // Singleton pattern used incorrectly + static getInstance() { + if (!ProductManager.instance) { + ProductManager.instance = new ProductManager(); + } + return ProductManager.instance; + } + + addProduct( + name: string, + price: number, + desc: string, + img: string, + category: string, + ) { + // Validation mixed with business logic + if (!name || price <= 0) { + throw new Error("Invalid product data"); + } + + // Authentication check shouldn't be here + if ( + !CURRENT_USER || + (CURRENT_USER.role !== "admin" && CURRENT_USER.role !== "manager") + ) { + throw new Error("Unauthorized access"); + } + + const id = generateId("prod"); + + // Direct database manipulation and notification logic mixed together + DATABASE.products.set(id, { + id, + name, + price, + description: desc, + image: img, + category, + status: "active", + created: new Date(), + createdBy: CURRENT_USER.id, + stock: 100, // Default hardcoded + ratings: [], + tags: category.split(",").map((t: string) => t.trim()), + lastModified: new Date(), + }); + + // Notification logic should be separated + NOTIFICATIONS.push({ + type: "product_added", + message: `New product added: ${name}`, + timestamp: new Date(), + }); + + // Logging should be a cross-cutting concern + log("product_added", { id, name, price }); + + // UI manipulation mixed with business logic + if (document) { + const productList = document.getElementById("product-list"); + if (productList) { + const productEl = document.createElement("div"); + productEl.innerHTML = `
${name} - $${price}
`; + productList.appendChild(productEl); + } + } + + // Analytics tracking mixed in with product creation + if (window) { + try { + (window as any).ga("send", "event", "Products", "Create", name); + } catch (e) { + console.error("Analytics error", e); + } + } + + return id; + } + + updateProduct(id: string, data: any) { + if (!DATABASE.products.has(id)) { + throw new Error("Product not found"); + } + + // Authentication check duplicated + if ( + !CURRENT_USER || + (CURRENT_USER.role !== "admin" && CURRENT_USER.role !== "manager") + ) { + throw new Error("Unauthorized access"); + } + + const product = DATABASE.products.get(id); + + // Updating with direct object manipulation + Object.keys(data).forEach((key) => { + if (key !== "id" && key !== "created" && key !== "createdBy") { + product[key] = data[key]; + } + }); + + product.lastModified = new Date(); + product.lastModifiedBy = CURRENT_USER.id; + + DATABASE.products.set(id, product); + + // More mixed responsibilities + log("product_updated", { id, changes: data }); + + // Duplicated notification logic + NOTIFICATIONS.push({ + type: "product_updated", + message: `Product updated: ${product.name}`, + timestamp: new Date(), + }); + + // Email notification logic mixed in + if (product.status === "discontinued") { + this.sendEmailToSubscribers( + product.id, + "Product Discontinued", + `The product ${product.name} has been discontinued.`, + ); + } + + return product; + } + + deleteProduct(id: string) { + // More authentication mixed in business logic + if (!CURRENT_USER || CURRENT_USER.role !== "admin") { + throw new Error("Only admins can delete products"); + } + + if (!DATABASE.products.has(id)) { + throw new Error("Product not found"); + } + + const product = DATABASE.products.get(id); + + // Business rules mixed with deletion logic + if (product.status === "active" && product.stock > 0) { + throw new Error("Cannot delete active product with stock"); + } + + // More mixed concerns + log("product_deleted", { id, name: product.name }); + NOTIFICATIONS.push({ + type: "product_deleted", + message: `Product deleted: ${product.name}`, + timestamp: new Date(), + }); + + DATABASE.products.delete(id); + + // Cache clearing mixed with business logic + if (window && (window as any).cache) { + (window as any).cache.invalidate("products"); + } + + return true; + } + + // Email functionality mixed in the product manager + sendEmailToSubscribers(productId: string, subject: string, body: string) { + const product = DATABASE.products.get(productId); + if (!product) return; + + // Email sending logic mixed with product management + console.log(`Sending email about ${product.name} to subscribers`); + // Imagine API call to email service here + } + + // Search functionality mixed in the same class + searchProducts(query: string, filters: any = {}) { + let results: any[] = []; + + DATABASE.products.forEach((product: any) => { + let matches = + product.name.toLowerCase().includes(query.toLowerCase()) || + product.description.toLowerCase().includes(query.toLowerCase()); + + if (!matches) return; + + // Filter logic mixed in search + if (filters.category && product.category !== filters.category) { + return; + } + + if (filters.minPrice && product.price < filters.minPrice) { + return; + } + + if (filters.maxPrice && product.price > filters.maxPrice) { + return; + } + + if (filters.status && product.status !== filters.status) { + return; + } + + results.push({ ...product }); + }); + + // Logging mixed with search functionality + log("product_search", { query, filters, resultCount: results.length }); + + return results; + } + + // Cart functionality shouldn't be in product manager + addToCart(productId: string, quantity: number = 1) { + if (!CURRENT_USER) { + throw new Error("Must be logged in to add to cart"); + } + + const product = DATABASE.products.get(productId); + if (!product) { + throw new Error("Product not found"); + } + + if (product.status !== "active") { + throw new Error("Product is not available"); + } + + if (product.stock < quantity) { + throw new Error("Not enough stock"); + } + + let cart = DATABASE.cart.get(CURRENT_USER.id) || []; + const existingItem = cart.find((item: any) => item.productId === productId); + + if (existingItem) { + existingItem.quantity += quantity; + } else { + cart.push({ + productId, + quantity, + price: product.price, + name: product.name, + addedAt: new Date(), + }); + } + + DATABASE.cart.set(CURRENT_USER.id, cart); + product.stock -= quantity; + DATABASE.products.set(productId, product); + + log("cart_add", { productId, quantity, userId: CURRENT_USER.id }); + + return cart; + } +} + +// Usage would be something like: +// const pm = ProductManager.getInstance(); +// pm.addProduct('Gaming Laptop', 1299.99, 'High performance gaming laptop', 'laptop.jpg', 'Electronics,Computers'); +// pm.addToCart('prod_1abc123', 2); From 42072288e8535d6eeb96dfc75212ea41d8088c54 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 24 Jun 2025 18:15:48 -0700 Subject: [PATCH 099/100] rename option --- gui/src/pages/config/ContinueFeaturesMenu.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/pages/config/ContinueFeaturesMenu.tsx b/gui/src/pages/config/ContinueFeaturesMenu.tsx index b84286a28..b1810e23b 100644 --- a/gui/src/pages/config/ContinueFeaturesMenu.tsx +++ b/gui/src/pages/config/ContinueFeaturesMenu.tsx @@ -54,7 +54,7 @@ export function ContinueFeaturesMenu({ handleOptInToggle(!optInNextEditFeature)} - text="Opt In to Special Feature" + text="Enable Next Edit Over Autocomplete" />
From 1928250f11e5a798e49276ee881eaf519079c2b7 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 24 Jun 2025 18:22:54 -0700 Subject: [PATCH 100/100] add unified diff to context --- core/core.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/core/core.ts b/core/core.ts index cce8a1b7d..cdd27a5af 100644 --- a/core/core.ts +++ b/core/core.ts @@ -68,8 +68,13 @@ import { walkDirCache } from "./indexing/walkDir"; import { LLMLogger } from "./llm/logger"; import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants"; import { llmStreamChat } from "./llm/streamChat"; -import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting"; +import { + BeforeAfterDiff, + createDiff, + DiffFormatType, +} from "./nextEdit/context/diffFormatting"; import { processNextEditData } from "./nextEdit/context/processNextEditData.js"; +import { NextEditProvider } from "./nextEdit/NextEditProvider"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { OnboardingModes } from "./protocol/core"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -723,6 +728,15 @@ export class Core { cursorPosBeforeEdit: Position, cursorPosAfterPrevEdit: Position, ) => { + NextEditProvider.getInstance().addDiffToContext( + createDiff( + beforeAfterdiff.beforeContent, + beforeAfterdiff.afterContent, + beforeAfterdiff.filePath, + DiffFormatType.Unified, + ), + ); + // Get the current context data from the most recent message const currentData = (global._editAggregator as any) .latestContextData || {