Repository navigation
Feat: PAC Support - #7633
Feat: PAC Support#7633Pragadesh-45 wants to merge 6 commits into
Conversation
✅ Snyk checks have passed. No issues have been found so far.
💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse. |
WalkthroughThis PR introduces PAC (Proxy Auto-Config) support to Bruno. Users can now select a PAC proxy mode, provide a PAC URL, and the application automatically resolves proxy directives per-request using QuickJS-based PAC parsing, with built-in caching and LRU eviction. Changes
Sequence DiagramsequenceDiagram
actor User
participant UI as ProxySettings UI
participant AxiosInstance as Axios Instance
participant ProxyUtil as Proxy Utility
participant PACResolver as PAC Resolver
participant QuickJS as QuickJS WASM
participant HTTPServer as PAC HTTP Server
User->>UI: Configure PAC URL
UI->>UI: Validate & Save
rect rgba(100, 150, 200, 0.5)
note over AxiosInstance,PACResolver: On Request
AxiosInstance->>ProxyUtil: setupProxyAgents(mode: 'pac', pacUrl)
activate ProxyUtil
ProxyUtil->>PACResolver: getPacResolver({pacUrl})
activate PACResolver
PACResolver->>HTTPServer: fetch PAC script
HTTPServer-->>PACResolver: PAC script content
PACResolver->>QuickJS: Initialize & Compile
QuickJS-->>PACResolver: Resolver function
PACResolver-->>ProxyUtil: Resolver object
deactivate PACResolver
ProxyUtil->>PACResolver: resolve(requestURL)
activate PACResolver
PACResolver->>QuickJS: Execute FindProxyForURL()
QuickJS-->>PACResolver: Directive string
PACResolver-->>ProxyUtil: [PROXY/DIRECT/SOCKS...]
deactivate PACResolver
ProxyUtil->>ProxyUtil: Apply agent (HTTP/HTTPS/SOCKS)
ProxyUtil-->>AxiosInstance: requestConfig with agents
deactivate ProxyUtil
AxiosInstance->>HTTPServer: Send request with agent
HTTPServer-->>AxiosInstance: Response
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/bruno-electron/src/ipc/network/axios-instance.js (2)
395-398:⚠️ Potential issue | 🔴 CriticalSame const reassignment issue in redirect error handler.
timelineis declared withconstat line 248. Reassigning it at line 397 will throw a runtime error.🐛 Proposed fix
catch(err) { - if (err.timeline) { - timeline = err.timeline; - } timeline.push({🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-electron/src/ipc/network/axios-instance.js` around lines 395 - 398, The catch block in the redirect error handler (catch(err) { if (err.timeline) { timeline = err.timeline; } }) attempts to reassign timeline which was declared as const (timeline at its original declaration); change the original timeline declaration (the variable named timeline where it is initialized) from const to let so it can be reassigned here, or alternatively merge err.timeline into the existing timeline object without reassignment—update the declaration near the timeline initialization and keep the catch block logic using the same timeline identifier.
188-191:⚠️ Potential issue | 🔴 CriticalConst reassignment will throw a runtime error.
timelineis declared withconstat line 106. Attempting to reassign it here withtimeline = err.timelinewill cause aTypeError: Assignment to constant variable.🐛 Proposed fix
If you need to use
err.timeline, push its entries onto the existing array or handle differently:catch(err) { if (err.timeline) { - timeline = err.timeline; + // Merge error timeline entries if present + err.timeline.forEach((entry) => timeline.push(entry)); } timeline.push({Or simply remove the reassignment if
err.timelineis already a reference to the same array:catch(err) { - if (err.timeline) { - timeline = err.timeline; - } timeline.push({🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-electron/src/ipc/network/axios-instance.js` around lines 188 - 191, The catch block in axios-instance.js attempts to reassign the const variable timeline inside catch(err) (the line with timeline = err.timeline), which causes a runtime TypeError; fix it by either merging the error timeline into the existing const array (e.g., push or spread its items into the existing timeline) or by removing the reassignment and handling err.timeline separately (e.g., assign to a new let/const like errTimeline or only read from err.timeline without reassigning timeline) — update the catch(err) block around the timeline handling to use timeline.push(...err.timeline) or similar non-reassignment approach, referencing the catch(err) block and the timeline variable in axios-instance.js.
🧹 Nitpick comments (4)
packages/bruno-common/src/net/pac-resolver.js (1)
20-30: Abort error could be more descriptive.When the timeout triggers, the error will be an
AbortErrorwithout context. Consider wrapping it for better diagnostics in timeline logs.♻️ Enhanced error handling
async function downloadPac(pacUrl, timeoutMs = 5000) { const controller = new AbortController(); const id = setTimeout(() => controller.abort(), timeoutMs); try { const res = await fetch(pacUrl, { signal: controller.signal }); if (!res.ok) throw new Error(`Failed to fetch PAC (${res.status})`); return await res.text(); + } catch (err) { + if (err.name === 'AbortError') { + throw new Error(`PAC download timed out after ${timeoutMs}ms`); + } + throw err; } finally { clearTimeout(id); } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-common/src/net/pac-resolver.js` around lines 20 - 30, In downloadPac, improve the AbortError diagnostics by catching errors from the fetch call (or the AbortController timeout) and rethrowing a more descriptive error that includes context such as the pacUrl and timeoutMs; specifically, update the async function downloadPac to wrap the fetch in a try/catch (or add a catch after await) that detects an AbortError and throws a new Error like "PAC download aborted (timeoutMs ms) for URL: pacUrl" while preserving the original error as cause or including its message for timeline logs.packages/bruno-common/package.json (1)
24-26: Missing ESMimportcondition in new subpath export.Other subpath exports (
.,./runner,./utils) define bothrequireandimportconditions. This export only providesrequire, which could cause issues if any ESM consumer attempts to import it.If this module is intentionally CJS-only (since it's consumed by Electron's main process), consider adding a comment to document that decision. Otherwise, add the
importmapping for consistency.♻️ Suggested fix for consistency
"./net/pac-resolver": { - "require": "./src/net/pac-resolver.js" + "require": "./src/net/pac-resolver.js", + "import": "./src/net/pac-resolver.js" }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-common/package.json` around lines 24 - 26, The new subpath export "./net/pac-resolver" in package.json only defines a "require" condition and lacks an "import" condition; update the package.json export for "./net/pac-resolver" to include an "import" mapping alongside "require" to support ESM consumers (or add an inline comment in package.json documenting that "./net/pac-resolver" is intentionally CJS-only if that is the deliberate choice). Locate the export entry for "./net/pac-resolver" and either add the same "import": "./src/net/pac-resolver.js" key as used in the other exports (e.g., ".", "./runner", "./utils") or add a clear comment explaining CJS-only intent.packages/bruno-electron/test/proxy-util.test.js (1)
16-44: Consider adding test coverage for PAC resolution failure.The happy path is covered, but the error handling branch (lines 434-436 in proxy-util.js) where PAC resolution fails and falls back to direct connection isn't tested here.
📝 Example additional test case
test('setupProxyAgents falls back to direct on PAC resolution error', async () => { jest.doMock('@usebruno/common/net/pac-resolver', () => ({ getPacResolver: async () => { throw new Error('PAC fetch failed'); }, clearCache: () => {} })); const { setupProxyAgents } = require('../src/utils/proxy-util'); const requestConfig = { url: 'http://example.com/resource' }; const timeline = []; await setupProxyAgents({ requestConfig, proxyMode: 'pac', proxyConfig: { pacUrl: 'http://bad-pac' }, httpsAgentRequestFields: {}, interpolationOptions: {}, timeline }); expect(requestConfig.httpsAgent).toBeDefined(); const hasError = timeline.some((t) => t.type === 'error' && /PAC resolution failed/.test(t.message)); expect(hasError).toBe(true); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-electron/test/proxy-util.test.js` around lines 16 - 44, Add a new test in packages/bruno-electron/test/proxy-util.test.js that verifies setupProxyAgents falls back to direct on PAC resolution error: mock the '@usebruno/common/net/pac-resolver' module so getPacResolver throws (e.g., throw new Error('PAC fetch failed')), require setupProxyAgents, call it with proxyMode: 'pac' and a bad pacUrl, then assert requestConfig.httpsAgent is still set and the timeline contains an error entry indicating PAC resolution failed; reference the setupProxyAgents function and the mocked getPacResolver/pac-resolver module so the test targets the error branch in proxy-util.js.packages/bruno-electron/src/utils/proxy-util.js (1)
403-410: Consider supportingHTTPSproxy directive type.Some PAC files return
HTTPS host:portfor HTTPS-capable proxies. The current regex only matchesPROXYandHTTP. If this is intentional, a comment would help future maintainers.- if (/^(PROXY|HTTP)\s+\S/i.test(directive)) { + if (/^(PROXY|HTTP|HTTPS)\s+\S/i.test(directive)) { const hostPort = directive.split(/\s+/)[1]; - const proxyUri = `http://${hostPort}`; + // Use https:// for HTTPS directive, http:// otherwise + const isHttps = /^HTTPS\s/i.test(directive); + const proxyUri = `${isHttps ? 'https' : 'http'}://${hostPort}`;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-electron/src/utils/proxy-util.js` around lines 403 - 410, The PAC directive-handling code currently only matches PROXY and HTTP; update the check in the block that reads directive to also accept HTTPS (e.g. change the regex to /^(PROXY|HTTP|HTTPS)\s+\S/i) and when the directive is HTTPS set proxyUri to use the https:// scheme (so proxyUri = `https://${hostPort}`) before constructing the agents (TimelineHttpsProxyAgent via createTimelineAgentClass(PatchedHttpsProxyAgent) and the HttpProxyAgent/httpsAgent assignments on requestConfig). Ensure the rest of the logic (agentSet = true; break) remains unchanged so HTTPS-capable PAC entries are honored.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/bruno-app/src/components/Preferences/ProxySettings/index.js`:
- Line 17: Remove the leftover debug console.log call that prints preferences in
the ProxySettings component (the console.log(preferences) statement); locate it
in the ProxySettings component file and delete the console.log line (or replace
it with a proper logger or conditional debug flag if runtime inspection is
required) so no debug output is emitted in production.
In `@packages/bruno-common/test/pac-resolver.integration.test.js`:
- Around line 181-202: The test asserts LRU behaviour by inspecting _CACHE
internals but only proves FIFO; to fix, after filling to CACHE_MAX_SIZE via
repeated getPacResolver calls, re-request one early URL (e.g., await
getPacResolver({ pacUrl: firstUrl })) to mark it as recently used, then insert
the overflow URL (pac/50) and assert that an untouched entry (not the
re-accessed firstUrl) was evicted; avoid relying on _CACHE internals—use
startPacServer/pacScript request counters or a handler-side hit counter to
detect which URL was re-downloaded (i.e., the evicted URL should trigger a
network request when fetched again), and update assertions to check server hit
counts or observable network requests rather than _CACHE.has/_CACHE.size
directly.
- Around line 128-142: The test's TTL timing is too tight and may flake; in the
block that calls getPacResolver with opts: { cacheTtlMs: 50 } and then awaits
new Promise(r => setTimeout(r, 60)), increase the sleep to a safely larger
margin (for example at least 2x the TTL or a fixed 100–200ms) so the cache entry
reliably expires before the second getPacResolver call; update the timeout
surrounding the downloadCount check to reference the same cacheTtlMs intent and
keep use of getPacResolver, startPacServer and downloadCount unchanged.
In `@packages/bruno-electron/test/pac-proxy.integration.test.js`:
- Around line 112-118: The test currently uses currentScript = pac('DIRECT')
which doesn't exercise multi-directive parsing; change currentScript to a PAC
string that returns a multi-directive response like "DIRECT; PROXY
proxy.example:8080" (or use pac('DIRECT; PROXY "proxy.example:8080"')) so the
code must parse multiple directives and choose DIRECT; then call
runSetup(pacUrl) as before and assert the same expectations
(requestConfig.httpsAgent defined, requestConfig.httpAgent undefined). Update
the test named "DIRECT-only in multi-directive list: sets plain agent" to use
the multi-directive pac value so it validates that the DIRECT choice is honored
when followed by a PROXY directive.
---
Outside diff comments:
In `@packages/bruno-electron/src/ipc/network/axios-instance.js`:
- Around line 395-398: The catch block in the redirect error handler (catch(err)
{ if (err.timeline) { timeline = err.timeline; } }) attempts to reassign
timeline which was declared as const (timeline at its original declaration);
change the original timeline declaration (the variable named timeline where it
is initialized) from const to let so it can be reassigned here, or alternatively
merge err.timeline into the existing timeline object without reassignment—update
the declaration near the timeline initialization and keep the catch block logic
using the same timeline identifier.
- Around line 188-191: The catch block in axios-instance.js attempts to reassign
the const variable timeline inside catch(err) (the line with timeline =
err.timeline), which causes a runtime TypeError; fix it by either merging the
error timeline into the existing const array (e.g., push or spread its items
into the existing timeline) or by removing the reassignment and handling
err.timeline separately (e.g., assign to a new let/const like errTimeline or
only read from err.timeline without reassigning timeline) — update the
catch(err) block around the timeline handling to use
timeline.push(...err.timeline) or similar non-reassignment approach, referencing
the catch(err) block and the timeline variable in axios-instance.js.
---
Nitpick comments:
In `@packages/bruno-common/package.json`:
- Around line 24-26: The new subpath export "./net/pac-resolver" in package.json
only defines a "require" condition and lacks an "import" condition; update the
package.json export for "./net/pac-resolver" to include an "import" mapping
alongside "require" to support ESM consumers (or add an inline comment in
package.json documenting that "./net/pac-resolver" is intentionally CJS-only if
that is the deliberate choice). Locate the export entry for "./net/pac-resolver"
and either add the same "import": "./src/net/pac-resolver.js" key as used in the
other exports (e.g., ".", "./runner", "./utils") or add a clear comment
explaining CJS-only intent.
In `@packages/bruno-common/src/net/pac-resolver.js`:
- Around line 20-30: In downloadPac, improve the AbortError diagnostics by
catching errors from the fetch call (or the AbortController timeout) and
rethrowing a more descriptive error that includes context such as the pacUrl and
timeoutMs; specifically, update the async function downloadPac to wrap the fetch
in a try/catch (or add a catch after await) that detects an AbortError and
throws a new Error like "PAC download aborted (timeoutMs ms) for URL: pacUrl"
while preserving the original error as cause or including its message for
timeline logs.
In `@packages/bruno-electron/src/utils/proxy-util.js`:
- Around line 403-410: The PAC directive-handling code currently only matches
PROXY and HTTP; update the check in the block that reads directive to also
accept HTTPS (e.g. change the regex to /^(PROXY|HTTP|HTTPS)\s+\S/i) and when the
directive is HTTPS set proxyUri to use the https:// scheme (so proxyUri =
`https://${hostPort}`) before constructing the agents (TimelineHttpsProxyAgent
via createTimelineAgentClass(PatchedHttpsProxyAgent) and the
HttpProxyAgent/httpsAgent assignments on requestConfig). Ensure the rest of the
logic (agentSet = true; break) remains unchanged so HTTPS-capable PAC entries
are honored.
In `@packages/bruno-electron/test/proxy-util.test.js`:
- Around line 16-44: Add a new test in
packages/bruno-electron/test/proxy-util.test.js that verifies setupProxyAgents
falls back to direct on PAC resolution error: mock the
'@usebruno/common/net/pac-resolver' module so getPacResolver throws (e.g., throw
new Error('PAC fetch failed')), require setupProxyAgents, call it with
proxyMode: 'pac' and a bad pacUrl, then assert requestConfig.httpsAgent is still
set and the timeline contains an error entry indicating PAC resolution failed;
reference the setupProxyAgents function and the mocked
getPacResolver/pac-resolver module so the test targets the error branch in
proxy-util.js.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: f894f96c-344f-49c1-8b9c-0dff781514e0
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (11)
packages/bruno-app/src/components/Preferences/ProxySettings/index.jspackages/bruno-common/package.jsonpackages/bruno-common/src/net/pac-resolver.jspackages/bruno-common/test/pac-resolver.integration.test.jspackages/bruno-common/test/pac-resolver.test.jspackages/bruno-electron/src/ipc/network/axios-instance.jspackages/bruno-electron/src/store/preferences.jspackages/bruno-electron/src/utils/proxy-util.jspackages/bruno-electron/test/pac-proxy.integration.test.jspackages/bruno-electron/test/proxy-util.test.jspackages/bruno-tests/collection/environments/Local.bru
| @@ -17,7 +17,7 @@ const ProxySettings = ({ close }) => { | |||
| console.log(preferences); | |||
There was a problem hiding this comment.
Remove debug console.log statement.
This appears to be a leftover debug artifact that shouldn't ship to production.
- console.log(preferences);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| console.log(preferences); |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/bruno-app/src/components/Preferences/ProxySettings/index.js` at line
17, Remove the leftover debug console.log call that prints preferences in the
ProxySettings component (the console.log(preferences) statement); locate it in
the ProxySettings component file and delete the console.log line (or replace it
with a proper logger or conditional debug flag if runtime inspection is
required) so no debug output is emitted in production.
| test('stale cache entry is re-fetched after TTL expires', async () => { | ||
| let downloadCount = 0; | ||
| const { server: s2, port: p2 } = await startPacServer((req, res) => { | ||
| downloadCount++; | ||
| res.writeHead(200); | ||
| res.end(pacScript('DIRECT')); | ||
| }); | ||
| const url2 = `http://127.0.0.1:${p2}/proxy.pac`; | ||
|
|
||
| try { | ||
| // 50ms TTL so it expires quickly | ||
| await getPacResolver({ pacUrl: url2, opts: { cacheTtlMs: 50 } }); | ||
| await new Promise((r) => setTimeout(r, 60)); | ||
| await getPacResolver({ pacUrl: url2, opts: { cacheTtlMs: 50 } }); | ||
| expect(downloadCount).toBe(2); |
There was a problem hiding this comment.
Give the TTL expiry check a larger timing margin.
Sleeping 60ms against a 50ms TTL is close enough to wall-clock jitter that this can flap on busy CI. Waiting comfortably past the TTL keeps the test deterministic without changing what it proves.
🕒 Suggested change
- // 50ms TTL so it expires quickly
+ // Keep a comfortable margin over the TTL to avoid clock jitter in CI
await getPacResolver({ pacUrl: url2, opts: { cacheTtlMs: 50 } });
- await new Promise((r) => setTimeout(r, 60));
+ await new Promise((r) => setTimeout(r, 150));
await getPacResolver({ pacUrl: url2, opts: { cacheTtlMs: 50 } });As per coding guidelines, "Ensure tests are deterministic and reproducible. No randomness, timing dependencies, or environment-specific assumptions without explicit control."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/bruno-common/test/pac-resolver.integration.test.js` around lines 128
- 142, The test's TTL timing is too tight and may flake; in the block that calls
getPacResolver with opts: { cacheTtlMs: 50 } and then awaits new Promise(r =>
setTimeout(r, 60)), increase the sleep to a safely larger margin (for example at
least 2x the TTL or a fixed 100–200ms) so the cache entry reliably expires
before the second getPacResolver call; update the timeout surrounding the
downloadCount check to reference the same cacheTtlMs intent and keep use of
getPacResolver, startPacServer and downloadCount unchanged.
| test('LRU evicts oldest entry when cache reaches max size', async () => { | ||
| const { default: CACHE_MAX_SIZE } = { default: 50 }; | ||
|
|
||
| // Fill up the cache beyond max size using unique URLs on a single server | ||
| const { server: s2, port: p2 } = await startPacServer((req, res) => { | ||
| res.writeHead(200); | ||
| res.end(pacScript('DIRECT')); | ||
| }); | ||
|
|
||
| try { | ||
| const firstUrl = `http://127.0.0.1:${p2}/pac/0`; | ||
| // Fill to max | ||
| for (let i = 0; i < 50; i++) { | ||
| await getPacResolver({ pacUrl: `http://127.0.0.1:${p2}/pac/${i}` }); | ||
| } | ||
| expect(_CACHE.has(`url:${firstUrl}`)).toBe(true); | ||
| expect(_CACHE.size).toBe(50); | ||
|
|
||
| // One more push evicts the oldest | ||
| await getPacResolver({ pacUrl: `http://127.0.0.1:${p2}/pac/50` }); | ||
| expect(_CACHE.size).toBe(50); | ||
| expect(_CACHE.has(`url:${firstUrl}`)).toBe(false); |
There was a problem hiding this comment.
This case still passes with a FIFO cache.
Nothing is re-accessed before the overflow insert, so the current assertions only prove "oldest inserted entry gets evicted." If LRU is the contract here, touch one early URL again and assert that an untouched entry is the one that falls out—ideally via a re-download check rather than _CACHE internals.
As per coding guidelines, "Write behaviour-driven tests, not implementation-driven ones. Tests should validate real expected output and observable behaviour, not internal details or mocked-out logic unless absolutely necessary."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/bruno-common/test/pac-resolver.integration.test.js` around lines 181
- 202, The test asserts LRU behaviour by inspecting _CACHE internals but only
proves FIFO; to fix, after filling to CACHE_MAX_SIZE via repeated getPacResolver
calls, re-request one early URL (e.g., await getPacResolver({ pacUrl: firstUrl
})) to mark it as recently used, then insert the overflow URL (pac/50) and
assert that an untouched entry (not the re-accessed firstUrl) was evicted; avoid
relying on _CACHE internals—use startPacServer/pacScript request counters or a
handler-side hit counter to detect which URL was re-downloaded (i.e., the
evicted URL should trigger a network request when fetched again), and update
assertions to check server hit counts or observable network requests rather than
_CACHE.has/_CACHE.size directly.
| test('DIRECT-only in multi-directive list: sets plain agent', async () => { | ||
| currentScript = pac('DIRECT'); | ||
| const { requestConfig } = await runSetup(pacUrl); | ||
|
|
||
| expect(requestConfig.httpsAgent).toBeDefined(); | ||
| expect(requestConfig.httpAgent).toBeUndefined(); | ||
| }); |
There was a problem hiding this comment.
Make this case actually exercise a multi-directive PAC result.
currentScript = pac('DIRECT') just duplicates the plain DIRECT test above, so a regression in handling DIRECT; PROXY ... would still pass here.
🧪 Suggested change
- test('DIRECT-only in multi-directive list: sets plain agent', async () => {
- currentScript = pac('DIRECT');
+ test('DIRECT first in a multi-directive list: keeps direct routing', async () => {
+ currentScript = pac('DIRECT; PROXY 10.0.0.1:3128');
const { requestConfig } = await runSetup(pacUrl);
expect(requestConfig.httpsAgent).toBeDefined();
expect(requestConfig.httpAgent).toBeUndefined();
});As per coding guidelines, "Cover both the 'happy path' and the realistically problematic paths. Validate expected success behaviour, but also validate error handling, edge cases, and degraded-mode behaviour when appropriate."
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| test('DIRECT-only in multi-directive list: sets plain agent', async () => { | |
| currentScript = pac('DIRECT'); | |
| const { requestConfig } = await runSetup(pacUrl); | |
| expect(requestConfig.httpsAgent).toBeDefined(); | |
| expect(requestConfig.httpAgent).toBeUndefined(); | |
| }); | |
| test('DIRECT first in a multi-directive list: keeps direct routing', async () => { | |
| currentScript = pac('DIRECT; PROXY 10.0.0.1:3128'); | |
| const { requestConfig } = await runSetup(pacUrl); | |
| expect(requestConfig.httpsAgent).toBeDefined(); | |
| expect(requestConfig.httpAgent).toBeUndefined(); | |
| }); |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/bruno-electron/test/pac-proxy.integration.test.js` around lines 112
- 118, The test currently uses currentScript = pac('DIRECT') which doesn't
exercise multi-directive parsing; change currentScript to a PAC string that
returns a multi-directive response like "DIRECT; PROXY proxy.example:8080" (or
use pac('DIRECT; PROXY "proxy.example:8080"')) so the code must parse multiple
directives and choose DIRECT; then call runSetup(pacUrl) as before and assert
the same expectations (requestConfig.httpsAgent defined, requestConfig.httpAgent
undefined). Update the test named "DIRECT-only in multi-directive list: sets
plain agent" to use the multi-directive pac value so it validates that the
DIRECT choice is honored when followed by a PROXY directive.
3b00354 to
6359164
Compare
chore(dependencies): update package-lock.json with new dependencies and version upgrades - Added new dependencies: ajv, git-url-parse, @opencollection/types, and storybook packages. - Updated existing dependencies to their latest versions, including eslint and babel packages. - Removed deprecated entries and cleaned up the package-lock structure for better maintainability.
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
fixes: #5980
Description
This PR adds support for a new PAC (Proxy Auto-Configuration) mode in Bruno, allowing users to specify a .pac URL that dynamically determines the proxy to use for each request. This PR includes the work of @dbrglc from #6056
Contribution Checklist:
Summary by CodeRabbit
Release Notes