@usebruno/filestore 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/formats/bru/utils/oauth2-additional-params.d.ts +38 -0
- package/dist/cjs/formats/bru/utils/request-parse-and-redact-body-data.d.ts +9 -0
- package/dist/cjs/index.d.ts +1 -0
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/workers/formats/bru/utils/oauth2-additional-params.d.ts +38 -0
- package/dist/cjs/workers/formats/bru/utils/request-parse-and-redact-body-data.d.ts +9 -0
- package/dist/cjs/workers/index.d.ts +1 -0
- package/dist/cjs/workers/worker-script.js +1 -1
- package/dist/cjs/workers/worker-script.js.map +1 -1
- package/dist/esm/formats/bru/utils/oauth2-additional-params.d.ts +38 -0
- package/dist/esm/formats/bru/utils/request-parse-and-redact-body-data.d.ts +9 -0
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/workers/formats/bru/utils/oauth2-additional-params.d.ts +38 -0
- package/dist/esm/workers/formats/bru/utils/request-parse-and-redact-body-data.d.ts +9 -0
- package/dist/esm/workers/index.d.ts +1 -0
- package/dist/esm/workers/worker-script.js +1 -1
- package/dist/esm/workers/worker-script.js.map +1 -1
- package/package.json +2 -2
- package/src/formats/bru/index.ts +132 -40
- package/src/formats/bru/tests/fixtures/oauth2-additional-params.js +116 -0
- package/src/formats/bru/tests/fixtures/request-parse-and-redact-body-data/input.bru +66 -0
- package/src/formats/bru/tests/fixtures/request-parse-and-redact-body-data/output.bru +35 -0
- package/src/formats/bru/tests/oauth2-additional-params.spec.js +45 -0
- package/src/formats/bru/tests/request-parse-and-redact-body-data.spec.js +44 -0
- package/src/formats/bru/utils/oauth2-additional-params.ts +141 -0
- package/src/formats/bru/utils/request-parse-and-redact-body-data.ts +77 -0
- package/src/index.ts +8 -0
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
type T_Oauth2ParameterSendInType = 'headers' | 'queryparams' | 'body';
|
|
2
|
+
export interface T_OAuth2AdditionalParam {
|
|
3
|
+
name: string;
|
|
4
|
+
value: string;
|
|
5
|
+
enabled: boolean;
|
|
6
|
+
sendIn: T_Oauth2ParameterSendInType;
|
|
7
|
+
}
|
|
8
|
+
export interface T_OAuth2AdditionalParameters {
|
|
9
|
+
authorization?: T_OAuth2AdditionalParam[];
|
|
10
|
+
token?: T_OAuth2AdditionalParam[];
|
|
11
|
+
refresh?: T_OAuth2AdditionalParam[];
|
|
12
|
+
}
|
|
13
|
+
export interface T_Oauth2Auth {
|
|
14
|
+
grantType: string;
|
|
15
|
+
additionalParameters?: T_OAuth2AdditionalParameters;
|
|
16
|
+
}
|
|
17
|
+
export interface T_BruJson {
|
|
18
|
+
auth: {
|
|
19
|
+
oauth2: T_Oauth2Auth;
|
|
20
|
+
};
|
|
21
|
+
oauth2_additional_parameters_auth_req_headers?: any[];
|
|
22
|
+
oauth2_additional_parameters_auth_req_queryparams?: any[];
|
|
23
|
+
oauth2_additional_parameters_access_token_req_headers?: any[];
|
|
24
|
+
oauth2_additional_parameters_access_token_req_queryparams?: any[];
|
|
25
|
+
oauth2_additional_parameters_access_token_req_bodyvalues?: any[];
|
|
26
|
+
oauth2_additional_parameters_refresh_token_req_headers?: any[];
|
|
27
|
+
oauth2_additional_parameters_refresh_token_req_queryparams?: any[];
|
|
28
|
+
oauth2_additional_parameters_refresh_token_req_bodyvalues?: any[];
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* This function extracts OAuth2 additional parameters from various sources in the bru json data and organizes
|
|
32
|
+
* them into a structured format based on their usage context (authorization, token, refresh).
|
|
33
|
+
*
|
|
34
|
+
* @param json - json object containing OAuth2 configuration and additional parameters
|
|
35
|
+
* @returns OAuth2 additional parameters
|
|
36
|
+
*/
|
|
37
|
+
export declare const getOauth2AdditionalParameters: (json: T_BruJson) => T_OAuth2AdditionalParameters;
|
|
38
|
+
export {};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parses a .bru file and extracts body content while redacting it from the main content
|
|
3
|
+
* @param {string} bruFileContent - The raw content of the .bru file
|
|
4
|
+
* @returns {Object} Object containing redacted file content and extracted body data
|
|
5
|
+
*/
|
|
6
|
+
export declare const bruRequestParseAndRedactBodyData: (bruFileContent: string) => {
|
|
7
|
+
bruFileStringWithRedactedBody: string;
|
|
8
|
+
extractedBodyContent: Record<string, string>;
|
|
9
|
+
};
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import BruParserWorker from './workers';
|
|
2
2
|
import { ParseOptions, StringifyOptions, ParsedRequest, ParsedCollection, ParsedEnvironment } from './types';
|
|
3
3
|
export declare const parseRequest: (content: string, options?: ParseOptions) => any;
|
|
4
|
+
export declare const parseRequestAndRedactBody: (content: string, options?: ParseOptions) => any;
|
|
4
5
|
export declare const stringifyRequest: (requestObj: ParsedRequest, options?: StringifyOptions) => string;
|
|
5
6
|
export declare const parseRequestViaWorker: (content: string) => Promise<any>;
|
|
6
7
|
export declare const stringifyRequestViaWorker: (requestObj: any) => Promise<string>;
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("lodash"),t=require("@usebruno/lang"),r=require("node:worker_threads"),s=require("node:path");function o(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var a=o(e);const u=(e,r=!1)=>{try{const s=r?e:t.collectionBruToJson(e),o={request:{headers:a.get(s,"headers",[]),auth:a.get(s,"auth",{}),script:a.get(s,"script",{}),vars:a.get(s,"vars",{}),tests:a.get(s,"tests","")},settings:a.get(s,"settings",{}),docs:a.get(s,"docs","")};if(s.meta&&(o.meta={name:s.meta.name},void 0!==s.meta.seq)){const e=s.meta.seq;o.meta.seq=isNaN(e)?1:Number(e)}return o}catch(e){return Promise.reject(e)}},n=(e,r)=>{try{const s={headers:a.get(e,"request.headers",[]),script:{req:a.get(e,"request.script.req",""),res:a.get(e,"request.script.res","")},vars:{req:a.get(e,"request.vars.req",[]),res:a.get(e,"request.vars.res",[])},tests:a.get(e,"request.tests",""),auth:a.get(e,"request.auth",{}),docs:a.get(e,"docs","")};if(e?.meta&&(s.meta={name:e.meta.name},void 0!==e.meta.seq)){const t=e.meta.seq;s.meta.seq=isNaN(t)?1:Number(t)}return r||(s.auth=a.get(e,"request.auth",{})),t.jsonToCollectionBru(s)}catch(e){throw e}};class i{constructor(){this.queue=[],this.isProcessing=!1,this.workers={}}async getWorkerForScriptPath(e){this.workers||(this.workers={});let t=this.workers[e];return t&&-1!==t.threadId||(this.workers[e]=t=new r.Worker(e)),t}async enqueue(e){const{priority:t,scriptPath:r,data:s,taskType:o}=e;return new Promise(((e,a)=>{this.queue.push({priority:t,scriptPath:r,data:s,taskType:o,resolve:e,reject:a}),this.queue?.sort(((e,t)=>e?.priority-t?.priority)),this.processQueue()}))}async processQueue(){if(this.isProcessing||0===this.queue.length)return;this.isProcessing=!0;const{scriptPath:e,data:t,taskType:r,resolve:s,reject:o}=this.queue.shift();try{const o=await this.runWorker({scriptPath:e,data:t,taskType:r});s?.(o)}catch(e){o?.(e)}finally{this.isProcessing=!1,this.processQueue()}}async runWorker({scriptPath:e,data:t,taskType:r}){return new Promise((async(s,o)=>{let a=await this.getWorkerForScriptPath(e);const u=e=>{a.off("message",u),a.off("error",n),a.off("exit",i),e?.error?o(new Error(e?.error)):s(e)},n=e=>{a.off("message",u),a.off("error",n),a.off("exit",i),o(e)},i=t=>{a.off("message",u),a.off("error",n),a.off("exit",i),delete this.workers[e],o(new Error(`Worker stopped with exit code ${t}`))};a.on("message",u),a.on("error",n),a.on("exit",i),a.postMessage({taskType:r,data:t})}))}async cleanup(){const e=Object.values(this.workers).map((e=>-1!==e.threadId?e.terminate():Promise.resolve()));await Promise.allSettled(e),this.workers={}}}const c=[{maxSize:.005},{maxSize:.1},{maxSize:1},{maxSize:10},{maxSize:100}];class p{constructor(){this.workerQueues=c?.map((e=>({maxSize:e?.maxSize,workerQueue:new i})))}getWorkerQueue(e){const t=this.workerQueues.find((t=>t.maxSize>=e));return t?.workerQueue??this.workerQueues[this.workerQueues.length-1].workerQueue}async enqueueTask({data:e,taskType:t}){const r=(e=>("string"==typeof e?Buffer.byteLength(e,"utf8"):Buffer.byteLength(JSON.stringify(e),"utf8"))/1048576)(e),o=this.getWorkerQueue(r),a=s.join(__dirname,"./workers/worker-script.js");return o.enqueue({data:e,priority:r,scriptPath:a,taskType:t})}async parseRequest(e){return this.enqueueTask({data:e,taskType:"parse"})}async stringifyRequest(e){return this.enqueueTask({data:e,taskType:"stringify"})}async cleanup(){const e=this.workerQueues.map((({workerQueue:e})=>e.cleanup()));await Promise.allSettled(e)}}let h=null;const m=()=>(h||(h=new p),h);exports.BruParserWorker=p,exports.parseCollection=(e,t={format:"bru"})=>{if("bru"===t.format)return u(e);throw new Error(`Unsupported format: ${t.format}`)},exports.parseDotEnv=e=>t.dotenvToJson(e),exports.parseEnvironment=(e,r={format:"bru"})=>{if("bru"===r.format)return(e=>{try{const r=t.bruToEnvJsonV2(e);return r&&r.variables&&r.variables.length&&a.each(r.variables,(e=>e.type="text")),r}catch(e){return Promise.reject(e)}})(e);throw new Error(`Unsupported format: ${r.format}`)},exports.parseFolder=(e,t={format:"bru"})=>{if("bru"===t.format)return u(e);throw new Error(`Unsupported format: ${t.format}`)},exports.parseRequest=(e,r={format:"bru"})=>{if("bru"===r.format)return((e,r=!1)=>{try{const s=r?e:t.bruToJsonV2(e);let o=a.get(s,"meta.type");o="http"===o?"http-request":"graphql"===o?"graphql-request":"http-request";const u=a.get(s,"meta.seq"),n={type:o,name:a.get(s,"meta.name"),seq:a.isNaN(u)?1:Number(u),settings:a.get(s,"settings",{}),tags:a.get(s,"meta.tags",[]),request:{method:a.upperCase(a.get(s,"http.method")),url:a.get(s,"http.url"),params:a.get(s,"params",[]),headers:a.get(s,"headers",[]),auth:a.get(s,"auth",{}),body:a.get(s,"body",{}),script:a.get(s,"script",{}),vars:a.get(s,"vars",{}),assertions:a.get(s,"assertions",[]),tests:a.get(s,"tests",""),docs:a.get(s,"docs","")}};return n.request.auth.mode=a.get(s,"http.auth","none"),n.request.body.mode=a.get(s,"http.body","none"),n}catch(e){return Promise.reject(e)}})(e);throw new Error(`Unsupported format: ${r.format}`)},exports.parseRequestViaWorker=async e=>{const t=m();return await t.parseRequest(e)},exports.stringifyCollection=(e,t={format:"bru"})=>{if("bru"===t.format)return n(e,!1);throw new Error(`Unsupported format: ${t.format}`)},exports.stringifyEnvironment=(e,r={format:"bru"})=>{if("bru"===r.format)return(e=>{try{return t.envJsonToBruV2(e)}catch(e){throw e}})(e);throw new Error(`Unsupported format: ${r.format}`)},exports.stringifyFolder=(e,t={format:"bru"})=>{if("bru"===t.format)return n(e,!0);throw new Error(`Unsupported format: ${t.format}`)},exports.stringifyRequest=(e,r={format:"bru"})=>{if("bru"===r.format)return(e=>{try{let r=a.get(e,"type");r="http-request"===r?"http":"graphql-request"===r?"graphql":"http";const s=a.get(e,"seq"),o={meta:{name:a.get(e,"name"),type:r,seq:a.isNaN(s)?1:Number(s),tags:a.get(e,"tags",[])},http:{method:a.lowerCase(a.get(e,"request.method")),url:a.get(e,"request.url"),auth:a.get(e,"request.auth.mode","none"),body:a.get(e,"request.body.mode","none")},params:a.get(e,"request.params",[]),headers:a.get(e,"request.headers",[]),auth:a.get(e,"request.auth",{}),body:a.get(e,"request.body",{}),script:a.get(e,"request.script",{}),vars:{req:a.get(e,"request.vars.req",[]),res:a.get(e,"request.vars.res",[])},assertions:a.get(e,"request.assertions",[]),tests:a.get(e,"request.tests",""),settings:a.get(e,"settings",{}),docs:a.get(e,"request.docs","")};return t.jsonToBruV2(o)}catch(e){throw e}})(e);throw new Error(`Unsupported format: ${r.format}`)},exports.stringifyRequestViaWorker=async e=>{const t=m();return await t.stringifyRequest(e)};
|
|
1
|
+
"use strict";var e=require("lodash"),t=require("@usebruno/lang"),r=require("node:worker_threads"),s=require("node:path");function o(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var a=o(e);const n=[{type:"authorization",sendIn:"headers",source:"oauth2_additional_parameters_auth_req_headers"},{type:"authorization",sendIn:"queryparams",source:"oauth2_additional_parameters_auth_req_queryparams"},{type:"token",sendIn:"headers",source:"oauth2_additional_parameters_access_token_req_headers"},{type:"token",sendIn:"queryparams",source:"oauth2_additional_parameters_access_token_req_queryparams"},{type:"token",sendIn:"body",source:"oauth2_additional_parameters_access_token_req_bodyvalues"},{type:"refresh",sendIn:"headers",source:"oauth2_additional_parameters_refresh_token_req_headers"},{type:"refresh",sendIn:"queryparams",source:"oauth2_additional_parameters_refresh_token_req_queryparams"},{type:"refresh",sendIn:"body",source:"oauth2_additional_parameters_refresh_token_req_bodyvalues"}],u=(e,t)=>e?.length?e.map((e=>({...e,sendIn:t}))):[],i=(e,t,r)=>{if(!((e,t)=>"authorization"===e?"authorization_code"===t||"implicit"===t:"token"!==e&&"refresh"!==e||"implicit"!==t)(t,r))return[];const s=n.filter((e=>e.type===t)),o=[];for(const t of s){const r=e[t.source],s=u(r,t.sendIn);o.push(...s)}return o},c=e=>{const t=e.auth.oauth2.grantType,r={};try{const s=["authorization","token","refresh"];for(const o of s){const s=i(e,o,t);s.length>0&&(r[o]=s)}}catch(e){console.error(e),console.error("Error while getting the oauth2 additional parameters!")}return r},p=(e,r=!1)=>{try{const s=r?e:t.collectionBruToJson(e),o={request:{headers:a.get(s,"headers",[]),auth:a.get(s,"auth",{}),script:a.get(s,"script",{}),vars:a.get(s,"vars",{}),tests:a.get(s,"tests","")},settings:a.get(s,"settings",{}),docs:a.get(s,"docs","")};if(s.meta&&(o.meta={name:s.meta.name},void 0!==s.meta.seq)){const e=s.meta.seq;o.meta.seq=isNaN(e)?1:Number(e)}const n=s?.auth?.oauth2?.grantType;if(n){const e=c(s);Object.keys(e).length>0&&(o.request.auth.oauth2.additionalParameters=e)}return o}catch(e){return Promise.reject(e)}},h=(e,r)=>{try{const s={headers:a.get(e,"request.headers",[]),script:{req:a.get(e,"request.script.req",""),res:a.get(e,"request.script.res","")},vars:{req:a.get(e,"request.vars.req",[]),res:a.get(e,"request.vars.res",[])},tests:a.get(e,"request.tests",""),auth:a.get(e,"request.auth",{}),docs:a.get(e,"docs","")};if(e?.meta&&(s.meta={name:e.meta.name},void 0!==e.meta.seq)){const t=e.meta.seq;s.meta.seq=isNaN(t)?1:Number(t)}return r||(s.auth=a.get(e,"request.auth",{})),t.jsonToCollectionBru(s)}catch(e){throw e}};class d{constructor(){this.queue=[],this.isProcessing=!1,this.workers={}}async getWorkerForScriptPath(e){this.workers||(this.workers={});let t=this.workers[e];return t&&-1!==t.threadId||(this.workers[e]=t=new r.Worker(e)),t}async enqueue(e){const{priority:t,scriptPath:r,data:s,taskType:o}=e;return new Promise(((e,a)=>{this.queue.push({priority:t,scriptPath:r,data:s,taskType:o,resolve:e,reject:a}),this.queue?.sort(((e,t)=>e?.priority-t?.priority)),this.processQueue()}))}async processQueue(){if(this.isProcessing||0===this.queue.length)return;this.isProcessing=!0;const{scriptPath:e,data:t,taskType:r,resolve:s,reject:o}=this.queue.shift();try{const o=await this.runWorker({scriptPath:e,data:t,taskType:r});s?.(o)}catch(e){o?.(e)}finally{this.isProcessing=!1,this.processQueue()}}async runWorker({scriptPath:e,data:t,taskType:r}){return new Promise((async(s,o)=>{let a=await this.getWorkerForScriptPath(e);const n=e=>{a.off("message",n),a.off("error",u),a.off("exit",i),e?.error?o(new Error(e?.error)):s(e)},u=e=>{a.off("message",n),a.off("error",u),a.off("exit",i),o(e)},i=t=>{a.off("message",n),a.off("error",u),a.off("exit",i),delete this.workers[e],o(new Error(`Worker stopped with exit code ${t}`))};a.on("message",n),a.on("error",u),a.on("exit",i),a.postMessage({taskType:r,data:t})}))}async cleanup(){const e=Object.values(this.workers).map((e=>-1!==e.threadId?e.terminate():Promise.resolve()));await Promise.allSettled(e),this.workers={}}}const g=[{maxSize:.005},{maxSize:.1},{maxSize:1},{maxSize:10},{maxSize:100}];class m{constructor(){this.workerQueues=g?.map((e=>({maxSize:e?.maxSize,workerQueue:new d})))}getWorkerQueue(e){const t=this.workerQueues.find((t=>t.maxSize>=e));return t?.workerQueue??this.workerQueues[this.workerQueues.length-1].workerQueue}async enqueueTask({data:e,taskType:t}){const r=(e=>("string"==typeof e?Buffer.byteLength(e,"utf8"):Buffer.byteLength(JSON.stringify(e),"utf8"))/1048576)(e),o=this.getWorkerQueue(r),a=s.join(__dirname,"./workers/worker-script.js");return o.enqueue({data:e,priority:r,scriptPath:a,taskType:t})}async parseRequest(e){return this.enqueueTask({data:e,taskType:"parse"})}async stringifyRequest(e){return this.enqueueTask({data:e,taskType:"stringify"})}async cleanup(){const e=this.workerQueues.map((({workerQueue:e})=>e.cleanup()));await Promise.allSettled(e)}}let f=null;const y=()=>(f||(f=new m),f);exports.BruParserWorker=m,exports.parseCollection=(e,t={format:"bru"})=>{if("bru"===t.format)return p(e);throw new Error(`Unsupported format: ${t.format}`)},exports.parseDotEnv=e=>t.dotenvToJson(e),exports.parseEnvironment=(e,r={format:"bru"})=>{if("bru"===r.format)return(e=>{try{const r=t.bruToEnvJsonV2(e);return r&&r.variables&&r.variables.length&&a.each(r.variables,(e=>e.type="text")),r}catch(e){return Promise.reject(e)}})(e);throw new Error(`Unsupported format: ${r.format}`)},exports.parseFolder=(e,t={format:"bru"})=>{if("bru"===t.format)return p(e);throw new Error(`Unsupported format: ${t.format}`)},exports.parseRequest=(e,r={format:"bru"})=>{if("bru"===r.format)return((e,r=!1)=>{try{const s=r?e:t.bruToJsonV2(e);let o=a.get(s,"meta.type");switch(o){case"http":default:o="http-request";break;case"graphql":o="graphql-request";break;case"grpc":o="grpc-request"}const n=a.get(s,"meta.seq"),u={type:o,name:a.get(s,"meta.name"),seq:a.isNaN(n)?1:Number(n),settings:a.get(s,"settings",{}),tags:a.get(s,"meta.tags",[]),request:{method:"grpc-request"===o?a.get(s,"grpc.method",""):a.upperCase(a.get(s,"http.method")),url:a.get(s,"grpc-request"===o?"grpc.url":"http.url"),headers:"grpc-request"===o?a.get(s,"metadata",[]):a.get(s,"headers",[]),auth:a.get(s,"auth",{}),body:a.get(s,"body",{}),script:a.get(s,"script",{}),vars:a.get(s,"vars",{}),assertions:a.get(s,"assertions",[]),tests:a.get(s,"tests",""),docs:a.get(s,"docs","")}};if("grpc-request"===o){const e=a.get(s,"grpc.methodType");e&&(u.request.methodType=e);const t=a.get(s,"grpc.protoPath");t&&(u.request.protoPath=t),u.request.auth.mode=a.get(s,"grpc.auth","none"),u.request.body=a.get(s,"body",{mode:"grpc",grpc:a.get(s,"body.grpc",[{name:"message 1",content:"{}"}])})}else u.request.params=a.get(s,"params",[]),u.request.auth.mode=a.get(s,"http.auth","none"),u.request.body.mode=a.get(s,"http.body","none");const i=s?.auth?.oauth2?.grantType;if(i){const e=c(s);Object.keys(e||{}).length>0&&(u.request.auth.oauth2.additionalParameters=e)}return u}catch(e){throw e}})(e);throw new Error(`Unsupported format: ${r.format}`)},exports.parseRequestAndRedactBody=(e,t={format:"bru"})=>{if("bru"===t.format)return(e=>{try{const t=["body:json {","body:text {","body:xml {","body:sparql {","body:graphql {"];e=(e||"").replace(/\r\n/g,"\n");const r="\n",s=e=>e&&e.length?e.split(r).map((e=>e.replace(/^ /,""))).join(r):e||"";let o=e.split(`${r}}${r}`);o=o.filter(Boolean).map((e=>e.trim()));const a=o.filter((e=>t.some((t=>e.startsWith(t))))).reduce(((e,t)=>{const o=t.split(r)[0].split("body:")[1].split(/\s/)[0],a=t.split(r).slice(1).join(r),n=s(a);return e[o]=n,e}),{});return{bruFileStringWithRedactedBody:o.filter((e=>!t.some((t=>e.startsWith(t))))).join(`${r}}${r}${r}`).concat(`${r}}${r}`),extractedBodyContent:a}}catch(t){return console.error("Error parsing and redacting body data:",t),{bruFileStringWithRedactedBody:e,extractedBodyContent:{}}}})(e);throw new Error(`Unsupported format: ${t.format}`)},exports.parseRequestViaWorker=async e=>{const t=y();return await t.parseRequest(e)},exports.stringifyCollection=(e,t={format:"bru"})=>{if("bru"===t.format)return h(e,!1);throw new Error(`Unsupported format: ${t.format}`)},exports.stringifyEnvironment=(e,r={format:"bru"})=>{if("bru"===r.format)return(e=>{try{return t.envJsonToBruV2(e)}catch(e){throw e}})(e);throw new Error(`Unsupported format: ${r.format}`)},exports.stringifyFolder=(e,t={format:"bru"})=>{if("bru"===t.format)return h(e,!0);throw new Error(`Unsupported format: ${t.format}`)},exports.stringifyRequest=(e,r={format:"bru"})=>{if("bru"===r.format)return(e=>{try{let r=a.get(e,"type");switch(r){case"http-request":default:r="http";break;case"graphql-request":r="graphql";break;case"grpc-request":r="grpc"}const s=a.get(e,"seq"),o={meta:{name:a.get(e,"name"),type:r,seq:a.isNaN(s)?1:Number(s),tags:a.get(e,"tags",[])}};if("http"===r||"graphql"===r)o.http={method:a.lowerCase(a.get(e,"request.method")),url:a.get(e,"request.url"),auth:a.get(e,"request.auth.mode","none"),body:a.get(e,"request.body.mode","none")},o.params=a.get(e,"request.params",[]),o.body=a.get(e,"request.body",{mode:"json",json:"{}"});else if("grpc"===r){o.grpc={url:a.get(e,"request.url"),auth:a.get(e,"request.auth.mode","none"),body:a.get(e,"request.body.mode","grpc")};const t=a.get(e,"request.method"),r=a.get(e,"request.methodType"),s=a.get(e,"request.protoPath");t&&(o.grpc.method=t),r&&(o.grpc.methodType=r),s&&(o.grpc.protoPath=s),o.body=a.get(e,"request.body",{mode:"grpc",grpc:a.get(e,"request.body.grpc",[{name:"message 1",content:"{}"}])})}return"grpc"===r?o.metadata=a.get(e,"request.headers",[]):o.headers=a.get(e,"request.headers",[]),o.auth=a.get(e,"request.auth",{}),o.script=a.get(e,"request.script",{}),o.vars={req:a.get(e,"request.vars.req",[]),res:a.get(e,"request.vars.res",[])},o.assertions=a.get(e,"request.assertions",[]),o.tests=a.get(e,"request.tests",""),o.settings=a.get(e,"settings",{}),o.docs=a.get(e,"request.docs",""),t.jsonToBruV2(o)}catch(e){throw e}})(e);throw new Error(`Unsupported format: ${r.format}`)},exports.stringifyRequestViaWorker=async e=>{const t=y();return await t.stringifyRequest(e)};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../src/formats/bru/index.ts","../../src/workers/WorkerQueue/index.ts","../../src/workers/index.ts","../../src/index.ts"],"sourcesContent":["import * as _ from 'lodash';\nimport {\n bruToJsonV2,\n jsonToBruV2,\n bruToEnvJsonV2,\n envJsonToBruV2,\n collectionBruToJson as _collectionBruToJson,\n jsonToCollectionBru as _jsonToCollectionBru\n} from '@usebruno/lang';\n\nexport const bruRequestToJson = (data: string | any, parsed: boolean = false): any => {\n try {\n const json = parsed ? data : bruToJsonV2(data);\n\n let requestType = _.get(json, 'meta.type');\n if (requestType === 'http') {\n requestType = 'http-request';\n } else if (requestType === 'graphql') {\n requestType = 'graphql-request';\n } else {\n requestType = 'http-request';\n }\n\n const sequence = _.get(json, 'meta.seq');\n const transformedJson = {\n type: requestType,\n name: _.get(json, 'meta.name'),\n seq: !_.isNaN(sequence) ? Number(sequence) : 1,\n settings: _.get(json, 'settings', {}),\n tags: _.get(json, 'meta.tags', []),\n request: {\n method: _.upperCase(_.get(json, 'http.method')),\n url: _.get(json, 'http.url'),\n params: _.get(json, 'params', []),\n headers: _.get(json, 'headers', []),\n auth: _.get(json, 'auth', {}),\n body: _.get(json, 'body', {}),\n script: _.get(json, 'script', {}),\n vars: _.get(json, 'vars', {}),\n assertions: _.get(json, 'assertions', []),\n tests: _.get(json, 'tests', ''),\n docs: _.get(json, 'docs', '')\n }\n };\n\n transformedJson.request.auth.mode = _.get(json, 'http.auth', 'none');\n transformedJson.request.body.mode = _.get(json, 'http.body', 'none');\n\n return transformedJson;\n } catch (e) {\n return Promise.reject(e);\n }\n};\n\nexport const jsonRequestToBru = (json: any): string => {\n try {\n let type = _.get(json, 'type');\n if (type === 'http-request') {\n type = 'http';\n } else if (type === 'graphql-request') {\n type = 'graphql';\n } else {\n type = 'http';\n }\n\n const sequence = _.get(json, 'seq');\n const bruJson = {\n meta: {\n name: _.get(json, 'name'),\n type: type,\n seq: !_.isNaN(sequence) ? Number(sequence) : 1,\n tags: _.get(json, 'tags', []),\n },\n http: {\n method: _.lowerCase(_.get(json, 'request.method')),\n url: _.get(json, 'request.url'),\n auth: _.get(json, 'request.auth.mode', 'none'),\n body: _.get(json, 'request.body.mode', 'none')\n },\n params: _.get(json, 'request.params', []),\n headers: _.get(json, 'request.headers', []),\n auth: _.get(json, 'request.auth', {}),\n body: _.get(json, 'request.body', {}),\n script: _.get(json, 'request.script', {}),\n vars: {\n req: _.get(json, 'request.vars.req', []),\n res: _.get(json, 'request.vars.res', [])\n },\n assertions: _.get(json, 'request.assertions', []),\n tests: _.get(json, 'request.tests', ''),\n settings: _.get(json, 'settings', {}),\n docs: _.get(json, 'request.docs', '')\n };\n\n const bru = jsonToBruV2(bruJson);\n return bru;\n } catch (error) {\n throw error;\n }\n};\n\nexport const bruCollectionToJson = (data: string | any, parsed: boolean = false): any => {\n try {\n const json = parsed ? data : _collectionBruToJson(data);\n\n const transformedJson: any = {\n request: {\n headers: _.get(json, 'headers', []),\n auth: _.get(json, 'auth', {}),\n script: _.get(json, 'script', {}),\n vars: _.get(json, 'vars', {}),\n tests: _.get(json, 'tests', '')\n },\n settings: _.get(json, 'settings', {}),\n docs: _.get(json, 'docs', '')\n };\n\n // add meta if it exists\n // this is only for folder bru file\n if (json.meta) {\n transformedJson.meta = {\n name: json.meta.name\n };\n \n // Include seq if it exists\n if (json.meta.seq !== undefined) {\n const sequence = json.meta.seq;\n transformedJson.meta.seq = !isNaN(sequence) ? Number(sequence) : 1;\n }\n }\n\n return transformedJson;\n } catch (error) {\n return Promise.reject(error);\n }\n};\n\nexport const jsonCollectionToBru = (json: any, isFolder?: boolean): string => {\n try {\n const collectionBruJson: any = {\n headers: _.get(json, 'request.headers', []),\n script: {\n req: _.get(json, 'request.script.req', ''),\n res: _.get(json, 'request.script.res', '')\n },\n vars: {\n req: _.get(json, 'request.vars.req', []),\n res: _.get(json, 'request.vars.res', [])\n },\n tests: _.get(json, 'request.tests', ''),\n auth: _.get(json, 'request.auth', {}),\n docs: _.get(json, 'docs', '')\n };\n\n // add meta if it exists\n // this is only for folder bru file\n if (json?.meta) {\n collectionBruJson.meta = {\n name: json.meta.name\n };\n \n // Include seq if it exists\n if (json.meta.seq !== undefined) {\n const sequence = json.meta.seq;\n collectionBruJson.meta.seq = !isNaN(sequence) ? Number(sequence) : 1;\n }\n }\n\n if (!isFolder) {\n collectionBruJson.auth = _.get(json, 'request.auth', {});\n }\n\n return _jsonToCollectionBru(collectionBruJson);\n } catch (error) {\n throw error;\n }\n};\n\nexport const bruEnvironmentToJson = (bru: string): any => {\n try {\n const json = bruToEnvJsonV2(bru);\n\n // the app env format requires each variable to have a type\n // this need to be evaluated and safely removed\n // i don't see it being used in schema validation\n if (json && json.variables && json.variables.length) {\n _.each(json.variables, (v: any) => (v.type = 'text'));\n }\n\n return json;\n } catch (error) {\n return Promise.reject(error);\n }\n};\n\nexport const jsonEnvironmentToBru = (json: any): string => {\n try {\n const bru = envJsonToBruV2(json);\n return bru;\n } catch (error) {\n throw error;\n }\n}; ","import { Worker } from 'node:worker_threads';\n\ninterface QueuedTask {\n priority: number;\n scriptPath: string;\n data: any;\n taskType: 'parse' | 'stringify';\n resolve?: (value: any) => void;\n reject?: (reason?: any) => void;\n}\n\nclass WorkerQueue {\n private queue: QueuedTask[];\n private isProcessing: boolean;\n private workers: Record<string, Worker>;\n\n constructor() {\n this.queue = [];\n this.isProcessing = false;\n this.workers = {};\n }\n\n async getWorkerForScriptPath(scriptPath: string) {\n if (!this.workers) this.workers = {}; \n let worker = this.workers[scriptPath];\n if (!worker || worker.threadId === -1) {\n this.workers[scriptPath] = worker = new Worker(scriptPath);\n }\n return worker;\n }\n \n async enqueue(task: QueuedTask) {\n const { priority, scriptPath, data, taskType } = task;\n\n return new Promise((resolve, reject) => {\n this.queue.push({ priority, scriptPath, data, taskType, resolve, reject });\n this.queue?.sort((taskX, taskY) => taskX?.priority - taskY?.priority);\n this.processQueue();\n });\n }\n\n async processQueue() {\n if (this.isProcessing || this.queue.length === 0){\n return;\n } \n\n this.isProcessing = true;\n const { scriptPath, data, taskType, resolve, reject } = this.queue.shift() as QueuedTask;\n\n try {\n const result = await this.runWorker({ scriptPath, data, taskType });\n resolve?.(result);\n } catch (error) {\n reject?.(error);\n } finally {\n this.isProcessing = false;\n this.processQueue();\n }\n }\n\n async runWorker({ scriptPath, data, taskType }: { scriptPath: string; data: any; taskType: 'parse' | 'stringify' }) {\n return new Promise(async (resolve, reject) => {\n let worker = await this.getWorkerForScriptPath(scriptPath);\n \n const messageHandler = (data: any) => {\n worker.off('message', messageHandler);\n worker.off('error', errorHandler);\n worker.off('exit', exitHandler);\n \n if (data?.error) {\n reject(new Error(data?.error));\n } else {\n resolve(data);\n }\n };\n\n const errorHandler = (error: Error) => {\n worker.off('message', messageHandler);\n worker.off('error', errorHandler);\n worker.off('exit', exitHandler);\n reject(error);\n };\n\n const exitHandler = (code: number) => {\n worker.off('message', messageHandler);\n worker.off('error', errorHandler);\n worker.off('exit', exitHandler);\n // Remove dead worker from cache\n delete this.workers[scriptPath];\n reject(new Error(`Worker stopped with exit code ${code}`));\n };\n \n worker.on('message', messageHandler);\n worker.on('error', errorHandler);\n worker.on('exit', exitHandler);\n\n worker.postMessage({ taskType, data });\n });\n }\n\n async cleanup() {\n const promises = Object.values(this.workers).map(worker => {\n if (worker.threadId !== -1) {\n return worker.terminate();\n }\n return Promise.resolve();\n });\n \n await Promise.allSettled(promises);\n this.workers = {};\n }\n}\n\nexport default WorkerQueue;","import WorkerQueue from './WorkerQueue';\nimport { Lane } from '../types';\nimport path from 'node:path';\n\nconst sizeInMB = (size: number): number => {\n return size / (1024 * 1024);\n}\n\nconst getSize = (data: any): number => {\n return sizeInMB(typeof data === 'string' ? Buffer.byteLength(data, 'utf8') : Buffer.byteLength(JSON.stringify(data), 'utf8'));\n}\n\n/**\n * Lanes are used to determine which worker queue to use based on the size of the data.\n * \n * The first lane is for smaller files (<0.1MB), the second lane is for larger files (>=0.1MB).\n * This helps with parsing performance.\n */\nconst LANES: Lane[] = [{\n maxSize: 0.005\n},{\n maxSize: 0.1\n},{\n maxSize: 1\n},{\n maxSize: 10\n},{\n maxSize: 100\n}];\n\ninterface WorkerQueueWithSize {\n maxSize: number;\n workerQueue: WorkerQueue;\n\n}\n\nclass BruParserWorker {\n private workerQueues: WorkerQueueWithSize[];\n\n constructor() {\n this.workerQueues = LANES?.map(lane => ({\n maxSize: lane?.maxSize,\n workerQueue: new WorkerQueue()\n }));\n }\n\n private getWorkerQueue(size: number): WorkerQueue {\n // Find the first queue that can handle the given size\n // or fallback to the last queue for largest files\n const queueForSize = this.workerQueues.find((queue) => \n queue.maxSize >= size\n );\n\n return queueForSize?.workerQueue ?? this.workerQueues[this.workerQueues.length - 1].workerQueue;\n }\n\n private async enqueueTask({ data, taskType }: { data: any; taskType: 'parse' | 'stringify' }): Promise<any> {\n const size = getSize(data);\n const workerQueue = this.getWorkerQueue(size);\n const workerScriptPath = path.join(__dirname, './workers/worker-script.js');\n \n return workerQueue.enqueue({\n data,\n priority: size,\n scriptPath: workerScriptPath,\n taskType,\n });\n }\n\n async parseRequest(data: any): Promise<any> {\n return this.enqueueTask({ data, taskType: 'parse' });\n }\n\n async stringifyRequest(data: any): Promise<any> {\n return this.enqueueTask({ data, taskType: 'stringify' });\n }\n\n async cleanup(): Promise<void> {\n const cleanupPromises = this.workerQueues.map(({ workerQueue }) => \n workerQueue.cleanup()\n );\n await Promise.allSettled(cleanupPromises);\n }\n}\n\nexport default BruParserWorker; ","import {\n bruRequestToJson,\n jsonRequestToBru,\n bruCollectionToJson,\n jsonCollectionToBru,\n bruEnvironmentToJson,\n jsonEnvironmentToBru\n} from './formats/bru';\nimport { dotenvToJson } from '@usebruno/lang';\nimport BruParserWorker from './workers';\nimport {\n ParseOptions,\n StringifyOptions,\n ParsedRequest,\n ParsedCollection,\n ParsedEnvironment\n} from './types';\n\nexport const parseRequest = (content: string, options: ParseOptions = { format: 'bru' }): any => {\n if (options.format === 'bru') {\n return bruRequestToJson(content);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\nexport const stringifyRequest = (requestObj: ParsedRequest, options: StringifyOptions = { format: 'bru' }): string => {\n if (options.format === 'bru') {\n return jsonRequestToBru(requestObj);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\nlet globalWorkerInstance: BruParserWorker | null = null;\n\nconst getWorkerInstance = (): BruParserWorker => {\n if (!globalWorkerInstance) {\n globalWorkerInstance = new BruParserWorker();\n }\n return globalWorkerInstance;\n};\n\nexport const parseRequestViaWorker = async (content: string): Promise<any> => {\n const fileParserWorker = getWorkerInstance();\n return await fileParserWorker.parseRequest(content);\n};\n\nexport const stringifyRequestViaWorker = async (requestObj: any): Promise<string> => {\n const fileParserWorker = getWorkerInstance();\n return await fileParserWorker.stringifyRequest(requestObj);\n};\n\nexport const parseCollection = (content: string, options: ParseOptions = { format: 'bru' }): any => {\n if (options.format === 'bru') {\n return bruCollectionToJson(content);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\nexport const stringifyCollection = (collectionObj: ParsedCollection, options: StringifyOptions = { format: 'bru' }): string => {\n if (options.format === 'bru') {\n return jsonCollectionToBru(collectionObj, false);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\nexport const parseFolder = (content: string, options: ParseOptions = { format: 'bru' }): any => {\n if (options.format === 'bru') {\n return bruCollectionToJson(content);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\nexport const stringifyFolder = (folderObj: any, options: StringifyOptions = { format: 'bru' }): string => {\n if (options.format === 'bru') {\n return jsonCollectionToBru(folderObj, true);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\nexport const parseEnvironment = (content: string, options: ParseOptions = { format: 'bru' }): any => {\n if (options.format === 'bru') {\n return bruEnvironmentToJson(content);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\nexport const stringifyEnvironment = (envObj: ParsedEnvironment, options: StringifyOptions = { format: 'bru' }): string => {\n if (options.format === 'bru') {\n return jsonEnvironmentToBru(envObj);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\n\nexport const parseDotEnv = (content: string): Record<string, string> => {\n return dotenvToJson(content);\n};\n\nexport { BruParserWorker };\nexport * from './types';"],"names":["bruCollectionToJson","data","parsed","json","_collectionBruToJson","collectionBruToJson","transformedJson","request","headers","_","get","auth","script","vars","tests","settings","docs","meta","name","undefined","seq","sequence","isNaN","Number","error","Promise","reject","jsonCollectionToBru","isFolder","collectionBruJson","req","res","_jsonToCollectionBru","WorkerQueue","constructor","this","queue","isProcessing","workers","getWorkerForScriptPath","scriptPath","worker","threadId","Worker","enqueue","task","priority","taskType","resolve","push","sort","taskX","taskY","processQueue","length","shift","result","runWorker","async","messageHandler","off","errorHandler","exitHandler","Error","code","on","postMessage","cleanup","promises","Object","values","map","terminate","allSettled","LANES","maxSize","BruParserWorker","workerQueues","lane","workerQueue","getWorkerQueue","size","queueForSize","find","enqueueTask","Buffer","byteLength","JSON","stringify","getSize","workerScriptPath","path","join","__dirname","parseRequest","stringifyRequest","cleanupPromises","globalWorkerInstance","getWorkerInstance","content","options","format","dotenvToJson","bru","bruToEnvJsonV2","variables","each","v","type","bruEnvironmentToJson","bruToJsonV2","requestType","tags","method","upperCase","url","params","body","assertions","mode","e","bruRequestToJson","fileParserWorker","collectionObj","envObj","envJsonToBruV2","jsonEnvironmentToBru","folderObj","requ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"index.js","sources":["../../src/formats/bru/utils/oauth2-additional-params.ts","../../src/formats/bru/index.ts","../../src/workers/WorkerQueue/index.ts","../../src/workers/index.ts","../../src/index.ts","../../src/formats/bru/utils/request-parse-and-redact-body-data.ts"],"sourcesContent":["type T_Oauth2ParameterType = 'authorization' | 'token' | 'refresh';\ntype T_Oauth2ParameterSendInType = 'headers' | 'queryparams' | 'body';\n\nexport interface T_OAuth2AdditionalParam {\n name: string;\n value: string;\n enabled: boolean;\n sendIn: T_Oauth2ParameterSendInType\n}\n\nexport interface T_OAuth2AdditionalParameters {\n authorization?: T_OAuth2AdditionalParam[];\n token?: T_OAuth2AdditionalParam[];\n refresh?: T_OAuth2AdditionalParam[];\n}\n\nexport interface T_Oauth2Auth {\n grantType: string;\n additionalParameters?: T_OAuth2AdditionalParameters;\n}\n\nexport interface T_BruJson {\n auth: {\n oauth2: T_Oauth2Auth;\n };\n oauth2_additional_parameters_auth_req_headers?: any[];\n oauth2_additional_parameters_auth_req_queryparams?: any[];\n oauth2_additional_parameters_access_token_req_headers?: any[];\n oauth2_additional_parameters_access_token_req_queryparams?: any[];\n oauth2_additional_parameters_access_token_req_bodyvalues?: any[];\n oauth2_additional_parameters_refresh_token_req_headers?: any[];\n oauth2_additional_parameters_refresh_token_req_queryparams?: any[];\n oauth2_additional_parameters_refresh_token_req_bodyvalues?: any[];\n}\n\ninterface T_Oauth2ParameterMapping {\n type: T_Oauth2ParameterType;\n sendIn: T_Oauth2ParameterSendInType;\n source: keyof T_BruJson;\n}\n\nconst PARAMETER_MAPPINGS: T_Oauth2ParameterMapping[] = [\n // Authorization parameters (only for authorization_code grant type)\n { type: 'authorization', sendIn: 'headers', source: 'oauth2_additional_parameters_auth_req_headers' },\n { type: 'authorization', sendIn: 'queryparams', source: 'oauth2_additional_parameters_auth_req_queryparams' },\n \n // Token parameters (for all grant types)\n { type: 'token', sendIn: 'headers', source: 'oauth2_additional_parameters_access_token_req_headers' },\n { type: 'token', sendIn: 'queryparams', source: 'oauth2_additional_parameters_access_token_req_queryparams' },\n { type: 'token', sendIn: 'body', source: 'oauth2_additional_parameters_access_token_req_bodyvalues' },\n \n // Refresh parameters (for grant types that support refresh)\n { type: 'refresh', sendIn: 'headers', source: 'oauth2_additional_parameters_refresh_token_req_headers' },\n { type: 'refresh', sendIn: 'queryparams', source: 'oauth2_additional_parameters_refresh_token_req_queryparams' },\n { type: 'refresh', sendIn: 'body', source: 'oauth2_additional_parameters_refresh_token_req_bodyvalues' },\n];\n\n/**\n * Maps source parameters to T_OAuth2AdditionalParam format\n */\nconst mapParametersFromSource = (sourceParams: any[], sendIn: T_Oauth2ParameterSendInType): T_OAuth2AdditionalParam[] => {\n if (!sourceParams?.length) {\n return [];\n }\n \n return sourceParams.map(param => ({\n ...param,\n sendIn\n }));\n};\n\n/**\n * Checks if a parameter type should be included based on grant type\n */\nconst shouldIncludeParameterType = (type: T_Oauth2ParameterType, grantType: string): boolean => {\n // Authorization parameters are only valid for authorization_code grant type\n if (type === 'authorization') {\n return grantType === 'authorization_code' || grantType === 'implicit';\n }\n\n if (type === 'token' || type === 'refresh') {\n return grantType !== 'implicit';\n }\n \n // Token and refresh parameters are valid for all grant types\n return true;\n};\n\n/**\n * Collects all parameters for a specific type (authorization, token, or refresh)\n */\nconst collectParametersForType = (\n json: T_BruJson, \n type: T_Oauth2ParameterType, \n grantType: string\n): T_OAuth2AdditionalParam[] => {\n if (!shouldIncludeParameterType(type, grantType)) {\n return [];\n }\n\n const relevantMappings = PARAMETER_MAPPINGS.filter(mapping => mapping.type === type);\n const allParams: T_OAuth2AdditionalParam[] = [];\n\n for (const mapping of relevantMappings) {\n const sourceParams = json[mapping.source] as any[];\n const mappedParams = mapParametersFromSource(sourceParams, mapping.sendIn);\n allParams.push(...mappedParams);\n }\n\n return allParams;\n};\n\n/**\n * This function extracts OAuth2 additional parameters from various sources in the bru json data and organizes\n * them into a structured format based on their usage context (authorization, token, refresh).\n * \n * @param json - json object containing OAuth2 configuration and additional parameters\n * @returns OAuth2 additional parameters\n */\nexport const getOauth2AdditionalParameters = (json: T_BruJson): T_OAuth2AdditionalParameters => {\n const grantType = json.auth.oauth2.grantType;\n const additionalParameters: T_OAuth2AdditionalParameters = {};\n\n try {\n // Collect parameters for each type\n const parameterTypes: T_Oauth2ParameterType[] = ['authorization', 'token', 'refresh'];\n \n for (const type of parameterTypes) {\n const params = collectParametersForType(json, type, grantType);\n if (params.length > 0) {\n additionalParameters[type] = params;\n }\n }\n }\n catch(error) {\n console.error(error);\n console.error(\"Error while getting the oauth2 additional parameters!\");\n }\n \n return additionalParameters;\n};","import * as _ from 'lodash';\nimport {\n bruToJsonV2,\n jsonToBruV2,\n bruToEnvJsonV2,\n envJsonToBruV2,\n collectionBruToJson as _collectionBruToJson,\n jsonToCollectionBru as _jsonToCollectionBru\n} from '@usebruno/lang';\nimport { getOauth2AdditionalParameters } from './utils/oauth2-additional-params';\n\nexport const bruRequestToJson = (data: string | any, parsed: boolean = false): any => {\n try {\n const json = parsed ? data : bruToJsonV2(data);\n\n let requestType = _.get(json, 'meta.type');\n switch (requestType) {\n case 'http':\n requestType = 'http-request';\n break;\n case 'graphql':\n requestType = 'graphql-request';\n break;\n case 'grpc':\n requestType = 'grpc-request';\n break;\n default:\n requestType = 'http-request';\n }\n\n const sequence = _.get(json, 'meta.seq');\n const transformedJson = {\n type: requestType,\n name: _.get(json, 'meta.name'),\n seq: !_.isNaN(sequence) ? Number(sequence) : 1,\n settings: _.get(json, 'settings', {}),\n tags: _.get(json, 'meta.tags', []),\n request: {\n method:\n requestType === 'grpc-request' ? _.get(json, 'grpc.method', '') : _.upperCase(_.get(json, 'http.method')),\n url: _.get(json, requestType === 'grpc-request' ? 'grpc.url' : 'http.url'),\n headers: requestType === 'grpc-request' ? _.get(json, 'metadata', []) : _.get(json, 'headers', []),\n auth: _.get(json, 'auth', {}),\n body: _.get(json, 'body', {}),\n script: _.get(json, 'script', {}),\n vars: _.get(json, 'vars', {}),\n assertions: _.get(json, 'assertions', []),\n tests: _.get(json, 'tests', ''),\n docs: _.get(json, 'docs', '')\n }\n };\n\n // Add request type specific fields\n if (requestType === 'grpc-request') {\n const selectedMethodType = _.get(json, 'grpc.methodType');\n selectedMethodType && ((transformedJson.request as any).methodType = selectedMethodType);\n const protoPath = _.get(json, 'grpc.protoPath');\n protoPath && ((transformedJson.request as any).protoPath = protoPath);\n transformedJson.request.auth.mode = _.get(json, 'grpc.auth', 'none');\n transformedJson.request.body = _.get(json, 'body', {\n mode: 'grpc',\n grpc: _.get(json, 'body.grpc', [\n {\n name: 'message 1',\n content: '{}'\n }\n ])\n });\n } else {\n // For HTTP and GraphQL\n (transformedJson.request as any).params = _.get(json, 'params', []);\n transformedJson.request.auth.mode = _.get(json, 'http.auth', 'none');\n transformedJson.request.body.mode = _.get(json, 'http.body', 'none');\n }\n\n // add oauth2 additional parameters if they exist\n const hasOauth2GrantType = json?.auth?.oauth2?.grantType;\n if (hasOauth2GrantType) {\n const additionalParameters = getOauth2AdditionalParameters(json);\n const hasAdditionalParameters = Object.keys(additionalParameters || {}).length > 0;\n if (hasAdditionalParameters) {\n transformedJson.request.auth.oauth2.additionalParameters = additionalParameters;\n }\n }\n\n return transformedJson;\n } catch (error) {\n throw error;\n }\n};\n\nexport const jsonRequestToBru = (json: any): string => {\n try {\n let type = _.get(json, 'type');\n switch (type) {\n case 'http-request':\n type = 'http';\n break;\n case 'graphql-request':\n type = 'graphql';\n break;\n case 'grpc-request':\n type = 'grpc';\n break;\n default:\n type = 'http';\n }\n\n const sequence = _.get(json, 'seq');\n\n // Start with the common meta section\n const bruJson = {\n meta: {\n name: _.get(json, 'name'),\n type: type,\n seq: !_.isNaN(sequence) ? Number(sequence) : 1,\n tags: _.get(json, 'tags', [])\n }\n } as any;\n\n // For HTTP and GraphQL requests, maintain the current structure\n if (type === 'http' || type === 'graphql') {\n bruJson.http = {\n method: _.lowerCase(_.get(json, 'request.method')),\n url: _.get(json, 'request.url'),\n auth: _.get(json, 'request.auth.mode', 'none'),\n body: _.get(json, 'request.body.mode', 'none')\n };\n bruJson.params = _.get(json, 'request.params', []);\n bruJson.body = _.get(json, 'request.body', {\n mode: 'json',\n json: '{}'\n });\n } // For gRPC, add gRPC-specific structure but maintain field names\n else if (type === 'grpc') {\n bruJson.grpc = {\n url: _.get(json, 'request.url'),\n auth: _.get(json, 'request.auth.mode', 'none'),\n body: _.get(json, 'request.body.mode', 'grpc')\n };\n // Only add method if it exists\n const method = _.get(json, 'request.method');\n const methodType = _.get(json, 'request.methodType');\n const protoPath = _.get(json, 'request.protoPath');\n if (method) bruJson.grpc.method = method;\n if (methodType) bruJson.grpc.methodType = methodType;\n if (protoPath) bruJson.grpc.protoPath = protoPath;\n bruJson.body = _.get(json, 'request.body', {\n mode: 'grpc',\n grpc: _.get(json, 'request.body.grpc', [\n {\n name: 'message 1',\n content: '{}'\n }\n ])\n });\n }\n\n // Common fields for all request types\n if (type === 'grpc') {\n bruJson.metadata = _.get(json, 'request.headers', []); // Use metadata for gRPC\n } else {\n bruJson.headers = _.get(json, 'request.headers', []); // Use headers for HTTP/GraphQL\n }\n bruJson.auth = _.get(json, 'request.auth', {});\n bruJson.script = _.get(json, 'request.script', {});\n bruJson.vars = {\n req: _.get(json, 'request.vars.req', []),\n res: _.get(json, 'request.vars.res', [])\n };\n // should we add assertions and tests for grpc requests?\n bruJson.assertions = _.get(json, 'request.assertions', []);\n bruJson.tests = _.get(json, 'request.tests', '');\n bruJson.settings = _.get(json, 'settings', {});\n bruJson.docs = _.get(json, 'request.docs', '');\n\n const bru = jsonToBruV2(bruJson);\n return bru;\n } catch (error) {\n throw error;\n }\n};\n\nexport const bruCollectionToJson = (data: string | any, parsed: boolean = false): any => {\n try {\n const json = parsed ? data : _collectionBruToJson(data);\n\n const transformedJson: any = {\n request: {\n headers: _.get(json, 'headers', []),\n auth: _.get(json, 'auth', {}),\n script: _.get(json, 'script', {}),\n vars: _.get(json, 'vars', {}),\n tests: _.get(json, 'tests', '')\n },\n settings: _.get(json, 'settings', {}),\n docs: _.get(json, 'docs', '')\n };\n\n // add meta if it exists\n // this is only for folder bru file\n if (json.meta) {\n transformedJson.meta = {\n name: json.meta.name\n };\n\n // Include seq if it exists\n if (json.meta.seq !== undefined) {\n const sequence = json.meta.seq;\n transformedJson.meta.seq = !isNaN(sequence) ? Number(sequence) : 1;\n }\n }\n\n // add oauth2 additional parameters if they exist\n const hasOauth2GrantType = json?.auth?.oauth2?.grantType;\n if (hasOauth2GrantType) {\n const additionalParameters = getOauth2AdditionalParameters(json);\n const hasAdditionalParameters = Object.keys(additionalParameters).length > 0;\n if (hasAdditionalParameters) {\n transformedJson.request.auth.oauth2.additionalParameters = additionalParameters;\n }\n }\n\n return transformedJson;\n } catch (error) {\n return Promise.reject(error);\n }\n};\n\nexport const jsonCollectionToBru = (json: any, isFolder?: boolean): string => {\n try {\n const collectionBruJson: any = {\n headers: _.get(json, 'request.headers', []),\n script: {\n req: _.get(json, 'request.script.req', ''),\n res: _.get(json, 'request.script.res', '')\n },\n vars: {\n req: _.get(json, 'request.vars.req', []),\n res: _.get(json, 'request.vars.res', [])\n },\n tests: _.get(json, 'request.tests', ''),\n auth: _.get(json, 'request.auth', {}),\n docs: _.get(json, 'docs', '')\n };\n\n // add meta if it exists\n // this is only for folder bru file\n if (json?.meta) {\n collectionBruJson.meta = {\n name: json.meta.name\n };\n\n // Include seq if it exists\n if (json.meta.seq !== undefined) {\n const sequence = json.meta.seq;\n collectionBruJson.meta.seq = !isNaN(sequence) ? Number(sequence) : 1;\n }\n }\n\n if (!isFolder) {\n collectionBruJson.auth = _.get(json, 'request.auth', {});\n }\n\n return _jsonToCollectionBru(collectionBruJson);\n } catch (error) {\n throw error;\n }\n};\n\nexport const bruEnvironmentToJson = (bru: string): any => {\n try {\n const json = bruToEnvJsonV2(bru);\n\n // the app env format requires each variable to have a type\n // this need to be evaluated and safely removed\n // i don't see it being used in schema validation\n if (json && json.variables && json.variables.length) {\n _.each(json.variables, (v: any) => (v.type = 'text'));\n }\n\n return json;\n } catch (error) {\n return Promise.reject(error);\n }\n};\n\nexport const jsonEnvironmentToBru = (json: any): string => {\n try {\n const bru = envJsonToBruV2(json);\n return bru;\n } catch (error) {\n throw error;\n }\n};\n","import { Worker } from 'node:worker_threads';\n\ninterface QueuedTask {\n priority: number;\n scriptPath: string;\n data: any;\n taskType: 'parse' | 'stringify';\n resolve?: (value: any) => void;\n reject?: (reason?: any) => void;\n}\n\nclass WorkerQueue {\n private queue: QueuedTask[];\n private isProcessing: boolean;\n private workers: Record<string, Worker>;\n\n constructor() {\n this.queue = [];\n this.isProcessing = false;\n this.workers = {};\n }\n\n async getWorkerForScriptPath(scriptPath: string) {\n if (!this.workers) this.workers = {}; \n let worker = this.workers[scriptPath];\n if (!worker || worker.threadId === -1) {\n this.workers[scriptPath] = worker = new Worker(scriptPath);\n }\n return worker;\n }\n \n async enqueue(task: QueuedTask) {\n const { priority, scriptPath, data, taskType } = task;\n\n return new Promise((resolve, reject) => {\n this.queue.push({ priority, scriptPath, data, taskType, resolve, reject });\n this.queue?.sort((taskX, taskY) => taskX?.priority - taskY?.priority);\n this.processQueue();\n });\n }\n\n async processQueue() {\n if (this.isProcessing || this.queue.length === 0){\n return;\n } \n\n this.isProcessing = true;\n const { scriptPath, data, taskType, resolve, reject } = this.queue.shift() as QueuedTask;\n\n try {\n const result = await this.runWorker({ scriptPath, data, taskType });\n resolve?.(result);\n } catch (error) {\n reject?.(error);\n } finally {\n this.isProcessing = false;\n this.processQueue();\n }\n }\n\n async runWorker({ scriptPath, data, taskType }: { scriptPath: string; data: any; taskType: 'parse' | 'stringify' }) {\n return new Promise(async (resolve, reject) => {\n let worker = await this.getWorkerForScriptPath(scriptPath);\n \n const messageHandler = (data: any) => {\n worker.off('message', messageHandler);\n worker.off('error', errorHandler);\n worker.off('exit', exitHandler);\n \n if (data?.error) {\n reject(new Error(data?.error));\n } else {\n resolve(data);\n }\n };\n\n const errorHandler = (error: Error) => {\n worker.off('message', messageHandler);\n worker.off('error', errorHandler);\n worker.off('exit', exitHandler);\n reject(error);\n };\n\n const exitHandler = (code: number) => {\n worker.off('message', messageHandler);\n worker.off('error', errorHandler);\n worker.off('exit', exitHandler);\n // Remove dead worker from cache\n delete this.workers[scriptPath];\n reject(new Error(`Worker stopped with exit code ${code}`));\n };\n \n worker.on('message', messageHandler);\n worker.on('error', errorHandler);\n worker.on('exit', exitHandler);\n\n worker.postMessage({ taskType, data });\n });\n }\n\n async cleanup() {\n const promises = Object.values(this.workers).map(worker => {\n if (worker.threadId !== -1) {\n return worker.terminate();\n }\n return Promise.resolve();\n });\n \n await Promise.allSettled(promises);\n this.workers = {};\n }\n}\n\nexport default WorkerQueue;","import WorkerQueue from './WorkerQueue';\nimport { Lane } from '../types';\nimport path from 'node:path';\n\nconst sizeInMB = (size: number): number => {\n return size / (1024 * 1024);\n}\n\nconst getSize = (data: any): number => {\n return sizeInMB(typeof data === 'string' ? Buffer.byteLength(data, 'utf8') : Buffer.byteLength(JSON.stringify(data), 'utf8'));\n}\n\n/**\n * Lanes are used to determine which worker queue to use based on the size of the data.\n * \n * The first lane is for smaller files (<0.1MB), the second lane is for larger files (>=0.1MB).\n * This helps with parsing performance.\n */\nconst LANES: Lane[] = [{\n maxSize: 0.005\n},{\n maxSize: 0.1\n},{\n maxSize: 1\n},{\n maxSize: 10\n},{\n maxSize: 100\n}];\n\ninterface WorkerQueueWithSize {\n maxSize: number;\n workerQueue: WorkerQueue;\n\n}\n\nclass BruParserWorker {\n private workerQueues: WorkerQueueWithSize[];\n\n constructor() {\n this.workerQueues = LANES?.map(lane => ({\n maxSize: lane?.maxSize,\n workerQueue: new WorkerQueue()\n }));\n }\n\n private getWorkerQueue(size: number): WorkerQueue {\n // Find the first queue that can handle the given size\n // or fallback to the last queue for largest files\n const queueForSize = this.workerQueues.find((queue) => \n queue.maxSize >= size\n );\n\n return queueForSize?.workerQueue ?? this.workerQueues[this.workerQueues.length - 1].workerQueue;\n }\n\n private async enqueueTask({ data, taskType }: { data: any; taskType: 'parse' | 'stringify' }): Promise<any> {\n const size = getSize(data);\n const workerQueue = this.getWorkerQueue(size);\n const workerScriptPath = path.join(__dirname, './workers/worker-script.js');\n \n return workerQueue.enqueue({\n data,\n priority: size,\n scriptPath: workerScriptPath,\n taskType,\n });\n }\n\n async parseRequest(data: any): Promise<any> {\n return this.enqueueTask({ data, taskType: 'parse' });\n }\n\n async stringifyRequest(data: any): Promise<any> {\n return this.enqueueTask({ data, taskType: 'stringify' });\n }\n\n async cleanup(): Promise<void> {\n const cleanupPromises = this.workerQueues.map(({ workerQueue }) => \n workerQueue.cleanup()\n );\n await Promise.allSettled(cleanupPromises);\n }\n}\n\nexport default BruParserWorker; ","import {\n bruRequestToJson,\n jsonRequestToBru,\n bruCollectionToJson,\n jsonCollectionToBru,\n bruEnvironmentToJson,\n jsonEnvironmentToBru\n} from './formats/bru';\nimport { dotenvToJson } from '@usebruno/lang';\nimport BruParserWorker from './workers';\nimport {\n ParseOptions,\n StringifyOptions,\n ParsedRequest,\n ParsedCollection,\n ParsedEnvironment\n} from './types';\nimport { bruRequestParseAndRedactBodyData } from './formats/bru/utils/request-parse-and-redact-body-data';\n\nexport const parseRequest = (content: string, options: ParseOptions = { format: 'bru' }): any => {\n if (options.format === 'bru') {\n return bruRequestToJson(content);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\nexport const parseRequestAndRedactBody = (content: string, options: ParseOptions = { format: 'bru' }): any => {\n if (options.format === 'bru') {\n return bruRequestParseAndRedactBodyData(content);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\nexport const stringifyRequest = (requestObj: ParsedRequest, options: StringifyOptions = { format: 'bru' }): string => {\n if (options.format === 'bru') {\n return jsonRequestToBru(requestObj);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\nlet globalWorkerInstance: BruParserWorker | null = null;\n\nconst getWorkerInstance = (): BruParserWorker => {\n if (!globalWorkerInstance) {\n globalWorkerInstance = new BruParserWorker();\n }\n return globalWorkerInstance;\n};\n\nexport const parseRequestViaWorker = async (content: string): Promise<any> => {\n const fileParserWorker = getWorkerInstance();\n return await fileParserWorker.parseRequest(content);\n};\n\nexport const stringifyRequestViaWorker = async (requestObj: any): Promise<string> => {\n const fileParserWorker = getWorkerInstance();\n return await fileParserWorker.stringifyRequest(requestObj);\n};\n\nexport const parseCollection = (content: string, options: ParseOptions = { format: 'bru' }): any => {\n if (options.format === 'bru') {\n return bruCollectionToJson(content);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\nexport const stringifyCollection = (collectionObj: ParsedCollection, options: StringifyOptions = { format: 'bru' }): string => {\n if (options.format === 'bru') {\n return jsonCollectionToBru(collectionObj, false);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\nexport const parseFolder = (content: string, options: ParseOptions = { format: 'bru' }): any => {\n if (options.format === 'bru') {\n return bruCollectionToJson(content);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\nexport const stringifyFolder = (folderObj: any, options: StringifyOptions = { format: 'bru' }): string => {\n if (options.format === 'bru') {\n return jsonCollectionToBru(folderObj, true);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\nexport const parseEnvironment = (content: string, options: ParseOptions = { format: 'bru' }): any => {\n if (options.format === 'bru') {\n return bruEnvironmentToJson(content);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\nexport const stringifyEnvironment = (envObj: ParsedEnvironment, options: StringifyOptions = { format: 'bru' }): string => {\n if (options.format === 'bru') {\n return jsonEnvironmentToBru(envObj);\n }\n throw new Error(`Unsupported format: ${options.format}`);\n};\n\n\nexport const parseDotEnv = (content: string): Record<string, string> => {\n return dotenvToJson(content);\n};\n\nexport { BruParserWorker };\nexport * from './types';","/**\n * Parses a .bru file and extracts body content while redacting it from the main content\n * @param {string} bruFileContent - The raw content of the .bru file\n * @returns {Object} Object containing redacted file content and extracted body data\n */\nexport const bruRequestParseAndRedactBodyData = (bruFileContent: string) => {\n try {\n // Define the patterns that indicate the start of different body types\n const bodyTypePatterns = [\n \"body:json {\",\n \"body:text {\",\n \"body:xml {\",\n \"body:sparql {\",\n \"body:graphql {\"\n ];\n\n // Normalize line endings to LF\n bruFileContent = (bruFileContent || '').replace(/\\r\\n/g, '\\n');\n\n const EOL = `\\n`;\n\n /**\n * Removes the leading 2-space indentation from each line of a string\n * @param {string} indentedString - The string with leading spaces to remove\n * @returns {string} The string with indentation removed\n */\n const removeLeadingIndentation = (indentedString: string) => {\n if (!indentedString || !indentedString.length) {\n return indentedString || '';\n }\n\n return indentedString\n .split(EOL)\n .map((line) => line.replace(/^ /, ''))\n .join(EOL);\n };\n\n // Split the file content into blocks\n let fileContentBlocks = bruFileContent.split(`${EOL}}${EOL}`);\n fileContentBlocks = fileContentBlocks.filter(Boolean).map(_ => _.trim());\n\n // Extract body blocks and their content\n const extractedBodyBlocks = fileContentBlocks\n .filter(block => bodyTypePatterns.some(pattern => block.startsWith(pattern)))\n .reduce((bodyContentMap: Record<string, string>, bodyBlock) => {\n // Extract the body type (json, text, xml, etc.) from the first line\n const firstLine = bodyBlock.split(EOL)[0];\n const bodyType = firstLine.split(`body:`)[1].split(/\\s/)[0];\n \n // Extract the body content (everything between the opening and closing braces)\n const bodyContentLines = bodyBlock.split(EOL).slice(1);\n const rawBodyContent = bodyContentLines.join(EOL);\n \n // Remove indentation from the body content\n const cleanBodyContent = removeLeadingIndentation(rawBodyContent);\n \n bodyContentMap[bodyType] = cleanBodyContent;\n return bodyContentMap;\n }, {});\n\n // Filter out body blocks to get the remaining file content\n const fileContentWithoutBodyBlocks = fileContentBlocks.filter(block => \n !bodyTypePatterns.some(pattern => block.startsWith(pattern))\n );\n\n return {\n bruFileStringWithRedactedBody: fileContentWithoutBodyBlocks.join(`${EOL}}${EOL}${EOL}`).concat(`${EOL}}${EOL}`),\n extractedBodyContent: extractedBodyBlocks\n };\n } catch (error) {\n console.error('Error parsing and redacting body data:', error);\n return {\n bruFileStringWithRedactedBody: bruFileContent,\n extractedBodyContent: {}\n };\n }\n};"],"names":["PARAMETER_MAPPINGS","type","sendIn","source","mapParametersFromSource","sourceParams","length","map","param","collectParametersForType","json","grantType","shouldIncludeParameterType","relevantMappings","filter","mapping","allParams","mappedParams","push","getOauth2AdditionalParameters","auth","oauth2","additionalParameters","parameterTypes","params","error","console","bruCollectionToJson","data","parsed","_collectionBruToJson","collectionBruToJson","transformedJson","request","headers","_","get","script","vars","tests","settings","docs","meta","name","undefined","seq","sequence","isNaN","Number","hasOauth2GrantType","Object","keys","Promise","reject","jsonCollectionToBru","isFolder","collectionBruJson","req","res","_jsonToCollectionBru","WorkerQueue","constructor","this","queue","isProcessing","workers","getWorkerForScriptPath","scriptPath","worker","threadId","Worker","enqueue","task","priority","taskType","resolve","sort","taskX","taskY","processQueue","shift","result","runWorker","async","messageHandler","off","errorHandler","exitHandler","Error","code","on","postMessage","cleanup","promises","values","terminate","allSettled","LANES","maxSize","BruParserWorker","workerQueues","lane","workerQueue","getWorkerQueue","size","queueForSize","find","enqueueTask","Buffer","byteLength","JSON","stringify","getSize","workerScriptPath","path","join","__dirname","parseRequest","stringifyRequest","cleanupPromises","globalWorkerInstance","getWorkerInstance","content","options","format","dotenvToJson","bru","bruToEnvJsonV2","variables","each","v","bruEnvironmentToJson","bruToJsonV2","requestType","tags","method","upperCase","url","body","assertions","selectedMethodType","methodType","protoPath","mode","grpc","bruRequestToJson","bruFileContent","bodyTypePatterns","replace","EOL","removeLeadingIndentation","indentedString","split","line","fileContentBlocks","Boolean","trim","extractedBodyBlocks","block","some","pattern","startsWith","reduce","bodyContentMap","bodyBlock","bodyType","rawBodyContent","slice","cleanBodyContent","bruFileStringWithRedactedBody","concat","extractedBodyContent","bruRequestParseAndRedactBodyData","fileParserWorker","collectionObj","envObj","envJsonToBruV2","jsonEnvironmentToBru","folderObj","requestObj","bruJson","http","lowerCase","metadata","jsonToBruV2","jsonRequestToBru"],"mappings":"uYAyCA,MAAMA,EAAiD,CAErD,CAAEC,KAAM,gBAAiBC,OAAQ,UAAWC,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,GAC/C0K,EAAQ9I,KAAO,CACbmB,IAAKtB,EAAEC,IAAI1B,EAAM,mBAAoB,IACrCgD,IAAKvB,EAAEC,IAAI1B,EAAM,mBAAoB,KAGvC0K,EAAQzC,WAAaxG,EAAEC,IAAI1B,EAAM,qBAAsB,IACvD0K,EAAQ7I,MAAQJ,EAAEC,IAAI1B,EAAM,gBAAiB,IAC7C0K,EAAQ5I,SAAWL,EAAEC,IAAI1B,EAAM,WAAY,CAAA,GAC3C0K,EAAQ3I,KAAON,EAAEC,IAAI1B,EAAM,eAAgB,IAE/B8K,cAAYJ,EAEzB,CAAC,MAAO3J,GACP,MAAMA,CACP,GGjJQgK,CAAiBN,GAE1B,MAAM,IAAI3F,MAAM,uBAAuBmC,EAAQC,SAAS,oCAiBjBzC,MAAOgG,IAC9C,MAAMN,EAAmBpD,IACzB,aAAaoD,EAAiBvD,iBAAiB6D,EAAW"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
type T_Oauth2ParameterSendInType = 'headers' | 'queryparams' | 'body';
|
|
2
|
+
export interface T_OAuth2AdditionalParam {
|
|
3
|
+
name: string;
|
|
4
|
+
value: string;
|
|
5
|
+
enabled: boolean;
|
|
6
|
+
sendIn: T_Oauth2ParameterSendInType;
|
|
7
|
+
}
|
|
8
|
+
export interface T_OAuth2AdditionalParameters {
|
|
9
|
+
authorization?: T_OAuth2AdditionalParam[];
|
|
10
|
+
token?: T_OAuth2AdditionalParam[];
|
|
11
|
+
refresh?: T_OAuth2AdditionalParam[];
|
|
12
|
+
}
|
|
13
|
+
export interface T_Oauth2Auth {
|
|
14
|
+
grantType: string;
|
|
15
|
+
additionalParameters?: T_OAuth2AdditionalParameters;
|
|
16
|
+
}
|
|
17
|
+
export interface T_BruJson {
|
|
18
|
+
auth: {
|
|
19
|
+
oauth2: T_Oauth2Auth;
|
|
20
|
+
};
|
|
21
|
+
oauth2_additional_parameters_auth_req_headers?: any[];
|
|
22
|
+
oauth2_additional_parameters_auth_req_queryparams?: any[];
|
|
23
|
+
oauth2_additional_parameters_access_token_req_headers?: any[];
|
|
24
|
+
oauth2_additional_parameters_access_token_req_queryparams?: any[];
|
|
25
|
+
oauth2_additional_parameters_access_token_req_bodyvalues?: any[];
|
|
26
|
+
oauth2_additional_parameters_refresh_token_req_headers?: any[];
|
|
27
|
+
oauth2_additional_parameters_refresh_token_req_queryparams?: any[];
|
|
28
|
+
oauth2_additional_parameters_refresh_token_req_bodyvalues?: any[];
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* This function extracts OAuth2 additional parameters from various sources in the bru json data and organizes
|
|
32
|
+
* them into a structured format based on their usage context (authorization, token, refresh).
|
|
33
|
+
*
|
|
34
|
+
* @param json - json object containing OAuth2 configuration and additional parameters
|
|
35
|
+
* @returns OAuth2 additional parameters
|
|
36
|
+
*/
|
|
37
|
+
export declare const getOauth2AdditionalParameters: (json: T_BruJson) => T_OAuth2AdditionalParameters;
|
|
38
|
+
export {};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parses a .bru file and extracts body content while redacting it from the main content
|
|
3
|
+
* @param {string} bruFileContent - The raw content of the .bru file
|
|
4
|
+
* @returns {Object} Object containing redacted file content and extracted body data
|
|
5
|
+
*/
|
|
6
|
+
export declare const bruRequestParseAndRedactBodyData: (bruFileContent: string) => {
|
|
7
|
+
bruFileStringWithRedactedBody: string;
|
|
8
|
+
extractedBodyContent: Record<string, string>;
|
|
9
|
+
};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import BruParserWorker from './workers';
|
|
2
2
|
import { ParseOptions, StringifyOptions, ParsedRequest, ParsedCollection, ParsedEnvironment } from './types';
|
|
3
3
|
export declare const parseRequest: (content: string, options?: ParseOptions) => any;
|
|
4
|
+
export declare const parseRequestAndRedactBody: (content: string, options?: ParseOptions) => any;
|
|
4
5
|
export declare const stringifyRequest: (requestObj: ParsedRequest, options?: StringifyOptions) => string;
|
|
5
6
|
export declare const parseRequestViaWorker: (content: string) => Promise<any>;
|
|
6
7
|
export declare const stringifyRequestViaWorker: (requestObj: any) => Promise<string>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("node:worker_threads"),t=require("lodash"),r=require("@usebruno/lang");function s(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var a=s(t);
|
|
1
|
+
"use strict";var e=require("node:worker_threads"),t=require("lodash"),r=require("@usebruno/lang");function s(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var a=s(t);const o=[{type:"authorization",sendIn:"headers",source:"oauth2_additional_parameters_auth_req_headers"},{type:"authorization",sendIn:"queryparams",source:"oauth2_additional_parameters_auth_req_queryparams"},{type:"token",sendIn:"headers",source:"oauth2_additional_parameters_access_token_req_headers"},{type:"token",sendIn:"queryparams",source:"oauth2_additional_parameters_access_token_req_queryparams"},{type:"token",sendIn:"body",source:"oauth2_additional_parameters_access_token_req_bodyvalues"},{type:"refresh",sendIn:"headers",source:"oauth2_additional_parameters_refresh_token_req_headers"},{type:"refresh",sendIn:"queryparams",source:"oauth2_additional_parameters_refresh_token_req_queryparams"},{type:"refresh",sendIn:"body",source:"oauth2_additional_parameters_refresh_token_req_bodyvalues"}],n=(e,t)=>e?.length?e.map((e=>({...e,sendIn:t}))):[],u=(e,t,r)=>{if(!((e,t)=>"authorization"===e?"authorization_code"===t||"implicit"===t:"token"!==e&&"refresh"!==e||"implicit"!==t)(t,r))return[];const s=o.filter((e=>e.type===t)),a=[];for(const t of s){const r=e[t.source],s=n(r,t.sendIn);a.push(...s)}return a},g=(e,t=!1)=>{try{const s=t?e:r.bruToJsonV2(e);let o=a.get(s,"meta.type");switch(o){case"http":default:o="http-request";break;case"graphql":o="graphql-request";break;case"grpc":o="grpc-request"}const n=a.get(s,"meta.seq"),g={type:o,name:a.get(s,"meta.name"),seq:a.isNaN(n)?1:Number(n),settings:a.get(s,"settings",{}),tags:a.get(s,"meta.tags",[]),request:{method:"grpc-request"===o?a.get(s,"grpc.method",""):a.upperCase(a.get(s,"http.method")),url:a.get(s,"grpc-request"===o?"grpc.url":"http.url"),headers:"grpc-request"===o?a.get(s,"metadata",[]):a.get(s,"headers",[]),auth:a.get(s,"auth",{}),body:a.get(s,"body",{}),script:a.get(s,"script",{}),vars:a.get(s,"vars",{}),assertions:a.get(s,"assertions",[]),tests:a.get(s,"tests",""),docs:a.get(s,"docs","")}};if("grpc-request"===o){const e=a.get(s,"grpc.methodType");e&&(g.request.methodType=e);const t=a.get(s,"grpc.protoPath");t&&(g.request.protoPath=t),g.request.auth.mode=a.get(s,"grpc.auth","none"),g.request.body=a.get(s,"body",{mode:"grpc",grpc:a.get(s,"body.grpc",[{name:"message 1",content:"{}"}])})}else g.request.params=a.get(s,"params",[]),g.request.auth.mode=a.get(s,"http.auth","none"),g.request.body.mode=a.get(s,"http.body","none");const c=s?.auth?.oauth2?.grantType;if(c){const e=(e=>{const t=e.auth.oauth2.grantType,r={};try{const s=["authorization","token","refresh"];for(const a of s){const s=u(e,a,t);s.length>0&&(r[a]=s)}}catch(e){console.error(e),console.error("Error while getting the oauth2 additional parameters!")}return r})(s);Object.keys(e||{}).length>0&&(g.request.auth.oauth2.additionalParameters=e)}return g}catch(e){throw e}};e.parentPort?.on("message",(async t=>{try{const{taskType:s,data:o}=t;let n;if("parse"===s)n=g(o);else{if("stringify"!==s)throw new Error(`Unknown task type: ${s}`);n=(e=>{try{let t=a.get(e,"type");switch(t){case"http-request":default:t="http";break;case"graphql-request":t="graphql";break;case"grpc-request":t="grpc"}const s=a.get(e,"seq"),o={meta:{name:a.get(e,"name"),type:t,seq:a.isNaN(s)?1:Number(s),tags:a.get(e,"tags",[])}};if("http"===t||"graphql"===t)o.http={method:a.lowerCase(a.get(e,"request.method")),url:a.get(e,"request.url"),auth:a.get(e,"request.auth.mode","none"),body:a.get(e,"request.body.mode","none")},o.params=a.get(e,"request.params",[]),o.body=a.get(e,"request.body",{mode:"json",json:"{}"});else if("grpc"===t){o.grpc={url:a.get(e,"request.url"),auth:a.get(e,"request.auth.mode","none"),body:a.get(e,"request.body.mode","grpc")};const t=a.get(e,"request.method"),r=a.get(e,"request.methodType"),s=a.get(e,"request.protoPath");t&&(o.grpc.method=t),r&&(o.grpc.methodType=r),s&&(o.grpc.protoPath=s),o.body=a.get(e,"request.body",{mode:"grpc",grpc:a.get(e,"request.body.grpc",[{name:"message 1",content:"{}"}])})}return"grpc"===t?o.metadata=a.get(e,"request.headers",[]):o.headers=a.get(e,"request.headers",[]),o.auth=a.get(e,"request.auth",{}),o.script=a.get(e,"request.script",{}),o.vars={req:a.get(e,"request.vars.req",[]),res:a.get(e,"request.vars.res",[])},o.assertions=a.get(e,"request.assertions",[]),o.tests=a.get(e,"request.tests",""),o.settings=a.get(e,"settings",{}),o.docs=a.get(e,"request.docs",""),r.jsonToBruV2(o)}catch(e){throw e}})(o)}e.parentPort?.postMessage(n)}catch(t){console.error("Worker error:",t),e.parentPort?.postMessage({error:t?.message})}}));
|
|
2
2
|
//# sourceMappingURL=worker-script.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-script.js","sources":["../../../src/workers/worker-script.ts","../../../src/formats/bru/index.ts"],"sourcesContent":["import { parentPort } from 'node:worker_threads';\nimport { bruRequestToJson, jsonRequestToBru } from '../formats/bru';\n\ninterface WorkerMessage {\n taskType: 'parse' | 'stringify';\n data: any;\n}\n\nparentPort?.on('message', async (message: WorkerMessage) => {\n try {\n const { taskType, data } = message;\n let result: any;\n\n if (taskType === 'parse') {\n result = bruRequestToJson(data);\n } else if (taskType === 'stringify') {\n result = jsonRequestToBru(data);\n } else {\n throw new Error(`Unknown task type: ${taskType}`);\n }\n\n parentPort?.postMessage(result);\n } catch (error: any) {\n console.error('Worker error:', error);\n parentPort?.postMessage({ error: error?.message });\n }\n});","import * as _ from 'lodash';\nimport {\n bruToJsonV2,\n jsonToBruV2,\n bruToEnvJsonV2,\n envJsonToBruV2,\n collectionBruToJson as _collectionBruToJson,\n jsonToCollectionBru as _jsonToCollectionBru\n} from '@usebruno/lang';\n\nexport const bruRequestToJson = (data: string | any, parsed: boolean = false): any => {\n try {\n const json = parsed ? data : bruToJsonV2(data);\n\n let requestType = _.get(json, 'meta.type');\n if (requestType === 'http') {\n requestType = 'http-request';\n } else if (requestType === 'graphql') {\n requestType = 'graphql-request';\n } else {\n requestType = 'http-request';\n }\n\n const sequence = _.get(json, 'meta.seq');\n const transformedJson = {\n type: requestType,\n name: _.get(json, 'meta.name'),\n seq: !_.isNaN(sequence) ? Number(sequence) : 1,\n settings: _.get(json, 'settings', {}),\n tags: _.get(json, 'meta.tags', []),\n request: {\n method: _.upperCase(_.get(json, 'http.method')),\n url: _.get(json, 'http.url'),\n params: _.get(json, 'params', []),\n headers: _.get(json, 'headers', []),\n auth: _.get(json, 'auth', {}),\n body: _.get(json, 'body', {}),\n script: _.get(json, 'script', {}),\n vars: _.get(json, 'vars', {}),\n assertions: _.get(json, 'assertions', []),\n tests: _.get(json, 'tests', ''),\n docs: _.get(json, 'docs', '')\n }\n };\n\n transformedJson.request.auth.mode = _.get(json, 'http.auth', 'none');\n transformedJson.request.body.mode = _.get(json, 'http.body', 'none');\n\n return transformedJson;\n } catch (e) {\n return Promise.reject(e);\n }\n};\n\nexport const jsonRequestToBru = (json: any): string => {\n try {\n let type = _.get(json, 'type');\n if (type === 'http-request') {\n type = 'http';\n } else if (type === 'graphql-request') {\n type = 'graphql';\n } else {\n type = 'http';\n }\n\n const sequence = _.get(json, 'seq');\n const bruJson = {\n meta: {\n name: _.get(json, 'name'),\n type: type,\n seq: !_.isNaN(sequence) ? Number(sequence) : 1,\n tags: _.get(json, 'tags', []),\n },\n http: {\n method: _.lowerCase(_.get(json, 'request.method')),\n url: _.get(json, 'request.url'),\n auth: _.get(json, 'request.auth.mode', 'none'),\n body: _.get(json, 'request.body.mode', 'none')\n },\n params: _.get(json, 'request.params', []),\n headers: _.get(json, 'request.headers', []),\n auth: _.get(json, 'request.auth', {}),\n body: _.get(json, 'request.body', {}),\n script: _.get(json, 'request.script', {}),\n vars: {\n req: _.get(json, 'request.vars.req', []),\n res: _.get(json, 'request.vars.res', [])\n },\n assertions: _.get(json, 'request.assertions', []),\n tests: _.get(json, 'request.tests', ''),\n settings: _.get(json, 'settings', {}),\n docs: _.get(json, 'request.docs', '')\n };\n\n const bru = jsonToBruV2(bruJson);\n return bru;\n } catch (error) {\n throw error;\n }\n};\n\nexport const bruCollectionToJson = (data: string | any, parsed: boolean = false): any => {\n try {\n const json = parsed ? data : _collectionBruToJson(data);\n\n const transformedJson: any = {\n request: {\n headers: _.get(json, 'headers', []),\n auth: _.get(json, 'auth', {}),\n script: _.get(json, 'script', {}),\n vars: _.get(json, 'vars', {}),\n tests: _.get(json, 'tests', '')\n },\n settings: _.get(json, 'settings', {}),\n docs: _.get(json, 'docs', '')\n };\n\n // add meta if it exists\n // this is only for folder bru file\n if (json.meta) {\n transformedJson.meta = {\n name: json.meta.name\n };\n \n // Include seq if it exists\n if (json.meta.seq !== undefined) {\n const sequence = json.meta.seq;\n transformedJson.meta.seq = !isNaN(sequence) ? Number(sequence) : 1;\n }\n }\n\n return transformedJson;\n } catch (error) {\n return Promise.reject(error);\n }\n};\n\nexport const jsonCollectionToBru = (json: any, isFolder?: boolean): string => {\n try {\n const collectionBruJson: any = {\n headers: _.get(json, 'request.headers', []),\n script: {\n req: _.get(json, 'request.script.req', ''),\n res: _.get(json, 'request.script.res', '')\n },\n vars: {\n req: _.get(json, 'request.vars.req', []),\n res: _.get(json, 'request.vars.res', [])\n },\n tests: _.get(json, 'request.tests', ''),\n auth: _.get(json, 'request.auth', {}),\n docs: _.get(json, 'docs', '')\n };\n\n // add meta if it exists\n // this is only for folder bru file\n if (json?.meta) {\n collectionBruJson.meta = {\n name: json.meta.name\n };\n \n // Include seq if it exists\n if (json.meta.seq !== undefined) {\n const sequence = json.meta.seq;\n collectionBruJson.meta.seq = !isNaN(sequence) ? Number(sequence) : 1;\n }\n }\n\n if (!isFolder) {\n collectionBruJson.auth = _.get(json, 'request.auth', {});\n }\n\n return _jsonToCollectionBru(collectionBruJson);\n } catch (error) {\n throw error;\n }\n};\n\nexport const bruEnvironmentToJson = (bru: string): any => {\n try {\n const json = bruToEnvJsonV2(bru);\n\n // the app env format requires each variable to have a type\n // this need to be evaluated and safely removed\n // i don't see it being used in schema validation\n if (json && json.variables && json.variables.length) {\n _.each(json.variables, (v: any) => (v.type = 'text'));\n }\n\n return json;\n } catch (error) {\n return Promise.reject(error);\n }\n};\n\nexport const jsonEnvironmentToBru = (json: any): string => {\n try {\n const bru = envJsonToBruV2(json);\n return bru;\n } catch (error) {\n throw error;\n }\n}; "],"names":["parentPort","on","async","message","taskType","data","result","parsed","json","bruToJsonV2","requestType","_","get","sequence","transformedJson","type","name","seq","isNaN","Number","settings","tags","request","method","upperCase","url","params","headers","auth","body","script","vars","assertions","tests","docs","mode","e","Promise","reject","bruRequestToJson","Error","bruJson","meta","http","lowerCase","req","res","jsonToBruV2","error","jsonRequestToBru","postMessage","console"],"mappings":"gXAQAA,EAAAA,YAAYC,GAAG,WAAWC,MAAOC,IAC/B,IACE,MAAMC,SAAEA,EAAQC,KAAEA,GAASF,EAC3B,IAAIG,EAEJ,GAAiB,UAAbF,EACFE,ECJ0B,EAACD,EAAoBE,GAAkB,KACrE,IACE,MAAMC,EAAOD,EAASF,EAAOI,EAAWA,YAACJ,GAEzC,IAAIK,EAAcC,EAAEC,IAAIJ,EAAM,aAE5BE,EADkB,SAAhBA,EACY,eACW,YAAhBA,EACK,kBAEA,eAGhB,MAAMG,EAAWF,EAAEC,IAAIJ,EAAM,YACvBM,EAAkB,CACtBC,KAAML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ACNE,IAAMN,EAAEO,MAAML,GAA+B,EAAnBM,OAAON,GACjCQ,KAAMV,EAAEC,IAAIJ,EAAM,OAAQ,KAE5BmC,KAAM,CACJpB,OAAQZ,EAAEiC,UAAUjC,EAAEC,IAAIJ,EAAM,mBAChCiB,IAAKd,EAAEC,IAAIJ,EAAM,eACjBoB,KAAMjB,EAAEC,IAAIJ,EAAM,oBAAqB,QACvCqB,KAAMlB,EAAEC,IAAIJ,EAAM,oBAAqB,SAEzCkB,OAAQf,EAAEC,IAAIJ,EAAM,iBAAkB,IACtCmB,QAAShB,EAAEC,IAAIJ,EAAM,kBAAmB,IACxCoB,KAAMjB,EAAEC,IAAIJ,EAAM,eAAgB,CAAA,GAClCqB,KAAMlB,EAAEC,IAAIJ,EAAM,eAAgB,CAAA,GAClCsB,OAAQnB,EAAEC,IAAIJ,EAAM,iBAAkB,CAAA,GACtCuB,KAAM,CACJc,IAAKlC,EAAEC,IAAIJ,EAAM,mBAAoB,IACrCsC,IAAKnC,EAAEC,IAAIJ,EAAM,mBAAoB,KAEvCwB,WAAYrB,EAAEC,IAAIJ,EAAM,qBAAsB,IAC9CyB,MAAOtB,EAAEC,IAAIJ,EAAM,gBAAiB,IACpCY,SAAUT,EAAEC,IAAIJ,EAAM,WAAY,CAAA,GAClC0B,KAAMvB,EAAEC,IAAIJ,EAAM,eAAgB,KAIpC,OADYuC,cAAYN,EAEzB,CAAC,MAAOO,GACP,MAAMA,CACP,GDlFYC,CAAiB5C,EAG3B,CAEDL,cAAYkD,YAAY5C,EACzB,CAAC,MAAO0C,GACPG,QAAQH,MAAM,gBAAiBA,GAC/BhD,EAAUA,YAAEkD,YAAY,CAAEF,MAAOA,GAAO7C,SACzC"}
|
|
1
|
+
{"version":3,"file":"worker-script.js","sources":["../../../src/formats/bru/utils/oauth2-additional-params.ts","../../../src/formats/bru/index.ts","../../../src/workers/worker-script.ts"],"sourcesContent":["type T_Oauth2ParameterType = 'authorization' | 'token' | 'refresh';\ntype T_Oauth2ParameterSendInType = 'headers' | 'queryparams' | 'body';\n\nexport interface T_OAuth2AdditionalParam {\n name: string;\n value: string;\n enabled: boolean;\n sendIn: T_Oauth2ParameterSendInType\n}\n\nexport interface T_OAuth2AdditionalParameters {\n authorization?: T_OAuth2AdditionalParam[];\n token?: T_OAuth2AdditionalParam[];\n refresh?: T_OAuth2AdditionalParam[];\n}\n\nexport interface T_Oauth2Auth {\n grantType: string;\n additionalParameters?: T_OAuth2AdditionalParameters;\n}\n\nexport interface T_BruJson {\n auth: {\n oauth2: T_Oauth2Auth;\n };\n oauth2_additional_parameters_auth_req_headers?: any[];\n oauth2_additional_parameters_auth_req_queryparams?: any[];\n oauth2_additional_parameters_access_token_req_headers?: any[];\n oauth2_additional_parameters_access_token_req_queryparams?: any[];\n oauth2_additional_parameters_access_token_req_bodyvalues?: any[];\n oauth2_additional_parameters_refresh_token_req_headers?: any[];\n oauth2_additional_parameters_refresh_token_req_queryparams?: any[];\n oauth2_additional_parameters_refresh_token_req_bodyvalues?: any[];\n}\n\ninterface T_Oauth2ParameterMapping {\n type: T_Oauth2ParameterType;\n sendIn: T_Oauth2ParameterSendInType;\n source: keyof T_BruJson;\n}\n\nconst PARAMETER_MAPPINGS: T_Oauth2ParameterMapping[] = [\n // Authorization parameters (only for authorization_code grant type)\n { type: 'authorization', sendIn: 'headers', source: 'oauth2_additional_parameters_auth_req_headers' },\n { type: 'authorization', sendIn: 'queryparams', source: 'oauth2_additional_parameters_auth_req_queryparams' },\n \n // Token parameters (for all grant types)\n { type: 'token', sendIn: 'headers', source: 'oauth2_additional_parameters_access_token_req_headers' },\n { type: 'token', sendIn: 'queryparams', source: 'oauth2_additional_parameters_access_token_req_queryparams' },\n { type: 'token', sendIn: 'body', source: 'oauth2_additional_parameters_access_token_req_bodyvalues' },\n \n // Refresh parameters (for grant types that support refresh)\n { type: 'refresh', sendIn: 'headers', source: 'oauth2_additional_parameters_refresh_token_req_headers' },\n { type: 'refresh', sendIn: 'queryparams', source: 'oauth2_additional_parameters_refresh_token_req_queryparams' },\n { type: 'refresh', sendIn: 'body', source: 'oauth2_additional_parameters_refresh_token_req_bodyvalues' },\n];\n\n/**\n * Maps source parameters to T_OAuth2AdditionalParam format\n */\nconst mapParametersFromSource = (sourceParams: any[], sendIn: T_Oauth2ParameterSendInType): T_OAuth2AdditionalParam[] => {\n if (!sourceParams?.length) {\n return [];\n }\n \n return sourceParams.map(param => ({\n ...param,\n sendIn\n }));\n};\n\n/**\n * Checks if a parameter type should be included based on grant type\n */\nconst shouldIncludeParameterType = (type: T_Oauth2ParameterType, grantType: string): boolean => {\n // Authorization parameters are only valid for authorization_code grant type\n if (type === 'authorization') {\n return grantType === 'authorization_code' || grantType === 'implicit';\n }\n\n if (type === 'token' || type === 'refresh') {\n return grantType !== 'implicit';\n }\n \n // Token and refresh parameters are valid for all grant types\n return true;\n};\n\n/**\n * Collects all parameters for a specific type (authorization, token, or refresh)\n */\nconst collectParametersForType = (\n json: T_BruJson, \n type: T_Oauth2ParameterType, \n grantType: string\n): T_OAuth2AdditionalParam[] => {\n if (!shouldIncludeParameterType(type, grantType)) {\n return [];\n }\n\n const relevantMappings = PARAMETER_MAPPINGS.filter(mapping => mapping.type === type);\n const allParams: T_OAuth2AdditionalParam[] = [];\n\n for (const mapping of relevantMappings) {\n const sourceParams = json[mapping.source] as any[];\n const mappedParams = mapParametersFromSource(sourceParams, mapping.sendIn);\n allParams.push(...mappedParams);\n }\n\n return allParams;\n};\n\n/**\n * This function extracts OAuth2 additional parameters from various sources in the bru json data and organizes\n * them into a structured format based on their usage context (authorization, token, refresh).\n * \n * @param json - json object containing OAuth2 configuration and additional parameters\n * @returns OAuth2 additional parameters\n */\nexport const getOauth2AdditionalParameters = (json: T_BruJson): T_OAuth2AdditionalParameters => {\n const grantType = json.auth.oauth2.grantType;\n const additionalParameters: T_OAuth2AdditionalParameters = {};\n\n try {\n // Collect parameters for each type\n const parameterTypes: T_Oauth2ParameterType[] = ['authorization', 'token', 'refresh'];\n \n for (const type of parameterTypes) {\n const params = collectParametersForType(json, type, grantType);\n if (params.length > 0) {\n additionalParameters[type] = params;\n }\n }\n }\n catch(error) {\n console.error(error);\n console.error(\"Error while getting the oauth2 additional parameters!\");\n }\n \n return additionalParameters;\n};","import * as _ from 'lodash';\nimport {\n bruToJsonV2,\n jsonToBruV2,\n bruToEnvJsonV2,\n envJsonToBruV2,\n collectionBruToJson as _collectionBruToJson,\n jsonToCollectionBru as _jsonToCollectionBru\n} from '@usebruno/lang';\nimport { getOauth2AdditionalParameters } from './utils/oauth2-additional-params';\n\nexport const bruRequestToJson = (data: string | any, parsed: boolean = false): any => {\n try {\n const json = parsed ? data : bruToJsonV2(data);\n\n let requestType = _.get(json, 'meta.type');\n switch (requestType) {\n case 'http':\n requestType = 'http-request';\n break;\n case 'graphql':\n requestType = 'graphql-request';\n break;\n case 'grpc':\n requestType = 'grpc-request';\n break;\n default:\n requestType = 'http-request';\n }\n\n const sequence = _.get(json, 'meta.seq');\n const transformedJson = {\n type: requestType,\n name: _.get(json, 'meta.name'),\n seq: !_.isNaN(sequence) ? Number(sequence) : 1,\n settings: _.get(json, 'settings', {}),\n tags: _.get(json, 'meta.tags', []),\n request: {\n method:\n requestType === 'grpc-request' ? _.get(json, 'grpc.method', '') : _.upperCase(_.get(json, 'http.method')),\n url: _.get(json, requestType === 'grpc-request' ? 'grpc.url' : 'http.url'),\n headers: requestType === 'grpc-request' ? _.get(json, 'metadata', []) : _.get(json, 'headers', []),\n auth: _.get(json, 'auth', {}),\n body: _.get(json, 'body', {}),\n script: _.get(json, 'script', {}),\n vars: _.get(json, 'vars', {}),\n assertions: _.get(json, 'assertions', []),\n tests: _.get(json, 'tests', ''),\n docs: _.get(json, 'docs', '')\n }\n };\n\n // Add request type specific fields\n if (requestType === 'grpc-request') {\n const selectedMethodType = _.get(json, 'grpc.methodType');\n selectedMethodType && ((transformedJson.request as any).methodType = selectedMethodType);\n const protoPath = _.get(json, 'grpc.protoPath');\n protoPath && ((transformedJson.request as any).protoPath = protoPath);\n transformedJson.request.auth.mode = _.get(json, 'grpc.auth', 'none');\n transformedJson.request.body = _.get(json, 'body', {\n mode: 'grpc',\n grpc: _.get(json, 'body.grpc', [\n {\n name: 'message 1',\n content: '{}'\n }\n ])\n });\n } else {\n // For HTTP and GraphQL\n (transformedJson.request as any).params = _.get(json, 'params', []);\n transformedJson.request.auth.mode = _.get(json, 'http.auth', 'none');\n transformedJson.request.body.mode = _.get(json, 'http.body', 'none');\n }\n\n // add oauth2 additional parameters if they exist\n const hasOauth2GrantType = json?.auth?.oauth2?.grantType;\n if (hasOauth2GrantType) {\n const additionalParameters = getOauth2AdditionalParameters(json);\n const hasAdditionalParameters = Object.keys(additionalParameters || {}).length > 0;\n if (hasAdditionalParameters) {\n transformedJson.request.auth.oauth2.additionalParameters = additionalParameters;\n }\n }\n\n return transformedJson;\n } catch (error) {\n throw error;\n }\n};\n\nexport const jsonRequestToBru = (json: any): string => {\n try {\n let type = _.get(json, 'type');\n switch (type) {\n case 'http-request':\n type = 'http';\n break;\n case 'graphql-request':\n type = 'graphql';\n break;\n case 'grpc-request':\n type = 'grpc';\n break;\n default:\n type = 'http';\n }\n\n const sequence = _.get(json, 'seq');\n\n // Start with the common meta section\n const bruJson = {\n meta: {\n name: _.get(json, 'name'),\n type: type,\n seq: !_.isNaN(sequence) ? Number(sequence) : 1,\n tags: _.get(json, 'tags', [])\n }\n } as any;\n\n // For HTTP and GraphQL requests, maintain the current structure\n if (type === 'http' || type === 'graphql') {\n bruJson.http = {\n method: _.lowerCase(_.get(json, 'request.method')),\n url: _.get(json, 'request.url'),\n auth: _.get(json, 'request.auth.mode', 'none'),\n body: _.get(json, 'request.body.mode', 'none')\n };\n bruJson.params = _.get(json, 'request.params', []);\n bruJson.body = _.get(json, 'request.body', {\n mode: 'json',\n json: '{}'\n });\n } // For gRPC, add gRPC-specific structure but maintain field names\n else if (type === 'grpc') {\n bruJson.grpc = {\n url: _.get(json, 'request.url'),\n auth: _.get(json, 'request.auth.mode', 'none'),\n body: _.get(json, 'request.body.mode', 'grpc')\n };\n // Only add method if it exists\n const method = _.get(json, 'request.method');\n const methodType = _.get(json, 'request.methodType');\n const protoPath = _.get(json, 'request.protoPath');\n if (method) bruJson.grpc.method = method;\n if (methodType) bruJson.grpc.methodType = methodType;\n if (protoPath) bruJson.grpc.protoPath = protoPath;\n bruJson.body = _.get(json, 'request.body', {\n mode: 'grpc',\n grpc: _.get(json, 'request.body.grpc', [\n {\n name: 'message 1',\n content: '{}'\n }\n ])\n });\n }\n\n // Common fields for all request types\n if (type === 'grpc') {\n bruJson.metadata = _.get(json, 'request.headers', []); // Use metadata for gRPC\n } else {\n bruJson.headers = _.get(json, 'request.headers', []); // Use headers for HTTP/GraphQL\n }\n bruJson.auth = _.get(json, 'request.auth', {});\n bruJson.script = _.get(json, 'request.script', {});\n bruJson.vars = {\n req: _.get(json, 'request.vars.req', []),\n res: _.get(json, 'request.vars.res', [])\n };\n // should we add assertions and tests for grpc requests?\n bruJson.assertions = _.get(json, 'request.assertions', []);\n bruJson.tests = _.get(json, 'request.tests', '');\n bruJson.settings = _.get(json, 'settings', {});\n bruJson.docs = _.get(json, 'request.docs', '');\n\n const bru = jsonToBruV2(bruJson);\n return bru;\n } catch (error) {\n throw error;\n }\n};\n\nexport const bruCollectionToJson = (data: string | any, parsed: boolean = false): any => {\n try {\n const json = parsed ? data : _collectionBruToJson(data);\n\n const transformedJson: any = {\n request: {\n headers: _.get(json, 'headers', []),\n auth: _.get(json, 'auth', {}),\n script: _.get(json, 'script', {}),\n vars: _.get(json, 'vars', {}),\n tests: _.get(json, 'tests', '')\n },\n settings: _.get(json, 'settings', {}),\n docs: _.get(json, 'docs', '')\n };\n\n // add meta if it exists\n // this is only for folder bru file\n if (json.meta) {\n transformedJson.meta = {\n name: json.meta.name\n };\n\n // Include seq if it exists\n if (json.meta.seq !== undefined) {\n const sequence = json.meta.seq;\n transformedJson.meta.seq = !isNaN(sequence) ? Number(sequence) : 1;\n }\n }\n\n // add oauth2 additional parameters if they exist\n const hasOauth2GrantType = json?.auth?.oauth2?.grantType;\n if (hasOauth2GrantType) {\n const additionalParameters = getOauth2AdditionalParameters(json);\n const hasAdditionalParameters = Object.keys(additionalParameters).length > 0;\n if (hasAdditionalParameters) {\n transformedJson.request.auth.oauth2.additionalParameters = additionalParameters;\n }\n }\n\n return transformedJson;\n } catch (error) {\n return Promise.reject(error);\n }\n};\n\nexport const jsonCollectionToBru = (json: any, isFolder?: boolean): string => {\n try {\n const collectionBruJson: any = {\n headers: _.get(json, 'request.headers', []),\n script: {\n req: _.get(json, 'request.script.req', ''),\n res: _.get(json, 'request.script.res', '')\n },\n vars: {\n req: _.get(json, 'request.vars.req', []),\n res: _.get(json, 'request.vars.res', [])\n },\n tests: _.get(json, 'request.tests', ''),\n auth: _.get(json, 'request.auth', {}),\n docs: _.get(json, 'docs', '')\n };\n\n // add meta if it exists\n // this is only for folder bru file\n if (json?.meta) {\n collectionBruJson.meta = {\n name: json.meta.name\n };\n\n // Include seq if it exists\n if (json.meta.seq !== undefined) {\n const sequence = json.meta.seq;\n collectionBruJson.meta.seq = !isNaN(sequence) ? Number(sequence) : 1;\n }\n }\n\n if (!isFolder) {\n collectionBruJson.auth = _.get(json, 'request.auth', {});\n }\n\n return _jsonToCollectionBru(collectionBruJson);\n } catch (error) {\n throw error;\n }\n};\n\nexport const bruEnvironmentToJson = (bru: string): any => {\n try {\n const json = bruToEnvJsonV2(bru);\n\n // the app env format requires each variable to have a type\n // this need to be evaluated and safely removed\n // i don't see it being used in schema validation\n if (json && json.variables && json.variables.length) {\n _.each(json.variables, (v: any) => (v.type = 'text'));\n }\n\n return json;\n } catch (error) {\n return Promise.reject(error);\n }\n};\n\nexport const jsonEnvironmentToBru = (json: any): string => {\n try {\n const bru = envJsonToBruV2(json);\n return bru;\n } catch (error) {\n throw error;\n }\n};\n","import { parentPort } from 'node:worker_threads';\nimport { bruRequestToJson, jsonRequestToBru } from '../formats/bru';\n\ninterface WorkerMessage {\n taskType: 'parse' | 'stringify';\n data: any;\n}\n\nparentPort?.on('message', async (message: WorkerMessage) => {\n try {\n const { taskType, data } = message;\n let result: any;\n\n if (taskType === 'parse') {\n result = bruRequestToJson(data);\n } else if (taskType === 'stringify') {\n result = jsonRequestToBru(data);\n } else {\n throw new Error(`Unknown task type: ${taskType}`);\n }\n\n parentPort?.postMessage(result);\n } catch (error: any) {\n console.error('Worker error:', error);\n parentPort?.postMessage({ error: error?.message });\n }\n});"],"names":["PARAMETER_MAPPINGS","type","sendIn","source","mapParametersFromSource","sourceParams","length","map","param","collectParametersForType","json","grantType","shouldIncludeParameterType","relevantMappings","filter","mapping","allParams","mappedParams","push","bruRequestToJson","data","parsed","bruToJsonV2","requestType","_","get","sequence","transformedJson","name","seq","isNaN","Number","settings","tags","request","method","upperCase","url","headers","auth","body","script","vars","assertions","tests","docs","selectedMethodType","methodType","protoPath","mode","grpc","content","params","hasOauth2GrantType","oauth2","additionalParameters","parameterTypes","error","console","getOauth2AdditionalParameters","Object","keys","parentPort","on","async","message","taskType","result","Error","bruJson","meta","http","lowerCase","metadata","req","res","jsonToBruV2","jsonRequestToBru","postMessage"],"mappings":"gXAyCA,MAAMA,EAAiD,CAErD,CAAEC,KAAM,gBAAiBC,OAAQ,UAAWC,OAAQ,iDACpD,CAAEF,KAAM,gBAAiBC,OAAQ,cAAeC,OAAQ,qDAGxD,CAAEF,KAAM,QAASC,OAAQ,UAAWC,OAAQ,yDAC5C,CAAEF,KAAM,QAASC,OAAQ,cAAeC,OAAQ,6DAChD,CAAEF,KAAM,QAASC,OAAQ,OAAQC,OAAQ,4DAGzC,CAAEF,KAAM,UAAWC,OAAQ,UAAWC,OAAQ,0DAC9C,CAAEF,KAAM,UAAWC,OAAQ,cAAeC,OAAQ,8DAClD,CAAEF,KAAM,UAAWC,OAAQ,OAAQC,OAAQ,8DAMvCC,EAA0B,CAACC,EAAqBH,IAC/CG,GAAcC,OAIZD,EAAaE,KAAIC,IAAU,IAC7BA,EACH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0C,cAAYgB,YAAYX,EACzB,CAAC,MAAOV,GACPC,QAAQD,MAAM,gBAAiBA,GAC/BK,EAAUA,YAAEgB,YAAY,CAAErB,MAAOA,GAAOQ,SACzC"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
type T_Oauth2ParameterSendInType = 'headers' | 'queryparams' | 'body';
|
|
2
|
+
export interface T_OAuth2AdditionalParam {
|
|
3
|
+
name: string;
|
|
4
|
+
value: string;
|
|
5
|
+
enabled: boolean;
|
|
6
|
+
sendIn: T_Oauth2ParameterSendInType;
|
|
7
|
+
}
|
|
8
|
+
export interface T_OAuth2AdditionalParameters {
|
|
9
|
+
authorization?: T_OAuth2AdditionalParam[];
|
|
10
|
+
token?: T_OAuth2AdditionalParam[];
|
|
11
|
+
refresh?: T_OAuth2AdditionalParam[];
|
|
12
|
+
}
|
|
13
|
+
export interface T_Oauth2Auth {
|
|
14
|
+
grantType: string;
|
|
15
|
+
additionalParameters?: T_OAuth2AdditionalParameters;
|
|
16
|
+
}
|
|
17
|
+
export interface T_BruJson {
|
|
18
|
+
auth: {
|
|
19
|
+
oauth2: T_Oauth2Auth;
|
|
20
|
+
};
|
|
21
|
+
oauth2_additional_parameters_auth_req_headers?: any[];
|
|
22
|
+
oauth2_additional_parameters_auth_req_queryparams?: any[];
|
|
23
|
+
oauth2_additional_parameters_access_token_req_headers?: any[];
|
|
24
|
+
oauth2_additional_parameters_access_token_req_queryparams?: any[];
|
|
25
|
+
oauth2_additional_parameters_access_token_req_bodyvalues?: any[];
|
|
26
|
+
oauth2_additional_parameters_refresh_token_req_headers?: any[];
|
|
27
|
+
oauth2_additional_parameters_refresh_token_req_queryparams?: any[];
|
|
28
|
+
oauth2_additional_parameters_refresh_token_req_bodyvalues?: any[];
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* This function extracts OAuth2 additional parameters from various sources in the bru json data and organizes
|
|
32
|
+
* them into a structured format based on their usage context (authorization, token, refresh).
|
|
33
|
+
*
|
|
34
|
+
* @param json - json object containing OAuth2 configuration and additional parameters
|
|
35
|
+
* @returns OAuth2 additional parameters
|
|
36
|
+
*/
|
|
37
|
+
export declare const getOauth2AdditionalParameters: (json: T_BruJson) => T_OAuth2AdditionalParameters;
|
|
38
|
+
export {};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parses a .bru file and extracts body content while redacting it from the main content
|
|
3
|
+
* @param {string} bruFileContent - The raw content of the .bru file
|
|
4
|
+
* @returns {Object} Object containing redacted file content and extracted body data
|
|
5
|
+
*/
|
|
6
|
+
export declare const bruRequestParseAndRedactBodyData: (bruFileContent: string) => {
|
|
7
|
+
bruFileStringWithRedactedBody: string;
|
|
8
|
+
extractedBodyContent: Record<string, string>;
|
|
9
|
+
};
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import BruParserWorker from './workers';
|
|
2
2
|
import { ParseOptions, StringifyOptions, ParsedRequest, ParsedCollection, ParsedEnvironment } from './types';
|
|
3
3
|
export declare const parseRequest: (content: string, options?: ParseOptions) => any;
|
|
4
|
+
export declare const parseRequestAndRedactBody: (content: string, options?: ParseOptions) => any;
|
|
4
5
|
export declare const stringifyRequest: (requestObj: ParsedRequest, options?: StringifyOptions) => string;
|
|
5
6
|
export declare const parseRequestViaWorker: (content: string) => Promise<any>;
|
|
6
7
|
export declare const stringifyRequestViaWorker: (requestObj: any) => Promise<string>;
|
package/dist/esm/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import*as e from"lodash";import{bruToJsonV2 as t,jsonToBruV2 as r,collectionBruToJson as s,jsonToCollectionBru as a,bruToEnvJsonV2 as o,envJsonToBruV2 as u,dotenvToJson as n}from"@usebruno/lang";import{Worker as i}from"node:worker_threads";import h from"node:path";const m=(t,r=!1)=>{try{const a=r?t:s(t),o={request:{headers:e.get(a,"headers",[]),auth:e.get(a,"auth",{}),script:e.get(a,"script",{}),vars:e.get(a,"vars",{}),tests:e.get(a,"tests","")},settings:e.get(a,"settings",{}),docs:e.get(a,"docs","")};if(a.meta&&(o.meta={name:a.meta.name},void 0!==a.meta.seq)){const e=a.meta.seq;o.meta.seq=isNaN(e)?1:Number(e)}return o}catch(e){return Promise.reject(e)}},c=(t,r)=>{try{const s={headers:e.get(t,"request.headers",[]),script:{req:e.get(t,"request.script.req",""),res:e.get(t,"request.script.res","")},vars:{req:e.get(t,"request.vars.req",[]),res:e.get(t,"request.vars.res",[])},tests:e.get(t,"request.tests",""),auth:e.get(t,"request.auth",{}),docs:e.get(t,"docs","")};if(t?.meta&&(s.meta={name:t.meta.name},void 0!==t.meta.seq)){const e=t.meta.seq;s.meta.seq=isNaN(e)?1:Number(e)}return r||(s.auth=e.get(t,"request.auth",{})),a(s)}catch(e){throw e}};class p{constructor(){this.queue=[],this.isProcessing=!1,this.workers={}}async getWorkerForScriptPath(e){this.workers||(this.workers={});let t=this.workers[e];return t&&-1!==t.threadId||(this.workers[e]=t=new i(e)),t}async enqueue(e){const{priority:t,scriptPath:r,data:s,taskType:a}=e;return new Promise(((e,o)=>{this.queue.push({priority:t,scriptPath:r,data:s,taskType:a,resolve:e,reject:o}),this.queue?.sort(((e,t)=>e?.priority-t?.priority)),this.processQueue()}))}async processQueue(){if(this.isProcessing||0===this.queue.length)return;this.isProcessing=!0;const{scriptPath:e,data:t,taskType:r,resolve:s,reject:a}=this.queue.shift();try{const a=await this.runWorker({scriptPath:e,data:t,taskType:r});s?.(a)}catch(e){a?.(e)}finally{this.isProcessing=!1,this.processQueue()}}async runWorker({scriptPath:e,data:t,taskType:r}){return new Promise((async(s,a)=>{let o=await this.getWorkerForScriptPath(e);const u=e=>{o.off("message",u),o.off("error",n),o.off("exit",i),e?.error?a(new Error(e?.error)):s(e)},n=e=>{o.off("message",u),o.off("error",n),o.off("exit",i),a(e)},i=t=>{o.off("message",u),o.off("error",n),o.off("exit",i),delete this.workers[e],a(new Error(`Worker stopped with exit code ${t}`))};o.on("message",u),o.on("error",n),o.on("exit",i),o.postMessage({taskType:r,data:t})}))}async cleanup(){const e=Object.values(this.workers).map((e=>-1!==e.threadId?e.terminate():Promise.resolve()));await Promise.allSettled(e),this.workers={}}}const g=[{maxSize:.005},{maxSize:.1},{maxSize:1},{maxSize:10},{maxSize:100}];class f{constructor(){this.workerQueues=g?.map((e=>({maxSize:e?.maxSize,workerQueue:new p})))}getWorkerQueue(e){const t=this.workerQueues.find((t=>t.maxSize>=e));return t?.workerQueue??this.workerQueues[this.workerQueues.length-1].workerQueue}async enqueueTask({data:e,taskType:t}){const r=(e=>("string"==typeof e?Buffer.byteLength(e,"utf8"):Buffer.byteLength(JSON.stringify(e),"utf8"))/1048576)(e),s=this.getWorkerQueue(r),a=h.join(__dirname,"./workers/worker-script.js");return s.enqueue({data:e,priority:r,scriptPath:a,taskType:t})}async parseRequest(e){return this.enqueueTask({data:e,taskType:"parse"})}async stringifyRequest(e){return this.enqueueTask({data:e,taskType:"stringify"})}async cleanup(){const e=this.workerQueues.map((({workerQueue:e})=>e.cleanup()));await Promise.allSettled(e)}}const d=(r,s={format:"bru"})=>{if("bru"===s.format)return((r,s=!1)=>{try{const a=s?r:t(r);let o=e.get(a,"meta.type");o="http"===o?"http-request":"graphql"===o?"graphql-request":"http-request";const u=e.get(a,"meta.seq"),n={type:o,name:e.get(a,"meta.name"),seq:e.isNaN(u)?1:Number(u),settings:e.get(a,"settings",{}),tags:e.get(a,"meta.tags",[]),request:{method:e.upperCase(e.get(a,"http.method")),url:e.get(a,"http.url"),params:e.get(a,"params",[]),headers:e.get(a,"headers",[]),auth:e.get(a,"auth",{}),body:e.get(a,"body",{}),script:e.get(a,"script",{}),vars:e.get(a,"vars",{}),assertions:e.get(a,"assertions",[]),tests:e.get(a,"tests",""),docs:e.get(a,"docs","")}};return n.request.auth.mode=e.get(a,"http.auth","none"),n.request.body.mode=e.get(a,"http.body","none"),n}catch(e){return Promise.reject(e)}})(r);throw new Error(`Unsupported format: ${s.format}`)},q=(t,s={format:"bru"})=>{if("bru"===s.format)return(t=>{try{let s=e.get(t,"type");s="http-request"===s?"http":"graphql-request"===s?"graphql":"http";const a=e.get(t,"seq"),o={meta:{name:e.get(t,"name"),type:s,seq:e.isNaN(a)?1:Number(a),tags:e.get(t,"tags",[])},http:{method:e.lowerCase(e.get(t,"request.method")),url:e.get(t,"request.url"),auth:e.get(t,"request.auth.mode","none"),body:e.get(t,"request.body.mode","none")},params:e.get(t,"request.params",[]),headers:e.get(t,"request.headers",[]),auth:e.get(t,"request.auth",{}),body:e.get(t,"request.body",{}),script:e.get(t,"request.script",{}),vars:{req:e.get(t,"request.vars.req",[]),res:e.get(t,"request.vars.res",[])},assertions:e.get(t,"request.assertions",[]),tests:e.get(t,"request.tests",""),settings:e.get(t,"settings",{}),docs:e.get(t,"request.docs","")};return r(o)}catch(e){throw e}})(t);throw new Error(`Unsupported format: ${s.format}`)};let y=null;const w=()=>(y||(y=new f),y),l=async e=>{const t=w();return await t.parseRequest(e)},k=async e=>{const t=w();return await t.stringifyRequest(e)},b=(e,t={format:"bru"})=>{if("bru"===t.format)return m(e);throw new Error(`Unsupported format: ${t.format}`)},P=(e,t={format:"bru"})=>{if("bru"===t.format)return c(e,!1);throw new Error(`Unsupported format: ${t.format}`)},v=(e,t={format:"bru"})=>{if("bru"===t.format)return m(e);throw new Error(`Unsupported format: ${t.format}`)},x=(e,t={format:"bru"})=>{if("bru"===t.format)return c(e,!0);throw new Error(`Unsupported format: ${t.format}`)},Q=(t,r={format:"bru"})=>{if("bru"===r.format)return(t=>{try{const r=o(t);return r&&r.variables&&r.variables.length&&e.each(r.variables,(e=>e.type="text")),r}catch(e){return Promise.reject(e)}})(t);throw new Error(`Unsupported format: ${r.format}`)},N=(e,t={format:"bru"})=>{if("bru"===t.format)return(e=>{try{return u(e)}catch(e){throw e}})(e);throw new Error(`Unsupported format: ${t.format}`)},S=e=>n(e);export{f as BruParserWorker,b as parseCollection,S as parseDotEnv,Q as parseEnvironment,v as parseFolder,d as parseRequest,l as parseRequestViaWorker,P as stringifyCollection,N as stringifyEnvironment,x as stringifyFolder,q as stringifyRequest,k as stringifyRequestViaWorker};
|
|
1
|
+
import*as e from"lodash";import{bruToJsonV2 as t,jsonToBruV2 as r,collectionBruToJson as s,jsonToCollectionBru as a,bruToEnvJsonV2 as o,envJsonToBruV2 as n,dotenvToJson as u}from"@usebruno/lang";import{Worker as i}from"node:worker_threads";import c from"node:path";const h=[{type:"authorization",sendIn:"headers",source:"oauth2_additional_parameters_auth_req_headers"},{type:"authorization",sendIn:"queryparams",source:"oauth2_additional_parameters_auth_req_queryparams"},{type:"token",sendIn:"headers",source:"oauth2_additional_parameters_access_token_req_headers"},{type:"token",sendIn:"queryparams",source:"oauth2_additional_parameters_access_token_req_queryparams"},{type:"token",sendIn:"body",source:"oauth2_additional_parameters_access_token_req_bodyvalues"},{type:"refresh",sendIn:"headers",source:"oauth2_additional_parameters_refresh_token_req_headers"},{type:"refresh",sendIn:"queryparams",source:"oauth2_additional_parameters_refresh_token_req_queryparams"},{type:"refresh",sendIn:"body",source:"oauth2_additional_parameters_refresh_token_req_bodyvalues"}],p=(e,t)=>e?.length?e.map((e=>({...e,sendIn:t}))):[],d=(e,t,r)=>{if(!((e,t)=>"authorization"===e?"authorization_code"===t||"implicit"===t:"token"!==e&&"refresh"!==e||"implicit"!==t)(t,r))return[];const s=h.filter((e=>e.type===t)),a=[];for(const t of s){const r=e[t.source],s=p(r,t.sendIn);a.push(...s)}return a},m=e=>{const t=e.auth.oauth2.grantType,r={};try{const s=["authorization","token","refresh"];for(const a of s){const s=d(e,a,t);s.length>0&&(r[a]=s)}}catch(e){console.error(e),console.error("Error while getting the oauth2 additional parameters!")}return r},g=(t,r=!1)=>{try{const a=r?t:s(t),o={request:{headers:e.get(a,"headers",[]),auth:e.get(a,"auth",{}),script:e.get(a,"script",{}),vars:e.get(a,"vars",{}),tests:e.get(a,"tests","")},settings:e.get(a,"settings",{}),docs:e.get(a,"docs","")};if(a.meta&&(o.meta={name:a.meta.name},void 0!==a.meta.seq)){const e=a.meta.seq;o.meta.seq=isNaN(e)?1:Number(e)}const n=a?.auth?.oauth2?.grantType;if(n){const e=m(a);Object.keys(e).length>0&&(o.request.auth.oauth2.additionalParameters=e)}return o}catch(e){return Promise.reject(e)}},f=(t,r)=>{try{const s={headers:e.get(t,"request.headers",[]),script:{req:e.get(t,"request.script.req",""),res:e.get(t,"request.script.res","")},vars:{req:e.get(t,"request.vars.req",[]),res:e.get(t,"request.vars.res",[])},tests:e.get(t,"request.tests",""),auth:e.get(t,"request.auth",{}),docs:e.get(t,"docs","")};if(t?.meta&&(s.meta={name:t.meta.name},void 0!==t.meta.seq)){const e=t.meta.seq;s.meta.seq=isNaN(e)?1:Number(e)}return r||(s.auth=e.get(t,"request.auth",{})),a(s)}catch(e){throw e}};class y{constructor(){this.queue=[],this.isProcessing=!1,this.workers={}}async getWorkerForScriptPath(e){this.workers||(this.workers={});let t=this.workers[e];return t&&-1!==t.threadId||(this.workers[e]=t=new i(e)),t}async enqueue(e){const{priority:t,scriptPath:r,data:s,taskType:a}=e;return new Promise(((e,o)=>{this.queue.push({priority:t,scriptPath:r,data:s,taskType:a,resolve:e,reject:o}),this.queue?.sort(((e,t)=>e?.priority-t?.priority)),this.processQueue()}))}async processQueue(){if(this.isProcessing||0===this.queue.length)return;this.isProcessing=!0;const{scriptPath:e,data:t,taskType:r,resolve:s,reject:a}=this.queue.shift();try{const a=await this.runWorker({scriptPath:e,data:t,taskType:r});s?.(a)}catch(e){a?.(e)}finally{this.isProcessing=!1,this.processQueue()}}async runWorker({scriptPath:e,data:t,taskType:r}){return new Promise((async(s,a)=>{let o=await this.getWorkerForScriptPath(e);const n=e=>{o.off("message",n),o.off("error",u),o.off("exit",i),e?.error?a(new Error(e?.error)):s(e)},u=e=>{o.off("message",n),o.off("error",u),o.off("exit",i),a(e)},i=t=>{o.off("message",n),o.off("error",u),o.off("exit",i),delete this.workers[e],a(new Error(`Worker stopped with exit code ${t}`))};o.on("message",n),o.on("error",u),o.on("exit",i),o.postMessage({taskType:r,data:t})}))}async cleanup(){const e=Object.values(this.workers).map((e=>-1!==e.threadId?e.terminate():Promise.resolve()));await Promise.allSettled(e),this.workers={}}}const q=[{maxSize:.005},{maxSize:.1},{maxSize:1},{maxSize:10},{maxSize:100}];class l{constructor(){this.workerQueues=q?.map((e=>({maxSize:e?.maxSize,workerQueue:new y})))}getWorkerQueue(e){const t=this.workerQueues.find((t=>t.maxSize>=e));return t?.workerQueue??this.workerQueues[this.workerQueues.length-1].workerQueue}async enqueueTask({data:e,taskType:t}){const r=(e=>("string"==typeof e?Buffer.byteLength(e,"utf8"):Buffer.byteLength(JSON.stringify(e),"utf8"))/1048576)(e),s=this.getWorkerQueue(r),a=c.join(__dirname,"./workers/worker-script.js");return s.enqueue({data:e,priority:r,scriptPath:a,taskType:t})}async parseRequest(e){return this.enqueueTask({data:e,taskType:"parse"})}async stringifyRequest(e){return this.enqueueTask({data:e,taskType:"stringify"})}async cleanup(){const e=this.workerQueues.map((({workerQueue:e})=>e.cleanup()));await Promise.allSettled(e)}}const b=(r,s={format:"bru"})=>{if("bru"===s.format)return((r,s=!1)=>{try{const a=s?r:t(r);let o=e.get(a,"meta.type");switch(o){case"http":default:o="http-request";break;case"graphql":o="graphql-request";break;case"grpc":o="grpc-request"}const n=e.get(a,"meta.seq"),u={type:o,name:e.get(a,"meta.name"),seq:e.isNaN(n)?1:Number(n),settings:e.get(a,"settings",{}),tags:e.get(a,"meta.tags",[]),request:{method:"grpc-request"===o?e.get(a,"grpc.method",""):e.upperCase(e.get(a,"http.method")),url:e.get(a,"grpc-request"===o?"grpc.url":"http.url"),headers:"grpc-request"===o?e.get(a,"metadata",[]):e.get(a,"headers",[]),auth:e.get(a,"auth",{}),body:e.get(a,"body",{}),script:e.get(a,"script",{}),vars:e.get(a,"vars",{}),assertions:e.get(a,"assertions",[]),tests:e.get(a,"tests",""),docs:e.get(a,"docs","")}};if("grpc-request"===o){const t=e.get(a,"grpc.methodType");t&&(u.request.methodType=t);const r=e.get(a,"grpc.protoPath");r&&(u.request.protoPath=r),u.request.auth.mode=e.get(a,"grpc.auth","none"),u.request.body=e.get(a,"body",{mode:"grpc",grpc:e.get(a,"body.grpc",[{name:"message 1",content:"{}"}])})}else u.request.params=e.get(a,"params",[]),u.request.auth.mode=e.get(a,"http.auth","none"),u.request.body.mode=e.get(a,"http.body","none");const i=a?.auth?.oauth2?.grantType;if(i){const e=m(a);Object.keys(e||{}).length>0&&(u.request.auth.oauth2.additionalParameters=e)}return u}catch(e){throw e}})(r);throw new Error(`Unsupported format: ${s.format}`)},w=(e,t={format:"bru"})=>{if("bru"===t.format)return(e=>{try{const t=["body:json {","body:text {","body:xml {","body:sparql {","body:graphql {"];e=(e||"").replace(/\r\n/g,"\n");const r="\n",s=e=>e&&e.length?e.split(r).map((e=>e.replace(/^ /,""))).join(r):e||"";let a=e.split(`${r}}${r}`);a=a.filter(Boolean).map((e=>e.trim()));const o=a.filter((e=>t.some((t=>e.startsWith(t))))).reduce(((e,t)=>{const a=t.split(r)[0].split("body:")[1].split(/\s/)[0],o=t.split(r).slice(1).join(r),n=s(o);return e[a]=n,e}),{});return{bruFileStringWithRedactedBody:a.filter((e=>!t.some((t=>e.startsWith(t))))).join(`${r}}${r}${r}`).concat(`${r}}${r}`),extractedBodyContent:o}}catch(t){return console.error("Error parsing and redacting body data:",t),{bruFileStringWithRedactedBody:e,extractedBodyContent:{}}}})(e);throw new Error(`Unsupported format: ${t.format}`)},k=(t,s={format:"bru"})=>{if("bru"===s.format)return(t=>{try{let s=e.get(t,"type");switch(s){case"http-request":default:s="http";break;case"graphql-request":s="graphql";break;case"grpc-request":s="grpc"}const a=e.get(t,"seq"),o={meta:{name:e.get(t,"name"),type:s,seq:e.isNaN(a)?1:Number(a),tags:e.get(t,"tags",[])}};if("http"===s||"graphql"===s)o.http={method:e.lowerCase(e.get(t,"request.method")),url:e.get(t,"request.url"),auth:e.get(t,"request.auth.mode","none"),body:e.get(t,"request.body.mode","none")},o.params=e.get(t,"request.params",[]),o.body=e.get(t,"request.body",{mode:"json",json:"{}"});else if("grpc"===s){o.grpc={url:e.get(t,"request.url"),auth:e.get(t,"request.auth.mode","none"),body:e.get(t,"request.body.mode","grpc")};const r=e.get(t,"request.method"),s=e.get(t,"request.methodType"),a=e.get(t,"request.protoPath");r&&(o.grpc.method=r),s&&(o.grpc.methodType=s),a&&(o.grpc.protoPath=a),o.body=e.get(t,"request.body",{mode:"grpc",grpc:e.get(t,"request.body.grpc",[{name:"message 1",content:"{}"}])})}return"grpc"===s?o.metadata=e.get(t,"request.headers",[]):o.headers=e.get(t,"request.headers",[]),o.auth=e.get(t,"request.auth",{}),o.script=e.get(t,"request.script",{}),o.vars={req:e.get(t,"request.vars.req",[]),res:e.get(t,"request.vars.res",[])},o.assertions=e.get(t,"request.assertions",[]),o.tests=e.get(t,"request.tests",""),o.settings=e.get(t,"settings",{}),o.docs=e.get(t,"request.docs",""),r(o)}catch(e){throw e}})(t);throw new Error(`Unsupported format: ${s.format}`)};let _=null;const P=()=>(_||(_=new l),_),v=async e=>{const t=P();return await t.parseRequest(e)},T=async e=>{const t=P();return await t.stringifyRequest(e)},x=(e,t={format:"bru"})=>{if("bru"===t.format)return g(e);throw new Error(`Unsupported format: ${t.format}`)},$=(e,t={format:"bru"})=>{if("bru"===t.format)return f(e,!1);throw new Error(`Unsupported format: ${t.format}`)},j=(e,t={format:"bru"})=>{if("bru"===t.format)return g(e);throw new Error(`Unsupported format: ${t.format}`)},S=(e,t={format:"bru"})=>{if("bru"===t.format)return f(e,!0);throw new Error(`Unsupported format: ${t.format}`)},Q=(t,r={format:"bru"})=>{if("bru"===r.format)return(t=>{try{const r=o(t);return r&&r.variables&&r.variables.length&&e.each(r.variables,(e=>e.type="text")),r}catch(e){return Promise.reject(e)}})(t);throw new Error(`Unsupported format: ${r.format}`)},z=(e,t={format:"bru"})=>{if("bru"===t.format)return(e=>{try{return n(e)}catch(e){throw e}})(e);throw new Error(`Unsupported format: ${t.format}`)},E=e=>u(e);export{l as BruParserWorker,x as parseCollection,E as parseDotEnv,Q as parseEnvironment,j as parseFolder,b as parseRequest,w as parseRequestAndRedactBody,v as parseRequestViaWorker,$ as stringifyCollection,z as stringifyEnvironment,S as stringifyFolder,k as stringifyRequest,T as stringifyRequestViaWorker};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|