Repository navigation
feat(cookies): add direct cookie access methods and update translations - #7073
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds first-class cookie support: new ReadOnlyPropertyList/PropertyList/CookieList modules, Bru stores requestUrl and exposes bru.cookies, translators updated for pm↔bru cookie mappings, QuickJS shim and editor hints extended, runtime call sites updated, and tests/e2e assets added. Changes
Sequence Diagram(s)sequenceDiagram
participant Script as User Script
participant Translator as Converter (pm↔bru)
participant Bru as Bru instance
participant CookieList as CookieList
participant Jar as CookieJar (requests.cookies)
Script->>Translator: translate cookie call (pm.cookies.* ↔ bru.cookies.*)
Translator-->>Script: translated code referencing bru.cookies.*
Script->>Bru: invoke bru.cookies.get(name)
Bru->>CookieList: CookieList.get(name) with interpolated requestUrl
CookieList->>Jar: jar.getCookie / getCookiesForUrl(requestUrl)
Jar-->>CookieList: cookie(s)
CookieList-->>Bru: result
Bru-->>Script: return value
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 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: 1
🤖 Fix all issues with AI agents
In `@packages/bruno-js/src/bru.js`:
- Around line 48-70: The get() method currently uses cookies.find(...) which
returns the first matching cookie while toObject() ends up with "last wins"
semantics; update get() (in the object containing get, has, toObject) to return
the last matching cookie for the interpolated this.requestUrl — e.g. use
Array.prototype.findLast (or iterate the cookies array in reverse) when
selecting cookie by key so get(name) and toObject() are consistent; keep the
existing interpolate(this.requestUrl) and getCookiesForUrl(url) usage and
preserve returning undefined when no url or no match.
🧹 Nitpick comments (2)
packages/bruno-js/src/runtime/vars-runtime.js (1)
40-40: 14 positional args toBruis getting unwieldy.The change itself is correct — passing
request?.urlaligns with the other runtime call sites. However, this constructor now takes 14 positional arguments withundefinedplaceholders for unused params. Consider moving to an options object in a follow-up to prevent ordering mistakes.packages/bruno-js/src/bru.js (1)
31-31: 14 positional constructor parameters — existing debt, but worth noting.This constructor keeps growing. A single options/config object would make call sites far more readable and resilient to parameter ordering bugs. I see this is pre-existing debt (flagged in
script-runtime.js:15-16), so not blocking.
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@packages/bruno-js/src/sandbox/quickjs/shims/bru.js`:
- Line 579: The wrapper for globalThis.bru.cookies.reduce always forwards acc
(which may be undefined) and thus breaks the no-initial-value semantics; change
the reduce wrapper around _allNative() so it forwards the call conditionally: if
the caller provided an initial accumulator (check arguments.length or presence
of a second arg) call _allNative().reduce(fn, acc), otherwise call
_allNative().reduce(fn) so the native behavior (use first element as initial or
throw on empty array) is preserved; update the function bound to
globalThis.bru.cookies.reduce accordingly.
🧹 Nitpick comments (7)
packages/bruno-js/src/readonly-property-list.js (2)
157-159:reduce()behaves differently from nativeArray.reducewhen called without an accumulator.
list.reduce(fn)passesundefinedas the initial value toArray.prototype.reduce, which differs from callingitems.reduce(fn)directly (native reduce without a second arg uses the first element as the initial accumulator and throws on empty arrays). If this is intentional to mirror Postman's PropertyList, it's fine — just worth a note.Optional: match native semantics
- reduce(fn, acc) { - return this._getItems().reduce(fn, acc); + reduce(fn, ...args) { + return this._getItems().reduce(fn, ...args); }
36-38: Dynamic mode:_dataSource()errors will bubble up unhandled.If a
dataSourcefunction throws, every read method will propagate the exception. This is likely fine for the cookie use case (wheregetCookiesForUrlis trusted internal code), but worth noting if this base class will be used more broadly.packages/bruno-js/src/cookie-list.js (1)
39-75: Write methods are clean — consistent null-URL guard pattern.Each method properly short-circuits on falsy URL with callback/Promise fallback. The
delete→removealias is straightforward.One small note: these public methods lack individual JSDoc (only the class-level doc lists them). Consider adding brief JSDoc per method. As per coding guidelines: "Add JSDoc comments to abstractions for additional details."
packages/bruno-js/src/property-list.js (2)
124-136:populate()andrepopulate()are identical implementations.Both methods assign
this._items = Array.isArray(items) ? [...items] : []. Since JS assignment is atomic, the "clear then populate" semantics ofrepopulatecollapse to the same operation. If this mirrors Postman's SDK surface, keeping both is fine for API compatibility, but a deduplication would be cleaner.Optional: deduplicate
populate(items) { this._assertStatic('populate'); this._items = Array.isArray(items) ? [...items] : []; } repopulate(items) { this._assertStatic('repopulate'); - this._items = Array.isArray(items) ? [...items] : []; + this.populate(items); }
66-76:insertAfter()silently appends whenafterisundefined, unlikeinsert()which handles it explicitly.
insert(item, before)explicitly checksbefore === undefinedand appends.insertAfter(item, after)doesn't — it falls through toindexOf(undefined) === -1→ append. The behavior is the same, but the intent is implicit. Consider adding an explicit guard for consistency, or documenting the fallback.packages/bruno-js/src/bru.js (1)
32-32: 14 positional constructor parameters is getting unwieldy.This isn't new to this PR, but adding
requestUrlas the 14th positional arg increases the risk of callers passing arguments in the wrong order. Consider consolidating into an options object in a follow-up.packages/bruno-js/src/sandbox/quickjs/shims/bru.js (1)
550-580: DuplicatecallWithCallbackdefinition — consider extracting to a shared helper.
callWithCallbackis defined identically both inside the block scope (Line 553) and in thejar()function (Line 585). This isn't a bug due to block scoping, but it's copy-pasted logic.
|
Glad to see a new cookies handling method. Anyway, don't forget to fix this before 9d3341e |
sure @ahamayeah59 #6679 the changes seems to be straight forward, will do my best to get it tested/reviewed and merged as soon as possible. |
8b2a501 to
bf2f1f8
Compare
sanish-bruno
left a comment
There was a problem hiding this comment.
PR Review
Found 3 issue(s): 0 major, 0 minor, 1 design, 1 suggestion, 1 nit.
Summary
- Well-structured PR with clean class hierarchy (
ReadOnlyPropertyList→CookieList) and comprehensive test coverage (unit + E2E) - The regex fallback path in
postman-translations.jshas a pre-existing jar pattern ordering issue that the PR reorganized but didn't fix - Minor
get()/one()duplicate-key resolution inconsistency inReadOnlyPropertyList - Autocomplete hint for
has()is incomplete
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@tests/scripting/bru-api/cookies/cookies.spec.ts`:
- Around line 4-27: Replace the parallel test suite with a serial one to match
project patterns: change the test suite declaration using test.describe.parallel
for the "bru.cookies PropertyList API" suite to use test.describe.serial so the
two tests ("all cookie tests pass in developer mode" and "all cookie tests pass
in safe mode") run deterministically; update any references to
test.describe.parallel in this block to test.describe.serial (keeping the suite
name and individual test names unchanged).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: a26b476d-ebf4-47b7-b7f6-36764283ac06
📒 Files selected for processing (1)
tests/scripting/bru-api/cookies/cookies.spec.ts
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 (1)
packages/bruno-tests/collection/scripting/api/bru/cookies/getCookies.bru (1)
57-57:⚠️ Potential issue | 🟡 MinorMissing
awaiton asyncjar.clear()call.The pre-request script correctly uses
await jar.clear(), but the cleanup here omits it. Since write methods inCookieListare async, this could leave stale cookies for subsequent tests if cleanup doesn't complete before the test runner moves on.Proposed fix
- jar.clear() + await jar.clear()🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-tests/collection/scripting/api/bru/cookies/getCookies.bru` at line 57, The call to jar.clear() in the test cleanup is missing an await, so the async CookieList.clear() may not finish before the next test; update the cleanup to await jar.clear() and ensure the enclosing function (the cleanup handler or test teardown) is async or returns the promise so the test runner waits for completion — reference the jar.clear() call in the cleanup block and the CookieList write behavior used in the pre-request script.
🧹 Nitpick comments (7)
packages/bruno-tests/collection/scripting/api/bru/cookies/getCookies.bru (1)
39-54: Minor: Inconsistent indentation.These nested
test()blocks have extra leading whitespace compared to the firsttest()block at line 32. Consider aligning for readability.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-tests/collection/scripting/api/bru/cookies/getCookies.bru` around lines 39 - 54, Fix the inconsistent indentation for the two nested test blocks by aligning their leading whitespace to match the first test block (the earlier test starting with test("should ...") at line 32); update the indentation of the test named "should have valid cookie structure in array" and the following test "should contain expected cookie properties" so their bodies and inner lines (including usages of data, cookie, index, and cookieKeys) use the same indentation level as the initial test block for consistent readability.packages/bruno-tests/collection/scripting/api/bru/cookies/directReadMethods.bru (2)
16-27: Use the same base URL source for request and cookie setup.Line 16 hardcodes
http://localhost:8081while the request is template-driven (Line 8). Reusing the same URL source will keep this test stable across env changes.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-tests/collection/scripting/api/bru/cookies/directReadMethods.bru` around lines 16 - 27, Replace the hardcoded 'http://localhost:8081' in the jar.setCookies call with the same base-URL variable used by the request template (the request's base URL/template variable referenced on Line 8) so the cookie setup reuses the request's URL source; update the jar.setCookies invocation accordingly (keep the cookies array intact) to ensure tests follow the same environment-driven URL.
41-49: Tightenall()/count()assertions for deterministic isolation.Using
at.least(2)can hide leaked cookies from prior tests. Prefer clearing before setup and asserting exact expected count.Proposed deterministic assertion update
script:pre-request { const jar = bru.cookies.jar() + await jar.clear() await jar.setCookies('http://localhost:8081', [ @@ test("all() should return an array with at least 2 items", function() { const cookies = bru.cookies.all(); expect(cookies).to.be.an('array'); - expect(cookies.length).to.be.at.least(2); + expect(cookies.length).to.equal(2); }); @@ test("count() should be at least 2", function() { - expect(bru.cookies.count()).to.be.at.least(2); + expect(bru.cookies.count()).to.equal(2); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-tests/collection/scripting/api/bru/cookies/directReadMethods.bru` around lines 41 - 49, The tests using bru.cookies.all() and bru.cookies.count() are using loose "at.least(2)" assertions that can hide leaked cookies; update the tests to deterministically clear cookies before setup (use a beforeEach or an explicit call to bru.cookies.clear() at the start of each test) and then assert the exact expected count/length (e.g., expect(bru.cookies.all().length).to.equal(2) and expect(bru.cookies.count()).to.equal(2)) in the test blocks named "all() should return an array with at least 2 items" and "count() should be at least 2".packages/bruno-tests/collection/scripting/api/bru/cookies/directGet.bru (1)
16-20: Align cookie scope URL with the request URL source.Line 16 hardcodes
http://localhost:8081while Line 8 uses{{localhost}}/ping. Please derive both from the same source so this test doesn’t silently break when env URL/port changes.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-tests/collection/scripting/api/bru/cookies/directGet.bru` around lines 16 - 20, The test hardcodes the cookie scope URL in the jar.setCookie call which can diverge from the request URL source; update the jar.setCookie invocation to derive its origin from the same template/variable used for the request (e.g. replace the literal "http://localhost:8081" with the shared placeholder or computed base URL such as `{{localhost}}` or the request's base variable) so that setCookie and the ping request use the identical host/port; modify the jar.setCookie call (symbol: jar.setCookie) to build the cookie URL from that shared value.packages/bruno-tests/collection/scripting/api/bru/cookies/directIteration.bru (1)
31-69: Strengthen iteration assertions to catch contamination.Current
include/containchecks can still pass when extra cookies exist. Prefer exact key-set/count assertions so leakage is detected immediately.Suggested assertion tightening
test("each() should iterate over all cookies", function() { const keys = []; bru.cookies.each(function(cookie) { keys.push(cookie.key); }); - expect(keys).to.include('x'); - expect(keys).to.include('y'); + expect(keys.sort()).to.deep.equal(['x', 'y']); }); @@ test("map() should transform cookies", function() { const keys = bru.cookies.map(function(c) { return c.key; }); expect(keys).to.be.an('array'); - expect(keys).to.include('x'); - expect(keys).to.include('y'); + expect(keys.sort()).to.deep.equal(['x', 'y']); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-tests/collection/scripting/api/bru/cookies/directIteration.bru` around lines 31 - 69, Replace the loose include/contain assertions in the tests "each() should iterate over all cookies", "map() should transform cookies", and "reduce() should accumulate over cookies" with exact-set and count checks to detect extra cookies: for the arrays produced by bru.cookies.each (keys) and bru.cookies.map (keys) assert both expect(keys).to.have.members(['x','y']) and expect(keys).to.have.lengthOf(2); for the string from bru.cookies.reduce, split/filter the result into an array of keys and assert the same members and length (e.g., parsedKeys should have.members(['x','y']) and have.lengthOf(2)) so any contamination is caught immediately.packages/bruno-tests/collection/scripting/api/bru/cookies/crossDomainIsolation.bru (2)
49-53: Test title and assertion API are inconsistent.The title says
bru.cookies.get()(Line 49), but the assertion usesbru.cookies.has()(Line 52). Rename the test title (or add aget()assertion) for intent clarity.✏️ Minimal rename option
- await test("bru.cookies.get() only returns cookies for the current request URL", function() { + await test("bru.cookies.has() only checks cookies for the current request URL", function() {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-tests/collection/scripting/api/bru/cookies/crossDomainIsolation.bru` around lines 49 - 53, The test title refers to bru.cookies.get() but the body asserts bru.cookies.has(), creating a mismatch; update the test to make intent consistent by either renaming the test title to mention bru.cookies.has() (change the string passed to test(...)) or add an assertion that checks bru.cookies.get("domainB") returns undefined/null in addition to or instead of bru.cookies.has("domainB"), ensuring you update the test named in the diff where test("bru.cookies.get() only returns cookies for the current request URL", ...) is declared and referencing bru.cookies.get and/or bru.cookies.has accordingly.
32-65: Make cleanup unconditional withtry/finally.
await jar.clear()on Line 64 can be skipped if any awaitedtest(...)throws. Wrapping the block intry/finallyprevents cookie state leakage across subsequent requests.♻️ Proposed refactor
tests { const jar = bru.cookies.jar() + try { await test("cookies on domain A are not visible on domain B", async function() { const cookiesA = await jar.getCookies("https://testbench-sanity.usebruno.com"); const cookiesB = await jar.getCookies("https://other.example.com"); @@ await test("jar.getCookie() respects domain isolation", async function() { const cookieA = await jar.getCookie("https://testbench-sanity.usebruno.com", "domainA"); const cookieBOnA = await jar.getCookie("https://testbench-sanity.usebruno.com", "domainB"); @@ expect(cookieBOnA).to.be.null; }); - await jar.clear() + } finally { + await jar.clear() + } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-tests/collection/scripting/api/bru/cookies/crossDomainIsolation.bru` around lines 32 - 65, Wrap the tests block that uses the cookie jar in a try/finally so jar.clear() always runs: ensure the sequence that creates const jar = bru.cookies.jar() and runs the tests (the async test(...) calls and jar.getCookie/getCookies assertions) is enclosed in a try block and move await jar.clear() into a finally block so cleanup always executes even if any test throws; reference the symbols jar, bru.cookies.jar(), the test(...) calls, and jar.clear() to locate where to add the try/finally.
🤖 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-tests/collection/scripting/api/bru/cookies/clearScope.bru`:
- Around line 35-47: The test is asserting scoped cookie clearing but calls
bru.cookies.clear() while the current request URL is {{localhost}}
(cookie-list.js uses this._getUrl()), so it never clears cookies for
testbench-sanity.usebruno.com; update the test to either change the request URL
to "https://testbench-sanity.usebruno.com/ping" so bru.cookies.clear() targets
that domain, or set cookies for {{localhost}} in the pre-request step and then
assert that jar.getCookies("http(s)://{{localhost}}") is emptied while
jar.getCookies("https://other.example.com") still contains the "c" cookie; also
add an explicit assertion after bru.cookies.clear() that validates the expected
domain's cookies were removed.
In
`@packages/bruno-tests/collection/scripting/api/bru/cookies/directIteration.bru`:
- Around line 16-27: The test seeds cookies with jar.setCookies using a
hardcoded URL ('http://localhost:8081') which can diverge from the request URL
'{{localhost}}/ping'; update the cookie seeding to use the same URL source as
the request so the cookie scope (scheme/host/port/path) matches—replace the
hardcoded URL in jar.setCookies with the same host/port/scheme
variable/expression used for the request (the '{{localhost}}' value) so
jar.setCookies(...) and the '{{localhost}}/ping' request share one canonical URL
source.
In `@tests/utils/page/runner.ts`:
- Around line 89-90: The runFolder function uses folderPath and accesses
folderPath[folderPath.length - 1] without checking for an empty array; add a
guard at the start of runFolder to handle an empty folderPath (either throw a
clear error or return early) before entering test.step so the subsequent
selector logic (the places referencing folderPath[folderPath.length - 1]) never
receives undefined and avoids noisy selector failures/timeouts.
- Around line 89-93: The runFolder helper currently scopes lookups from the
whole collections sidebar (variable sidebar) instead of narrowing to the
specific collection named by collectionName, which can pick the wrong folder
when multiple collections share folder names; update all locators inside
runFolder (and the similar lookups around the occurrences noted) to first locate
the collection container by matching collectionName (e.g., find the collection
item within sidebar using its visible name or a data-testid combined with
collectionName) and then perform folderPath resolution starting from that
collection-specific locator so every getByTestId/getByText call is constrained
to the selected collection.
---
Outside diff comments:
In `@packages/bruno-tests/collection/scripting/api/bru/cookies/getCookies.bru`:
- Line 57: The call to jar.clear() in the test cleanup is missing an await, so
the async CookieList.clear() may not finish before the next test; update the
cleanup to await jar.clear() and ensure the enclosing function (the cleanup
handler or test teardown) is async or returns the promise so the test runner
waits for completion — reference the jar.clear() call in the cleanup block and
the CookieList write behavior used in the pre-request script.
---
Nitpick comments:
In
`@packages/bruno-tests/collection/scripting/api/bru/cookies/crossDomainIsolation.bru`:
- Around line 49-53: The test title refers to bru.cookies.get() but the body
asserts bru.cookies.has(), creating a mismatch; update the test to make intent
consistent by either renaming the test title to mention bru.cookies.has()
(change the string passed to test(...)) or add an assertion that checks
bru.cookies.get("domainB") returns undefined/null in addition to or instead of
bru.cookies.has("domainB"), ensuring you update the test named in the diff where
test("bru.cookies.get() only returns cookies for the current request URL", ...)
is declared and referencing bru.cookies.get and/or bru.cookies.has accordingly.
- Around line 32-65: Wrap the tests block that uses the cookie jar in a
try/finally so jar.clear() always runs: ensure the sequence that creates const
jar = bru.cookies.jar() and runs the tests (the async test(...) calls and
jar.getCookie/getCookies assertions) is enclosed in a try block and move await
jar.clear() into a finally block so cleanup always executes even if any test
throws; reference the symbols jar, bru.cookies.jar(), the test(...) calls, and
jar.clear() to locate where to add the try/finally.
In `@packages/bruno-tests/collection/scripting/api/bru/cookies/directGet.bru`:
- Around line 16-20: The test hardcodes the cookie scope URL in the
jar.setCookie call which can diverge from the request URL source; update the
jar.setCookie invocation to derive its origin from the same template/variable
used for the request (e.g. replace the literal "http://localhost:8081" with the
shared placeholder or computed base URL such as `{{localhost}}` or the request's
base variable) so that setCookie and the ping request use the identical
host/port; modify the jar.setCookie call (symbol: jar.setCookie) to build the
cookie URL from that shared value.
In
`@packages/bruno-tests/collection/scripting/api/bru/cookies/directIteration.bru`:
- Around line 31-69: Replace the loose include/contain assertions in the tests
"each() should iterate over all cookies", "map() should transform cookies", and
"reduce() should accumulate over cookies" with exact-set and count checks to
detect extra cookies: for the arrays produced by bru.cookies.each (keys) and
bru.cookies.map (keys) assert both expect(keys).to.have.members(['x','y']) and
expect(keys).to.have.lengthOf(2); for the string from bru.cookies.reduce,
split/filter the result into an array of keys and assert the same members and
length (e.g., parsedKeys should have.members(['x','y']) and have.lengthOf(2)) so
any contamination is caught immediately.
In
`@packages/bruno-tests/collection/scripting/api/bru/cookies/directReadMethods.bru`:
- Around line 16-27: Replace the hardcoded 'http://localhost:8081' in the
jar.setCookies call with the same base-URL variable used by the request template
(the request's base URL/template variable referenced on Line 8) so the cookie
setup reuses the request's URL source; update the jar.setCookies invocation
accordingly (keep the cookies array intact) to ensure tests follow the same
environment-driven URL.
- Around line 41-49: The tests using bru.cookies.all() and bru.cookies.count()
are using loose "at.least(2)" assertions that can hide leaked cookies; update
the tests to deterministically clear cookies before setup (use a beforeEach or
an explicit call to bru.cookies.clear() at the start of each test) and then
assert the exact expected count/length (e.g.,
expect(bru.cookies.all().length).to.equal(2) and
expect(bru.cookies.count()).to.equal(2)) in the test blocks named "all() should
return an array with at least 2 items" and "count() should be at least 2".
In `@packages/bruno-tests/collection/scripting/api/bru/cookies/getCookies.bru`:
- Around line 39-54: Fix the inconsistent indentation for the two nested test
blocks by aligning their leading whitespace to match the first test block (the
earlier test starting with test("should ...") at line 32); update the
indentation of the test named "should have valid cookie structure in array" and
the following test "should contain expected cookie properties" so their bodies
and inner lines (including usages of data, cookie, index, and cookieKeys) use
the same indentation level as the initial test block for consistent readability.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: e5d5d17f-3984-4e25-b57a-27887fd964dd
📒 Files selected for processing (18)
packages/bruno-tests/collection/scripting/api/bru/cookies/clear.brupackages/bruno-tests/collection/scripting/api/bru/cookies/clearScope.brupackages/bruno-tests/collection/scripting/api/bru/cookies/crossDomainIsolation.brupackages/bruno-tests/collection/scripting/api/bru/cookies/deleteCookie.brupackages/bruno-tests/collection/scripting/api/bru/cookies/deleteCookies.brupackages/bruno-tests/collection/scripting/api/bru/cookies/directGet.brupackages/bruno-tests/collection/scripting/api/bru/cookies/directIteration.brupackages/bruno-tests/collection/scripting/api/bru/cookies/directReadMethods.brupackages/bruno-tests/collection/scripting/api/bru/cookies/directWrite.brupackages/bruno-tests/collection/scripting/api/bru/cookies/getCookie.brupackages/bruno-tests/collection/scripting/api/bru/cookies/getCookies.brupackages/bruno-tests/collection/scripting/api/bru/cookies/hasCookie.brupackages/bruno-tests/collection/scripting/api/bru/cookies/setCookie.brupackages/bruno-tests/collection/scripting/api/bru/cookies/setCookies.brutests/scripting/bru-api/cookies/cookies.spec.tstests/scripting/bru-api/cookies/init-user-data/collection-security.jsontests/scripting/bru-api/cookies/init-user-data/preferences.jsontests/utils/page/runner.ts
✅ Files skipped from review due to trivial changes (8)
- packages/bruno-tests/collection/scripting/api/bru/cookies/clear.bru
- packages/bruno-tests/collection/scripting/api/bru/cookies/setCookie.bru
- packages/bruno-tests/collection/scripting/api/bru/cookies/hasCookie.bru
- packages/bruno-tests/collection/scripting/api/bru/cookies/setCookies.bru
- packages/bruno-tests/collection/scripting/api/bru/cookies/getCookie.bru
- tests/scripting/bru-api/cookies/init-user-data/preferences.json
- tests/scripting/bru-api/cookies/init-user-data/collection-security.json
- packages/bruno-tests/collection/scripting/api/bru/cookies/directWrite.bru
🚧 Files skipped from review as they are similar to previous changes (1)
- tests/scripting/bru-api/cookies/cookies.spec.ts
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/bruno-tests/collection/scripting/api/bru/cookies/directIteration.bru (1)
13-29: Prefer URL-scoped cookie cleanup for better test isolation.This fixture currently clears the entire jar (
jar.clear()), which can create cross-test coupling. Since this request is URL-scoped, clearing only current-request cookies is safer and keeps fixtures independent.♻️ Suggested update
script:pre-request { - const jar = bru.cookies.jar() - - const host = bru.getEnvVar('localhost'); - await jar.setCookies(host, [ + const jar = bru.cookies.jar() + const requestUrl = '{{localhost}}/ping'; + + // isolate this fixture to current request URL + await bru.cookies.clear(); + await jar.setCookies(requestUrl, [ { key: 'x', value: '10', path: '/' @@ tests { @@ - const jar = bru.cookies.jar() - await jar.clear() + await bru.cookies.clear() }Also applies to: 88-89
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-tests/collection/scripting/api/bru/cookies/directIteration.bru` around lines 13 - 29, The test currently calls jar.clear() which wipes the entire cookie jar and can cause cross-test coupling; change the cleanup to only clear cookies for the current request by calling the URL-scoped clear with the existing host variable (e.g., replace jar.clear() with jar.clear(host)) so only cookies for this request/host are removed; update any similar usages (e.g., the case at lines 88-89) to the same URL-scoped clear call.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In
`@packages/bruno-tests/collection/scripting/api/bru/cookies/directIteration.bru`:
- Around line 13-29: The test currently calls jar.clear() which wipes the entire
cookie jar and can cause cross-test coupling; change the cleanup to only clear
cookies for the current request by calling the URL-scoped clear with the
existing host variable (e.g., replace jar.clear() with jar.clear(host)) so only
cookies for this request/host are removed; update any similar usages (e.g., the
case at lines 88-89) to the same URL-scoped clear call.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 1de6e0ee-b333-4c24-ad5f-8ebed7e600e5
📒 Files selected for processing (18)
packages/bruno-tests/collection/scripting/api/bru/cookies/clear.brupackages/bruno-tests/collection/scripting/api/bru/cookies/clearScope.brupackages/bruno-tests/collection/scripting/api/bru/cookies/crossDomainIsolation.brupackages/bruno-tests/collection/scripting/api/bru/cookies/deleteCookie.brupackages/bruno-tests/collection/scripting/api/bru/cookies/deleteCookies.brupackages/bruno-tests/collection/scripting/api/bru/cookies/directGet.brupackages/bruno-tests/collection/scripting/api/bru/cookies/directIteration.brupackages/bruno-tests/collection/scripting/api/bru/cookies/directReadMethods.brupackages/bruno-tests/collection/scripting/api/bru/cookies/directWrite.brupackages/bruno-tests/collection/scripting/api/bru/cookies/getCookie.brupackages/bruno-tests/collection/scripting/api/bru/cookies/getCookies.brupackages/bruno-tests/collection/scripting/api/bru/cookies/hasCookie.brupackages/bruno-tests/collection/scripting/api/bru/cookies/setCookie.brupackages/bruno-tests/collection/scripting/api/bru/cookies/setCookies.brutests/scripting/bru-api/cookies/cookies.spec.tstests/scripting/bru-api/cookies/init-user-data/collection-security.jsontests/scripting/bru-api/cookies/init-user-data/preferences.jsontests/utils/page/runner.ts
✅ Files skipped from review due to trivial changes (11)
- packages/bruno-tests/collection/scripting/api/bru/cookies/getCookie.bru
- packages/bruno-tests/collection/scripting/api/bru/cookies/clear.bru
- packages/bruno-tests/collection/scripting/api/bru/cookies/setCookie.bru
- packages/bruno-tests/collection/scripting/api/bru/cookies/deleteCookie.bru
- packages/bruno-tests/collection/scripting/api/bru/cookies/setCookies.bru
- packages/bruno-tests/collection/scripting/api/bru/cookies/deleteCookies.bru
- tests/scripting/bru-api/cookies/init-user-data/collection-security.json
- tests/scripting/bru-api/cookies/init-user-data/preferences.json
- packages/bruno-tests/collection/scripting/api/bru/cookies/hasCookie.bru
- packages/bruno-tests/collection/scripting/api/bru/cookies/crossDomainIsolation.bru
- packages/bruno-tests/collection/scripting/api/bru/cookies/directReadMethods.bru
🚧 Files skipped from review as they are similar to previous changes (5)
- packages/bruno-tests/collection/scripting/api/bru/cookies/getCookies.bru
- tests/scripting/bru-api/cookies/cookies.spec.ts
- packages/bruno-tests/collection/scripting/api/bru/cookies/directWrite.bru
- packages/bruno-tests/collection/scripting/api/bru/cookies/directGet.bru
- packages/bruno-tests/collection/scripting/api/bru/cookies/clearScope.bru
5525086 to
9ddd04b
Compare
- Introduced new methods for direct cookie access: `bru.cookies.get`, `bru.cookies.has`, and `bru.cookies.toObject`. - Updated translation mappings in `bruno-to-postman-translator` and `postman-to-bruno-translator` to support these new methods. - Enhanced tests to verify correct translation between `bru` and `pm` cookie methods, including mixed usage scenarios. - Updated `Bru` class to handle cookie access based on the current request URL.
- Added new cookie methods: `toString`, `clear`, `delete`, `one`, `all`, `idx`, `count`, `indexOf`, `find`, `filter`, `each`, `map`, and `reduce` to `bru.cookies`. - Refactored `Bru` class to utilize a new `CookieList` for cookie management, improving structure and readability. - Updated translation mappings in `bruno-to-postman-translator` and `postman-to-bruno-translator` to include new cookie methods. - Introduced `PropertyList` and `ReadOnlyPropertyList` classes for better data structure management. - Enhanced tests for comprehensive coverage of new cookie functionalities and their interactions.
- Added new cookie methods: `get`, `has`, `toString`, `clear`, `upsert`, `remove`, `idx`, and `indexOf` to enhance cookie management. - Updated translation mappings for `bru.cookies` to include new methods in `bruno-to-postman-translator` and `postman-to-bruno-translator`. - Introduced tests for new methods and their interactions, ensuring comprehensive coverage of cookie functionalities. - Enhanced existing tests to validate correct behavior of cookie methods across different scenarios.
…ve error handling
- Introduced regression tests to ensure that jar patterns are correctly prioritized over direct cookie access patterns in translations. - Updated `CookieList` to extend `ReadOnlyPropertyList` instead of `PropertyList`, clarifying its functionality. - Refactored cookie method handling in the `bru` shim to utilize a new asynchronous bridge for improved error handling and consistency.
- Enhanced comments in `postman-translations.js` to clarify the order of cookie jar translations. - Updated `cookie-list.js` comments to better describe the factory function for the cookie jar. - Removed the `PropertyList` class and its associated tests, streamlining the codebase and focusing on `ReadOnlyPropertyList` and `CookieList` for cookie management.
…d comments - Updated `CookieList` to normalize tough-cookie instances to plain objects, preventing circular references and exposing internal structures. - Enhanced comments in the `remove` method to clarify behavior when removing non-existent or empty-named cookies.
…d enhance translation comments - Modified the autocomplete hint for `bru.cookies.has` to include the new signature with an optional value parameter. - Improved comments in `postman-translations.js` to clarify the order of cookie jar translation patterns for better understanding.
…gement - Introduced a new `createPropertyListBridge` utility to streamline the integration of cookie methods into the QuickJS VM. - Replaced the previous async cookie bridge with a more flexible approach, allowing for both synchronous and asynchronous cookie operations. - Added comprehensive tests to validate the functionality of the new cookie methods in both developer and safe modes. - Updated existing cookie tests to ensure compatibility with the new PropertyList structure.
- Updated the expected number of passed requests in the cookie tests from 34 to 6 to reflect the correct validation results. - Ensured consistency in test assertions across multiple test cases for the PropertyList API.
- Changed all cookie-related test scripts to use `{{localhost}}` instead of `{{host}}` for the ping URL, ensuring consistency in local testing environments.
- Updated the cookie test suite to reflect the new URL structure, enhancing the reliability of the tests.
- Removed outdated cookie test files to streamline the test suite.
- Updated cookie test scripts to utilize the `{{localhost}}` variable for setting and retrieving cookies, ensuring consistency across tests.
- Enhanced clarity in comments regarding cookie behavior for different domains.
- Improved test assertions to validate cookie management functionality more effectively.
…e private class fields
… method improvements - Updated the `CookieList` class to provide comprehensive documentation on cookie management methods, including `add`, `upsert`, `remove`, and `delete`. - Improved method signatures to support both callback and Promise-based usage for asynchronous operations. - Added detailed descriptions for read and write methods, including examples and expected behavior. - Enhanced the integration of the `CookieList` with the QuickJS VM by updating the property list bridge to include `toJSON` in sync read object methods.
…tation - Enhanced the `createPropertyListBridge` function documentation with comprehensive examples for setting up cookie methods in QuickJS. - Clarified the two-phase setup process for async write methods, detailing the registration of bridge functions and the generation of JavaScript code for method wrappers. - Added a new test case for the `toJSON()` method to ensure it returns a cloned array of all cookies, validating the expected structure and properties.
9ddd04b to
75465bc
Compare
- Added a semicolon at the end of the response parser assignment to ensure proper syntax in the AssertRuntime class.
…ns (usebruno#7073) * feat(cookies): add direct cookie access methods and update translations - Introduced new methods for direct cookie access: `bru.cookies.get`, `bru.cookies.has`, and `bru.cookies.toObject`. - Updated translation mappings in `bruno-to-postman-translator` and `postman-to-bruno-translator` to support these new methods. - Enhanced tests to verify correct translation between `bru` and `pm` cookie methods, including mixed usage scenarios. - Updated `Bru` class to handle cookie access based on the current request URL. * feat(cookies): enhance cookie management with new methods and refactor - Added new cookie methods: `toString`, `clear`, `delete`, `one`, `all`, `idx`, `count`, `indexOf`, `find`, `filter`, `each`, `map`, and `reduce` to `bru.cookies`. - Refactored `Bru` class to utilize a new `CookieList` for cookie management, improving structure and readability. - Updated translation mappings in `bruno-to-postman-translator` and `postman-to-bruno-translator` to include new cookie methods. - Introduced `PropertyList` and `ReadOnlyPropertyList` classes for better data structure management. - Enhanced tests for comprehensive coverage of new cookie functionalities and their interactions. * docs(readonly-property-list): clarify array usage in constructor comments * feat(cookies): add direct cookie manipulation tests and methods * feat(cookies): add hasCookie method for checking cookie existence * fix * refactor(cookies): simplify cookie method translations * feat(cookies): expand cookie API with new methods and tests - Added new cookie methods: `get`, `has`, `toString`, `clear`, `upsert`, `remove`, `idx`, and `indexOf` to enhance cookie management. - Updated translation mappings for `bru.cookies` to include new methods in `bruno-to-postman-translator` and `postman-to-bruno-translator`. - Introduced tests for new methods and their interactions, ensuring comprehensive coverage of cookie functionalities. - Enhanced existing tests to validate correct behavior of cookie methods across different scenarios. * refactor(cookies): update CookieList to extend PropertyList and improve error handling * test(cookies): add regression tests for jar and direct cookie patterns - Introduced regression tests to ensure that jar patterns are correctly prioritized over direct cookie access patterns in translations. - Updated `CookieList` to extend `ReadOnlyPropertyList` instead of `PropertyList`, clarifying its functionality. - Refactored cookie method handling in the `bru` shim to utilize a new asynchronous bridge for improved error handling and consistency. * refactor(cookies): update translations and remove PropertyList - Enhanced comments in `postman-translations.js` to clarify the order of cookie jar translations. - Updated `cookie-list.js` comments to better describe the factory function for the cookie jar. - Removed the `PropertyList` class and its associated tests, streamlining the codebase and focusing on `ReadOnlyPropertyList` and `CookieList` for cookie management. * fix(cookies): normalize tough-cookie objects and improve remove method comments - Updated `CookieList` to normalize tough-cookie instances to plain objects, preventing circular references and exposing internal structures. - Enhanced comments in the `remove` method to clarify behavior when removing non-existent or empty-named cookies. * test(cookies): update tests to use async/await for consistency * test(cookies): use async/await in cookie tests for consistency * refactor(readonly-property-list): update get and reduce methods for improved behavior * fix(cookies): update cookie method signature in autocomplete hints and enhance translation comments - Modified the autocomplete hint for `bru.cookies.has` to include the new signature with an optional value parameter. - Improved comments in `postman-translations.js` to clarify the order of cookie jar translation patterns for better understanding. * refactor(cookies): introduce PropertyList for enhanced cookie management * refactor(property-list): simplify repopulate method and enhance item handling logic * feat(cookies): implement PropertyList bridge for enhanced cookie management - Introduced a new `createPropertyListBridge` utility to streamline the integration of cookie methods into the QuickJS VM. - Replaced the previous async cookie bridge with a more flexible approach, allowing for both synchronous and asynchronous cookie operations. - Added comprehensive tests to validate the functionality of the new cookie methods in both developer and safe modes. - Updated existing cookie tests to ensure compatibility with the new PropertyList structure. * fix(tests): correct expected passed requests in cookie tests - Updated the expected number of passed requests in the cookie tests from 34 to 6 to reflect the correct validation results. - Ensured consistency in test assertions across multiple test cases for the PropertyList API. * fix(cookies): update cookie URLs to use localhost for testing - Changed all cookie-related test scripts to use `{{localhost}}` instead of `{{host}}` for the ping URL, ensuring consistency in local testing environments. - Updated the cookie test suite to reflect the new URL structure, enhancing the reliability of the tests. - Removed outdated cookie test files to streamline the test suite. * refactor(cookies): standardize cookie handling with localhost variable - Updated cookie test scripts to utilize the `{{localhost}}` variable for setting and retrieving cookies, ensuring consistency across tests. - Enhanced clarity in comments regarding cookie behavior for different domains. - Improved test assertions to validate cookie management functionality more effectively. * refactor(property-list, readonly-property-list): update methods to use private class fields * feat(cookies): enhance CookieList API with detailed documentation and method improvements - Updated the `CookieList` class to provide comprehensive documentation on cookie management methods, including `add`, `upsert`, `remove`, and `delete`. - Improved method signatures to support both callback and Promise-based usage for asynchronous operations. - Added detailed descriptions for read and write methods, including examples and expected behavior. - Enhanced the integration of the `CookieList` with the QuickJS VM by updating the property list bridge to include `toJSON` in sync read object methods. * feat(cookies): add detailed examples and improve async bridge documentation - Enhanced the `createPropertyListBridge` function documentation with comprehensive examples for setting up cookie methods in QuickJS. - Clarified the two-phase setup process for async write methods, detailing the registration of bridge functions and the generation of JavaScript code for method wrappers. - Added a new test case for the `toJSON()` method to ensure it returns a cloned array of all cookies, validating the expected structure and properties. * fix(assert-runtime): correct syntax error in response parser assignment - Added a semicolon at the end of the response parser assignment to ensure proper syntax in the AssertRuntime class.
Jira
Summary
Adds direct
bru.cookies.*access methods that mirror Postman'spm.cookiesAPI, allowing users to read, iterate, and manipulate cookies without going throughbru.cookies.jar().Previously, all cookie operations required explicitly creating a jar and passing URLs:
Now, users can work with cookies scoped to the current request URL directly:
The existing
jar()API remains fully supported and backward-compatible.Architecture
Class hierarchy (
packages/bruno-js/src/)ReadOnlyPropertyList— Base collection class supporting two modes:dataSourcefunction returns fresh items on every read (used by cookies)PropertyList— Adds sync mutation methods (add,remove,upsert,clear, etc.) for static mode. Throws in dynamic mode to enforce subclass overrides.CookieList— Cookie-specific subclass using dynamic mode. Read/iteration methods are inherited; write methods (add,upsert,remove,delete,clear) delegate to the cookie jar asynchronously.jar()provides direct jar access with URL interpolation.QuickJS sandbox bridge (
packages/bruno-js/src/sandbox/quickjs/utils/property-list-bridge.js)A reusable factory that auto-wires PropertyList methods onto QuickJS VM objects:
vm.newFunctionreturning marshalled valuescleanCircularJson()for safe serialization_prefixbridge pattern: native callback → QuickJS promiseall()as the data sourceNew
bru.cookiesmethodsget(name),has(name, [value]),one(name),all(),count(),idx(n),indexOf(item),toObject(),toString()each(fn),find(fn),filter(fn),map(fn),reduce(fn, acc)add(obj),upsert(obj),remove(name),delete(name),clear()Key behaviors
clear()vsjar().clear():bru.cookies.clear()removes only cookies for the current URL;jar().clear()removes ALL cookies globallyadd()=upsert(): Both delegate tojar.setCookie()(cookie jars inherently upsert)remove()=delete(): Aliases for the same operationChanges
Core implementation
bru.js— Replaced inline cookies object withnew CookieList(...), acceptsrequestUrlparametersandbox/quickjs/shims/bru.js— Exposed all new cookie methods to the QuickJS sandbox viacreatePropertyListBridgeruntime/*.js(script-runtime,test-runtime,assert-runtime,vars-runtime) — Passrequest?.urltoBruconstructorTranslators
postman-translations.js— Added regex translations forpm.cookies.*direct access methods; reordered jar patterns before simpler patterns to prevent false matchespostman-to-bruno-translator.js— Added AST simple translations forpm.cookies.*; removed complex AST transforms forpm.cookies.has/get/toObject(no longer needed since translations are now 1:1)bruno-to-postman-translator.js— Added reverse translations forbru.cookies.*Autocomplete
autocomplete.js— Added all newbru.cookies.*method hints +jar().hasCookie()E2E test fixtures (
packages/bruno-tests/collection/scripting/api/bru/cookies/)directGet.bru— Testsget()andhas()(with value matching)directReadMethods.bru— Testsone(),all(),count(),idx(),toObject(),toString()directIteration.bru— Testseach(),find(),filter(),map(),reduce(),indexOf(),idx()edge casesdirectWrite.bru— Testsadd(),upsert(),remove(),delete(),clear()clearScope.bru— Verifiesbru.cookies.clear()only clears current URL vsjar().clear()clears allcrossDomainIsolation.bru— Verifies cookies from other domains are not visible viabru.cookies*.brufiles updated to use{{localhost}}variable for consistencyPlaywright E2E tests (
tests/scripting/bru-api/cookies/)cookies.spec.ts— Runs all cookie tests in both developer and safe sandbox modes (16 requests each)runner.ts— NewrunFolder()utility for running a specific folder within a collectionUnit tests (
packages/bruno-js/tests/)readonly-property-list.spec.js— Covers all read/search/iteration/transform methods, static + dynamic modes, edge casesproperty-list.spec.js— Covers all mutation methods in static mode, dynamic mode guardscookie-list.spec.js— Covers async write delegation, jar integration, URL interpolation, no-URL edge cases, tough-cookie normalizationTest plan
npm run test --workspace=packages/bruno-jsnpm run test --workspace=packages/bruno-convertersbru run scripting/api/bru/cookies --env=Prod(42/42 pass)bru.cookies.get()works in pre-request/test scriptspm.cookies.get()and verify it translates correctlyContribution Checklist:
Note: Keeping the PR small and focused helps make it easier to review and merge. If you have multiple changes you want to make, please consider submitting them as separate pull requests.
Publishing to New Package Managers
Please see here for more information.
Summary by CodeRabbit
New Features
get(),has(),remove(),clear(),add(),upsert(),one(),all(),count(),find(),filter(),each(),map(),reduce(), andtoObject()for more comprehensive cookie manipulation.Tests