Compare commits

..

52 Commits

Author SHA1 Message Date
ramki-bruno
1c58e007b3 Made clear that the Save button for Font related settings is local 2025-02-22 14:58:58 +05:30
ramki-bruno
3dc84f46e5 Fix: Review fixes and add schema for editor-preferences 2025-02-22 14:56:26 +05:30
ramki-bruno
884fa77bac Added editor-keymap preference selection under Display/Code Editor 2025-02-20 21:50:50 +05:30
Sanjai Kumar
b28b60d4a7 chore: update BugReport template for clarity and additional information 2025-02-18 21:59:23 +05:30
Sanjai Kumar
2fc45de430 chore: update BugReport template to include version and OS information 2025-02-18 21:59:23 +05:30
Ryan
c58604716e Update FeatureRequest.yaml (#3974)
updated submittal questions
2025-02-18 21:56:41 +05:30
lohit
31409c6206 feat: reuse worker threads for bru file parsing (#4054) 2025-02-18 19:58:37 +05:30
Anoop M D
dfb0b1b966 fix: allow popus in notification iframes
This is to allow is to allow users to open pages (like bruno downloads) from the app
2025-02-14 21:25:28 +05:30
Anoop M D
f8b4a0b85b feat: notification visibility rules based on semver 2025-02-14 18:16:34 +05:30
naman-bruno
200732bac5 fix: space on collection docs 2025-02-14 17:54:20 +05:30
ramki-bruno
c997924c42 Strengthen CSP 2025-02-14 16:01:25 +05:30
ramki-bruno
711eb24c01 Refactoring InfoTip to support just text and children instead of HTML 2025-02-14 16:00:59 +05:30
ramki-bruno
3b8a613914 Refactor ToolHint to use text prop as text instead of HTML
Currently there is no usage of ToolHint where we are passing HTML
content, so this should not break anything.
2025-02-14 16:00:59 +05:30
naman-bruno
81930f6fe6 Fix: Import collection failed for postman custom method 2025-02-14 02:43:31 +05:30
sreelakshmi-bruno
e0750148e6 Styling improvements in failed-load-request summary (#3956)
Co-authored-by: Sreelakshmi Jayarajan <sreelakshmi@Sreelakshmis-MacBook-Air.local>
2025-02-14 02:42:14 +05:30
Anoop M D
528f822294 feat: notifications are displayed using iframe 2025-02-14 02:37:07 +05:30
lohit
31c11830a6 fix: should be able to save the request after reverting the changes (#3999) 2025-02-11 20:38:04 +05:30
lohxt1
eff3b29bfb fix: should be able to save request after reverting all the changes 2025-02-11 20:27:05 +05:30
lohxt1
4656958f2f fix: should be able to save request after reverting all the changes 2025-02-11 20:27:05 +05:30
ramki-bruno
aa4575b0ea Fix: CLI-Tests Workflow lacks contents:read permission 2025-02-11 18:08:01 +05:30
Sanjai Kumar
14d798eea7 Revert "fix: improve handling of Buffer responses and set default charset to utf-8"
This reverts commit d8a2e6f405.
2025-02-11 18:06:30 +05:30
Sanjai Kumar
8af285d41e Revert "refactor: enhance JSON parsing logic for Buffer responses"
This reverts commit 14e9227e07.
2025-02-11 18:06:30 +05:30
naman-bruno
6a0eb1ccde fix: nonReplaceableTabTypes getting duplicate 2025-02-11 15:35:52 +05:30
naman-bruno
4a613ed1b7 Fix: duplicate collection tabs 2025-02-11 15:35:52 +05:30
sanjai0py
7566d658d4 Fix: Prevent interpolation of buffer values in JSON requests 2025-02-11 15:32:44 +05:30
ramki-bruno
70ee819bae Fix: Postman-import-translation not adding comments for unsupported APIs
There was an error in one of the WIP feature which is breaking the
translation, for now commenting it out.
2025-02-10 21:47:43 +05:30
lohxt1
8810b9e291 fix graphql variables editor and tests editor height 2025-02-10 21:42:53 +05:30
Sanjai Kumar
89a4cd62bc Feat: Move-Collection with Drag-and-Drop (#3755)
---------

Co-authored-by: sanjai0py <sanjailucifer666@gmail.com>
Co-authored-by: ramki-bruno <ramki@usebruno.com>
2025-02-10 20:46:42 +05:30
Anoop M D
4c1765e9f9 feat(#2896): add support for cheerio and xml2json as inbuilt library 2025-02-10 18:55:20 +05:30
Sreelakshmi Jayarajan
8351589994 Fixing typo in pm translation of util function 2025-02-10 18:55:11 +05:30
Sreelakshmi Jayarajan
4d063b2d0b Revert "Fixing typo in pm translation of util functions"
This reverts commit fceff56872.
2025-02-10 18:55:11 +05:30
Sreelakshmi Jayarajan
288628003f Fixing typo in pm translation of util functions 2025-02-10 18:55:11 +05:30
Pooja Belaramani
ced6ddfab5 add: translation for skipRequest and stopExecution 2025-02-10 11:45:23 +05:30
Pragadesh-45
5291bbaef7 Fix: Import failing for collections with special characters in Windows (#3969)
* fix: correct variable used in collection name update
* fix: sanitize collection names by removing invalid filesystem characters
* refactor: refactor collection name sanitization to use `sanitizeDirectoryName`
2025-02-10 11:37:50 +05:30
ramki-bruno
667b15386c Fix: Unresponsive click-area in folder-collection-item between chevron-icon and name 2025-02-06 23:34:58 +05:30
ramki-bruno
086e943c04 Fix: Collectio-items not loading when clicking on chevron icon the first-time 2025-02-06 23:34:58 +05:30
ramki-bruno
901c4e1ca2 Fix: Request-send action should make the Tab permanent/non-preview 2025-02-06 23:34:58 +05:30
sanjai0py
14e9227e07 refactor: enhance JSON parsing logic for Buffer responses 2025-02-06 21:24:55 +05:30
sanjai0py
d8a2e6f405 fix: improve handling of Buffer responses and set default charset to utf-8 2025-02-06 21:24:55 +05:30
lohxt1
5c096cff7b fix worker lane logic 2025-02-06 21:20:23 +05:30
Sanjai Kumar
0913e668e0 refactor: update browseFiles action to remove default properties and improve file dialog handling (#3957)
---------
Co-authored-by: sanjai0py <sanjailucifer666@gmail.com>
2025-02-06 20:26:49 +05:30
Sahil Khan
f0c3125227 fix:handle render svg response (#3833) 2025-02-06 20:23:27 +05:30
naman-bruno
a5d23599a1 Fixed: user cookie header getting overwritten by stored cookie in cli 2025-02-06 20:03:42 +05:30
naman-bruno
28ca0494e0 Fixed: user cookie header getting overwritten by stored cookie 2025-02-06 20:03:42 +05:30
naman-bruno
722d9788ca Feature: Improve tab UX (#3831)
---------
Co-authored-by: ramki-bruno <ramki@usebruno.com>
2025-02-06 19:34:10 +05:30
lohit
038f2d1f0b temp. revert tests for file body (#3941)
* temporarily revert tests for file body
2025-02-04 22:12:59 +05:30
lohit
8f604efc7e fixes tests for the file body pr (#3940)
fixes tests for bruno-app and bruno-electron
2025-02-04 22:12:59 +05:30
Sanjai Kumar
af182a9c00 refactor: rename binaryFile to file and update related references 2025-02-04 22:12:59 +05:30
Sanjai Kumar
dd23962958 improvements (#3930)
Co-authored-by: Sanjai Kumar <sanjai@usebruno.com>
2025-02-04 22:12:59 +05:30
Marcos Adriano
324b7cec51 feat: raw binary files handling in request body (#3734)
--------------
Co-authored-by: lohit <lohit@usebruno.com>
Co-authored-by: Anoop M D <anoop.md1421@gmail.com>
2025-02-04 22:12:59 +05:30
lohxt1
8abf8ff9c8 skipped request should not be considered as errors in junit reports 2025-02-04 21:48:10 +05:30
Pragadesh-45
ec5a5c9b56 fix: correct variable used in collection name update 2025-02-04 18:49:02 +05:30
98 changed files with 1704 additions and 640 deletions

View File

@@ -6,26 +6,47 @@ body:
attributes:
value: |
Thanks for taking the time to fill out this bug report!
Before submitting, please make sure you've searched existing issues:
👉 [Search existing issues](https://github.com/usebruno/bruno/issues?q=is%3Aissue)
- type: checkboxes
attributes:
label: 'I have checked the following:'
options:
- label: I use the newest version of bruno.
required: true
- label: I've searched existing issues and found nothing related to my issue.
- label: "I have searched existing issues and found nothing related to my issue."
required: true
- type: input
attributes:
label: Bruno version
description: Please specify the version of Bruno you are using in which the issue occurs.
placeholder: 1.38.1
validations:
required: true
- type: input
attributes:
label: Operating System
description: Information about the operating system the issue occurs on.
placeholder: Windows / Mac / Linux
validations:
required: true
- type: textarea
attributes:
label: Describe the bug
description: A clear and concise description of the bug.
description: A clear and concise description of the bug and also include steps to reproduce it.
validations:
required: true
- type: textarea
attributes:
label: .bru file to reproduce the bug
description: Attach your .bru file here that can reqroduce the problem.
description: Attach your .bru file here that can reproduce the problem.
validations:
required: false
- type: textarea
attributes:
label: Screenshots/Live demo link

View File

@@ -8,13 +8,23 @@ body:
options:
- label: I've searched existing issues and found nothing related to my issue.
required: true
- type: checkboxes
attributes:
label: 'This feature'
options:
- label: blocks me from using Bruno
required: false
- label: would improve my quality of life in Bruno
required: false
- label: is something I've never seen an API client do before
required: false
- type: markdown
attributes:
value: |
Suggest an idea for this project.
- type: textarea
attributes:
label: Describe the feature you want to add
label: Describe the feature you want to add, and how it would change your usage of Bruno
description: A clear and concise description of the feature you want to be added.
validations:
required: true
@@ -23,4 +33,4 @@ body:
label: Mockups or Images of the feature
description: Add some images to support your feature.
validations:
required: true
required: false

View File

@@ -5,14 +5,13 @@ on:
pull_request:
branches: [main]
permissions:
contents: read
jobs:
unit-test:
name: Unit Tests
timeout-minutes: 60
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
@@ -55,6 +54,7 @@ jobs:
permissions:
checks: write
pull-requests: write
contents: read
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4

442
package-lock.json generated
View File

@@ -50,7 +50,6 @@
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz",
"integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.5",
@@ -787,7 +786,6 @@
"version": "7.26.0",
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.26.0.tgz",
"integrity": "sha512-i1SLeK+DzNnQ3LL/CswPCa/E5u4lh1k6IAEphON8F+cXt0t9euTshDru0q7/IqMa1PMPz5RnHuHscF8/ZJsStg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@ampproject/remapping": "^2.2.0",
@@ -818,7 +816,6 @@
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz",
"integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==",
"dev": true,
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
@@ -836,7 +833,6 @@
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"dev": true,
"license": "MIT"
},
"node_modules/@babel/generator": {
@@ -1116,7 +1112,6 @@
"version": "7.26.0",
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.0.tgz",
"integrity": "sha512-tbhNuIxNcVb21pInl3ZSjksLCvgdZy9KwJ8brv993QtIVKJBBkYXz4q4ZbAv31GdnC+R90np23L5FbEBlthAEw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/template": "^7.25.9",
@@ -7083,7 +7078,6 @@
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz",
"integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/lodash": {
@@ -7096,7 +7090,6 @@
"version": "12.2.3",
"resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-12.2.3.tgz",
"integrity": "sha512-GKMHFfv3458yYy+v/N8gjufHO6MSZKCOXpZc5GXIWWy8uldwfmPn98vp81gZ5f9SVw8YYBctgfJ22a2d7AOMeQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/linkify-it": "*",
@@ -7107,7 +7100,6 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-2.0.0.tgz",
"integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/ms": {
@@ -7199,6 +7191,13 @@
"@types/estree": "*"
}
},
"node_modules/@types/trusted-types": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
"license": "MIT",
"optional": true
},
"node_modules/@types/verror": {
"version": "1.10.10",
"resolved": "https://registry.npmjs.org/@types/verror/-/verror-1.10.10.tgz",
@@ -8586,7 +8585,6 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
"integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==",
"dev": true,
"license": "ISC"
},
"node_modules/boolean": {
@@ -9417,6 +9415,229 @@
"node": "*"
}
},
"node_modules/cheerio": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0.tgz",
"integrity": "sha512-quS9HgjQpdaXOvsZz82Oz7uxtXiy6UIsIQcpBj7HRw2M63Skasm9qlDocAM7jNuaxdhpPU7c4kJN+gA5MCu4ww==",
"license": "MIT",
"dependencies": {
"cheerio-select": "^2.1.0",
"dom-serializer": "^2.0.0",
"domhandler": "^5.0.3",
"domutils": "^3.1.0",
"encoding-sniffer": "^0.2.0",
"htmlparser2": "^9.1.0",
"parse5": "^7.1.2",
"parse5-htmlparser2-tree-adapter": "^7.0.0",
"parse5-parser-stream": "^7.1.2",
"undici": "^6.19.5",
"whatwg-mimetype": "^4.0.0"
},
"engines": {
"node": ">=18.17"
},
"funding": {
"url": "https://github.com/cheeriojs/cheerio?sponsor=1"
}
},
"node_modules/cheerio-select": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-2.1.0.tgz",
"integrity": "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==",
"license": "BSD-2-Clause",
"dependencies": {
"boolbase": "^1.0.0",
"css-select": "^5.1.0",
"css-what": "^6.1.0",
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3",
"domutils": "^3.0.1"
},
"funding": {
"url": "https://github.com/sponsors/fb55"
}
},
"node_modules/cheerio-select/node_modules/css-select": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/css-select/-/css-select-5.1.0.tgz",
"integrity": "sha512-nwoRF1rvRRnnCqqY7updORDsuqKzqYJ28+oSMaJMMgOauh3fvwHqMS7EZpIPqK8GL+g9mKxF1vP/ZjSeNjEVHg==",
"license": "BSD-2-Clause",
"dependencies": {
"boolbase": "^1.0.0",
"css-what": "^6.1.0",
"domhandler": "^5.0.2",
"domutils": "^3.0.1",
"nth-check": "^2.0.1"
},
"funding": {
"url": "https://github.com/sponsors/fb55"
}
},
"node_modules/cheerio-select/node_modules/dom-serializer": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
"integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
"license": "MIT",
"dependencies": {
"domelementtype": "^2.3.0",
"domhandler": "^5.0.2",
"entities": "^4.2.0"
},
"funding": {
"url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
}
},
"node_modules/cheerio-select/node_modules/domelementtype": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
"integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "BSD-2-Clause"
},
"node_modules/cheerio-select/node_modules/domhandler": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
"integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
"license": "BSD-2-Clause",
"dependencies": {
"domelementtype": "^2.3.0"
},
"engines": {
"node": ">= 4"
},
"funding": {
"url": "https://github.com/fb55/domhandler?sponsor=1"
}
},
"node_modules/cheerio-select/node_modules/domutils": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
"integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
"license": "BSD-2-Clause",
"dependencies": {
"dom-serializer": "^2.0.0",
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3"
},
"funding": {
"url": "https://github.com/fb55/domutils?sponsor=1"
}
},
"node_modules/cheerio-select/node_modules/entities": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
"integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.12"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/cheerio/node_modules/dom-serializer": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
"integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
"license": "MIT",
"dependencies": {
"domelementtype": "^2.3.0",
"domhandler": "^5.0.2",
"entities": "^4.2.0"
},
"funding": {
"url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
}
},
"node_modules/cheerio/node_modules/domelementtype": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
"integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "BSD-2-Clause"
},
"node_modules/cheerio/node_modules/domhandler": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
"integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
"license": "BSD-2-Clause",
"dependencies": {
"domelementtype": "^2.3.0"
},
"engines": {
"node": ">= 4"
},
"funding": {
"url": "https://github.com/fb55/domhandler?sponsor=1"
}
},
"node_modules/cheerio/node_modules/domutils": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
"integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
"license": "BSD-2-Clause",
"dependencies": {
"dom-serializer": "^2.0.0",
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3"
},
"funding": {
"url": "https://github.com/fb55/domutils?sponsor=1"
}
},
"node_modules/cheerio/node_modules/entities": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
"integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.12"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/cheerio/node_modules/htmlparser2": {
"version": "9.1.0",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-9.1.0.tgz",
"integrity": "sha512-5zfg6mHUoaer/97TxnGpxmbR7zJtPwIYFMZ/H5ucTlPZhKvtum05yiPK3Mgai3a0DyVxv7qYqoweaEd2nrYQzQ==",
"funding": [
"https://github.com/fb55/htmlparser2?sponsor=1",
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "MIT",
"dependencies": {
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3",
"domutils": "^3.1.0",
"entities": "^4.5.0"
}
},
"node_modules/cheerio/node_modules/parse5": {
"version": "7.2.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-7.2.1.tgz",
"integrity": "sha512-BuBYQYlv1ckiPdQi/ohiivi9Sagc9JG+Ozs0r7b/0iK3sKmrb0b9FdWdBbOdx6hBCM/F9Ir82ofnBhtZOjCRPQ==",
"license": "MIT",
"dependencies": {
"entities": "^4.5.0"
},
"funding": {
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/chokidar": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
@@ -10115,7 +10336,6 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
"integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
"dev": true,
"license": "MIT"
},
"node_modules/cookie": {
@@ -10583,7 +10803,6 @@
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/css-what/-/css-what-6.1.0.tgz",
"integrity": "sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">= 6"
@@ -11256,6 +11475,15 @@
"domelementtype": "1"
}
},
"node_modules/dompurify": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.2.4.tgz",
"integrity": "sha512-ysFSFEDVduQpyhzAob/kkuJjf5zWkZD8/A9ywSp1byueyuCfHamrCBa14/Oc2iiB0e51B+NpxSl5gmzn+Ms/mg==",
"license": "(MPL-2.0 OR Apache-2.0)",
"optionalDependencies": {
"@types/trusted-types": "^2.0.7"
}
},
"node_modules/domutils": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz",
@@ -11718,13 +11946,25 @@
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz",
"integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"iconv-lite": "^0.6.2"
}
},
"node_modules/encoding-sniffer": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/encoding-sniffer/-/encoding-sniffer-0.2.0.tgz",
"integrity": "sha512-ju7Wq1kg04I3HtiYIOrUrdfdDvkyO9s5XM8QAj/bN61Yo/Vb4vgJxy5vi4Yxk01gWHbrofpPtpxM8bKger9jhg==",
"license": "MIT",
"dependencies": {
"iconv-lite": "^0.6.3",
"whatwg-encoding": "^3.1.1"
},
"funding": {
"url": "https://github.com/fb55/encoding-sniffer?sponsor=1"
}
},
"node_modules/end-of-stream": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz",
@@ -12739,7 +12979,6 @@
"version": "1.0.0-beta.2",
"resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
"integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -17377,7 +17616,6 @@
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz",
"integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"boolbase": "^1.0.0"
@@ -17782,6 +18020,106 @@
"dev": true,
"license": "MIT"
},
"node_modules/parse5-htmlparser2-tree-adapter": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-7.1.0.tgz",
"integrity": "sha512-ruw5xyKs6lrpo9x9rCZqZZnIUntICjQAd0Wsmp396Ul9lN/h+ifgVV1x1gZHi8euej6wTfpqX8j+BFQxF0NS/g==",
"license": "MIT",
"dependencies": {
"domhandler": "^5.0.3",
"parse5": "^7.0.0"
},
"funding": {
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/parse5-htmlparser2-tree-adapter/node_modules/domelementtype": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
"integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "BSD-2-Clause"
},
"node_modules/parse5-htmlparser2-tree-adapter/node_modules/domhandler": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
"integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
"license": "BSD-2-Clause",
"dependencies": {
"domelementtype": "^2.3.0"
},
"engines": {
"node": ">= 4"
},
"funding": {
"url": "https://github.com/fb55/domhandler?sponsor=1"
}
},
"node_modules/parse5-htmlparser2-tree-adapter/node_modules/entities": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
"integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.12"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/parse5-htmlparser2-tree-adapter/node_modules/parse5": {
"version": "7.2.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-7.2.1.tgz",
"integrity": "sha512-BuBYQYlv1ckiPdQi/ohiivi9Sagc9JG+Ozs0r7b/0iK3sKmrb0b9FdWdBbOdx6hBCM/F9Ir82ofnBhtZOjCRPQ==",
"license": "MIT",
"dependencies": {
"entities": "^4.5.0"
},
"funding": {
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/parse5-parser-stream": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-7.1.2.tgz",
"integrity": "sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow==",
"license": "MIT",
"dependencies": {
"parse5": "^7.0.0"
},
"funding": {
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/parse5-parser-stream/node_modules/entities": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
"integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.12"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/parse5-parser-stream/node_modules/parse5": {
"version": "7.2.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-7.2.1.tgz",
"integrity": "sha512-BuBYQYlv1ckiPdQi/ohiivi9Sagc9JG+Ozs0r7b/0iK3sKmrb0b9FdWdBbOdx6hBCM/F9Ir82ofnBhtZOjCRPQ==",
"license": "MIT",
"dependencies": {
"entities": "^4.5.0"
},
"funding": {
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
@@ -21170,7 +21508,6 @@
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.4.1.tgz",
"integrity": "sha512-+aWOz7yVScEGoKNd4PA10LZ8sk0A/z5+nXQG5giUO5rprX9jgYsTdov9qCchZiPIZezbZH+jRut8nPodFAX4Jg==",
"dev": true,
"license": "ISC"
},
"node_modules/scheduler": {
@@ -23213,7 +23550,7 @@
"version": "4.9.5",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz",
"integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==",
"dev": true,
"devOptional": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
@@ -23229,6 +23566,15 @@
"integrity": "sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA==",
"license": "MIT"
},
"node_modules/undici": {
"version": "6.21.1",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.21.1.tgz",
"integrity": "sha512-q/1rj5D0/zayJB2FraXdaWxbhWiNKDvu8naDT2dl1yTlvJp4BLtOcp2a5BvgGNQpYYJzau7tf1WgKv3b+7mqpQ==",
"license": "MIT",
"engines": {
"node": ">=18.17"
}
},
"node_modules/undici-types": {
"version": "6.20.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz",
@@ -23757,6 +24103,27 @@
"node": ">=10.13.0"
}
},
"node_modules/whatwg-encoding": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz",
"integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==",
"license": "MIT",
"dependencies": {
"iconv-lite": "0.6.3"
},
"engines": {
"node": ">=18"
}
},
"node_modules/whatwg-mimetype": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz",
"integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
@@ -23898,6 +24265,28 @@
"node": ">= 16"
}
},
"node_modules/xml2js": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz",
"integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==",
"license": "MIT",
"dependencies": {
"sax": ">=0.6.0",
"xmlbuilder": "~11.0.0"
},
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/xml2js/node_modules/xmlbuilder": {
"version": "11.0.1",
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz",
"integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==",
"license": "MIT",
"engines": {
"node": ">=4.0"
}
},
"node_modules/xmlbuilder": {
"version": "15.1.1",
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",
@@ -24019,7 +24408,7 @@
},
"packages/bruno-app": {
"name": "@usebruno/app",
"version": "0.3.0",
"version": "1.39.0",
"dependencies": {
"@babel/preset-env": "^7.26.0",
"@fontsource/inter": "^5.0.15",
@@ -24034,6 +24423,7 @@
"codemirror": "5.65.2",
"codemirror-graphql": "2.1.1",
"cookie": "0.7.1",
"dompurify": "^3.2.4",
"escape-html": "^1.0.3",
"file": "^0.2.2",
"file-dialog": "^0.0.8",
@@ -24043,7 +24433,7 @@
"graphiql": "3.7.1",
"graphql": "^16.6.0",
"graphql-request": "^3.7.0",
"httpsnippet": "^3.0.6",
"httpsnippet": "^3.0.9",
"i18next": "24.1.2",
"idb": "^7.0.0",
"immer": "^9.0.15",
@@ -24078,6 +24468,7 @@
"react-redux": "^7.2.9",
"react-tooltip": "^5.5.2",
"sass": "^1.46.0",
"semver": "^7.7.1",
"strip-json-comments": "^5.0.1",
"styled-components": "^5.3.3",
"system": "^2.0.1",
@@ -24135,6 +24526,17 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"packages/bruno-app/node_modules/semver": {
"version": "7.7.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.1.tgz",
"integrity": "sha512-hlq8tAfn0m/61p4BVRcPzIGr6LKiMwo4VM6dGi6pt4qcRkmNzTcWq6eCEjEh+qXjkMDvPlOFFSGwQjoEa6gyMA==",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"packages/bruno-cli": {
"name": "@usebruno/cli",
"version": "1.16.0",
@@ -24365,6 +24767,7 @@
"btoa": "^1.2.1",
"chai": "^4.3.7",
"chai-string": "^1.5.0",
"cheerio": "^1.0.0",
"crypto-js": "^4.1.1",
"json-query": "^2.2.2",
"lodash": "^4.17.21",
@@ -24374,7 +24777,8 @@
"node-vault": "^0.10.2",
"path": "^0.12.7",
"quickjs-emscripten": "^0.29.2",
"uuid": "^9.0.0"
"uuid": "^9.0.0",
"xml2js": "^0.6.2"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^23.0.2",

View File

@@ -1,6 +1,6 @@
{
"name": "@usebruno/app",
"version": "0.3.0",
"version": "1.39.0",
"private": true,
"scripts": {
"dev": "rsbuild dev",
@@ -24,6 +24,7 @@
"codemirror": "5.65.2",
"codemirror-graphql": "2.1.1",
"cookie": "0.7.1",
"dompurify": "^3.2.4",
"escape-html": "^1.0.3",
"file": "^0.2.2",
"file-dialog": "^0.0.8",
@@ -33,7 +34,7 @@
"graphiql": "3.7.1",
"graphql": "^16.6.0",
"graphql-request": "^3.7.0",
"httpsnippet": "^3.0.6",
"httpsnippet": "^3.0.9",
"i18next": "24.1.2",
"idb": "^7.0.0",
"immer": "^9.0.15",
@@ -68,6 +69,7 @@
"react-redux": "^7.2.9",
"react-tooltip": "^5.5.2",
"sass": "^1.46.0",
"semver": "^7.7.1",
"strip-json-comments": "^5.0.1",
"styled-components": "^5.3.3",
"system": "^2.0.1",

View File

@@ -13,6 +13,7 @@ import * as jsonlint from '@prantlf/jsonlint';
import { JSHINT } from 'jshint';
import stripJsonComments from 'strip-json-comments';
import { getAllVariables } from 'utils/collections';
import { connect } from 'react-redux';
let CodeMirror;
const SERVER_RENDERED = typeof window === 'undefined' || global['PREVENT_CODEMIRROR_RENDER'] === true;
@@ -117,7 +118,7 @@ if (!SERVER_RENDERED) {
};
}
export default class CodeEditor extends React.Component {
class CodeEditor extends React.Component {
constructor(props) {
super(props);
@@ -142,7 +143,7 @@ export default class CodeEditor extends React.Component {
lineWrapping: true,
tabSize: TAB_SIZE,
mode: this.props.mode || 'application/ld+json',
keyMap: 'sublime',
keyMap: this.props.editorPrefs?.keymap || 'sublime',
autoCloseBrackets: true,
matchBrackets: true,
showCursorWhenSelecting: true,
@@ -424,3 +425,7 @@ export default class CodeEditor extends React.Component {
}
};
}
const mapStateToProps = (state) => ({ editorPrefs: state.app?.preferences?.editor });
export default connect(mapStateToProps)(CodeEditor);

View File

@@ -1,11 +1,7 @@
import styled from 'styled-components';
const StyledWrapper = styled.div`
div.CodeMirror {
.CodeMirror-scroll {
padding-bottom: 0px;
}
}
.editing-mode {
cursor: pointer;
}

View File

@@ -1,10 +1,14 @@
import React from 'react';
import React from "react";
import { getTotalRequestCountInCollection } from 'utils/collections/';
import { IconFolder, IconFileOff, IconWorld, IconApi } from '@tabler/icons';
import { IconFolder, IconWorld, IconApi, IconClock } from '@tabler/icons';
import { areItemsLoading, getItemsLoadStats } from "utils/collections/index";
const Info = ({ collection }) => {
const totalRequestsInCollection = getTotalRequestCountInCollection(collection);
const isCollectionLoading = areItemsLoading(collection);
const { loading: itemsLoadingCount, total: totalItems } = getItemsLoadStats(collection);
return (
<div className="w-full flex flex-col h-fit">
<div className="rounded-lg py-6">
@@ -42,8 +46,10 @@ const Info = ({ collection }) => {
</div>
<div className="ml-4">
<div className="font-semibold text-sm">Requests</div>
<div className="mt-1 text-sm text-muted">
{totalRequestsInCollection} request{totalRequestsInCollection !== 1 ? 's' : ''} in collection
<div className="mt-1 text-sm text-muted font-mono">
{
isCollectionLoading? `${totalItems - itemsLoadingCount} out of ${totalItems} requests in the collection loaded` : `${totalRequestsInCollection} request${totalRequestsInCollection !== 1 ? 's' : ''} in collection`
}
</div>
</div>
</div>
@@ -53,4 +59,4 @@ const Info = ({ collection }) => {
);
};
export default Info;
export default Info;

View File

@@ -2,8 +2,15 @@ import React from 'react';
import { flattenItems } from "utils/collections";
import { IconAlertTriangle } from '@tabler/icons';
import StyledWrapper from "./StyledWrapper";
import { useDispatch, useSelector } from 'react-redux';
import { isItemARequest, itemIsOpenedInTabs } from 'utils/tabs/index';
import { getDefaultRequestPaneTab } from 'utils/collections/index';
import { addTab, focusTab } from 'providers/ReduxStore/slices/tabs';
import { hideHomePage } from 'providers/ReduxStore/slices/app';
const RequestsNotLoaded = ({ collection }) => {
const dispatch = useDispatch();
const tabs = useSelector((state) => state.tabs.tabs);
const flattenedItems = flattenItems(collection.items);
const itemsFailedLoading = flattenedItems?.filter(item => item?.partial && !item?.loading);
@@ -11,6 +18,29 @@ const RequestsNotLoaded = ({ collection }) => {
return null;
}
const handleRequestClick = (item) => e => {
e.preventDefault();
if (isItemARequest(item)) {
dispatch(hideHomePage());
if (itemIsOpenedInTabs(item, tabs)) {
dispatch(
focusTab({
uid: item.uid
})
);
return;
}
dispatch(
addTab({
uid: item.uid,
collectionUid: collection.uid,
requestPaneTab: getDefaultRequestPaneTab(item)
})
);
return;
}
}
return (
<StyledWrapper className="w-full card my-2">
<div className="flex items-center gap-2 px-3 py-2 title bg-yellow-50 dark:bg-yellow-900/20">
@@ -31,7 +61,7 @@ const RequestsNotLoaded = ({ collection }) => {
<tbody>
{flattenedItems?.map((item, index) => (
item?.partial && !item?.loading ? (
<tr key={index}>
<tr key={index} className='cursor-pointer' onClick={handleRequestClick(item)}>
<td className="py-1.5 px-3">
{item?.pathname?.split(`${collection?.pathname}/`)?.[1]}
</td>

View File

@@ -104,18 +104,15 @@ const ProxySettings = ({ proxyConfig, onUpdate }) => {
<div className="mb-3 flex items-center">
<label className="settings-label flex items-center" htmlFor="enabled">
Config
<InfoTip
text={`
<InfoTip infotipId="request-var">
<div>
<ul>
<li><span style="width: 50px;display:inline-block;">global</span> - use global proxy config</li>
<li><span style="width: 50px;display:inline-block;">enabled</span> - use collection proxy config</li>
<li><span style="width: 50px;display:inline-block;">disable</span> - disable proxy</li>
<li><span style={{width: "50px", display: "inline-block"}}>global</span> - use global proxy config</li>
<li><span style={{width: "50px", display: "inline-block"}}>enabled</span> - use collection proxy config</li>
<li><span style={{width: "50px", display: "inline-block"}}>disable</span> - disable proxy</li>
</ul>
</div>
`}
infotipId="request-var"
/>
</InfoTip>
</label>
<div className="flex items-center">
<label className="flex items-center">

View File

@@ -89,7 +89,7 @@ const VarsTable = ({ collection, vars, varType }) => {
<td>
<div className="flex items-center">
<span>Expr</span>
<InfoTip text="You can write any valid JS Template Literal here" infotipId="request-var" />
<InfoTip content="You can write any valid JS Template Literal here" infotipId="request-var" />
</div>
</td>
)}

View File

@@ -6,10 +6,9 @@ import { IconX } from '@tabler/icons';
import { isWindowsOS } from 'utils/common/platform';
import slash from 'utils/common/slash';
const FilePickerEditor = ({ value, onChange, collection, isSingleFilePicker = false}) => {
value = value || [];
const FilePickerEditor = ({ value, onChange, collection, isSingleFilePicker = false }) => {
const dispatch = useDispatch();
const filenames = value
const filenames = (isSingleFilePicker ? [value] : value || [])
.filter((v) => v != null && v != '')
.map((v) => {
const separator = isWindowsOS() ? '\\' : '/';
@@ -20,7 +19,7 @@ const FilePickerEditor = ({ value, onChange, collection, isSingleFilePicker = fa
const title = filenames.map((v) => `- ${v}`).join('\n');
const browse = () => {
dispatch(browseFiles([],['']))
dispatch(browseFiles([], [!isSingleFilePicker ? "multiSelections": ""]))
.then((filePaths) => {
// If file is in the collection's directory, then we use relative path
// Otherwise, we use the absolute path
@@ -34,7 +33,7 @@ const FilePickerEditor = ({ value, onChange, collection, isSingleFilePicker = fa
return filePath;
});
onChange(filePaths);
onChange(isSingleFilePicker ? filePaths[0] : filePaths);
})
.catch((error) => {
console.error(error);
@@ -42,7 +41,7 @@ const FilePickerEditor = ({ value, onChange, collection, isSingleFilePicker = fa
};
const clear = () => {
onChange([]);
onChange(isSingleFilePicker ? '' : []);
};
const renderButtonText = (filenames) => {
@@ -66,9 +65,9 @@ const FilePickerEditor = ({ value, onChange, collection, isSingleFilePicker = fa
</div>
) : (
<button className="btn btn-secondary px-1" style={{ width: '100%' }} onClick={browse}>
{isSingleFilePicker? 'Select File' : 'Select Files'}
{isSingleFilePicker ? 'Select File' : 'Select Files'}
</button>
);
};
export default FilePickerEditor;
export default FilePickerEditor;

View File

@@ -88,7 +88,7 @@ const VarsTable = ({ folder, collection, vars, varType }) => {
<td>
<div className="flex items-center">
<span>Expr</span>
<InfoTip text="You can write any valid JS expression here" infotipId="response-var" />
<InfoTip content="You can write any valid JS expression here" infotipId="response-var" />
</div>
</td>
)}

View File

@@ -1,7 +1,7 @@
import React from 'react';
import { Tooltip as ReactInfoTip } from 'react-tooltip';
const InfoTip = ({ text, infotipId }) => {
const InfoTip = ({ html: _ignored, infotipId, ...props }) => {
return (
<>
<svg
@@ -17,7 +17,7 @@ const InfoTip = ({ text, infotipId }) => {
<path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z" />
<path d="M5.255 5.786a.237.237 0 0 0 .241.247h.825c.138 0 .248-.113.266-.25.09-.656.54-1.134 1.342-1.134.686 0 1.314.343 1.314 1.168 0 .635-.374.927-.965 1.371-.673.489-1.206 1.06-1.168 1.987l.003.217a.25.25 0 0 0 .25.246h.811a.25.25 0 0 0 .25-.25v-.105c0-.718.273-.927 1.01-1.486.609-.463 1.244-.977 1.244-2.056 0-1.511-1.276-2.241-2.673-2.241-1.267 0-2.655.59-2.75 2.286zm1.557 5.763c0 .533.425.927 1.01.927.609 0 1.028-.394 1.028-.927 0-.552-.42-.94-1.029-.94-.584 0-1.009.388-1.009.94z" />
</svg>
<ReactInfoTip anchorId={infotipId} html={text} />
<ReactInfoTip anchorId={infotipId} {...props} />
</>
);
};

View File

@@ -3,6 +3,7 @@ import { useState } from 'react';
import StyledWrapper from './StyleWrapper';
import Modal from 'components/Modal/index';
import { useEffect } from 'react';
import { useApp } from 'providers/App';
import {
fetchNotifications,
markAllNotificationsAsRead,
@@ -11,18 +12,18 @@ import {
import { useDispatch, useSelector } from 'react-redux';
import { humanizeDate, relativeDate } from 'utils/common';
import ToolHint from 'components/ToolHint';
import { useTheme } from 'providers/Theme';
import DOMPurify from 'dompurify';
const PAGE_SIZE = 5;
const Notifications = () => {
const dispatch = useDispatch();
const { version } = useApp();
const notifications = useSelector((state) => state.notifications.notifications);
const [showNotificationsModal, setShowNotificationsModal] = useState(false);
const [selectedNotification, setSelectedNotification] = useState(null);
const [pageNumber, setPageNumber] = useState(1);
const { storedTheme } = useTheme();
const notificationsStartIndex = (pageNumber - 1) * PAGE_SIZE;
const notificationsEndIndex = pageNumber * PAGE_SIZE;
@@ -30,7 +31,9 @@ const Notifications = () => {
const unreadNotifications = notifications.filter((notification) => !notification.read);
useEffect(() => {
dispatch(fetchNotifications());
dispatch(fetchNotifications({
currentVersion: version
}));
}, []);
useEffect(() => {
@@ -66,6 +69,13 @@ const Notifications = () => {
dispatch(markNotificationAsRead({ notificationId: notification?.id }));
};
const getSanitizedDescription = (description) => {
return DOMPurify.sanitize(encodeURIComponent(description), {
ALLOWED_TAGS: ['a', 'ul', 'img', 'li', 'div', 'span', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
ALLOWED_ATTR: ['href', 'style', 'target', 'src', 'alt']
});
};
const modalCustomHeader = (
<div className="flex flex-row gap-8">
<div>NOTIFICATIONS</div>
@@ -90,7 +100,9 @@ const Notifications = () => {
<a
className="relative cursor-pointer"
onClick={() => {
dispatch(fetchNotifications());
dispatch(fetchNotifications({
currentVersion: version
}));
setShowNotificationsModal(true);
}}
aria-label="Check all Notifications"
@@ -179,10 +191,11 @@ const Notifications = () => {
<div className="w-full notification-date text-xs mb-4">
{humanizeDate(selectedNotification?.date)}
</div>
<div
className="flex w-full flex-col flex-wrap h-fit"
dangerouslySetInnerHTML={{ __html: selectedNotification?.description }}
></div>
<iframe
src={`data:text/html,${getSanitizedDescription(selectedNotification?.description)}`}
sandbox="allow-popups"
style={{ width: '100%', height: '100%' }}
></iframe>
</div>
</div>
) : (

View File

@@ -1,10 +1,7 @@
import styled from 'styled-components';
const StyledWrapper = styled.div`
div.CodeMirror {
/* todo: find a better way */
height: calc(100vh - 220px);
}
color: ${(props) => props.theme.text};
`;
export default StyledWrapper;

View File

@@ -0,0 +1,56 @@
import React, { useState } from 'react';
import get from 'lodash/get';
import { useSelector, useDispatch } from 'react-redux';
import { savePreferences } from 'providers/ReduxStore/slices/app';
import StyledWrapper from './StyledWrapper';
// https://codemirror.net/5/keymap/
const codemirrorKeymaps = [
{ value: 'sublime', label: 'Sublime' },
{ value: 'vim', label: 'Vim' },
{ value: 'emacs', label: 'Emacs' },
];
const EditorKeymapSettings = ({ close }) => {
const dispatch = useDispatch();
const preferences = useSelector((state) => state.app.preferences);
const editorPreferences = preferences.editor || {};
const keymap = editorPreferences.keymap || 'sublime';
const handleKeymapChange = (e) => {
dispatch(
savePreferences({
...preferences,
editor: { ...editorPreferences, keymap: e.target.value }
})
).catch(console.error);
};
return (
<StyledWrapper>
<div className="bruno-form">
<label className="block">Keymap</label>
<div className="flex items-center mt-2">
{codemirrorKeymaps.map(({ value, label }) => (
<>
<input
id={label}
className="cursor-pointer ml-4 first:ml-0"
type="radio"
name="keymap"
onChange={handleKeymapChange}
value={value}
checked={keymap === value}
/>
<label htmlFor={label} className="ml-1 cursor-pointer select-none">
{label}
</label>
</>
))}
</div>
</div>
</StyledWrapper>
);
};
export default EditorKeymapSettings;

View File

@@ -37,9 +37,9 @@ const Font = ({ close }) => {
return (
<StyledWrapper>
<div className="flex flex-row gap-2 w-full">
<div className="flex flex-row gap-2 w-fit">
<div className="w-4/5">
<label className="block">Code Editor Font</label>
<label className="block">Font Family</label>
<input
type="text"
className="block textbox mt-2 w-full"
@@ -63,10 +63,7 @@ const Font = ({ close }) => {
defaultValue={codeFontSize}
/>
</div>
</div>
<div className="mt-10">
<button type="submit" className="submit btn btn-sm btn-secondary" onClick={handleSave}>
<button type="submit" className="submit btn btn-md btn-secondary self-end" onClick={handleSave}>
Save
</button>
</div>

View File

@@ -1,18 +1,24 @@
import React from 'react';
import Font from './Font/index';
import Theme from './Theme/index';
import EditorKeymapSettings from './EditorKeymapSettings/index';
const Display = ({ close }) => {
return (
<div className="flex flex-col my-2 gap-10 w-full">
<div className='w-full flex flex-col gap-2'>
<span>
<span className="font-semibold">
Theme
</span>
<Theme close={close} />
</div>
<div className='h-[1px] bg-[#aaa5] w-full'></div>
<div className='w-fit flex flex-col gap-2'>
<div className='w-full flex flex-col gap-2'>
<span className="font-semibold">
Code Editor
</span>
<EditorKeymapSettings />
<div className='w-full'></div>
<Font close={close} />
</div>
</div>

View File

@@ -1,68 +1,53 @@
import React from 'react';
import get from 'lodash/get';
import cloneDeep from 'lodash/cloneDeep';
import React, { useState, useEffect } from 'react';
import { get, cloneDeep, isArray } from 'lodash';
import { IconTrash } from '@tabler/icons';
import { useDispatch } from 'react-redux';
import { useTheme } from 'providers/Theme';
import {
addBinaryFile,
updateBinaryFile,
deleteBinaryFile
} from 'providers/ReduxStore/slices/collections';
import { addFile as _addFile, updateFile, deleteFile } from 'providers/ReduxStore/slices/collections/index';
import { sendRequest, saveRequest } from 'providers/ReduxStore/slices/collections/actions';
import StyledWrapper from './StyledWrapper';
import FilePickerEditor from 'components/FilePickerEditor';
import FilePickerEditor from 'components/FilePickerEditor/index';
import SingleLineEditor from 'components/SingleLineEditor/index';
import { isArray } from 'lodash';
import path from 'node:path';
import { useState } from 'react';
const Binary = ({ item, collection }) => {
const FileBody = ({ item, collection }) => {
const dispatch = useDispatch();
const { storedTheme } = useTheme();
const params = item.draft ? get(item, 'draft.request.body.binaryFile') : get(item, 'request.body.binaryFile');
const params = item.draft ? get(item, 'draft.request.body.file') : get(item, 'request.body.file');
const [enabledFileUid, setEnableFileUid] = useState(params && params.length ? params[0].uid : '');
const addFile = () => {
dispatch(
addBinaryFile({
_addFile({
itemUid: item.uid,
collectionUid: collection.uid,
type: 'binaryFile',
value: [''],
})
);
};
const onSave = () => dispatch(saveRequest(item.uid, collection.uid));
const handleRun = () => dispatch(sendRequest(item, collection.uid));
const handleParamChange = (e, _param, type) => {
const param = cloneDeep(_param);
switch (type) {
case 'value': {
param.value = isArray(e.target.value) && e.target.value.length > 0 ? e.target.value : [''];
param.name = param.value.length === 0 ? '': path.basename(param.value[0], path.extname(param.value[0]));
case 'filePath': {
param.filePath = e.target.filePath;
param.contentType = "";
break;
}
case 'contentType': {
param.contentType = e.target.value;
param.contentType = e.target.contentType;
break;
}
case 'enabled': {
param.enabled = e.target.checked;
setEnableFileUid(param.uid);
case 'selected': {
param.selected = e.target.selected;
setEnableFileUid(param.uid)
break;
}
}
dispatch(
updateBinaryFile({
updateFile({
param: param,
itemUid: item.uid,
collectionUid: collection.uid
@@ -72,7 +57,7 @@ const Binary = ({ item, collection }) => {
const handleRemoveParams = (param) => {
dispatch(
deleteBinaryFile({
deleteFile({
paramUid: param.uid,
itemUid: item.uid,
collectionUid: collection.uid
@@ -85,9 +70,15 @@ const Binary = ({ item, collection }) => {
<table>
<thead>
<tr>
<td><div className="flex items-center justify-center">File</div></td>
<td><div className="flex items-center justify-center">Content-Type</div></td>
<td><div className="flex items-center justify-center">Enabled</div></td>
<td>
<div className="flex items-center justify-center">File</div>
</td>
<td>
<div className="flex items-center justify-center">Content-Type</div>
</td>
<td>
<div className="flex items-center justify-center">Selected</div>
</td>
<td></td>
</tr>
</thead>
@@ -97,26 +88,26 @@ const Binary = ({ item, collection }) => {
return (
<tr key={param.uid}>
<td>
<FilePickerEditor
isSingleFilePicker={true}
value={param.value}
onChange={(newValue) =>
handleParamChange(
{
target: {
value: newValue
}
},
param,
'value'
)
}
collection={collection}
/>
<FilePickerEditor
isSingleFilePicker={true}
value={param.filePath}
onChange={(path) =>
handleParamChange(
{
target: {
filePath: path
}
},
param,
'filePath'
)
}
collection={collection}
/>
</td>
<td>
<SingleLineEditor
className='flex items-center justify-center'
className="flex items-center justify-center"
onSave={onSave}
theme={storedTheme}
placeholder="Auto"
@@ -125,7 +116,7 @@ const Binary = ({ item, collection }) => {
handleParamChange(
{
target: {
value: newValue
contentType: newValue
}
},
param,
@@ -141,19 +132,19 @@ const Binary = ({ item, collection }) => {
<input
key={param.uid}
type="radio"
name="enabled"
checked={enabledFileUid === param.uid || param.enabled}
name="selected"
checked={enabledFileUid === param.uid || param.selected}
tabIndex="-1"
className="mr-1 mousetrap"
onChange={(e) => handleParamChange(e, param, 'enabled')}
onChange={(e) => handleParamChange(e, param, 'selected')}
/>
</div>
</td>
<td>
<div className="flex items-center justify-center">
<button tabIndex="-1" onClick={() => handleRemoveParams(param)}>
<IconTrash strokeWidth={1.5} size={20} />
</button>
<div className="flex items-center justify-center">
<button tabIndex="-1" onClick={() => handleRemoveParams(param)}>
<IconTrash strokeWidth={1.5} size={20} />
</button>
</div>
</td>
</tr>
@@ -170,4 +161,4 @@ const Binary = ({ item, collection }) => {
</StyledWrapper>
);
};
export default Binary;
export default FileBody;

View File

@@ -154,7 +154,7 @@ const GraphQLRequestPane = ({ item, collection, leftPaneWidth, onSchemaLoad, tog
</div>
<GraphQLSchemaActions item={item} collection={collection} onSchemaLoad={setSchema} toggleDocs={toggleDocs} />
</div>
<section className="flex w-full mt-5 flex-1">{getTabPanel(focusedTab.requestPaneTab)}</section>
<section className="flex w-full mt-5 flex-1 relative">{getTabPanel(focusedTab.requestPaneTab)}</section>
</StyledWrapper>
);
};

View File

@@ -49,7 +49,7 @@ const GraphQLVariables = ({ variables, item, collection }) => {
const onSave = () => dispatch(saveRequest(item.uid, collection.uid));
return (
<StyledWrapper className="w-full relative">
<>
<button
className="btn-add-param text-link px-4 py-4 select-none absolute top-0 right-0 z-10"
onClick={onPrettify}
@@ -68,7 +68,7 @@ const GraphQLVariables = ({ variables, item, collection }) => {
onRun={onRun}
onSave={onSave}
/>
</StyledWrapper>
</>
);
};

View File

@@ -176,8 +176,7 @@ const QueryParams = ({ item, collection }) => {
</button>
<div className="mb-2 title text-xs flex items-stretch">
<span>Path</span>
<InfoTip
text={`
<InfoTip infotipId="path-param-InfoTip">
<div>
Path variables are automatically added whenever the
<code className="font-mono mx-2">:name</code>
@@ -186,9 +185,7 @@ const QueryParams = ({ item, collection }) => {
https://example.com/v1/users/<span>:id</span>
</code>
</div>
`}
infotipId="path-param-InfoTip"
/>
</InfoTip>
</div>
<table>
<thead>

View File

@@ -132,10 +132,10 @@ const RequestBodyMode = ({ item, collection }) => {
className="dropdown-item"
onClick={() => {
dropdownTippyRef.current.hide();
onModeChange('binaryFile');
onModeChange('file');
}}
>
Binary File
File / Binary
</div>
<div
className="dropdown-item"

View File

@@ -8,7 +8,7 @@ import { useTheme } from 'providers/Theme';
import { updateRequestBody } from 'providers/ReduxStore/slices/collections';
import { sendRequest, saveRequest } from 'providers/ReduxStore/slices/collections/actions';
import StyledWrapper from './StyledWrapper';
import Binary from '../Binary/index';
import FileBody from '../FileBody/index';
const RequestBody = ({ item, collection }) => {
const dispatch = useDispatch();
@@ -63,8 +63,8 @@ const RequestBody = ({ item, collection }) => {
);
}
if (bodyMode === 'binaryFile') {
return <Binary item={item} collection={collection}/>
if (bodyMode === 'file') {
return <FileBody item={item} collection={collection}/>
}
if (bodyMode === 'formUrlEncoded') {
@@ -77,4 +77,4 @@ const RequestBody = ({ item, collection }) => {
return <StyledWrapper className="w-full">No Body</StyledWrapper>;
};
export default RequestBody;
export default RequestBody;

View File

@@ -5,7 +5,6 @@ import CodeEditor from 'components/CodeEditor';
import { updateRequestTests } from 'providers/ReduxStore/slices/collections';
import { sendRequest, saveRequest } from 'providers/ReduxStore/slices/collections/actions';
import { useTheme } from 'providers/Theme';
import StyledWrapper from './StyledWrapper';
const Tests = ({ item, collection }) => {
const dispatch = useDispatch();
@@ -28,19 +27,17 @@ const Tests = ({ item, collection }) => {
const onSave = () => dispatch(saveRequest(item.uid, collection.uid));
return (
<StyledWrapper className="w-full">
<CodeEditor
collection={collection}
value={tests || ''}
theme={displayedTheme}
font={get(preferences, 'font.codeFont', 'default')}
fontSize={get(preferences, 'font.codeFontSize')}
onEdit={onEdit}
mode="javascript"
onRun={onRun}
onSave={onSave}
/>
</StyledWrapper>
<CodeEditor
collection={collection}
value={tests || ''}
theme={displayedTheme}
font={get(preferences, 'font.codeFont', 'default')}
fontSize={get(preferences, 'font.codeFontSize')}
onEdit={onEdit}
mode="javascript"
onRun={onRun}
onSave={onSave}
/>
);
};

View File

@@ -98,7 +98,7 @@ const VarsTable = ({ item, collection, vars, varType }) => {
) : (
<div className="flex items-center">
<span>Expr</span>
<InfoTip text="You can write any valid JS expression here" infotipId="response-var" />
<InfoTip content="You can write any valid JS expression here" infotipId="response-var" />
</div>
), accessor: 'value', width: '46%' },
{ name: '', accessor: '', width: '14%' }

View File

@@ -1,4 +1,4 @@
import { IconLoader2, IconFile } from '@tabler/icons';
import { IconLoader2, IconFile, IconAlertTriangle } from '@tabler/icons';
import { loadRequest, loadRequestViaWorker } from 'providers/ReduxStore/slices/collections/actions';
import { useDispatch } from 'react-redux';
import StyledWrapper from './StyledWrapper';
@@ -15,65 +15,59 @@ const RequestNotLoaded = ({ collection, item }) => {
return <StyledWrapper>
<div className='flex flex-col p-4'>
<div className='card shadow-sm rounded-md p-4 w-[600px]'>
<div className='card shadow-sm rounded-md p-4 w-[685px]'>
<div>
<div className='font-medium flex items-center gap-2 pb-4'>
<IconFile size={16} strokeWidth={1.5} className="text-gray-400" />
File Info
</div>
<div className='hr'/>
<div className='hr' />
<div className='flex items-center mt-2'>
<span className='w-12 mr-2 text-muted'>Name:</span>
<div>{item?.name}</div>
</div>
<div className='flex items-center mt-1'>
<span className='w-12 mr-2 text-muted'>Path:</span>
<div className='break-all'>{item?.pathname}</div>
</div>
<div className='flex items-center mt-1 pb-4'>
<span className='w-12 mr-2 text-muted'>Size:</span>
<div>{item?.size?.toFixed?.(2)} MB</div>
</div>
{!item?.error && (
<>
<div className='hr'/>
<div className='text-muted text-xs mt-4 mb-2'>
Due to its large size, this request wasn't loaded automatically.
<div className='flex flex-col'>
<div className='flex items-center gap-2 px-3 py-2 title bg-yellow-50 dark:bg-yellow-900/20'>
<IconAlertTriangle size={16} className="text-yellow-500" />
<span>The request wasn't loaded due to its large size. Please try again with the following options:</span>
</div>
<div className='flex flex-col gap-6 mt-4'>
<div className='flex flex-col'>
<button
className={`submit btn btn-sm btn-secondary w-fit h-fit flex flex-row gap-2 ${item?.loading? 'opacity-50 cursor-blocked': ''}`}
onClick={handleLoadRequest}
>
Load Request
</button>
<small className='text-muted mt-1'>
May cause the app to freeze temporarily while it runs.
</small>
</div>
<div className='flex flex-col'>
<div className='flex flex-row mt-6 gap-2 items-center w-full'>
<button
className={`submit btn btn-sm btn-secondary w-fit h-fit flex flex-row gap-2 ${item?.loading? 'opacity-50 cursor-blocked': ''}`}
onClick={handleLoadRequestViaWorker}
>
Load Request in Background
Load in background
</button>
<small className='text-muted mt-1'>
Runs in background.
</small>
</div>
<p>(Runs in background)</p>
</div>
</>
<div className='flex flex-row mt-6 items-center gap-2 w-full'>
<button
className={`submit btn btn-sm btn-secondary w-fit h-fit flex flex-row gap-2 ${item?.loading? 'opacity-50 cursor-blocked': ''}`}
onClick={handleLoadRequest}
>
Force load
</button>
<p>(May cause the app to freeze temporarily while it runs)</p>
</div>
</div>
)}
{item?.loading && (
<>
<div className='hr mt-4'/>
<div className='hr mt-4' />
<div className='flex items-center gap-2 mt-4'>
<IconLoader2 className="animate-spin" size={16} strokeWidth={2} />
<span>Loading...</span>

View File

@@ -35,7 +35,7 @@ const CollectionToolBar = ({ collection }) => {
const viewCollectionSettings = () => {
dispatch(
addTab({
uid: uuid(),
uid: collection.uid,
collectionUid: collection.uid,
type: 'collection-settings'
})

View File

@@ -2,15 +2,15 @@ import React from 'react';
import CloseTabIcon from './CloseTabIcon';
import { IconVariable, IconSettings, IconRun, IconFolder, IconShieldLock } from '@tabler/icons';
const SpecialTab = ({ handleCloseClick, type, tabName }) => {
const SpecialTab = ({ handleCloseClick, type, tabName, handleDoubleClick }) => {
const getTabInfo = (type, tabName) => {
switch (type) {
case 'collection-settings': {
return (
<>
<div onDoubleClick={handleDoubleClick} className="flex items-center flex-nowrap overflow-hidden">
<IconSettings size={18} strokeWidth={1.5} className="text-yellow-600" />
<span className="ml-1 leading-6">Collection</span>
</>
</div>
);
}
case 'collection-overview': {
@@ -31,7 +31,7 @@ const SpecialTab = ({ handleCloseClick, type, tabName }) => {
}
case 'folder-settings': {
return (
<div className="flex items-center flex-nowrap overflow-hidden">
<div onDoubleClick={handleDoubleClick} className="flex items-center flex-nowrap overflow-hidden">
<IconFolder size={18} strokeWidth={1.5} className="text-yellow-600 min-w-[18px]" />
<span className="ml-1 leading-6 truncate">{tabName || 'Folder'}</span>
</div>

View File

@@ -1,6 +1,6 @@
import React, { useState, useRef, Fragment } from 'react';
import get from 'lodash/get';
import { closeTabs } from 'providers/ReduxStore/slices/tabs';
import { closeTabs, makeTabPermanent } from 'providers/ReduxStore/slices/tabs';
import { saveRequest } from 'providers/ReduxStore/slices/collections/actions';
import { deleteRequestDraft } from 'providers/ReduxStore/slices/collections';
import { useTheme } from 'providers/Theme';
@@ -73,13 +73,13 @@ const RequestTab = ({ tab, collection, tabIndex, collectionRequestTabs, folderUi
if (['collection-settings', 'collection-overview', 'folder-settings', 'variables', 'collection-runner', 'security-settings'].includes(tab.type)) {
return (
<StyledWrapper
className="flex items-center justify-between tab-container px-1"
className={`flex items-center justify-between tab-container px-1 ${tab.preview ? "italic" : ""}`}
onMouseUp={handleMouseUp} // Add middle-click behavior here
>
{tab.type === 'folder-settings' ? (
<SpecialTab handleCloseClick={handleCloseClick} type={tab.type} tabName={folder?.name} />
<SpecialTab handleCloseClick={handleCloseClick} handleDoubleClick={() => dispatch(makeTabPermanent({ uid: tab.uid }))} type={tab.type} tabName={folder?.name} />
) : (
<SpecialTab handleCloseClick={handleCloseClick} type={tab.type} />
<SpecialTab handleCloseClick={handleCloseClick} handleDoubleClick={() => dispatch(makeTabPermanent({ uid: tab.uid }))} type={tab.type} />
)}
</StyledWrapper>
);
@@ -144,8 +144,9 @@ const RequestTab = ({ tab, collection, tabIndex, collectionRequestTabs, folderUi
/>
)}
<div
className="flex items-baseline tab-label pl-2"
className={`flex items-baseline tab-label pl-2 ${tab.preview ? "italic" : ""}`}
onContextMenu={handleRightClick}
onDoubleClick={() => dispatch(makeTabPermanent({ uid: tab.uid }))}
onMouseUp={(e) => {
if (!item.draft) return handleMouseUp(e);

View File

@@ -127,7 +127,7 @@ const CloneCollection = ({ onClose, collection }) => {
<label htmlFor="collection-folder-name" className="flex items-center mt-3">
<span className="font-semibold">Folder Name</span>
<InfoTip
text="This folder will be created under the selected location"
content="This folder will be created under the selected location"
infotipId="collection-folder-name-infotip"
/>
</label>

View File

@@ -5,7 +5,7 @@ import classnames from 'classnames';
import { useDrag, useDrop } from 'react-dnd';
import { IconChevronRight, IconDots } from '@tabler/icons';
import { useSelector, useDispatch } from 'react-redux';
import { addTab, focusTab } from 'providers/ReduxStore/slices/tabs';
import { addTab, focusTab, makeTabPermanent } from 'providers/ReduxStore/slices/tabs';
import { moveItem, showInFolder, sendRequest } from 'providers/ReduxStore/slices/collections/actions';
import { collectionFolderClicked } from 'providers/ReduxStore/slices/collections';
import Dropdown from 'components/Dropdown';
@@ -23,13 +23,16 @@ import { hideHomePage } from 'providers/ReduxStore/slices/app';
import toast from 'react-hot-toast';
import StyledWrapper from './StyledWrapper';
import NetworkError from 'components/ResponsePane/NetworkError/index';
import CollectionItemIcon from './CollectionItemIcon/index';
import { findItemInCollection } from 'utils/collections';
import CollectionItemIcon from './CollectionItemIcon';
import { scrollToTheActiveTab } from 'utils/tabs';
const CollectionItem = ({ item, collection, searchText }) => {
const tabs = useSelector((state) => state.tabs.tabs);
const activeTabUid = useSelector((state) => state.tabs.activeTabUid);
const isSidebarDragging = useSelector((state) => state.app.isDragging);
const dispatch = useDispatch();
const collectionItemRef = useRef(null);
const [renameItemModalOpen, setRenameItemModalOpen] = useState(false);
const [cloneItemModalOpen, setCloneItemModalOpen] = useState(false);
@@ -43,28 +46,31 @@ const CollectionItem = ({ item, collection, searchText }) => {
const itemIsCollapsed = hasSearchText ? false : item.collapsed;
const [{ isDragging }, drag] = useDrag({
type: `COLLECTION_ITEM_${collection.uid}`,
type: `collection-item-${collection.uid}`,
item: item,
collect: (monitor) => ({
isDragging: monitor.isDragging()
})
}),
options: {
dropEffect: "move"
}
});
const [{ isOver }, drop] = useDrop({
accept: `COLLECTION_ITEM_${collection.uid}`,
accept: `collection-item-${collection.uid}`,
drop: (draggedItem) => {
if (draggedItem.uid !== item.uid) {
dispatch(moveItem(collection.uid, draggedItem.uid, item.uid));
}
dispatch(moveItem(collection.uid, draggedItem.uid, item.uid));
},
canDrop: (draggedItem) => {
return draggedItem.uid !== item.uid;
},
collect: (monitor) => ({
isOver: monitor.isOver()
})
isOver: monitor.isOver(),
}),
});
drag(drop(collectionItemRef));
const dropdownTippyRef = useRef();
const MenuIcon = forwardRef((props, ref) => {
return (
@@ -83,13 +89,6 @@ const CollectionItem = ({ item, collection, searchText }) => {
'item-hovered': isOver
});
const scrollToTheActiveTab = () => {
const activeTab = document.querySelector('.request-tab.active');
if (activeTab) {
activeTab.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
};
const handleRun = async () => {
dispatch(sendRequest(item, collection.uid)).catch((err) =>
toast.custom((t) => <NetworkError onClose={() => toast.dismiss(t.id)} />, {
@@ -99,10 +98,13 @@ const CollectionItem = ({ item, collection, searchText }) => {
};
const handleClick = (event) => {
if (event.detail != 1) return;
//scroll to the active tab
setTimeout(scrollToTheActiveTab, 50);
if (isItemARequest(item)) {
const isRequest = isItemARequest(item);
if (isRequest) {
dispatch(hideHomePage());
if (itemIsOpenedInTabs(item, tabs)) {
dispatch(
@@ -112,20 +114,21 @@ const CollectionItem = ({ item, collection, searchText }) => {
);
return;
}
dispatch(
addTab({
uid: item.uid,
collectionUid: collection.uid,
requestPaneTab: getDefaultRequestPaneTab(item)
requestPaneTab: getDefaultRequestPaneTab(item),
type: 'request',
})
);
return;
}
} else {
dispatch(
addTab({
uid: item.uid,
collectionUid: collection.uid,
type: 'folder-settings'
type: 'folder-settings',
})
);
dispatch(
@@ -134,9 +137,12 @@ const CollectionItem = ({ item, collection, searchText }) => {
collectionUid: collection.uid
})
);
}
};
const handleFolderCollapse = () => {
const handleFolderCollapse = (e) => {
e.stopPropagation();
e.preventDefault();
dispatch(
collectionFolderClicked({
itemUid: item.uid,
@@ -156,10 +162,6 @@ const CollectionItem = ({ item, collection, searchText }) => {
}
};
const handleDoubleClick = (event) => {
setRenameItemModalOpen(true);
};
let indents = range(item.depth);
const onDropdownCreate = (ref) => (dropdownTippyRef.current = ref);
const isFolder = isItemAFolder(item);
@@ -180,6 +182,10 @@ const CollectionItem = ({ item, collection, searchText }) => {
}
}
const handleDoubleClick = (event) => {
dispatch(makeTabPermanent({ uid: item.uid }))
};
// we need to sort request items by seq property
const sortRequestItems = (items = []) => {
return items.sort((a, b) => a.seq - b.seq);
@@ -253,7 +259,7 @@ const CollectionItem = ({ item, collection, searchText }) => {
{generateCodeItemModalOpen && (
<GenerateCodeItem collection={collection} item={item} onClose={() => setGenerateCodeItemModalOpen(false)} />
)}
<div className={itemRowClassName} ref={(node) => drag(drop(node))}>
<div className={itemRowClassName} ref={collectionItemRef}>
<div className="flex items-center h-full w-full">
{indents && indents.length
? indents.map((i) => {
@@ -280,6 +286,9 @@ const CollectionItem = ({ item, collection, searchText }) => {
style={{
paddingLeft: 8
}}
onClick={handleClick}
onContextMenu={handleRightClick}
onDoubleClick={handleDoubleClick}
>
<div style={{ width: 16, minWidth: 16 }}>
{isFolder ? (
@@ -295,9 +304,6 @@ const CollectionItem = ({ item, collection, searchText }) => {
<div
className="ml-1 flex w-full h-full items-center overflow-hidden"
onClick={handleClick}
onContextMenu={handleRightClick}
onDoubleClick={handleDoubleClick}
>
<CollectionItemIcon item={item} />
<span className="item-name" title={item.name}>

View File

@@ -12,6 +12,17 @@ const Wrapper = styled.div`
transform: rotateZ(90deg);
}
&.item-hovered {
background: ${(props) => props.theme.sidebar.collection.item.hoverBg};
.collection-actions {
.dropdown {
div[aria-expanded='false'] {
visibility: visible;
}
}
}
}
.collection-actions {
.dropdown {
div[aria-expanded='true'] {

View File

@@ -2,13 +2,13 @@ import React, { useState, forwardRef, useRef, useEffect } from 'react';
import classnames from 'classnames';
import { uuid } from 'utils/common';
import filter from 'lodash/filter';
import { useDrop } from 'react-dnd';
import { useDrop, useDrag } from 'react-dnd';
import { IconChevronRight, IconDots, IconLoader2 } from '@tabler/icons';
import Dropdown from 'components/Dropdown';
import { collapseCollection } from 'providers/ReduxStore/slices/collections';
import { mountCollection, moveItemToRootOfCollection } from 'providers/ReduxStore/slices/collections/actions';
import { useDispatch } from 'react-redux';
import { addTab } from 'providers/ReduxStore/slices/tabs';
import { mountCollection, moveItemToRootOfCollection, moveCollectionAndPersist } from 'providers/ReduxStore/slices/collections/actions';
import { useDispatch, useSelector } from 'react-redux';
import { addTab, makeTabPermanent } from 'providers/ReduxStore/slices/tabs';
import NewRequest from 'components/Sidebar/NewRequest';
import NewFolder from 'components/Sidebar/NewFolder';
import CollectionItem from './CollectionItem';
@@ -20,7 +20,8 @@ import { isItemAFolder, isItemARequest } from 'utils/collections';
import RenameCollection from './RenameCollection';
import StyledWrapper from './StyledWrapper';
import CloneCollection from './CloneCollection';
import { areItemsLoading } from 'utils/collections';
import { areItemsLoading, findItemInCollection } from 'utils/collections';
import { scrollToTheActiveTab } from 'utils/tabs';
const Collection = ({ collection, searchText }) => {
const [showNewFolderModal, setShowNewFolderModal] = useState(false);
@@ -29,8 +30,10 @@ const Collection = ({ collection, searchText }) => {
const [showCloneCollectionModalOpen, setShowCloneCollectionModalOpen] = useState(false);
const [showExportCollectionModal, setShowExportCollectionModal] = useState(false);
const [showRemoveCollectionModal, setShowRemoveCollectionModal] = useState(false);
const tabs = useSelector((state) => state.tabs.tabs);
const dispatch = useDispatch();
const isLoading = areItemsLoading(collection);
const collectionRef = useRef(null);
const menuDropdownTippyRef = useRef();
const onMenuDropdownCreate = (ref) => (menuDropdownTippyRef.current = ref);
@@ -52,6 +55,16 @@ const Collection = ({ collection, searchText }) => {
);
};
const ensureCollectionIsMounted = () => {
if (collection.mountStatus === 'unmounted') {
dispatch(mountCollection({
collectionUid: collection.uid,
collectionPathname: collection.pathname,
brunoConfig: collection.brunoConfig
}));
}
}
const hasSearchText = searchText && searchText?.trim()?.length;
const collectionIsCollapsed = hasSearchText ? false : collection.collapsed;
@@ -60,30 +73,37 @@ const Collection = ({ collection, searchText }) => {
});
const handleClick = (event) => {
if (event.detail != 1) return;
// Check if the click came from the chevron icon
const isChevronClick = event.target.closest('svg')?.classList.contains('chevron-icon');
if (collection.mountStatus === 'unmounted') {
dispatch(mountCollection({
collectionUid: collection.uid,
collectionPathname: collection.pathname,
brunoConfig: collection.brunoConfig
}));
}
dispatch(collapseCollection(collection.uid));
setTimeout(scrollToTheActiveTab, 50);
// Only open collection settings if not clicking the chevron
ensureCollectionIsMounted();
dispatch(collapseCollection(collection.uid));
if(!isChevronClick) {
dispatch(
addTab({
uid: uuid(),
uid: collection.uid,
collectionUid: collection.uid,
type: 'collection-settings'
type: 'collection-settings',
})
);
}
};
const handleDoubleClick = (event) => {
dispatch(makeTabPermanent({ uid: collection.uid }))
};
const handleCollectionCollapse = (e) => {
e.stopPropagation();
e.preventDefault();
ensureCollectionIsMounted();
dispatch(collapseCollection(collection.uid));
}
const handleRightClick = (event) => {
const _menuDropdown = menuDropdownTippyRef.current;
if (_menuDropdown) {
@@ -98,33 +118,58 @@ const Collection = ({ collection, searchText }) => {
const viewCollectionSettings = () => {
dispatch(
addTab({
uid: uuid(),
uid: collection.uid,
collectionUid: collection.uid,
type: 'collection-settings'
})
);
};
const isCollectionItem = (itemType) => {
return itemType.startsWith('collection-item');
};
const [{ isDragging }, drag] = useDrag({
type: "collection",
item: collection,
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
options: {
dropEffect: "move"
}
});
const [{ isOver }, drop] = useDrop({
accept: `COLLECTION_ITEM_${collection.uid}`,
drop: (draggedItem) => {
dispatch(moveItemToRootOfCollection(collection.uid, draggedItem.uid));
accept: ["collection", `collection-item-${collection.uid}`],
drop: (draggedItem, monitor) => {
const itemType = monitor.getItemType();
if (isCollectionItem(itemType)) {
dispatch(moveItemToRootOfCollection(collection.uid, draggedItem.uid))
} else {
dispatch(moveCollectionAndPersist({draggedItem, targetItem: collection}));
}
},
canDrop: (draggedItem) => {
// todo need to make sure that draggedItem belongs to the collection
return true;
return draggedItem.uid !== collection.uid;
},
collect: (monitor) => ({
isOver: monitor.isOver()
})
isOver: monitor.isOver(),
}),
});
drag(drop(collectionRef));
if (searchText && searchText.length) {
if (!doesCollectionHaveItemsMatchingSearchText(collection, searchText)) {
return null;
}
}
const collectionRowClassName = classnames('flex py-1 collection-name items-center', {
'item-hovered': isOver
});
// we need to sort request items by seq property
const sortRequestItems = (items = []) => {
return items.sort((a, b) => a.seq - b.seq);
@@ -154,10 +199,13 @@ const Collection = ({ collection, searchText }) => {
{showCloneCollectionModalOpen && (
<CloneCollection collection={collection} onClose={() => setShowCloneCollectionModalOpen(false)} />
)}
<div className="flex py-1 collection-name items-center" ref={drop}>
<div className={collectionRowClassName}
ref={collectionRef}
>
<div
className="flex flex-grow items-center overflow-hidden"
onClick={handleClick}
onDoubleClick={handleDoubleClick}
onContextMenu={handleRightClick}
>
<IconChevronRight
@@ -165,6 +213,7 @@ const Collection = ({ collection, searchText }) => {
strokeWidth={2}
className={`chevron-icon ${iconClassName}`}
style={{ width: 16, minWidth: 16, color: 'rgb(160 160 160)' }}
onClick={handleCollectionCollapse}
/>
<div className="ml-1" id="sidebar-collection-name">
{collection.name}

View File

@@ -8,12 +8,10 @@ import {
IconSortDescendingLetters,
IconX
} from '@tabler/icons';
import Collection from '../Collections/Collection';
import Collection from './Collection';
import CreateCollection from '../CreateCollection';
import StyledWrapper from './StyledWrapper';
import CreateOrOpenCollection from './CreateOrOpenCollection';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { sortCollections } from 'providers/ReduxStore/slices/collections/actions';
// todo: move this to a separate folder
@@ -119,9 +117,7 @@ const Collections = () => {
{collections && collections.length
? collections.map((c) => {
return (
<DndProvider backend={HTML5Backend} key={c.uid}>
<Collection searchText={searchText} collection={c} key={c.uid} />
</DndProvider>
<Collection searchText={searchText} collection={c} key={c.uid} />
);
})
: null}

View File

@@ -120,7 +120,7 @@ const CreateCollection = ({ onClose }) => {
<label htmlFor="collection-folder-name" className="flex items-center mt-3">
<span className="font-semibold">Folder Name</span>
<InfoTip
text="This folder will be created under the selected location"
content="This folder will be created under the selected location"
infotipId="collection-folder-name-infotip"
/>
</label>

View File

@@ -5,6 +5,7 @@ import Preferences from 'components/Preferences';
import Cookies from 'components/Cookies';
import ToolHint from 'components/ToolHint';
import GoldenEdition from './GoldenEdition';
import { useApp } from 'providers/App';
import { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
@@ -20,7 +21,7 @@ const Sidebar = () => {
const leftSidebarWidth = useSelector((state) => state.app.leftSidebarWidth);
const preferencesOpen = useSelector((state) => state.app.showPreferences);
const [goldenEditionOpen, setGoldenEditionOpen] = useState(false);
const { version } = useApp();
const [asideWidth, setAsideWidth] = useState(leftSidebarWidth);
const [cookiesOpen, setCookiesOpen] = useState(false);
@@ -184,7 +185,7 @@ const Sidebar = () => {
Star
</GitHubButton> */}
</div>
<div className="flex flex-grow items-center justify-end text-xs mr-2">v1.36.1</div>
<div className="flex flex-grow items-center justify-end text-xs mr-2">v{version}</div>
</div>
</div>
</div>

View File

@@ -34,7 +34,7 @@ const ToolHint = ({
<StyledWrapper theme={appliedTheme}>
<ReactToolHint
anchorId={toolhintId}
html={text}
content={text}
className="toolhint"
offset={offset}
place={place}

View File

@@ -1,6 +1,8 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './pages/index';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
const rootElement = document.getElementById('root');
@@ -8,7 +10,9 @@ if (rootElement) {
const root = ReactDOM.createRoot(rootElement);
root.render(
<React.StrictMode>
<App />
<DndProvider backend={HTML5Backend}>
<App />
</DndProvider>
</React.StrictMode>
);
}

View File

@@ -33,6 +33,8 @@ if (!SERVER_RENDERED) {
require('codemirror/addon/search/searchcursor');
require('codemirror/addon/display/placeholder');
require('codemirror/keymap/sublime');
require('codemirror/keymap/vim');
require('codemirror/keymap/emacs');
require('codemirror-graphql/hint');
require('codemirror-graphql/info');

View File

@@ -6,11 +6,12 @@ import ConfirmAppClose from './ConfirmAppClose';
import useIpcEvents from './useIpcEvents';
import useTelemetry from './useTelemetry';
import StyledWrapper from './StyledWrapper';
import { version } from '../../../package.json';
export const AppContext = React.createContext();
export const AppProvider = (props) => {
useTelemetry();
useTelemetry({ version });
useIpcEvents();
const dispatch = useDispatch();
@@ -37,7 +38,7 @@ export const AppProvider = (props) => {
}, []);
return (
<AppContext.Provider {...props} value="appProvider">
<AppContext.Provider {...props} value={{ version }}>
<StyledWrapper>
<ConfirmAppClose />
{props.children}
@@ -46,4 +47,12 @@ export const AppProvider = (props) => {
);
};
export const useApp = () => {
const context = React.useContext(AppContext);
if (!context) {
throw new Error('useApp must be used within an AppProvider');
}
return context;
};
export default AppProvider;

View File

@@ -42,7 +42,7 @@ const getAnonymousTrackingId = () => {
return id;
};
const trackStart = () => {
const trackStart = (version) => {
if (isPlaywrightTestRunning()) {
return;
}
@@ -58,16 +58,18 @@ const trackStart = () => {
event: 'start',
properties: {
os: platformLib.os.family,
version: '1.38.1'
version: version
}
});
};
const useTelemetry = () => {
const useTelemetry = ({ version }) => {
useEffect(() => {
trackStart();
setInterval(trackStart, 24 * 60 * 60 * 1000);
}, []);
if (posthogApiKey && posthogApiKey.length) {
trackStart(version);
setInterval(trackStart, 24 * 60 * 60 * 1000);
}
}, [posthogApiKey]);
};
export default useTelemetry;

View File

@@ -6,12 +6,13 @@ import collectionsReducer from './slices/collections';
import tabsReducer from './slices/tabs';
import notificationsReducer from './slices/notifications';
import globalEnvironmentsReducer from './slices/global-environments';
import { draftDetectMiddleware } from './middlewares/draft/middleware';
const isDevEnv = () => {
return import.meta.env.MODE === 'development';
};
let middleware = [tasksMiddleware.middleware];
let middleware = [tasksMiddleware.middleware, draftDetectMiddleware];
if (isDevEnv()) {
middleware = [...middleware, debugMiddleware.middleware];
}

View File

@@ -0,0 +1,56 @@
import { handleMakeTabParmanent } from "./utils";
const actionsToIntercept = [
'collections/requestUrlChanged',
'collections/updateAuth',
'collections/addQueryParam',
'collections/moveQueryParam',
'collections/updateQueryParam',
'collections/deleteQueryParam',
'collections/updatePathParam',
'collections/addRequestHeader',
'collections/updateRequestHeader',
'collections/deleteRequestHeader',
'collections/moveRequestHeader',
'collections/addFormUrlEncodedParam',
'collections/updateFormUrlEncodedParam',
'collections/deleteFormUrlEncodedParam',
'collections/moveFormUrlEncodedParam',
'collections/addMultipartFormParam',
'collections/updateMultipartFormParam',
'collections/deleteMultipartFormParam',
'collections/moveMultipartFormParam',
'collections/updateRequestAuthMode',
'collections/updateRequestBodyMode',
'collections/updateRequestBody',
'collections/updateRequestGraphqlQuery',
'collections/updateRequestGraphqlVariables',
'collections/updateRequestScript',
'collections/updateResponseScript',
'collections/updateRequestTests',
'collections/updateRequestMethod',
'collections/addAssertion',
'collections/updateAssertion',
'collections/deleteAssertion',
'collections/moveAssertion',
'collections/addVar',
'collections/updateVar',
'collections/deleteVar',
'collections/moveVar',
'collections/addFolderHeader',
'collections/updateFolderHeader',
'collections/deleteFolderHeader',
'collections/addFolderVar',
'collections/updateFolderVar',
'collections/deleteFolderVar',
'collections/updateRequestDocs',
'collections/runRequestEvent', // TODO: This doesn't necessarily related to a draft state, need to rethink.
];
export const draftDetectMiddleware = ({ dispatch, getState }) => (next) => (action) => {
if (actionsToIntercept.includes(action.type)) {
const state = getState();
handleMakeTabParmanent(state, action, dispatch);
}
return next(action);
};

View File

@@ -0,0 +1,21 @@
import { makeTabPermanent } from "providers/ReduxStore/slices/tabs";
import { findCollectionByUid, findItemInCollection } from "utils/collections/index";
import find from 'lodash/find';
function handleMakeTabParmanent(state, action, dispatch) {
const tabs = state.tabs.tabs;
const activeTabUid = state.tabs.activeTabUid;
const focusedTab = find(tabs, (t) => t.uid === activeTabUid);
const itemUid = action.payload.itemUid || action.payload.folderUid
const collection = findCollectionByUid(state.collections.collections, action.payload.collectionUid);
if (collection) {
const item = findItemInCollection(collection, itemUid);
if (item && focusedTab.preview == true) {
dispatch(makeTabPermanent({ uid: itemUid }));
}
}
}
export {
handleMakeTabParmanent
}

View File

@@ -97,6 +97,7 @@ export const {
updateSystemProxyEnvVariables
} = appSlice.actions;
// TODO: Need a equivalent method which allows setting preferences for individual sub-section
export const savePreferences = (preferences) => (dispatch, getState) => {
return new Promise((resolve, reject) => {
const { ipcRenderer } = window;

View File

@@ -32,6 +32,7 @@ import {
selectEnvironment as _selectEnvironment,
sortCollections as _sortCollections,
updateCollectionMountStatus,
moveCollection,
requestCancelled,
resetRunResults,
responseReceived,
@@ -759,7 +760,7 @@ export const newHttpRequest = (params) => (dispatch, getState) => {
sparql: null,
multipartForm: null,
formUrlEncoded: null,
binaryFile: null
file: null
},
auth: auth ?? {
mode: 'none'
@@ -1039,14 +1040,17 @@ export const browseDirectory = () => (dispatch, getState) => {
};
export const browseFiles =
(filters = [], properties = ['multiSelections']) =>
(dispatch, getState) => {
(filters, properties) =>
(_dispatch, _getState) => {
const { ipcRenderer } = window;
return new Promise((resolve, reject) => {
ipcRenderer.invoke('renderer:browse-files', undefined, undefined, undefined, filters, properties).then(resolve).catch(reject);
ipcRenderer
.invoke('renderer:browse-files', filters, properties)
.then(resolve)
.catch(reject);
});
};
};
export const updateBrunoConfig = (brunoConfig, collectionUid) => (dispatch, getState) => {
const state = getState();
@@ -1148,6 +1152,22 @@ export const importCollection = (collection, collectionLocation) => (dispatch, g
});
};
export const moveCollectionAndPersist = ({ draggedItem, targetItem }) => (dispatch, getState) => {
dispatch(moveCollection({ draggedItem, targetItem }));
return new Promise((resolve, reject) => {
const { ipcRenderer } = window;
const state = getState();
const collectionPaths = state.collections.collections.map((collection) => collection.pathname);
ipcRenderer
.invoke('renderer:update-collection-paths', collectionPaths)
.then(resolve)
.catch(reject);
});
};
export const saveCollectionSecurityConfig = (collectionUid, securityConfig) => (dispatch, getState) => {
return new Promise((resolve, reject) => {
const { ipcRenderer } = window;

View File

@@ -1,5 +1,5 @@
import { uuid } from 'utils/common';
import { find, map, forOwn, concat, filter, each, cloneDeep, get, set } from 'lodash';
import { find, map, forOwn, concat, filter, each, cloneDeep, get, set, findIndex } from 'lodash';
import { createSlice } from '@reduxjs/toolkit';
import {
addDepth,
@@ -59,7 +59,9 @@ export const collectionsSlice = createSlice({
updateCollectionMountStatus: (state, action) => {
const collection = findCollectionByUid(state.collections, action.payload.collectionUid);
if (collection) {
collection.mountStatus = action.payload.mountStatus;
if (action.payload.mountStatus) {
collection.mountStatus = action.payload.mountStatus;
}
}
},
setCollectionSecurityConfig: (state, action) => {
@@ -100,6 +102,12 @@ export const collectionsSlice = createSlice({
break;
}
},
moveCollection: (state, action) => {
const { draggedItem, targetItem } = action.payload;
state.collections = state.collections.filter((i) => i.uid !== draggedItem.uid); // Remove dragged item
const targetItemIndex = state.collections.findIndex((i) => i.uid === targetItem.uid); // Find target item
state.collections.splice(targetItemIndex, 0, draggedItem); // Insert dragged-item above target-item
},
updateLastAction: (state, action) => {
const { collectionUid, lastAction } = action.payload;
const collection = findCollectionByUid(state.collections, collectionUid);
@@ -875,89 +883,95 @@ export const collectionsSlice = createSlice({
}
}
},
moveMultipartFormParam: (state, action) => {
// Ensure item.draft is a deep clone of item if not already present
if (!item.draft) {
item.draft = cloneDeep(item);
}
// Extract payload data
const { updateReorderedItem } = action.payload;
const params = item.draft.request.body.multipartForm;
item.draft.request.body.multipartForm = updateReorderedItem.map((uid) => {
return params.find((param) => param.uid === uid);
});
},
addBinaryFile: (state, action) => {
moveMultipartFormParam: (state, action) => {
const collection = findCollectionByUid(state.collections, action.payload.collectionUid);
if (collection) {
const item = findItemInCollection(collection, action.payload.itemUid);
if (item && isItemARequest(item)) {
// Ensure item.draft is a deep clone of item if not already present
if (!item.draft) {
item.draft = cloneDeep(item);
}
item.draft.request.body.binaryFile = item.draft.request.body.binaryFile || [];
item.draft.request.body.binaryFile.push({
// Extract payload data
const { updateReorderedItem } = action.payload;
const params = item.draft.request.body.multipartForm;
item.draft.request.body.multipartForm = updateReorderedItem.map((uid) => {
return params.find((param) => param.uid === uid);
});
}
}
},
addFile: (state, action) => {
const collection = findCollectionByUid(state.collections, action.payload.collectionUid);
if (collection) {
const item = findItemInCollection(collection, action.payload.itemUid);
if (item && isItemARequest(item)) {
if (!item.draft) {
item.draft = cloneDeep(item);
}
item.draft.request.body.file = item.draft.request.body.file || [];
item.draft.request.body.file.push({
uid: uuid(),
type: action.payload.type,
name: '',
value: [''],
filePath: '',
contentType: '',
enabled: false
selected: false
});
}
}
},
updateBinaryFile: (state, action) => {
updateFile: (state, action) => {
const collection = findCollectionByUid(state.collections, action.payload.collectionUid);
if (collection) {
const item = findItemInCollection(collection, action.payload.itemUid);
if (item && isItemARequest(item)) {
if (!item.draft) {
item.draft = cloneDeep(item);
}
item.draft.request.body.binaryFile = item.draft.request.body.binaryFile.map((p) => {
p.enabled = false;
return p;
});
const param = find(item.draft.request.body.binaryFile, (p) => p.uid === action.payload.param.uid);
const param = find(item.draft.request.body.file, (p) => p.uid === action.payload.param.uid);
if (param) {
const contentType = mime.contentType(path.extname(action.payload.param.value[0]));
param.type = action.payload.param.type;
param.name = action.payload.param.name;
param.value = action.payload.param.value;
const contentType = mime.contentType(path.extname(action.payload.param.filePath));
param.filePath = action.payload.param.filePath;
param.contentType = action.payload.param.contentType || contentType || '';
param.enabled = action.payload.param.enabled;
param.selected = action.payload.param.selected;
item.draft.request.body.file = item.draft.request.body.file.map((p) => {
p.selected = p.uid === param.uid;
return p;
});
}
}
}
},
deleteBinaryFile: (state, action) => {
deleteFile: (state, action) => {
const collection = findCollectionByUid(state.collections, action.payload.collectionUid);
if (collection) {
const item = findItemInCollection(collection, action.payload.itemUid);
if (item && isItemARequest(item)) {
if (!item.draft) {
item.draft = cloneDeep(item);
}
item.draft.request.body.binaryFile = filter(
item.draft.request.body.binaryFile,
item.draft.request.body.file = filter(
item.draft.request.body.file,
(p) => p.uid !== action.payload.paramUid
);
if (item.draft.request.body.file.length > 0) {
item.draft.request.body.file[0].selected = true;
}
}
}
},
@@ -1017,8 +1031,8 @@ export const collectionsSlice = createSlice({
item.draft.request.body.sparql = action.payload.content;
break;
}
case 'binaryFile': {
item.draft.request.body.binaryFile = action.payload.content;
case 'file': {
item.draft.request.body.file = action.payload.content;
break;
}
case 'formUrlEncoded': {
@@ -1755,6 +1769,12 @@ export const collectionsSlice = createSlice({
// we don't want to lose the draft in this case
if (areItemsTheSameExceptSeqUpdate(item, file.data)) {
item.seq = file.data.seq;
if (item?.draft) {
item.draft.seq = file.data.seq;
}
if (item?.draft && areItemsTheSameExceptSeqUpdate(item?.draft, file.data)) {
item.draft = null;
}
} else {
item.name = file.data.name;
item.type = file.data.type;
@@ -2022,9 +2042,9 @@ export const {
addMultipartFormParam,
updateMultipartFormParam,
deleteMultipartFormParam,
addBinaryFile,
updateBinaryFile,
deleteBinaryFile,
addFile,
updateFile,
deleteFile,
moveMultipartFormParam,
updateRequestAuthMode,
updateRequestBodyMode,
@@ -2076,7 +2096,8 @@ export const {
runFolderEvent,
resetCollectionRunner,
updateRequestDocs,
updateFolderDocs
updateFolderDocs,
moveCollection
} = collectionsSlice.actions;
export default collectionsSlice.reducer;

View File

@@ -1,7 +1,7 @@
import toast from 'react-hot-toast';
import { createSlice } from '@reduxjs/toolkit';
import { getAppInstallDate } from 'utils/common/platform';
import semver from 'semver';
const getReadNotificationIds = () => {
try {
let readNotificationIdsString = window.localStorage.getItem('bruno.notifications.read');
@@ -27,6 +27,26 @@ const initialState = {
readNotificationIds: getReadNotificationIds() || []
};
export const filterNotificationsByVersion = (notifications, currentVersion) => {
try {
if (!notifications) return [];
if (!currentVersion) return notifications;
return notifications.filter(notification => {
const { minVersion, maxVersion } = notification;
if (!minVersion && !maxVersion) return true;
if (!minVersion) return semver.lte(currentVersion, maxVersion);
if (!maxVersion) return semver.gte(currentVersion, minVersion);
return semver.gte(currentVersion, minVersion) && semver.lte(currentVersion, maxVersion);
});
} catch (error) {
console.error(error);
return [];
}
};
export const notificationSlice = createSlice({
name: 'notifications',
initialState,
@@ -86,13 +106,14 @@ export const notificationSlice = createSlice({
export const { setNotifications, setFetchingStatus, markNotificationAsRead, markAllNotificationsAsRead } =
notificationSlice.actions;
export const fetchNotifications = () => (dispatch, getState) => {
export const fetchNotifications = ({currentVersion}) => (dispatch, getState) => {
return new Promise((resolve) => {
const { ipcRenderer } = window;
dispatch(setFetchingStatus(true));
ipcRenderer
.invoke('renderer:fetch-notifications')
.then((notifications) => {
notifications = filterNotificationsByVersion(notifications, currentVersion);
dispatch(setNotifications({ notifications }));
dispatch(setFetchingStatus(false));
resolve(notifications);

View File

@@ -0,0 +1,133 @@
const { filterNotificationsByVersion } = require('./notifications');
describe('filterNotificationsByVersion - basic', () => {
it('should filter notifications by version', () => {
const notifications = [{ minVersion: '1.0.0', maxVersion: '1.1.0' }];
const currentVersion = '1.0.5';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
expect(filteredNotifications).toEqual([{ minVersion: '1.0.0', maxVersion: '1.1.0' }]);
});
it('should gracefully handle no notifications', () => {
const notifications = [];
const currentVersion = '1.0.5';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
expect(filteredNotifications).toEqual([]);
});
it('should gracefully handle notifications are undefined', () => {
const notifications = undefined;
const currentVersion = '1.0.5';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
expect(filteredNotifications).toEqual([]);
});
it('should gracefully handle scenario when no current version is provided', () => {
const notifications = [{ minVersion: '1.0.0', maxVersion: '1.1.0' }];
const filteredNotifications = filterNotificationsByVersion(notifications);
expect(filteredNotifications).toEqual(notifications);
});
it('should gracefully handle scenario minVersion is undefined', () => {
const notifications = [{ minVersion: undefined, maxVersion: '1.1.0' }];
const currentVersion = '1.0.5';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
expect(filteredNotifications).toEqual(notifications);
});
it('should gracefully handle scenario maxVersion is undefined', () => {
const notifications = [{ minVersion: '1.0.0', maxVersion: undefined }];
const currentVersion = '1.0.5';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
expect(filteredNotifications).toEqual(notifications);
});
it('should gracefully handle scenario minVersion and maxVersion are undefined', () => {
const notifications = [{ minVersion: undefined, maxVersion: undefined }];
const currentVersion = '1.0.5';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
expect(filteredNotifications).toEqual(notifications);
});
});
describe('filterNotificationsByVersion - semver', () => {
it('should filter out notifications outside version range', () => {
const notifications = [
{ minVersion: '1.0.0', maxVersion: '1.1.0' }, // should be included
{ minVersion: '2.0.0', maxVersion: '2.1.0' }, // should be filtered out
{ minVersion: '0.5.0', maxVersion: '0.9.0' } // should be filtered out
];
const currentVersion = '1.0.5';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
expect(filteredNotifications).toEqual([
{ minVersion: '1.0.0', maxVersion: '1.1.0' }
]);
});
it('should handle mixed valid and invalid version ranges', () => {
const notifications = [
{ minVersion: '1.0.0', maxVersion: '2.0.0' }, // should be included
{ minVersion: '3.0.0', maxVersion: '4.0.0' }, // should be filtered out
{ minVersion: '1.5.0', maxVersion: '1.8.0' }, // should be included
{ minVersion: '0.1.0', maxVersion: '0.5.0' } // should be filtered out
];
const currentVersion = '1.6.0';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
expect(filteredNotifications).toEqual([
{ minVersion: '1.0.0', maxVersion: '2.0.0' },
{ minVersion: '1.5.0', maxVersion: '1.8.0' }
]);
});
it('should handle edge cases of version ranges', () => {
const notifications = [
{ minVersion: '1.0.0', maxVersion: '1.0.0' }, // should be included
{ minVersion: '1.0.1', maxVersion: '2.0.0' }, // should be filtered out
{ minVersion: '0.9.9', maxVersion: '1.0.0' } // should be included
];
const currentVersion = '1.0.0';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
expect(filteredNotifications).toEqual([
{ minVersion: '1.0.0', maxVersion: '1.0.0' },
{ minVersion: '0.9.9', maxVersion: '1.0.0' }
]);
});
});
describe('filterNotificationsByVersion - undefined version bounds', () => {
it('should include notifications when minVersion is undefined and current version is below maxVersion', () => {
const notifications = [
{ minVersion: undefined, maxVersion: '2.0.0' }
];
const currentVersion = '1.5.0';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
expect(filteredNotifications).toEqual(notifications);
});
it('should exclude notifications when minVersion is undefined and current version is above maxVersion', () => {
const notifications = [
{ minVersion: undefined, maxVersion: '2.0.0' }
];
const currentVersion = '2.1.0';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
expect(filteredNotifications).toEqual([]);
});
it('should include notifications when maxVersion is undefined and current version is above minVersion', () => {
const notifications = [
{ minVersion: '1.0.0', maxVersion: undefined }
];
const currentVersion = '2.0.0';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
expect(filteredNotifications).toEqual(notifications);
});
it('should exclude notifications when maxVersion is undefined and current version is below minVersion', () => {
const notifications = [
{ minVersion: '1.0.0', maxVersion: undefined }
];
const currentVersion = '0.9.0';
const filteredNotifications = filterNotificationsByVersion(notifications, currentVersion);
expect(filteredNotifications).toEqual([]);
});
});

View File

@@ -1,4 +1,5 @@
import { createSlice } from '@reduxjs/toolkit';
import { findIndex } from 'lodash';
import filter from 'lodash/filter';
import find from 'lodash/find';
import last from 'lodash/last';
@@ -19,31 +20,59 @@ export const tabsSlice = createSlice({
initialState,
reducers: {
addTab: (state, action) => {
const alreadyExists = find(state.tabs, (tab) => tab.uid === action.payload.uid);
if (alreadyExists) {
const { uid, collectionUid, type, requestPaneTab, preview } = action.payload;
const nonReplaceableTabTypes = [
"variables",
"collection-runner",
"security-settings",
];
const existingTab = find(state.tabs, (tab) => tab.uid === uid);
if (existingTab) {
state.activeTabUid = existingTab.uid;
return;
}
if (
['variables', 'collection-settings', 'collection-overview', 'collection-runner', 'security-settings'].includes(action.payload.type)
) {
const tab = tabTypeAlreadyExists(state.tabs, action.payload.collectionUid, action.payload.type);
if (tab) {
state.activeTabUid = tab.uid;
if (nonReplaceableTabTypes.includes(type)) {
const existingTab = tabTypeAlreadyExists(state.tabs, collectionUid, type);
if (existingTab) {
state.activeTabUid = existingTab.uid;
return;
}
}
const lastTab = state.tabs[state.tabs.length - 1];
if (state.tabs.length > 0 && lastTab.preview) {
state.tabs[state.tabs.length - 1] = {
uid,
collectionUid,
requestPaneWidth: null,
requestPaneTab: requestPaneTab || 'params',
responsePaneTab: 'response',
type: type || 'request',
preview: preview !== undefined
? preview
: !nonReplaceableTabTypes.includes(type),
...(uid ? { folderUid: uid } : {})
}
state.activeTabUid = uid;
return
}
state.tabs.push({
uid: action.payload.uid,
collectionUid: action.payload.collectionUid,
uid,
collectionUid,
requestPaneWidth: null,
requestPaneTab: action.payload.requestPaneTab || 'params',
requestPaneTab: requestPaneTab || 'params',
responsePaneTab: 'response',
type: action.payload.type || 'request',
...(action.payload.uid ? { folderUid: action.payload.uid } : {})
type: type || 'request',
...(uid ? { folderUid: uid } : {}),
preview: preview !== undefined
? preview
: !nonReplaceableTabTypes.includes(type)
});
state.activeTabUid = action.payload.uid;
state.activeTabUid = uid;
},
focusTab: (state, action) => {
state.activeTabUid = action.payload.uid;
@@ -124,6 +153,15 @@ export const tabsSlice = createSlice({
const collectionUid = action.payload.collectionUid;
state.tabs = filter(state.tabs, (t) => t.collectionUid !== collectionUid);
state.activeTabUid = null;
},
makeTabPermanent: (state, action) => {
const { uid } = action.payload;
const tab = find(state.tabs, (t) => t.uid === uid);
if (tab) {
tab.preview = false;
} else{
console.error("Tab not found!")
}
}
}
});
@@ -136,7 +174,8 @@ export const {
updateRequestPaneTab,
updateResponsePaneTab,
closeTabs,
closeAllCollectionTabs
closeAllCollectionTabs,
makeTabPermanent
} = tabsSlice.actions;
export default tabsSlice.reducer;
export default tabsSlice.reducer;

View File

@@ -14,7 +14,7 @@ const createContentType = (mode) => {
return 'application/json';
case 'multipartForm':
return 'multipart/form-data';
case 'binaryFile':
case 'file':
return 'application/octet-stream';
default:
return '';
@@ -65,6 +65,23 @@ const createPostData = (body, type) => {
switch (body.mode) {
case 'formUrlEncoded':
return {
mimeType: contentType,
text: new URLSearchParams(
body[body.mode]
.filter((param) => param.enabled)
.reduce((acc, param) => {
acc[param.name] = param.value;
return acc;
}, {})
).toString(),
params: body[body.mode]
.filter((param) => param.enabled)
.map((param) => ({
name: param.name,
value: param.value
}))
};
case 'multipartForm':
return {
mimeType: contentType,
@@ -76,21 +93,15 @@ const createPostData = (body, type) => {
...(param.type === 'file' && { fileName: param.value })
}))
};
case 'binaryFile':
const binary = {
mimeType: 'application/octet-stream',
// mimeType: body[body.mode].filter((param) => param.enabled)[0].contentType,
case 'file':
return {
mimeType: body[body.mode].filter((param) => param.enabled)[0].contentType,
params: body[body.mode]
.filter((param) => param.enabled)
.filter((param) => param.selected)
.map((param) => ({
name: param.name,
value: param.value,
fileName: param.value
value: param.filePath,
}))
};
console.log('curl-binary', binary);
return binary;
default:
return {
mimeType: contentType,
@@ -100,10 +111,6 @@ const createPostData = (body, type) => {
};
export const buildHarRequest = ({ request, headers, type }) => {
console.log('buildHarRequest', request, headers, type);
console.log('buildHarRequest-postData', createPostData(request.body, type));
return {
method: request.method,
url: encodeURI(request.url),

View File

@@ -14,7 +14,7 @@ export const deleteUidsInItems = (items) => {
each(get(item, 'request.vars.assertions'), (a) => delete a.uid);
each(get(item, 'request.body.multipartForm'), (param) => delete param.uid);
each(get(item, 'request.body.formUrlEncoded'), (param) => delete param.uid);
each(get(item, 'request.body.binaryFile'), (param) => delete param.uid);
each(get(item, 'request.body.file'), (param) => delete param.uid);
}
if (item.items && item.items.length) {

View File

@@ -1,13 +1,4 @@
import get from 'lodash/get';
import each from 'lodash/each';
import find from 'lodash/find';
import findIndex from 'lodash/findIndex';
import isString from 'lodash/isString';
import map from 'lodash/map';
import filter from 'lodash/filter';
import sortBy from 'lodash/sortBy';
import isEqual from 'lodash/isEqual';
import cloneDeep from 'lodash/cloneDeep';
import {cloneDeep, isEqual, sortBy, filter, map, isString, findIndex, find, each, get } from 'lodash';
import { uuid } from 'utils/common';
import path from 'path';
import slash from 'utils/common/slash';
@@ -146,6 +137,20 @@ export const areItemsLoading = (folder) => {
}, false);
}
export const getItemsLoadStats = (folder) => {
let loadingCount = 0;
let flattenedItems = flattenItems(folder.items);
flattenedItems?.forEach(i => {
if(i?.loading) {
loadingCount += 1;
}
});
return {
loading: loadingCount,
total: flattenedItems?.length
};
}
export const moveCollectionItem = (collection, draggedItem, targetItem) => {
let draggedItemParent = findParentItemInCollection(collection, draggedItem.uid);
@@ -281,15 +286,13 @@ export const transformCollectionToSaveToExportAsFile = (collection, options = {}
});
};
const copyBinaryFileParams = (params = []) => {
const copyFileParams = (params = []) => {
return map(params, (param) => {
return {
uid: param.uid,
type: param.type,
name: param.name,
value: param.value,
filePath: param.filePath,
contentType: param.contentType,
enabled: param.enabled
selected: param.selected
}
});
}
@@ -322,7 +325,7 @@ export const transformCollectionToSaveToExportAsFile = (collection, options = {}
sparql: si.request.body.sparql,
formUrlEncoded: copyFormUrlEncodedParams(si.request.body.formUrlEncoded),
multipartForm: copyMultipartFormParams(si.request.body.multipartForm),
binaryFile: copyBinaryFileParams(si.request.body.binaryFile)
file: copyFileParams(si.request.body.file)
},
script: si.request.script,
vars: si.request.vars,
@@ -675,8 +678,8 @@ export const humanizeRequestBodyMode = (mode) => {
label = 'SPARQL';
break;
}
case 'binaryFile': {
label = 'Binary File';
case 'file': {
label = 'File / Binary';
break;
}
case 'formUrlEncoded': {
@@ -779,7 +782,7 @@ export const refreshUidsInItem = (item) => {
each(get(item, 'request.params'), (param) => (param.uid = uuid()));
each(get(item, 'request.body.multipartForm'), (param) => (param.uid = uuid()));
each(get(item, 'request.body.formUrlEncoded'), (param) => (param.uid = uuid()));
each(get(item, 'request.body.binaryFile'), (param) => (param.uid = uuid()));
each(get(item, 'request.body.file'), (param) => (param.uid = uuid()));
return item;
};
@@ -790,13 +793,13 @@ export const deleteUidsInItem = (item) => {
const headers = get(item, 'request.headers', []);
const bodyFormUrlEncoded = get(item, 'request.body.formUrlEncoded', []);
const bodyMultipartForm = get(item, 'request.body.multipartForm', []);
const binaryFile = get(item, 'request.body.binaryFile', []);
const file = get(item, 'request.body.file', []);
params.forEach((param) => delete param.uid);
headers.forEach((header) => delete header.uid);
bodyFormUrlEncoded.forEach((param) => delete param.uid);
bodyMultipartForm.forEach((param) => delete param.uid);
binaryFile.forEach((param) => delete param.uid);
file.forEach((param) => delete param.uid);
return item;
};

View File

@@ -159,6 +159,8 @@ export const getCodeMirrorModeBasedOnContentType = (contentType, body) => {
if (contentType.includes('json')) {
return 'application/ld+json';
} else if (contentType.includes('image')) {
return 'application/image';
} else if (contentType.includes('xml')) {
return 'application/xml';
} else if (contentType.includes('html')) {
@@ -169,8 +171,6 @@ export const getCodeMirrorModeBasedOnContentType = (contentType, body) => {
return 'application/xml';
} else if (contentType.includes('yaml')) {
return 'application/yaml';
} else if (contentType.includes('image')) {
return 'application/image';
} else {
return 'application/text';
}

View File

@@ -94,6 +94,8 @@ export const getContentType = (headers) => {
if (contentType && contentType.length) {
if (typeof contentType[0] == 'string' && /^[\w\-]+\/([\w\-]+\+)?json/.test(contentType[0])) {
return 'application/ld+json';
} else if (typeof contentType[0] === 'string' && /^image\/svg\+xml/i.test(contentType[0])) {
return 'image/svg+xml';
} else if (typeof contentType[0] == 'string' && /^[\w\-]+\/([\w\-]+\+)?xml/.test(contentType[0])) {
return 'application/xml';
}

View File

@@ -102,30 +102,24 @@ function getFilesString(request) {
data.data = {};
if (request.isDataBinary){
if (request.isDataBinary) {
let filePath = '';
let filePath = ''
if(request.data.startsWith('@')){
if (request.data.startsWith('@')) {
filePath = request.data.slice(1);
}else{
} else {
filePath = request.data;
}
const fileName = path.basename(filePath);
data.data = [
{
name: repr(fileName),
value: [repr(filePath)],
enabled: true,
filePath: repr(filePath),
contentType: request.headers['Content-Type'],
type: 'binaryFile'
selected: true,
}
];
return data;
}
data.files = {};
@@ -190,13 +184,11 @@ const curlToJson = (curlCommand) => {
if (request.query) {
requestJson.queries = getQueries(request);
}
else if (request.multipartUploads || request.isDataBinary) {
} else if (request.multipartUploads || request.isDataBinary) {
Object.assign(requestJson, getFilesString(request));
} else if (typeof request.data === 'string' || typeof request.data === 'number') {
Object.assign(requestJson, getDataString(request));
}
}
if (request.insecure) {
requestJson.insecure = false;

View File

@@ -113,11 +113,9 @@ describe('curlToJson', () => {
isDataBinary: true,
data: [
{
name: 'file',
value: ['/path/to/file'],
enabled: true,
filePath: '/path/to/file',
contentType: 'application/json;charset=utf-8',
type: 'binaryFile'
selected: true
}
]
});

View File

@@ -51,7 +51,7 @@ export const getRequestFromCurlCommand = (curlCommand, requestType = 'http-reque
multipartForm: null,
formUrlEncoded: null,
graphql: null,
binaryFile: null
file: null
};
if (parsedBody && contentType && typeof contentType === 'string') {
@@ -59,8 +59,8 @@ export const getRequestFromCurlCommand = (curlCommand, requestType = 'http-reque
body.mode = 'graphql';
body.graphql = parseGraphQL(parsedBody);
} else if (requestType === 'http-request' && request.isDataBinary) {
body.mode = 'binaryFile';
body.binaryFile = parsedBody;
body.mode = 'file';
body.file = parsedBody;
}else if (contentType.includes('application/json')) {
body.mode = 'json';
body.json = convertToCodeMirrorJson(parsedBody);

View File

@@ -35,7 +35,7 @@ export const updateUidsInCollection = (_collection) => {
each(get(item, 'request.assertions'), (a) => (a.uid = uuid()));
each(get(item, 'request.body.multipartForm'), (param) => (param.uid = uuid()));
each(get(item, 'request.body.formUrlEncoded'), (param) => (param.uid = uuid()));
each(get(item, 'request.body.binaryFile'), (param) => (param.uid = uuid()));
each(get(item, 'request.body.file'), (param) => (param.uid = uuid()));
if (item.items && item.items.length) {
updateItemUids(item.items);

View File

@@ -181,6 +181,7 @@ const importPostmanV2CollectionItem = (brunoParent, item, parentAuth, options) =
brunoParent.items = brunoParent.items || [];
const folderMap = {};
const requestMap = {};
const requestMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', 'TRACE']
each(item, (i) => {
if (isItemAFolder(i)) {
@@ -230,6 +231,11 @@ const importPostmanV2CollectionItem = (brunoParent, item, parentAuth, options) =
} else {
if (i.request) {
if(!requestMethods.includes(i?.request?.method.toUpperCase())){
console.warn("Unexpected request.method")
return;
}
const baseRequestName = i.name;
let requestName = baseRequestName;
let count = 1;

View File

@@ -24,6 +24,10 @@ const replacements = {
'postman\\.setEnvironmentVariable\\(': 'bru.setEnvVar(',
'postman\\.getEnvironmentVariable\\(': 'bru.getEnvVar(',
'postman\\.clearEnvironmentVariable\\(': 'bru.deleteEnvVar(',
'pm\\.execution\\.skipRequest\\(\\)': 'bru.runner.skipRequest()',
'pm\\.execution\\.skipRequest': 'bru.runner.skipRequest',
'pm\\.execution\\.setNextRequest\\(null\\)': 'bru.runner.stopExecution()',
'pm\\.execution\\.setNextRequest\\(\'null\'\\)': 'bru.runner.stopExecution()',
};
const extendedReplacements = Object.keys(replacements).reduce((acc, key) => {
@@ -50,7 +54,7 @@ export const postmanTranslation = (script, logCallback) => {
}
if (modifiedScript.includes('pm.') || modifiedScript.includes('postman.')) {
modifiedScript = modifiedScript.replace(/^(.*(pm\.|postman\.).*)$/gm, '// $1');
logCallback?.();
//logCallback?.();
}
return modifiedScript;
} catch (e) {

View File

@@ -11,3 +11,10 @@ export const isItemAFolder = (item) => {
export const itemIsOpenedInTabs = (item, tabs) => {
return find(tabs, (t) => t.uid === item.uid);
};
export const scrollToTheActiveTab = () => {
const activeTab = document.querySelector('.request-tab.active');
if (activeTab) {
activeTab.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
};

View File

@@ -62,7 +62,10 @@ const makeJUnitOutput = async (results, outputPath) => {
suite.testcase.push(testcase);
});
if (result.error) {
if (result?.skipped) {
suite['@skipped'] = 1;
}
else if (result.error) {
suite['@errors'] = 1;
suite['@tests'] = 1;
suite.testcase = [

View File

@@ -265,7 +265,30 @@ const runSingleRequest = async function (
if (!options.disableCookies) {
const cookieString = getCookieStringForUrl(request.url);
if (cookieString && typeof cookieString === 'string' && cookieString.length) {
request.headers['cookie'] = cookieString;
const existingCookieHeaderName = Object.keys(request.headers).find(
name => name.toLowerCase() === 'cookie'
);
const existingCookieString = existingCookieHeaderName ? request.headers[existingCookieHeaderName] : '';
// Helper function to parse cookies into an object
const parseCookies = (str) => str.split(';').reduce((cookies, cookie) => {
const [name, ...rest] = cookie.split('=');
if (name && name.trim()) {
cookies[name.trim()] = rest.join('=').trim();
}
return cookies;
}, {});
const mergedCookies = {
...parseCookies(existingCookieString),
...parseCookies(cookieString),
};
const combinedCookieString = Object.entries(mergedCookies)
.map(([name, value]) => `${name}=${value}`)
.join('; ');
request.headers[existingCookieHeaderName || 'Cookie'] = combinedCookieString;
}
}

View File

@@ -1,8 +1,9 @@
const { sizeInMB } = require("../../utils/filesystem");
const WorkerQueue = require("../../workers");
const path = require("path");
const getSize = (data) => {
return typeof data === 'string' ? Buffer.byteLength(data, 'utf8') : Buffer.byteLength(JSON.stringify(data), 'utf8');
return sizeInMB(typeof data === 'string' ? Buffer.byteLength(data, 'utf8') : Buffer.byteLength(JSON.stringify(data), 'utf8'));
}
/**
@@ -12,7 +13,13 @@ const getSize = (data) => {
* This helps with parsing performance.
*/
const LANES = [{
maxSize: 0.005
},{
maxSize: 0.1
},{
maxSize: 1
},{
maxSize: 10
},{
maxSize: 100
}];

View File

@@ -1,14 +1,16 @@
const { workerData, parentPort } = require('worker_threads');
const { parentPort } = require('worker_threads');
const {
bruToJsonV2,
} = require('@usebruno/lang');
try {
const bru = workerData;
const json = bruToJsonV2(bru);
parentPort.postMessage(json);
}
catch(error) {
console.error(error);
parentPort.postMessage({ error: error?.message });
}
parentPort.on('message', (workerData) => {
try {
const bru = workerData;
const json = bruToJsonV2(bru);
parentPort.postMessage(json);
}
catch(error) {
console.error(error);
parentPort.postMessage({ error: error?.message });
}
});

View File

@@ -1,13 +1,16 @@
const { workerData, parentPort } = require('worker_threads');
const { parentPort } = require('worker_threads');
const {
jsonToBruV2,
} = require('@usebruno/lang');
try {
const json = workerData;
const bru = jsonToBruV2(json);
parentPort.postMessage(bru);
}
catch(error) {
console.error(error);
parentPort.postMessage({ error: error?.message });
}
parentPort.on('message', (workerData) => {
try {
const json = workerData;
const bru = jsonToBruV2(json);
parentPort.postMessage(bru);
}
catch(error) {
console.error(error);
parentPort.postMessage({ error: error?.message });
}
});

View File

@@ -30,9 +30,9 @@ const lastOpenedCollections = new LastOpenedCollections();
// Reference: https://content-security-policy.com/
const contentSecurityPolicy = [
"default-src 'self'",
"script-src * 'unsafe-inline' 'unsafe-eval'",
"connect-src * 'unsafe-inline'",
"connect-src 'self' https://*.posthog.com",
"font-src 'self' https:",
"frame-src data:",
// this has been commented out to make oauth2 work
// "form-action 'none'",
// we make an exception and allow http for images so that

View File

@@ -20,7 +20,6 @@ const {
normalizeWslPath,
normalizeAndResolvePath,
safeToRename,
sanitizeCollectionName,
isWindowsOS,
isValidFilename,
hasSubDirectories,
@@ -41,9 +40,9 @@ const collectionSecurityStore = new CollectionSecurityStore();
const uiStateSnapshotStore = new UiStateSnapshotStore();
// size and file count limits to determine whether the bru files in the collection should be loaded asynchronously or not.
const MAX_COLLECTION_SIZE_IN_MB = 5;
const MAX_SINGLE_FILE_SIZE_IN_COLLECTION_IN_MB = 2;
const MAX_COLLECTION_FILES_COUNT = 100;
const MAX_COLLECTION_SIZE_IN_MB = 20;
const MAX_SINGLE_FILE_SIZE_IN_COLLECTION_IN_MB = 5;
const MAX_COLLECTION_FILES_COUNT = 2000;
const envHasSecrets = (environment = {}) => {
const secrets = _.filter(environment.variables, (v) => v.secret);
@@ -62,14 +61,11 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
});
// browse directory for file
ipcMain.handle('renderer:browse-files', async (event, pathname, request, filters, properties) => {
ipcMain.handle('renderer:browse-files', async (_, filters, properties) => {
try {
const filePaths = await browseFiles(mainWindow, filters, properties);
return filePaths;
return await browseFiles(mainWindow, filters, properties);
} catch (error) {
return Promise.reject(error);
throw error;
}
});
@@ -79,7 +75,6 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
async (event, collectionName, collectionFolderName, collectionLocation) => {
try {
collectionFolderName = sanitizeDirectoryName(collectionFolderName);
collectionName = sanitizeCollectionName(collectionName);
const dirPath = path.join(collectionLocation, collectionFolderName);
if (fs.existsSync(dirPath)) {
const files = fs.readdirSync(dirPath);
@@ -121,7 +116,7 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
ipcMain.handle(
'renderer:clone-collection',
async (event, collectionName, collectionFolderName, collectionLocation, previousPath) => {
collectionFolderName = sanitizeCollectionName(collectionFolderName);
collectionFolderName = sanitizeDirectoryName(collectionFolderName);
const dirPath = path.join(collectionLocation, collectionFolderName);
if (fs.existsSync(dirPath)) {
throw new Error(`collection: ${dirPath} already exists`);
@@ -142,7 +137,7 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
// Change new name of collection
let brunoConfig = JSON.parse(content);
brunoConfig.name = collectionName;
const cont = await stringifyJson(json);
const cont = await stringifyJson(brunoConfig);
// write the bruno.json to new dir
await writeFile(path.join(dirPath, 'bruno.json'), cont);
@@ -171,7 +166,6 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
// rename collection
ipcMain.handle('renderer:rename-collection', async (event, newName, collectionPathname) => {
try {
newName = sanitizeCollectionName(newName);
const brunoJsonFilePath = path.join(collectionPathname, 'bruno.json');
const content = fs.readFileSync(brunoJsonFilePath, 'utf8');
const json = JSON.parse(content);
@@ -522,9 +516,13 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
}
});
ipcMain.handle('renderer:update-collection-paths', async (_, collectionPaths) => {
lastOpenedCollections.update(collectionPaths);
})
ipcMain.handle('renderer:import-collection', async (event, collection, collectionLocation) => {
try {
let collectionName = sanitizeCollectionName(collection.name);
let collectionName = sanitizeDirectoryName(collection.name);
let collectionPath = path.join(collectionLocation, collectionName);
if (fs.existsSync(collectionPath)) {

View File

@@ -28,7 +28,7 @@ const { makeAxiosInstance } = require('./axios-instance');
const { addAwsV4Interceptor, resolveAwsV4Credentials } = require('./awsv4auth-helper');
const { addDigestInterceptor } = require('./digestauth-helper');
const { shouldUseProxy, PatchedHttpsProxyAgent } = require('../../utils/proxy-util');
const { chooseFileToSave, writeBinaryFile, writeFile } = require('../../utils/filesystem');
const { chooseFileToSave, writeFile } = require('../../utils/filesystem');
const { getCookieStringForUrl, addCookieToJar, getDomainsWithCookies } = require('../../utils/cookies');
const {
resolveOAuth2AuthorizationCodeAccessToken,
@@ -332,7 +332,30 @@ const configureRequest = async (
if (preferencesUtil.shouldSendCookies()) {
const cookieString = getCookieStringForUrl(request.url);
if (cookieString && typeof cookieString === 'string' && cookieString.length) {
request.headers['cookie'] = cookieString;
const existingCookieHeaderName = Object.keys(request.headers).find(
name => name.toLowerCase() === 'cookie'
);
const existingCookieString = existingCookieHeaderName ? request.headers[existingCookieHeaderName] : '';
// Helper function to parse cookies into an object
const parseCookies = (str) => str.split(';').reduce((cookies, cookie) => {
const [name, ...rest] = cookie.split('=');
if (name && name.trim()) {
cookies[name.trim()] = rest.join('=').trim();
}
return cookies;
}, {});
const mergedCookies = {
...parseCookies(existingCookieString),
...parseCookies(cookieString),
};
const combinedCookieString = Object.entries(mergedCookies)
.map(([name, value]) => `${name}=${value}`)
.join('; ');
request.headers[existingCookieHeaderName || 'Cookie'] = combinedCookieString;
}
}
@@ -576,18 +599,14 @@ const registerNetworkIpc = (mainWindow) => {
});
const abortController = new AbortController();
const collectionRoot = get(collection, 'root', {});
const request = await prepareRequest(item, collection, abortController);
request.__bruno__executionMode = 'standalone';
const brunoConfig = getBrunoConfig(collectionUid);
const scriptingConfig = get(brunoConfig, 'scripts', {});
scriptingConfig.runtime = getJsSandboxRuntime(collection);
try {
request.signal = abortController.signal;
saveCancelToken(cancelTokenUid, abortController);
await runPreRequest(
@@ -618,7 +637,7 @@ const registerNetworkIpc = (mainWindow) => {
url: request.url,
method: request.method,
headers: request.headers,
data: request.mode == 'binaryFile'? undefined: safeParseJSON(safeStringifyJSON(request.data)) ,
data: request.mode == 'file'? "<request body redacted>": safeParseJSON(safeStringifyJSON(request.data)) ,
timestamp: Date.now()
},
collectionUid,
@@ -1375,7 +1394,7 @@ const registerNetworkIpc = (mainWindow) => {
if (encoding === 'utf-8') {
await writeFile(filePath, data);
} else {
await writeBinaryFile(filePath, data);
await writeFile(filePath, data, true);
}
}
} catch (error) {

View File

@@ -65,7 +65,11 @@ const interpolateVars = (request, envVariables = {}, runtimeVariables = {}, proc
const contentType = getContentType(request.headers);
if (contentType.includes('json')) {
/*
We explicitly avoid interpolating buffer values because the file content is read as a buffer object in raw body mode.
Even if the selected file's content type is JSON, this prevents the buffer object from being interpolated.
*/
if (contentType.includes('json') && !Buffer.isBuffer(request.data)) {
if (typeof request.data === 'string') {
if (request.data.length) {
request.data = _interpolate(request.data);

View File

@@ -1,4 +1,4 @@
const { get, each, filter } = require('lodash');
const { get, each, filter, find } = require('lodash');
const decomment = require('decomment');
const crypto = require('node:crypto');
const fs = require('node:fs/promises');
@@ -176,10 +176,10 @@ const setAuthHeaders = (axiosRequest, request, collectionRoot) => {
return axiosRequest;
};
const prepareRequest = async (item, collection, abortController) => {
const prepareRequest = async (item, collection = {}, abortController) => {
const request = item.draft ? item.draft.request : item.request;
const collectionRoot = get(collection, 'root', {});
const collectionPath = collection.pathname;
const collectionPath = collection?.pathname;
const headers = {};
let contentTypeDefined = false;
let url = request.url;
@@ -191,7 +191,7 @@ const prepareRequest = async (item, collection, abortController) => {
}
});
const scriptFlow = collection.brunoConfig?.scripts?.flow ?? 'sandwich';
const scriptFlow = collection?.brunoConfig?.scripts?.flow ?? 'sandwich';
const requestTreePath = getTreePathFromCollectionToItem(collection, item);
if (requestTreePath && requestTreePath.length > 0) {
mergeHeaders(collection, request, requestTreePath);
@@ -253,31 +253,26 @@ const prepareRequest = async (item, collection, abortController) => {
axiosRequest.data = request.body.sparql;
}
if (request.body.mode === 'binaryFile') {
if (request.body.mode === 'file') {
if (!contentTypeDefined) {
axiosRequest.headers['content-type'] = 'application/octet-stream';
axiosRequest.headers['content-type'] = 'application/octet-stream'; // Default headers for binary file uploads
}
if (request.body.binaryFile && request.body.binaryFile.length > 0) {
axiosRequest.headers['content-type'] = request.body.binaryFile[0].contentType;
let filePath = request.body.binaryFile[0].value[0];
if (filePath && filePath !== '') {
const bodyFile = find(request.body.file, (param) => param.selected);
if (bodyFile) {
let { filePath, contentType } = bodyFile;
axiosRequest.headers['content-type'] = contentType;
if (filePath) {
if (!path.isAbsolute(filePath)) {
filePath = path.join(collectionPath, filePath);
}
const file = await fs.readFile(filePath, abortController)
axiosRequest.data = file
if(axiosRequest.headers['content-type'].includes('application/json')) {
axiosRequest.data = JSON.parse(file)
try {
const fileContent = await fs.readFile(filePath);
axiosRequest.data = fileContent;
} catch (error) {
console.error('Error reading file:', error);
}
}
}

View File

@@ -16,18 +16,20 @@ class LastOpenedCollections {
}
add(collectionPath) {
const collections = this.store.get('lastOpenedCollections') || [];
const collections = this.getAll();
if (isDirectory(collectionPath)) {
if (!collections.includes(collectionPath)) {
collections.push(collectionPath);
this.store.set('lastOpenedCollections', collections);
}
if (isDirectory(collectionPath) && !collections.includes(collectionPath)) {
collections.push(collectionPath);
this.store.set('lastOpenedCollections', collections);
}
}
update(collectionPaths) {
this.store.set('lastOpenedCollections', collectionPaths);
}
remove(collectionPath) {
let collections = this.store.get('lastOpenedCollections') || [];
let collections = this.getAll();
if (collections.includes(collectionPath)) {
collections = _.filter(collections, (c) => c !== collectionPath);
@@ -36,7 +38,7 @@ class LastOpenedCollections {
}
removeAll() {
return this.store.set('lastOpenedCollections', []);
this.store.set('lastOpenedCollections', []);
}
}

View File

@@ -58,6 +58,9 @@ const preferencesSchema = Yup.object().shape({
codeFont: Yup.string().nullable(),
codeFontSize: Yup.number().min(1).max(32).nullable()
}),
editor: Yup.object().shape({
keymap: Yup.string().oneOf(['sublime', 'vim', 'emacs']).nullable(),
}),
proxy: Yup.object({
mode: Yup.string().oneOf(['off', 'on', 'system']),
protocol: Yup.string().oneOf(['http', 'https', 'socks4', 'socks5']),

View File

@@ -240,6 +240,7 @@ const hydrateRequestWithUuid = (request, pathname) => {
const assertions = get(request, 'request.assertions', []);
const bodyFormUrlEncoded = get(request, 'request.body.formUrlEncoded', []);
const bodyMultipartForm = get(request, 'request.body.multipartForm', []);
const file = get(request, 'request.body.file', []);
params.forEach((param) => (param.uid = uuid()));
headers.forEach((header) => (header.uid = uuid()));
@@ -248,6 +249,7 @@ const hydrateRequestWithUuid = (request, pathname) => {
assertions.forEach((assertion) => (assertion.uid = uuid()));
bodyFormUrlEncoded.forEach((param) => (param.uid = uuid()));
bodyMultipartForm.forEach((param) => (param.uid = uuid()));
file.forEach((param) => (param.uid = uuid()));
return request;
};

View File

@@ -68,20 +68,13 @@ function normalizeWslPath(pathname) {
return pathname.replace(/^\/wsl.localhost/, '\\\\wsl.localhost').replace(/\//g, '\\');
}
const writeFile = async (pathname, content) => {
const writeFile = async (pathname, content, isBinary = false) => {
try {
fs.writeFileSync(pathname, content, {
encoding: 'utf8'
await fs.writeFile(pathname, content, {
encoding: !isBinary ? "utf-8" : null
});
} catch (err) {
return Promise.reject(err);
}
};
const writeBinaryFile = async (pathname, content) => {
try {
fs.writeFileSync(pathname, content);
} catch (err) {
console.error(`Error writing file at ${pathname}:`, err);
return Promise.reject(err);
}
};
@@ -121,7 +114,7 @@ const browseDirectory = async (win) => {
return isDirectory(resolvedPath) ? resolvedPath : false;
};
const browseFiles = async (win, filters, properties) => {
const browseFiles = async (win, filters = [], properties = []) => {
const { filePaths } = await dialog.showOpenDialog(win, {
properties: ['openFile', ...properties],
filters
@@ -161,10 +154,6 @@ const searchForBruFiles = (dir) => {
return searchForFiles(dir, '.bru');
};
const sanitizeCollectionName = (name) => {
return name.trim();
}
const sanitizeDirectoryName = (name) => {
return name.replace(/[<>:"/\\|?*\x00-\x1F]+/g, '-').trim();
};
@@ -265,7 +254,6 @@ module.exports = {
isWSLPath,
normalizeWslPath,
writeFile,
writeBinaryFile,
hasJsonExtension,
hasBruExtension,
createDirectory,
@@ -275,7 +263,6 @@ module.exports = {
searchForFiles,
searchForBruFiles,
sanitizeDirectoryName,
sanitizeCollectionName,
isWindowsOS,
safeToRename,
isValidFilename,

View File

@@ -4,8 +4,18 @@ class WorkerQueue {
constructor() {
this.queue = [];
this.isProcessing = false;
this.workers = {};
}
async getWorkerForScriptPath(scriptPath) {
if (!this.workers) this.workers = {};
let worker = this.workers[scriptPath];
if (!worker || worker.threadId === -1) {
this.workers[scriptPath] = worker = new Worker(scriptPath);
}
return worker;
}
async enqueue(task) {
const { priority, scriptPath, data } = task;
@@ -36,22 +46,20 @@ class WorkerQueue {
}
async runWorker({ scriptPath, data }) {
return new Promise((resolve, reject) => {
const worker = new Worker(scriptPath, { workerData: data });
return new Promise(async (resolve, reject) => {
let worker = await this.getWorkerForScriptPath(scriptPath);
worker.postMessage(data);
worker.on('message', (data) => {
if (data?.error) {
reject(new Error(data?.error));
}
resolve(data);
worker.terminate();
});
worker.on('error', (error) => {
reject(error);
worker.terminate();
});
worker.on('exit', (code) => {
reject(new Error(`stopped with ${code} exit code`));
worker.terminate();
});
});
}

View File

@@ -7,15 +7,17 @@ describe('prepare-request: prepareRequest', () => {
describe('Decomments request body', () => {
it('If request body is valid JSON', async () => {
const body = { mode: 'json', json: '{\n"test": "{{someVar}}" // comment\n}' };
const expected = '{\n"test": "{{someVar}}" \n}';
const result = prepareRequest({ request: { body } }, {});
const expected = `{
\"test\": \"{{someVar}}\"
}`;
const result = await prepareRequest({ request: { body }, collection: { pathname: '' } });
expect(result.data).toEqual(expected);
});
it('If request body is not valid JSON', async () => {
const body = { mode: 'json', json: '{\n"test": {{someVar}} // comment\n}' };
const expected = '{\n"test": {{someVar}} \n}';
const result = prepareRequest({ request: { body } }, {});
const result = await prepareRequest({ request: { body }, collection: { pathname: '' } });
expect(result.data).toEqual(expected);
});

View File

@@ -25,6 +25,7 @@
"btoa": "^1.2.1",
"chai": "^4.3.7",
"chai-string": "^1.5.0",
"cheerio": "^1.0.0",
"crypto-js": "^4.1.1",
"json-query": "^2.2.2",
"lodash": "^4.17.21",
@@ -34,7 +35,8 @@
"node-vault": "^0.10.2",
"path": "^0.12.7",
"quickjs-emscripten": "^0.29.2",
"uuid": "^9.0.0"
"uuid": "^9.0.0",
"xml2js": "^0.6.2"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^23.0.2",

View File

@@ -28,6 +28,8 @@ const fetch = require('node-fetch');
const chai = require('chai');
const CryptoJS = require('crypto-js');
const NodeVault = require('node-vault');
const xml2js = require('xml2js');
const cheerio = require('cheerio');
const { executeQuickJsVmAsync } = require('../sandbox/quickjs');
class ScriptRuntime {
@@ -145,6 +147,8 @@ class ScriptRuntime {
chai,
'node-fetch': fetch,
'crypto-js': CryptoJS,
'xml2js': xml2js,
cheerio,
...whitelistedModules,
fs: allowScriptFilesystemAccess ? fs : undefined,
'node-vault': NodeVault

View File

@@ -30,6 +30,8 @@ const axios = require('axios');
const fetch = require('node-fetch');
const CryptoJS = require('crypto-js');
const NodeVault = require('node-vault');
const xml2js = require('xml2js');
const cheerio = require('cheerio');
const { executeQuickJsVmAsync } = require('../sandbox/quickjs');
const getResultsSummary = (results) => {
@@ -205,6 +207,8 @@ class TestRuntime {
chai,
'node-fetch': fetch,
'crypto-js': CryptoJS,
'xml2js': xml2js,
cheerio,
...whitelistedModules,
fs: allowScriptFilesystemAccess ? fs : undefined,
'node-vault': NodeVault

View File

@@ -25,7 +25,7 @@ const grammar = ohm.grammar(`Bru {
BruFile = (meta | http | query | params | headers | auths | bodies | varsandassert | script | tests | docs)*
auths = authawsv4 | authbasic | authbearer | authdigest | authNTLM | authOAuth2 | authwsse | authapikey
bodies = bodyjson | bodytext | bodyxml | bodysparql | bodygraphql | bodygraphqlvars | bodyforms | body
bodyforms = bodyformurlencoded | bodymultipart | bodybinaryfile
bodyforms = bodyformurlencoded | bodymultipart | bodyfile
params = paramspath | paramsquery
nl = "\\r"? "\\n"
@@ -102,7 +102,7 @@ const grammar = ohm.grammar(`Bru {
bodyformurlencoded = "body:form-urlencoded" dictionary
bodymultipart = "body:multipart-form" dictionary
bodybinaryfile = "body:binary-file" dictionary
bodyfile = "body:file" dictionary
script = scriptreq | scriptres
scriptreq = "script:pre-request" st* "{" nl* textblock tagend
@@ -174,12 +174,12 @@ const multipartExtractContentType = (pair) => {
}
};
const binaryFileExtractContentType = (pair) => {
const fileExtractContentType = (pair) => {
if (_.isString(pair.value)) {
const match = pair.value.match(/^(.*?)\s*@contentType\((.*?)\)\s*$/);
if (match != null && match.length > 2) {
pair.value = match[1];
pair.contentType = match[2];
if (match && match.length > 2) {
pair.value = match[1].trim();
pair.contentType = match[2].trim();
} else {
pair.contentType = '';
}
@@ -204,23 +204,27 @@ const mapPairListToKeyValPairsMultipart = (pairList = [], parseEnabled = true) =
});
};
const mapPairListToKeyValPairsBinaryFile = (pairList = [], parseEnabled = true) => {
const mapPairListToKeyValPairsFile = (pairList = [], parseEnabled = true) => {
const pairs = mapPairListToKeyValPairs(pairList, parseEnabled);
return pairs.map((pair) => {
binaryFileExtractContentType(pair);
fileExtractContentType(pair);
if (pair.value.startsWith('@file(') && pair.value.endsWith(')')) {
let filestr = pair.value.replace(/^@file\(/, '').replace(/\)$/, '');
pair.type = 'binaryFile';
pair.value = filestr != '' ? filestr.split('|') : [''];
let filePath = pair.value.replace(/^@file\(/, '').replace(/\)$/, '');
pair.filePath = filePath;
pair.selected = pair.enabled
// Remove pair.value as it only contains the file path reference
delete pair.value;
// Remove pair.name as it is auto-generated (e.g., file1, file2, file3, etc.)
delete pair.name;
delete pair.enabled;
}
return pair;
});
};
const concatArrays = (objValue, srcValue) => {
if (_.isArray(objValue) && _.isArray(srcValue)) {
return objValue.concat(srcValue);
@@ -605,10 +609,10 @@ const sem = grammar.createSemantics().addAttribute('ast', {
}
};
},
bodybinaryfile(_1, dictionary) {
bodyfile(_1, dictionary) {
return {
body: {
binaryFile: mapPairListToKeyValPairsBinaryFile(dictionary.ast)
file: mapPairListToKeyValPairsFile(dictionary.ast)
}
};
},
@@ -746,3 +750,4 @@ const parser = (input) => {
};
module.exports = parser;

View File

@@ -2,8 +2,8 @@ const _ = require('lodash');
const { indentString } = require('../../v1/src/utils');
const enabled = (items = []) => items.filter((item) => item.enabled);
const disabled = (items = []) => items.filter((item) => !item.enabled);
const enabled = (items = [], key = "enabled") => items.filter((item) => item[key]);
const disabled = (items = [], key = "enabled") => items.filter((item) => !item[key]);
// remove the last line if two new lines are found
const stripLastLine = (text) => {
@@ -314,23 +314,21 @@ ${indentString(body.sparql)}
}
if (body && body.binaryFile && body.binaryFile.length) {
bru += `body:binary-file {`;
const binaryFiles = enabled(body.binaryFile).concat(disabled(body.binaryFile));
if (body && body.file && body.file.length) {
bru += `body:file {`;
const files = enabled(body.file, "selected").concat(disabled(body.file, "selected"));
if (binaryFiles.length) {
if (files.length) {
bru += `\n${indentString(
binaryFiles
files
.map((item) => {
const enabled = item.enabled ? '' : '~';
const selected = item.selected ? '' : '~';
const contentType =
item.contentType && item.contentType !== '' ? ' @contentType(' + item.contentType + ')' : '';
if (item.type === 'binaryFile') {
let filestr = item.value[0] || '';
const value = `@file(${filestr})`;
return `${enabled}${item.name}: ${value}${contentType}`;
}
const filePath = item.filePath || '';
const value = `@file(${filePath})`;
const itemName = "file";
return `${selected}${itemName}: ${value}${contentType}`;
})
.join('\n')
)}`;

View File

@@ -102,9 +102,10 @@ body:multipart-form {
~message: hello
}
body:binary-file {
body:file {
file: @file(path/to/file.json) @contentType(application/json)
~file2: @file(path/to/file2.json) @contentType(application/json)
file: @file(path/to/file.json) @contentType(application/json)
~file: @file(path/to/file2.json) @contentType(application/json)
}
body:graphql {

View File

@@ -138,20 +138,21 @@
"type": "text"
}
],
"binaryFile" : [
"file" : [
{
"name": "file",
"value": ["path/to/file.json"],
"enabled": true,
"type": "binaryFile",
"contentType": "application/json"
"filePath": "path/to/file.json",
"contentType": "application/json",
"selected": true
},
{
"name": "file2",
"value": ["path/to/file2.json"],
"enabled": false,
"type": "binaryFile",
"contentType": "application/json"
"filePath": "path/to/file.json",
"contentType": "application/json",
"selected": true
},
{
"filePath": "path/to/file2.json",
"contentType": "application/json",
"selected": false
}
]
},

View File

@@ -75,20 +75,18 @@ const multipartFormSchema = Yup.object({
.strict();
const binaryFileSchema = Yup.object({
const fileSchema = Yup.object({
uid: uidSchema,
type: Yup.string().oneOf(['binaryFile']).required('type is required'),
name: Yup.string().nullable(),
value: Yup.array().of(Yup.string().nullable()).nullable(),
filePath: Yup.string().nullable(),
contentType: Yup.string().nullable(),
enabled: Yup.boolean()
selected: Yup.boolean()
})
.noUnknown(true)
.strict();
const requestBodySchema = Yup.object({
mode: Yup.string()
.oneOf(['none', 'json', 'text', 'xml', 'formUrlEncoded', 'multipartForm', 'graphql', 'sparql', 'binaryFile'])
.oneOf(['none', 'json', 'text', 'xml', 'formUrlEncoded', 'multipartForm', 'graphql', 'sparql', 'file'])
.required('mode is required'),
json: Yup.string().nullable(),
text: Yup.string().nullable(),
@@ -97,7 +95,7 @@ const requestBodySchema = Yup.object({
formUrlEncoded: Yup.array().of(keyValueSchema).nullable(),
multipartForm: Yup.array().of(multipartFormSchema).nullable(),
graphql: graphqlBodySchema.nullable(),
binaryFile: Yup.array().of(binaryFileSchema).nullable()
file: Yup.array().of(fileSchema).nullable()
})
.noUnknown(true)
.strict();

View File

@@ -1,27 +0,0 @@
meta {
name: binary-files-types
type: http
seq: 1
}
post {
url: {{host}}/api/binaryFile/binary-file-types
body: binaryFile
auth: none
}
body:binary-file {
file1: @file() @contentType()
file2: @file(binaryFile/binary-file.json) @contentType()
file3: @file(binaryFile/binary-file.json) @contentType(application/json)
}
assert {
res.status: eq 200
res.body.find(p=>p.name === 'file1').value[0]: isUndefined
res.body.find(p=>p.name === 'file1').contentType: isUndefined
res.body.find(p=>p.name === 'file2').value[0]: eq binaryFile/binary-file.json
res.body.find(p=>p.name === 'file2').contentType: eq isUndefined
res.body.find(p=>p.name === 'file3').value[0]: eq binaryFile/binary-file.json
res.body.find(p=>p.name === 'file3').contentType: eq application/json
}

View File

@@ -1,9 +0,0 @@
{
"version": "1",
"name": "bruno-testing",
"type": "collection",
"ignore": [
"node_modules",
".git"
]
}

View File

@@ -0,0 +1,15 @@
meta {
name: echo binary
type: http
seq: 1
}
post {
url: {{echo-host}}
body: file
auth: none
}
body:file {
file: @file(bruno.png) @contentType(image/png)
}

View File

@@ -0,0 +1,3 @@
file.txt
hello, bruno

View File

@@ -1,15 +0,0 @@
meta {
name: ping-another-one
type: http
seq: 2
}
get {
url: {{host}}/ping
body: none
auth: none
}
script:pre-request {
throw new Error('this should not execute in a collection run');
}

View File

@@ -0,0 +1,42 @@
meta {
name: cheerio
type: http
seq: 1
}
post {
url: https://echo.usebruno.com
body: text
auth: none
}
body:text {
<h2 class="title">Hello Bruno!</h2>
}
script:pre-request {
const cheerio = require('cheerio');
const $ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
bru.setVar("cheerio-test-html", $.html());
}
tests {
const cheerio = require('cheerio');
test("cheerio html - from scripts", function() {
const expected = '<html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>';
const html = bru.getVar('cheerio-test-html');
expect(html).to.eql(expected);
});
test("cheerio html - from tests", function() {
const expected = '<html><head></head><body><h2 class="title">Hello Bruno!</h2></body></html>';
const $ = cheerio.load(res.body);
expect($.html()).to.eql(expected);
});
}

View File

@@ -0,0 +1,41 @@
meta {
name: xml2js
type: http
seq: 1
}
get {
url: {{host}}/ping
body: none
auth: none
}
script:pre-request {
var parseString = require('xml2js').parseString;
var xml = "<root>Hello xml2js!</root>"
parseString(xml, function (err, result) {
bru.setVar("xml2js-test-result", result);
});
}
tests {
var parseString = require('xml2js').parseString;
test("xml2js parseString in scripts", function() {
const expected = {
root: 'Hello xml2js!'
};
const result = bru.getVar('xml2js-test-result');
expect(result).to.eql(expected);
});
test("xml2js parseString in tests", async function() {
var xml = "<root>Hello inside test!</root>"
const expected = {
root: 'Hello inside test!'
};
parseString(xml, function (err, result) {
expect(result).to.eql(expected);
});
});
}

View File

@@ -19,6 +19,17 @@ router.post('/xml-raw', (req, res) => {
return res.send(req.rawBody);
});
router.post('/bin', (req, res) => {
const rawBody = req.body;
if (!rawBody || rawBody.length === 0) {
return res.status(400).send('No data received');
}
res.set('Content-Type', req.headers['content-type'] || 'application/octet-stream');
res.send(rawBody);
});
router.get('/bom-json-test', (req, res) => {
const jsonData = {
message: 'Hello!',

View File

@@ -10,6 +10,7 @@ const multipartRouter = require('./multipart');
const app = new express();
const port = process.env.PORT || 8080;
app.use(express.raw({type: '*/*', limit: '100mb'}));
app.use(cors());
app.use(xmlParser());
app.use(bodyParser.text());