Merge branch 'main' of github.com:continuedev/continue into jacob/feature/next-edit-mvp

This commit is contained in:
Jacob Kim 2025-06-24 16:23:05 -07:00
commit 8ae5b4e06f
30 changed files with 1063 additions and 443 deletions

View file

@ -75,6 +75,33 @@ jobs:
cd packages/config-yaml
npm ci
install-openai-adapters:
needs: install-root
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Install openai-adapters dependencies
if: steps.openai-adapters-cache.outputs.cache-hit != 'true'
run: |
cd packages/openai-adapters
npm ci
config-yaml-checks:
needs: install-config-yaml
runs-on: ubuntu-latest
@ -133,7 +160,7 @@ jobs:
npm ci
core-checks:
needs: [install-core, install-config-yaml]
needs: [install-core, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -160,11 +187,21 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Type check and lint
run: |
cd core
@ -174,7 +211,8 @@ jobs:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
install-gui:
needs: [install-root, install-core, install-config-yaml]
needs:
[install-root, install-core, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -205,11 +243,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Install gui dependencies
if: steps.gui-cache.outputs.cache-hit != 'true'
run: |
@ -221,7 +270,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -242,6 +290,12 @@ jobs:
path: gui/node_modules
key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
@ -253,6 +307,11 @@ jobs:
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Type check and lint
run: |
cd gui
@ -260,7 +319,8 @@ jobs:
npm run lint
binary-checks:
needs: [install-root, install-core, install-config-yaml]
needs:
[install-root, install-core, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -291,11 +351,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Install binary dependencies
if: steps.binary-cache.outputs.cache-hit != 'true'
run: |
@ -308,7 +379,8 @@ jobs:
npx tsc --noEmit
install-vscode:
needs: [install-root, install-core, install-config-yaml]
needs:
[install-root, install-core, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -339,11 +411,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Install vscode dependencies
if: steps.vscode-cache.outputs.cache-hit != 'true'
run: |
@ -384,11 +467,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Type check and lint
run: |
cd extensions/vscode
@ -402,7 +496,7 @@ jobs:
npm run vitest
core-tests:
needs: [install-core, install-config-yaml]
needs: [install-core, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -422,11 +516,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Run core tests
run: |
cd core
@ -476,7 +581,7 @@ jobs:
- uses: actions/checkout@v4
- name: Cache node modules
uses: actions/cache@v3
uses: actions/cache@v4
with:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
@ -515,7 +620,13 @@ jobs:
vscode-package-extension:
runs-on: ubuntu-latest
needs: [install-vscode, install-core, install-config-yaml]
needs:
[
install-vscode,
install-core,
install-config-yaml,
install-openai-adapters,
]
steps:
- uses: actions/checkout@v4
@ -541,11 +652,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Package extension
run: |
cd extensions/vscode
@ -559,7 +681,13 @@ jobs:
vscode-download-e2e-dependencies:
runs-on: ubuntu-latest
needs: [install-vscode, install-core, install-config-yaml]
needs:
[
install-vscode,
install-core,
install-config-yaml,
install-openai-adapters,
]
steps:
- uses: actions/checkout@v4
@ -612,6 +740,7 @@ jobs:
install-vscode,
install-core,
install-config-yaml,
install-openai-adapters,
]
runs-on: ubuntu-latest
# Tests requiring secrets need approval from maintainers
@ -658,11 +787,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Fix VSCode binary permissions
run: |
chmod +x extensions/vscode/e2e/storage/VSCode-linux-x64/code
@ -726,7 +866,8 @@ jobs:
path: extensions/vscode/e2e.log
gui-tests:
needs: [install-gui, install-core, install-config-yaml]
needs:
[install-gui, install-core, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -752,11 +893,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Install GUI dependencies
if: steps.gui-cache.outputs.cache-hit != 'true'
run: cd gui && npm ci
@ -769,7 +921,8 @@ jobs:
npm test
jetbrains-tests:
needs: [install-root, core-checks, install-config-yaml]
needs:
[install-root, core-checks, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -784,11 +937,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Setup Java
uses: actions/setup-java@v4.5.0
with:
@ -903,6 +1067,7 @@ jobs:
- jetbrains-tests
- config-yaml-checks
- install-config-yaml
- install-openai-adapters
steps:
- name: Decide whether the needed jobs succeeded or failed

View file

@ -292,6 +292,7 @@ export abstract class BaseLLM implements ILLM {
apiKey: this.apiKey ?? "",
apiBase: this.apiBase,
requestOptions: this.requestOptions,
env: this._llmOptions.env,
});
}

View file

@ -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<string, string> = {
"Content-Type": "application/json",

65
core/package-lock.json generated
View file

@ -14,9 +14,9 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.13",
"@continuedev/fetch": "^1.0.14",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.32",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -141,7 +141,7 @@
},
"../packages/config-yaml": {
"name": "@continuedev/config-yaml",
"version": "1.0.92",
"version": "1.0.94",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
@ -161,6 +161,30 @@
"zod-to-json-schema": "^3.24.5"
}
},
"../packages/openai-adapters": {
"name": "@continuedev/openai-adapters",
"version": "1.0.40",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.5",
"@continuedev/config-yaml": "^1.0.51",
"@continuedev/fetch": "^1.0.11",
"dotenv": "^16.5.0",
"json-schema": "^0.4.0",
"node-fetch": "^3.3.2",
"openai": "^4.76.0",
"uuid": "^11.1.0",
"zod": "^3.24.2"
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.14",
"@types/json-schema": "^7.0.15",
"cross-env": "^7.0.3",
"ts-jest": "^29.2.3",
"ts-node": "^10.9.2"
}
},
"node_modules/@75lb/deep-merge": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz",
@ -2885,9 +2909,10 @@
"link": true
},
"node_modules/@continuedev/fetch": {
"version": "1.0.13",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.13.tgz",
"integrity": "sha512-7vwsefFBozsutv355zD7mEhFfl6UT4KXRH1QXRzjdbCaYneiRdFLe6UAwV2wGnH71Lj76gOLnTlcGoTV357OZg==",
"version": "1.0.14",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.14.tgz",
"integrity": "sha512-r/CUwW0tt7VrjLVNeowA281aq7VQvToE+Ro9+0EhfINBMNre4eU2MbNOgbRmYCr5VkIuSnltPUDI357Kns7uCw==",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.5",
"follow-redirects": "^1.15.6",
@ -2902,32 +2927,8 @@
"integrity": "sha512-/htL7p4li3zQSwn9bXkI23WRpZNklWTPzRSSG3Fd5gvYW8cizjhlf7OzeDdKxBfi1S0lpqMm0VwHlx3KjMKLpw=="
},
"node_modules/@continuedev/openai-adapters": {
"version": "1.0.32",
"resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.32.tgz",
"integrity": "sha512-teNzbpcsa7Y0eBk+dxlLDo0m43sWI5txTYMIk6ezyS0cZAKFJODDB0Gkp3aEHXbD8mDE7H5dDSlM23ohKCirAA==",
"dependencies": {
"@continuedev/config-types": "^1.0.5",
"@continuedev/config-yaml": "^1.0.51",
"@continuedev/fetch": "^1.0.11",
"dotenv": "^16.5.0",
"json-schema": "^0.4.0",
"node-fetch": "^3.3.2",
"openai": "^4.76.0",
"uuid": "^11.1.0",
"zod": "^3.24.2"
}
},
"node_modules/@continuedev/openai-adapters/node_modules/uuid": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz",
"integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"bin": {
"uuid": "dist/esm/bin/uuid"
}
"resolved": "../packages/openai-adapters",
"link": true
},
"node_modules/@dabh/diagnostics": {
"version": "2.0.3",

View file

@ -52,9 +52,9 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.13",
"@continuedev/fetch": "^1.0.14",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.32",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",

View file

@ -16,7 +16,7 @@ export const createRuleBlock: Tool = {
'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.',
parameters: {
type: "object",
required: ["name", "rule", "alwaysApply", "description"],
required: ["name", "rule", "description"],
properties: {
name: {
type: "string",

View file

@ -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",
{

18
docs/package-lock.json generated
View file

@ -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",

View file

@ -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",

View file

@ -110,7 +110,7 @@
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.13",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.32",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",

2
gui/package-lock.json generated
View file

@ -115,7 +115,7 @@
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.13",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.32",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",

View file

@ -1,7 +1,4 @@
import { ArrowPathIcon } from "@heroicons/react/24/outline";
import { useState } from "react";
import { useAuth } from "../../context/Auth";
import { cn } from "../../util/cn";
import { AssistantOption } from "./AssistantOption";
interface AssistantOptionsProps {
@ -13,30 +10,13 @@ export function AssistantOptions({
selectedProfileId,
onClose,
}: AssistantOptionsProps) {
const [loading, setLoading] = useState(false);
const { profiles, refreshProfiles } = useAuth();
const { profiles } = useAuth();
return (
<>
{/* Assistants Section Header */}
<div className="flex gap-1.5 px-3 pb-1 pt-2">
<label className="text-vsc-foreground font-semibold">Assistants</label>
<div
className="flex cursor-pointer flex-row items-center gap-1 hover:brightness-125"
onClick={async (e) => {
e.stopPropagation();
setLoading(true);
await refreshProfiles();
setLoading(false);
}}
>
<ArrowPathIcon
className={cn(
"text-description h-2.5 w-2.5",
loading && "animate-spin-slow",
)}
/>
</div>
<div className="flex cursor-pointer flex-row items-center gap-1 hover:brightness-125"></div>
</div>
<div className="thin-scrollbar flex max-h-[300px] flex-col overflow-y-auto">

View file

@ -1,6 +1,9 @@
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import { ArrowPathIcon } from "@heroicons/react/24/solid";
import type { ProfileDescription } from "core/config/ConfigHandler";
import { useAppSelector } from "../../redux/hooks";
import { fontSize } from "../../util";
import { cn } from "../../util/cn";
import { useLump } from "../mainInput/Lump/LumpContext";
import { ListboxButton } from "../ui";
import { AssistantIcon } from "./AssistantIcon";
@ -13,6 +16,8 @@ export function SelectedAssistantButton({
selectedProfile,
}: SelectedAssistantButtonProps) {
const { isToolbarExpanded } = useLump();
const configLoading = useAppSelector((store) => store.config.loading);
return (
<ListboxButton
data-testid="assistant-select-button"
@ -20,14 +25,28 @@ export function SelectedAssistantButton({
style={{ fontSize: fontSize(-3) }}
>
<div className="flex flex-row items-center gap-1.5">
<div className="h-3 w-3 flex-shrink-0 select-none">
<AssistantIcon size={3} assistant={selectedProfile} />
</div>
<span
className={`line-clamp-1 select-none break-all ${isToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
>
{selectedProfile.title}
</span>
{configLoading ? (
<span className="text-description flex flex-row items-center">
<ArrowPathIcon
className={cn(
"text-description mr-1.5 h-3 w-3",
configLoading && "animate-spin-slow",
)}
/>
Loading
</span>
) : (
<>
<div className="h-3 w-3 flex-shrink-0 select-none">
<AssistantIcon size={3} assistant={selectedProfile} />
</div>
<span
className={`line-clamp-1 select-none break-all ${isToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
>
{selectedProfile.title}
</span>
</>
)}
</div>
<ChevronDownIcon
className="h-2 w-2 flex-shrink-0 select-none"

View file

@ -1,4 +1,4 @@
import { PlusIcon } from "@heroicons/react/24/outline";
import { ArrowPathIcon, PlusIcon } from "@heroicons/react/24/outline";
import { isOnPremSession } from "core/control-plane/AuthTypes";
import { useContext, useEffect, useRef } from "react";
import { useAuth } from "../../context/Auth";
@ -9,6 +9,7 @@ import {
setSelectedProfile,
} from "../../redux/slices/profilesSlice";
import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
import { cn } from "../../util/cn";
import { useLump } from "../mainInput/Lump/LumpContext";
import {
Listbox,
@ -28,8 +29,15 @@ export function AssistantAndOrgListbox() {
const currentOrg = useAppSelector(selectCurrentOrg);
const ideMessenger = useContext(IdeMessengerContext);
const { isToolbarExpanded } = useLump();
const { profiles, selectedProfile, session, login, organizations } =
useAuth();
const {
profiles,
selectedProfile,
session,
login,
organizations,
refreshProfiles,
} = useAuth();
const configLoading = useAppSelector((store) => store.config.loading);
const smallFont = useFontSize(-3);
const tinyFont = useFontSize(-4);
const shouldRenderOrgInfo =
@ -152,6 +160,30 @@ export function AssistantAndOrgListbox() {
</span>
</ListboxOption>
<ListboxOption
value="new-assistant"
fontSizeModifier={-2}
className="border-border border-b px-2 py-1.5"
onClick={session ? onNewAssistant : () => login(false)}
>
<span
className="text-description flex flex-row items-center"
style={{ fontSize: tinyFont }}
onClick={async (e) => {
e.stopPropagation();
await refreshProfiles();
}}
>
<ArrowPathIcon
className={cn(
"mr-1 h-3 w-3",
configLoading && "animate-spin-slow",
)}
/>
Reload config
</span>
</ListboxOption>
<AccountOption onClose={close} />
<div

View file

@ -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 (
<Listbox>
<div className="relative">
@ -134,15 +144,7 @@ export default function FreeTrialButton({
)}
<div className="mt-4 flex gap-2">
<SecondaryButton
className="flex-1"
onClick={async () => {
await ideMessenger.request("controlPlane/openUrl", {
path: "setup-models",
orgSlug: undefined,
});
}}
>
<SecondaryButton className="flex-1" onClick={onExitFreeTrial}>
Exit trial
</SecondaryButton>
<Button

View file

@ -24,6 +24,7 @@ import { ToolsSectionTooltip } from "../sections/tool-policies/ToolPoliciesSecti
import { usesFreeTrialApiKey } from "core/config/usesFreeTrialApiKey";
import type { FreeTrialStatus } from "core/control-plane/client";
import { getLocalStorage } from "../../../../util/localStorage";
import { AssistantAndOrgListbox } from "../../../AssistantAndOrgListbox";
interface BlockSettingsToolbarIcon {
@ -151,7 +152,8 @@ export function BlockSettingsTopToolbar() {
const [freeTrialStatus, setFreeTrialStatus] =
useState<FreeTrialStatus | null>(null);
const isUsingFreeTrial = usesFreeTrialApiKey(config);
const hasExitedFreeTrial = getLocalStorage("hasExitedFreeTrial");
const isUsingFreeTrial = usesFreeTrialApiKey(config) && !hasExitedFreeTrial;
useEffect(() => {
const fetchFreeTrialStatus = () => {

View file

@ -12,6 +12,7 @@ import React, {
} from "react";
import { useWebviewListener } from "../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import { setConfigLoading } from "../redux/slices/configSlice";
import {
selectCurrentOrg,
selectSelectedProfile,
@ -94,17 +95,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]);

View file

@ -5,7 +5,7 @@ import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
import { FromCoreProtocol } from "core/protocol";
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,
@ -100,6 +100,7 @@ function ParallelListeners() {
const initialLoadAuthAndConfig = useCallback(
async (initial: boolean) => {
dispatch(setConfigLoading(true));
const result = await ideMessenger.request(
"config/getSerializedProfileInfo",
undefined,
@ -107,6 +108,7 @@ function ParallelListeners() {
if (result.status === "success") {
await handleConfigUpdate(initial, result.content);
}
dispatch(setConfigLoading(false));
},
[ideMessenger, handleConfigUpdate],
);

View file

@ -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<boolean>) => {
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,

View file

@ -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<void, undefined, ThunkApiType>(
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<void, undefined, ThunkApiType>(
);
}
// 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(

View file

@ -16,11 +16,13 @@ type LocalStorageTypes = {
showTutorialCard: boolean;
shownProfilesIntroduction: boolean;
disableIndexing: boolean;
hasExitedFreeTrial: boolean;
};
export enum LocalStorageKey {
IsExploreDialogOpen = "isExploreDialogOpen",
HasDismissedExploreDialog = "hasDismissedExploreDialog",
HasExitedFreeTrial = "hasExitedFreeTrial",
}
export function getLocalStorage<T extends keyof LocalStorageTypes>(

View file

@ -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",

View file

@ -0,0 +1,187 @@
import * as fs from "node:fs";
import { beforeEach, expect, test, vi } from "vitest";
import { CertsCache, 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);
});
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([]);
});

129
packages/fetch/src/certs.ts Normal file
View file

@ -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:[<mediatype>][;base64],<data>
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<string, string> = 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<string | undefined> {
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<string[]> {
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<string[]> {
if (!caBundlePath) {
return this.fixedCa;
}
const customCerts = await this.getAllCachedCustomCerts(caBundlePath);
return [...this.fixedCa, ...customCerts];
}
async clear(): Promise<void> {
this._customCerts.clear();
this._initialized = false;
this._fixedCa = [];
}
}

View file

@ -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();
});

View file

@ -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;
@ -89,18 +89,13 @@ 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;
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 =
requestOptions?.noProxy?.includes(url.hostname) ||
shouldBypassProxy(url.hostname);
const shouldBypass = shouldBypassProxy(url.hostname, requestOptions);
// Create agent
const protocol = url.protocol === "https:" ? https : http;

View file

@ -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:[<mediatype>][;base64],<data>
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);
});

View file

@ -1,56 +1,19 @@
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:[<mediatype>][;base64],<data>
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 certsCache = CertsCache.getInstance();
const ca = await certsCache.getCa(requestOptions?.caBundlePath);
const agentOptions: { [key: string]: any } = {
ca,
@ -73,5 +36,21 @@ export function getAgentOptions(requestOptions?: RequestOptions): {
}
}
if (process.env.VERBOSE_FETCH) {
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"}`,
);
console.log(
`\trejectUnauthorized/verifySsl: ${agentOptions.rejectUnauthorized ?? "not set (defaults to true)"}`,
);
}
return agentOptions;
}

View file

@ -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);
});

View file

@ -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,91 @@ 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) {
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.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)) {
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),
);
}