@http-forge/core 0.6.24 → 0.6.25

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/index.js CHANGED
@@ -49,7 +49,7 @@ ${i}
49
49
 
50
50
  // --- Next Script ---
51
51
 
52
- `)}function Vu(t,e){return JSON.stringify(t)!==JSON.stringify(e)}function Ja(t){return t.map(e=>{let r=e.args.map(n=>{if(typeof n=="object")try{return JSON.stringify(n,null,2)}catch{return String(n)}return String(n)}).join(" ");return`[${e.level}] ${r}`})}function SP(t){return{log:(...e)=>t.push({level:"log",args:e}),info:(...e)=>t.push({level:"info",args:e}),warn:(...e)=>t.push({level:"warn",args:e}),error:(...e)=>t.push({level:"error",args:e})}}function Km(t){let e=[],r=(n,i)=>{try{let s=i();if(s&&typeof s.then=="function"){let o=s.then(()=>{t.push({name:n,passed:!0})},l=>{t.push({name:n,passed:!1,message:l.message||String(l)})});e.push(o)}else t.push({name:n,passed:!0})}catch(s){t.push({name:n,passed:!1,message:s.message})}};return r.skip=(n,i)=>{t.push({name:n,passed:!0,skipped:!0})},r.fail=n=>{t.push({name:n||"Failed test",passed:!1,message:n||"pm.test.fail()"})},r.index=()=>t.length,r._pendingTests=e,r}function Qm(t){let e={};for(let[r,n]of Object.entries(t))e[r]=Array.isArray(n)?n.join(", "):n;return e}function Zm(t,e,r){let n;if(r)try{n=new URL(r).hostname}catch{n=void 0}let i=_t.parseCookieHeaders(t||{},n);return i.length>0?i:Array.isArray(e)&&e.length>0?e.filter(s=>s&&s.name).map(s=>({name:s.name,value:s.value,domain:s.domain??n,path:s.path,expires:s.expires,maxAge:s.maxAge,httpOnly:s.httpOnly,secure:s.secure,sameSite:s.sameSite})):[]}var hd=le(()=>{"use strict";ka()});function $z(t){let e=null;try{e=new URL(t)}catch{}return{toString(){return t},valueOf(){return t},[Symbol.toPrimitive](n){return n==="number"?NaN:t},getHost(){return e?e.hostname:""},getPath(){return e?e.pathname:t},getPathWithQuery(){return e?e.pathname+e.search:t},getQueryString(){return e?e.search.startsWith("?")?e.search.slice(1):e.search:""},getRemote(){if(!e)return"";let n=e.port||(e.protocol==="https:"?"443":"80");return`${e.hostname}:${n}`},getOAuth1BaseUrl(){return e?`${e.protocol}//${e.host}${e.pathname}`:t},get protocol(){return e?.protocol?.replace(":","")||""},get host(){return e?e.hostname.split("."):[]},get port(){return e?.port||""},get path(){return e?e.pathname.split("/").filter(Boolean):[]},get hash(){return e?.hash?.replace("#","")||""},query:{toObject(){if(!e)return{};let n={};return e.searchParams.forEach((i,s)=>{n[s]=i}),n},has(n){return e?e.searchParams.has(n):!1},get(n){return e?e.searchParams.get(n):void 0},each(n){e&&e.searchParams.forEach((i,s)=>n({key:s,value:i}))}}}}var V0,Wu,W0=le(()=>{"use strict";V0=ve(require("vm"));vP();Ym();hd();Wu=class{constructor(e,r){this.deps=e;this.initialContext=r;this.timerRegistry=yP(n=>{let i=n instanceof Error?n.message:String(n);this.consoleMessages.push({level:"error",args:[`Uncaught error in async callback: ${i}`]})}),this.initializeSession()}deps;initialContext;vmContext=null;ctx=null;modifiedRequest=null;assertions=[];consoleMessages=[];_variables={};_collectionVariables={};_globals={};_environmentVariables={};_liveEnvironmentScope=null;_liveGlobalsScope=null;_liveCollectionScope=null;_nextRequest=void 0;_skipRequest=!1;_visualizerData=void 0;timerRegistry;initializeSession(){this.modifiedRequest={url:this.initialContext.request.url,method:this.initialContext.request.method,headers:{...this.initialContext.request.headers},body:this.initialContext.request.body?{...this.initialContext.request.body}:null,params:this.initialContext.request.params?{...this.initialContext.request.params}:{},query:this.initialContext.request.query?{...this.initialContext.request.query}:{}},this.assertions=[],this.ctx=this.createSharedContext(),this.consoleMessages=[];let e=this,r={log:(...n)=>{e.consoleMessages.push({level:"log",args:n})},info:(...n)=>{e.consoleMessages.push({level:"info",args:n})},warn:(...n)=>{e.consoleMessages.push({level:"warn",args:n})},error:(...n)=>{e.consoleMessages.push({level:"error",args:n})}};this.vmContext=this.deps.createVM(this.ctx,r,this.timerRegistry.timers)}createSharedContext(){let e=this.initialContext,r=this.modifiedRequest,n=this.deps.createCommonContext(e,"prerequest");this._variables={...e.variables},this._collectionVariables={...e.collectionVariables||{}},this._globals={...e.globals||{}},this._environmentVariables={...e.environmentVariables||{}},this._liveEnvironmentScope=n.environment,this._liveGlobalsScope=n.globals,this._liveCollectionScope=n.collectionVariables;let i;try{i=new URL(e.request.url).hostname}catch{}let s={get:l=>e.cookieJar?e.cookieJar.get(l,i)?.value:void 0,set:(l,c)=>{e.cookieJar&&e.cookieJar.set({name:l,value:c,domain:i})},has:l=>e.cookieJar?e.cookieJar.has(l,i):!1,list:()=>e.cookieJar?e.cookieJar.getAll(i).map(l=>({name:l.name,value:l.value})):[],toObject:()=>{if(!e.cookieJar)return{};let l=e.cookieJar.getAll(i),c={};for(let d of l)c[d.name]=d.value;return c},jar:()=>{let l=e.cookieJar,c=d=>{if(d==null)return;let p=typeof d=="string"?d:typeof d=="object"||typeof d=="number"||typeof d=="boolean"?String(d):void 0;if(!p)return;let m=p.trim();if(m)try{return new URL(m).hostname}catch{return m}};return{getAll(d,p){try{if(!l){p(null,[]);return}let m=c(d),y=l.getAll(m).map(b=>({name:b.name,value:b.value,domain:b.domain,path:b.path,httpOnly:b.httpOnly,secure:b.secure}));p(null,y)}catch(m){p(m,[])}},get(d,p,m){try{if(!l){m(null,void 0);return}let y=c(d),b=l.get(p,y);m(null,b?{name:b.name,value:b.value,domain:b.domain}:void 0)}catch(y){m(y,void 0)}},set(d,p,m,y){try{if(!l){(y||m)?.(null);return}let b=c(d);typeof p=="string"&&typeof m=="string"?(l.set({name:p,value:m,domain:b}),y?.(null)):typeof p=="object"&&(l.set({...p,domain:b}),m?.(null))}catch(b){(y||m)?.(b)}},unset(d,p,m){try{if(!l){m?.(null);return}let y=c(d);l.delete(p,y),m?.(null)}catch(y){m?.(y)}},clear(d,p){try{let m=typeof d=="function"?d:p;if(!l){m?.(null);return}let y=typeof d=="function"?void 0:c(d);y&&typeof l.clearDomain=="function"?l.clearDomain(y):l.clear(),m?.(null)}catch(m){(typeof d=="function"?d:p)?.(m)}}}},remove:l=>{e.cookieJar&&e.cookieJar.delete(l,i)},unset:l=>{e.cookieJar&&e.cookieJar.delete(l,i)},clear:()=>{e.cookieJar&&e.cookieJar.clear()}},o=this;return{request:this.createRequestObject(r,e),response:null,test:Km(this.assertions),expect:za,cookies:s,execution:{setNextRequest(l){o._nextRequest=l},skipRequest(){o._skipRequest=!0},runRequest(l,c){let p=(async()=>{if(typeof n.sendRequest!="function")throw new Error("pm.execution.runRequest is not available \u2014 HTTP service not configured.");let m=typeof l=="string"?{url:l,method:"GET"}:l,y=await n.sendRequest(m),b=Array.isArray(y?.cookies)?y.cookies.filter(v=>v?.name):[],q=y?.body,x=0;if(typeof q=="string")x=Buffer.byteLength(q,"utf8");else if(Buffer.isBuffer(q))x=q.length;else if(q!=null)try{x=Buffer.byteLength(JSON.stringify(q),"utf8")}catch{}return dd({executedRequest:null,status:y?.status??0,statusText:y?.statusText??"",headers:y?.headers??{},body:q,cookies:b,responseTime:y?.time,responseSize:x})})();if(typeof c=="function"){p.then(m=>c(null,m),m=>c(m));return}return p},location:{current:n.info?.requestName||"",currentRequestName:n.info?.requestName||"",eventName:"prerequest",toString(){return n.info?.requestName||""}}},setNextRequest(l){o._nextRequest=l},visualizer:{set(l,c){o._visualizerData={template:l,data:c}},clear(){o._visualizerData=void 0}},...n,info:{...n.info||{},eventName:"prerequest",requestName:n.info?.requestName||void 0,requestId:n.info?.requestId||void 0,iteration:e.iteration||0,iterationCount:e.iterationCount||1}}}createRequestObject(e,r){let n=l=>{if(!l)return"none";switch(l){case"raw":return"raw";case"form-data":return"formdata";case"x-www-form-urlencoded":return"urlencoded";case"binary":return"file";case"graphql":return"graphql";case"none":return"none";default:return"raw"}},i=l=>{if(!l)return"none";switch(l){case"raw":return"raw";case"formdata":return"form-data";case"urlencoded":return"x-www-form-urlencoded";case"file":return"binary";case"graphql":return"graphql";case"none":return"none";default:return"raw"}},s={...e.headers,add:l=>{l&&l.key&&(e.headers[l.key]=l.value||"")},get:l=>{for(let[c,d]of Object.entries(e.headers))if(c.toLowerCase()===l.toLowerCase())return d},has:l=>{for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.toLowerCase())return!0;return!1},remove:l=>{for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.toLowerCase()){delete e.headers[c];break}},update:l=>{if(l&&l.key){for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.key.toLowerCase()){e.headers[c]=l.value||"";return}}},upsert:l=>{if(l&&l.key){for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.key.toLowerCase()){e.headers[c]=l.value||"";return}e.headers[l.key]=l.value||""}},toObject:()=>{let l={};for(let[c,d]of Object.entries(e.headers))typeof d=="string"&&(l[c]=d);return l},each:l=>{for(let[c,d]of Object.entries(e.headers))typeof d=="string"&&l({key:c,value:d})}},o={get mode(){return n(e.body?.type)},set mode(l){let c=i(l);e.body?e.body.type=c:e.body={type:c,content:null}},get raw(){let l=e.body?.content;return typeof l=="string"?l:l&&typeof l=="object"?JSON.stringify(l):""},set raw(l){e.body?(e.body.type="raw",e.body.content=l):e.body={type:"raw",content:l}},get formdata(){return e.body?.type==="form-data"&&Array.isArray(e.body.content)?e.body.content:[]},get urlencoded(){return e.body?.type==="x-www-form-urlencoded"&&Array.isArray(e.body.content)?e.body.content:[]},get graphql(){return e.body?.type==="graphql"?e.body.content:null},get file(){return e.body?.type==="binary"?e.body.content:null}};return{get url(){return $z(e.url)},set url(l){e.url=typeof l=="string"?l:String(l)},get method(){return e.method},set method(l){e.method=l},headers:s,get body(){return o},set body(l){if(l==null)e.body=null;else if(typeof l=="string")e.body={type:"raw",content:l};else if(typeof l=="object")if(l.type||l.mode||l.content!==void 0){let c=l.mode?i(l.mode):l.type||"raw";e.body={type:c,format:l.format,content:l.content}}else e.body={type:"raw",content:l}},get params(){return e.params||{}},set params(l){e.params=l||{}},get query(){return e.query||{}},set query(l){e.query=l||{}},get auth(){return r.request?.auth||null},set auth(l){r.request&&(r.request.auth=l)},get certificate(){return r.request?.certificate||null},set certificate(l){r.request&&(r.request.certificate=l)},get description(){return r.request?.description||null},set description(l){r.request&&(r.request.description=l)},get name(){return r.request?.name||null},set name(l){r.request&&(r.request.name=l)},get id(){return r.request?.id||null},get disabled(){return r.request?.disabled||!1},set disabled(l){r.request&&(r.request.disabled=l)},get messages(){return r.request?.messages||[]},get methodPath(){return r.request?.methodPath||null},get metadata(){return r.request?.metadata||[]},getHeaders(l){let c={};for(let[d,p]of Object.entries(e.headers))typeof p=="string"&&(c[d]=p);return c},addQueryParams(l){if(typeof l=="string"){let c=new URLSearchParams(l);for(let[d,p]of c)e.query||(e.query={}),e.query[d]=p}else Array.isArray(l)&&(e.query||(e.query={}),l.forEach(c=>{c.key&&(e.query[c.key]=c.value||"")}))},removeQueryParams(l){e.query&&(typeof l=="string"?delete e.query[l]:Array.isArray(l)&&l.forEach(c=>{let d=typeof c=="string"?c:c.key;d&&delete e.query[d]}))},authorizeUsing(l,c){r.request&&(typeof l=="string"?(r.request.auth||(r.request.auth={}),r.request.auth.type=l,c&&(r.request.auth.parameters=c)):typeof l=="object"&&(r.request.auth=l))},clone(){return{url:e.url,method:e.method,headers:{...e.headers},body:e.body?{...e.body}:null,params:e.params?{...e.params}:{},query:e.query?{...e.query}:{},auth:r.request?.auth,certificate:r.request?.certificate,description:r.request?.description,name:r.request?.name,id:r.request?.id,disabled:r.request?.disabled,metadata:r.request?.metadata,messages:r.request?.messages,methodPath:r.request?.methodPath}},describe(l,c){r.request&&(r.request.description={content:l,type:c||"text/plain"})},setHeader(l,c){e.headers[l]=c},addHeader(l,c){typeof l=="object"&&l!==null?e.headers[l.key]=l.value:e.headers[l]=c},removeHeader(l){delete e.headers[l]},setBody(l,c,d){e.body={type:c||e.body?.type||"raw",format:d||e.body?.format,content:l}}}}injectLegacyGlobals(e,r){let n=this.vmContext;if(!n)return;let i=this.initialContext,s=e==="test"&&r?.executedRequest?r.executedRequest:this.modifiedRequest,o={};for(let[b,q]of Object.entries(s?.headers||{}))typeof q=="string"&&(o[b]=q);let l=s?.body,c=l==null?null:typeof l=="object"&&"content"in l?l.content:l,d=i.request;if(n.request={id:d?.id??"",name:d?.name??"",description:d?.description??"",url:typeof s?.url=="string"?s.url:String(s?.url??""),method:s?.method??"GET",headers:o,data:c},n.environment=this._liveEnvironmentScope?.toObject?.()??{...this._environmentVariables},n.globals=this._liveGlobalsScope?.toObject?.()??{...this._globals},n.data={...i.iterationData||{}},typeof n.iteration!="number"&&(n.iteration=0),e!=="test"||!r)return;let p=r.body;n.responseBody=p==null?"":typeof p=="string"?p:JSON.stringify(p);let m=r.statusText||"";n.responseCode={code:r.status,name:m,detail:m},n.responseHeaders={...r.headers||{}},n.responseTime=r.responseTime??0,n.responseCookies=(r.cookies||[]).map(b=>({...b}));let y=this;n.tests=new Proxy({},{set(b,q,x){return y.assertions.push({name:String(q),passed:!!x,message:x?void 0:`"${String(q)}" was false`}),!0}})}async executePreRequest(e){let r=pd(e,this.deps.isolateScripts);if(!r||!r.trim())return{success:!0};try{this.consoleMessages.length=0,this.injectLegacyGlobals("prerequest");let n=this.ctx.variables.replaceIn(r),i=this.deps.scriptTimeoutMs??5e3,s=V0.runInContext(n,this.vmContext,{timeout:i});this.deps.isolateScripts&&s&&typeof s.then=="function"&&await s,(await this.timerRegistry.drain(i)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${i}ms; pending async work was cancelled.`]});let l=Ja(this.consoleMessages),c=this.initialContext.request.body,d=!this.bodiesEqual(this.modifiedRequest.body,c);return{success:!0,modifiedRequest:{url:this.modifiedRequest.url!==this.initialContext.request.url?this.modifiedRequest.url:void 0,headers:Vu(this.modifiedRequest.headers,this.initialContext.request.headers)?this.modifiedRequest.headers:void 0,body:d?this.modifiedRequest.body:void 0,params:Vu(this.modifiedRequest.params,this.initialContext.request.params||{})?this.modifiedRequest.params:void 0,query:Vu(this.modifiedRequest.query,this.initialContext.request.query||{})?this.modifiedRequest.query:void 0},modifiedVariables:this.ctx.variables.toObject(),localVariables:this.ctx.variables.toLocalObject?.()??{},modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,consoleOutput:l.length>0?l:void 0,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}catch(n){let i=[...Ja(this.consoleMessages),`[error] Script execution failed: ${n.message}`];return{success:!1,error:n.message||"Pre-request script execution failed",consoleOutput:i,modifiedVariables:this.ctx?.variables?.toObject(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}}async executePostResponse(e,r){let n=pd(e,this.deps.isolateScripts);if(!n||!n.trim())return{testResults:[],consoleOutput:[]};try{this.consoleMessages.length=0,this.assertions.length=0,this.ctx.info.eventName="test",this.ctx.response=dd(r),this.ctx.request=this.createRequestObject(r.executedRequest,this.initialContext),this.injectLegacyGlobals("test",r);let i=this.ctx.variables.replaceIn(n),s=this.deps.scriptTimeoutMs??5e3,o=V0.runInContext(i,this.vmContext,{timeout:s});this.deps.isolateScripts&&o&&typeof o.then=="function"&&await o,this.ctx.test._pendingTests?.length>0&&(await Promise.all(this.ctx.test._pendingTests),this.ctx.test._pendingTests.length=0),(await this.timerRegistry.drain(s)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${s}ms; pending async work was cancelled.`]});let c=Ja(this.consoleMessages);return{testResults:[...this.assertions],consoleOutput:c.length>0?c:void 0,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}catch(i){this.assertions.push({name:"Script Execution",passed:!1,message:i.message||"Script execution failed"});let s=[...Ja(this.consoleMessages),`[error] Script execution failed: ${i.message}`];return{testResults:[...this.assertions],consoleOutput:s,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}}bodiesEqual(e,r){return e===r||!e&&!r?!0:!e||!r?!1:e.type===r.type&&e.format===r.format&&JSON.stringify(e.content)===JSON.stringify(r.content)}dispose(){this.timerRegistry.clearAll(),this.vmContext=null,this.ctx=null,this.assertions=[]}}});function RP(t,e){if(t)return t.split(",").map(r=>{let n=r.trim();if(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))return n.slice(1,-1);let i=Number(n);if(!isNaN(i)&&n!=="")return i;if(e&&n in e){let s=e[n],o=Number(s);return!isNaN(o)&&s!==""?o:s}return n})}function xP(t){if(typeof t=="string"&&t.charCodeAt(0)===30)try{return JSON.parse(t.slice(1))}catch{return t}return t}function Mz(t,e){if(t==="@")return"";if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);let r=t.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(r){let n=RP(r[2],e),i=Vi(r[1],n);return i!==null?i:void 0}if(e[t]!==void 0)return xP(e[t]);if(go(t)){let n=mo(t,e),i=ui(t,n);if(i!==void 0)return i}}function wP(t,e,r,n){let i=Buffer.concat([Buffer.from(t,"utf8"),n||Buffer.alloc(0)]),s=[],o=Buffer.alloc(0);for(;Buffer.concat(s).length<e+r;)o=br.createHash("md5").update(Buffer.concat([o,i])).digest(),s.push(o);let l=Buffer.concat(s);return{key:l.subarray(0,e),iv:l.subarray(e,e+r)}}function z0(t,e,r){let n=i=>t==="aes"?`aes-${i*8}-cbc`:t==="des"?"des-cbc":t==="des-ede3"?"des-ede3-cbc":t;return{encrypt(i,s,o){let l=i instanceof Qe?i.toBuffer():Buffer.from(String(i),"utf8");if(typeof s=="string"){let c=br.randomBytes(8),{key:d,iv:p}=wP(s,e,r,c),m=br.createCipheriv(n(e),d,p),y=Buffer.concat([m.update(l),m.final()]),b=Buffer.concat([Buffer.from("Salted__"),c,y]);return{ciphertext:new Qe(y),salt:new Qe(c),toString:q=>q?q.stringify(new Qe(b)):b.toString("base64")}}else{let c=s.toBuffer(),d=o?.iv&&o.iv instanceof Qe?o.iv.toBuffer():Buffer.alloc(r),p=br.createCipheriv(n(c.length),c,d);o?.padding===!1&&p.setAutoPadding(!1);let m=Buffer.concat([p.update(l),p.final()]);return{ciphertext:new Qe(m),toString:y=>y?y.stringify(new Qe(m)):m.toString("base64")}}},decrypt(i,s,o){if(typeof s=="string"){let l=typeof i=="string"?Buffer.from(i,"base64"):i.ciphertext.toBuffer(),c,d;l.subarray(0,8).toString()==="Salted__"?(d=l.subarray(8,16),c=l.subarray(16)):(d=Buffer.alloc(0),c=l);let{key:p,iv:m}=wP(s,e,r,d),y=br.createDecipheriv(n(e),p,m);return new Qe(Buffer.concat([y.update(c),y.final()]))}else{let l=s.toBuffer(),c=o?.iv&&o.iv instanceof Qe?o.iv.toBuffer():Buffer.alloc(r),d=typeof i=="string"?Buffer.from(i,"base64"):i.ciphertext?i.ciphertext.toBuffer():Buffer.from(i),p=br.createDecipheriv(n(l.length),l,c);return o?.padding===!1&&p.setAutoPadding(!1),new Qe(Buffer.concat([p.update(d),p.final()]))}}}}function Fz(){let t=r=>n=>{let i=n instanceof Qe?n.toBuffer():Buffer.from(String(n),"utf8");return new Qe(br.createHash(r).update(i).digest())},e=r=>(n,i)=>{let s=n instanceof Qe?n.toBuffer():Buffer.from(String(n),"utf8"),o=i instanceof Qe?i.toBuffer():Buffer.from(String(i),"utf8");return new Qe(br.createHmac(r,o).update(s).digest())};return{MD5:t("md5"),SHA1:t("sha1"),SHA224:t("sha224"),SHA256:t("sha256"),SHA384:t("sha384"),SHA512:t("sha512"),SHA3:t("sha3-256"),RIPEMD160:t("ripemd160"),HmacMD5:e("md5"),HmacSHA1:e("sha1"),HmacSHA256:e("sha256"),HmacSHA512:e("sha512"),AES:z0("aes",32,16),DES:z0("des",8,8),TripleDES:z0("des-ede3",24,8),PBKDF2(r,n,i){let s=r instanceof Qe?r.toBuffer():Buffer.from(String(r),"utf8"),o=n instanceof Qe?n.toBuffer():Buffer.from(String(n),"utf8"),l=(i?.keySize||4)*4,c=i?.iterations||1;return new Qe(br.pbkdf2Sync(s,o,c,l,"sha1"))},enc:{Base64:{stringify:r=>(r instanceof Qe?r.toBuffer():Buffer.from(String(r))).toString("base64"),parse:r=>Qe.fromBase64(r)},Utf8:{stringify:r=>(r instanceof Qe?r.toBuffer():Buffer.from(String(r))).toString("utf8"),parse:r=>Qe.fromUtf8(r)},Hex:{stringify:r=>(r instanceof Qe?r.toBuffer():Buffer.from(String(r))).toString("hex"),parse:r=>Qe.fromHex(r)},Latin1:{stringify:r=>(r instanceof Qe?r.toBuffer():Buffer.from(String(r))).toString("latin1"),parse:r=>new Qe(Buffer.from(r,"latin1"))},Utf16:{stringify:r=>(r instanceof Qe?r.toBuffer():Buffer.from(String(r))).toString("utf16le"),parse:r=>new Qe(Buffer.from(r,"utf16le"))},Utf16BE:{stringify:r=>(r instanceof Qe?r.toBuffer():Buffer.from(String(r))).swap16().toString("utf16le"),parse:r=>new Qe(Buffer.from(r,"utf16le").swap16())}},lib:{WordArray:{create:r=>r?typeof r=="string"?new Qe(Buffer.from(r,"utf8")):Buffer.isBuffer(r)?new Qe(r):new Qe(Buffer.from(String(r))):new Qe(Buffer.alloc(0)),random:r=>new Qe(br.randomBytes(r))}},pad:{Pkcs7:{_name:"pkcs7"},NoPadding:{_name:"nopadding"},ZeroPadding:{_name:"zeropadding"}},mode:{CBC:{_name:"cbc"},ECB:{_name:"ecb"}}}}var br,Nz,_P,Qe,Ki,md=le(()=>{"use strict";br=ve(require("crypto")),Nz=ve(require("querystring")),_P=ve(require("vm"));om();Pf();um();B0();W0();Ym();Qe=class t{_buffer;constructor(e){this._buffer=typeof e=="string"?Buffer.from(e,"utf8"):e}toString(e){return e?e.stringify(this):this._buffer.toString("hex")}toBuffer(){return this._buffer}static fromHex(e){return new t(Buffer.from(e,"hex"))}static fromBase64(e){return new t(Buffer.from(e,"base64"))}static fromUtf8(e){return new t(Buffer.from(e,"utf8"))}};Ki=class t{constructor(e,r=[],n,i="shared",s=5e3){this.httpService=e;this.secretRegistry=n;this.scopeMode=i;this.scriptTimeoutMs=s;this.moduleLoader=Jm(r)}httpService;secretRegistry;scopeMode;scriptTimeoutMs;moduleLoader;createRequestSession(e){return new Wu({createVM:this.createVM.bind(this),createCommonContext:this.createCommonContext.bind(this),isolateScripts:this.scopeMode==="isolated",scriptTimeoutMs:this.scriptTimeoutMs},e)}createVM(e,r,n){let i=this.moduleLoader.getGlobalSetupExports(),s=this.moduleLoader.createRequireFunction();e.require=s,e.vault=this.createVault();let o={ctx:e,hf:e,pm:e,console:r,...i||{},global:i,setTimeout:n?.setTimeout??setTimeout,setInterval:n?.setInterval??setInterval,clearTimeout:n?.clearTimeout??clearTimeout,clearInterval:n?.clearInterval??clearInterval,URL,URLSearchParams,Buffer,atob:l=>Buffer.from(l,"base64").toString("binary"),btoa:l=>Buffer.from(l,"binary").toString("base64"),TextEncoder,TextDecoder,crypto:br,_:s("lodash"),require:s,moment:fd(),querystring:Nz,CryptoJS:Fz(),tv4:(()=>{try{return s("tv4")}catch{return}})(),postman:{setNextRequest:l=>e.setNextRequest?.(l),setGlobalVariable:(l,c)=>e.globals?.set(l,c),getGlobalVariable:l=>e.globals?.get(l),clearGlobalVariable:l=>e.globals?.unset(l),setEnvironmentVariable:(l,c)=>e.environment?.set(l,c),getEnvironmentVariable:l=>e.environment?.get(l),clearEnvironmentVariable:l=>e.environment?.unset(l),getResponseHeader:l=>{let c=e.response?.headers?.get?.(l);return c===void 0?null:c},getResponseCookie:l=>{let c=e.response?.cookies;if(c&&typeof c[Symbol.iterator]=="function"){for(let d of c)if(d?.name&&d.name.toLowerCase()===l.toLowerCase())return{...d}}return null}},jsonStringify:(l,c,d)=>JSON.stringify(l,c,d),jsonParse:l=>JSON.parse(l),xml2Json:l=>{try{let c=this.moduleLoader.createRequireFunction()("xml2js"),d;return c.parseString(l,{explicitArray:!1},(p,m)=>{if(p)throw p;d=m}),d}catch{throw new Error("xml2Json() requires the xml2js module. Add it to your modules/package.json and run npm install.")}}};return _P.createContext(o)}createCommonContext(e,r){let n={...e.variables},i={...e.collectionVariables||{}},s={...e.globals||{}},o={...e.environmentVariables||{}},l=e.iterationData||{},c=this.createMergedVariableScope(n,o,i,s,l),d=this.createGlobalsScope(s,e.onGlobalsChange),p=this.createVariableScope(i),m=this.createEnvironmentScope(o,e.environmentName,e.onEnvironmentChange,!0),y={...m,set:(x,v)=>{let R=this.serializeValue(v);m.set(x,R),n[x]=R},unset(x){m.unset(x),delete n[x]},clear(){let x=Object.keys(o);m.clear();for(let v of x)delete n[v]}},b={...d,set:(x,v)=>{let R=this.serializeValue(v);d.set(x,R),n[x]=R},unset(x){d.unset(x),delete n[x]},clear(){let x=Object.keys(s);d.clear();for(let v of x)delete n[v]}};return b.replaceIn=c.replaceIn,p.replaceIn=c.replaceIn,y.replaceIn=c.replaceIn,{globals:b,collectionVariables:p,variables:c,environment:y,iterationData:{get:x=>l[x],has:x=>x in l,toObject:()=>({...l}),toJSON:()=>JSON.stringify(l)},sendRequest:this.createSendRequest(),expect:za,info:e.info||{eventName:r,requestName:void 0,requestId:void 0}}}static JSON_TYPE_MARKER="";serializeValue(e){return typeof e=="string"?e:e===void 0?t.JSON_TYPE_MARKER+"undefined":t.JSON_TYPE_MARKER+JSON.stringify(e)}deserializeValue(e){if(e!==void 0){if(typeof e=="string"&&e.charCodeAt(0)===30){let r=e.slice(1);if(r==="undefined")return;try{return JSON.parse(r)}catch{}}return e}}createVariableScope(e){return{get:r=>this.deserializeValue(e[r]),set:(r,n)=>{e[r]=this.serializeValue(n)},has(r){return r in e},unset(r){delete e[r]},clear(){Object.keys(e).forEach(r=>delete e[r])},toObject(){return{...e}}}}createGlobalsScope(e,r){let n=(i,s,o)=>{r&&r(i,s,o)};return{get:i=>this.deserializeValue(e[i]),set:(i,s)=>{let o=this.serializeValue(s);e[i]=o,n("set",i,o)},has(i){return i in e},unset(i){delete e[i],n("unset",i)},clear(){Object.keys(e).forEach(i=>delete e[i]),n("clear")},toObject(){return{...e}}}}createMergedVariableScope(e,r,n,i,s={}){let o={get:l=>l in e?this.deserializeValue(e[l]):l in s?s[l]:l in r?this.deserializeValue(r[l]):l in n?this.deserializeValue(n[l]):this.deserializeValue(i[l]),set:(l,c)=>{e[l]=this.serializeValue(c)},has(l){return l in e||l in s||l in r||l in r||l in n||l in i},unset(l){delete e[l]},clear(){Object.keys(e).forEach(l=>delete e[l])},toObject(){return{...i,...n,...r,...s,...e}},toLocalObject(){return{...n,...r,...s,...e}},replaceIn(l){if(!l||typeof l!="string")return l;let c=o.toObject(),d=20,p=y=>y.replace(/\{\{([^}]+)\}\}/g,(b,q)=>{let x=q.trim(),v=x.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(v)try{let E=RP(v[2],c),k=Vi(v[1],E);return k!==null?String(k):b}catch{return b}let R=xu(x);if(R){let E=Mz(R.input,c);if(E!==void 0){let k=Cu(E,R.filters,c);return k!==void 0?String(k):b}return b}if(o.has(x)){let E=o.get(x);return E===void 0?"":String(E)}if(go(x)){let E={};for(let[M,j]of Object.entries(c))E[M]=xP(j);let k=mo(x,E),P=ui(x,k);if(P!==void 0)return String(P)}return b}),m=l;for(let y=0;y<d;y++){let b=p(m);if(b===m)break;m=b}return m}};return o}createEnvironmentScope(e,r,n,i){let s=(o,l,c)=>{n&&(i?n(o,l,c):n(l||"",o==="set"?c:void 0))};return{name:r||"",get:o=>this.deserializeValue(e[o]),set:(o,l)=>{let c=this.serializeValue(l);e[o]=c,s("set",o,c)},has(o){return o in e},unset(o){delete e[o],s("unset",o)},clear(){Object.keys(e).forEach(o=>delete e[o]),s("clear")},toObject(){return{...e}}}}createVault(){let e=this.secretRegistry,r=()=>{throw new Error("pm.vault is read-only in HTTP Forge. Use environment variables or {{secret:provider/path}} tokens to manage secrets.")};return{async get(n){if(!e)throw new Error('pm.vault is not available \u2014 no secret providers are configured. Configure a provider under "secrets.providers" to use pm.vault.get().');let i=`secret:${n}`;return(await e.resolveSecretTokens(`{{${i}}}`))[i]},set:r,unset:r}}createSendRequest(){return this.httpService?(e,r)=>{let n=typeof e=="string"?{url:e,method:"GET"}:e,i=this.httpService.execute({url:n.url,method:n.method||"GET",headers:n.headers||{},body:n.body,...n});if(r){i.then(s=>r(null,s)).catch(s=>r(s,null));return}return i}:(e,r)=>{let n=new Error("sendRequest not available - HTTP service not configured");if(r){r(n,null);return}return Promise.reject(n)}}}});var CP,jz,G0,Xm,J0,eg,ln,Eo,gd=le(()=>{"use strict";CP=ve(require("fs")),jz=ve(require("http")),G0=ve(require("https")),Xm=ve(require("path")),J0=require("url"),eg=ve(require("zlib")),ln={timeout:3e4,followRedirects:!0,followOriginalMethod:!1,followAuthHeader:!1,maxRedirects:10,strictSSL:!0,decompress:!0,includeCookies:!1,tls:{},certificates:[]},Eo=class{settings;version;basePath;constructor(e,r=process.cwd()){this.settings={...ln,...e},this.basePath=r;try{this.version=require("../../package.json").version||"0.0.0"}catch{this.version="0.0.0"}this.settings.strictSSL===!1&&console.log("[NodeHttpClient] SSL verification disabled (strictSSL: false)")}async send(e){let r=this.mergeSettings(e.settings);return await this.executeInternal(e,r,0)}mergeSettings(e){return{timeout:e?.timeout??this.settings.timeout,followRedirects:e?.followRedirects??this.settings.followRedirects,followOriginalMethod:e?.followOriginalMethod??this.settings.followOriginalMethod,followAuthHeader:e?.followAuthHeader??this.settings.followAuthHeader,maxRedirects:e?.maxRedirects??this.settings.maxRedirects,strictSSL:e?.strictSSL??this.settings.strictSSL,decompress:e?.decompress??this.settings.decompress,includeCookies:e?.includeCookies??this.settings.includeCookies,tls:e?.tls??this.settings.tls??{},certificates:e?.certificates??this.settings.certificates??[]}}async executeInternal(e,r,n,i){let s=Date.now(),o=new J0.URL(e.url),l=o.protocol==="https:",c=this.sanitizeHeaders(e.headers||{});Object.keys(c).some(m=>m.toLowerCase()==="user-agent")||(c["User-Agent"]=`HttpForge/${this.version}`);let p={hostname:o.hostname,port:o.port||(l?443:80),path:o.pathname+o.search,method:e.method,headers:{...c},timeout:r.timeout||void 0};if(r.decompress&&!c["accept-encoding"]&&!c["Accept-Encoding"]&&(p.headers["Accept-Encoding"]="gzip, deflate"),l){let m=this.resolveTlsSettings(o,r),y=p;y.rejectUnauthorized=r.strictSSL;let b={rejectUnauthorized:r.strictSSL},q=this.readOptionalFile(m.caPath,"CA certificate");q&&(b.ca=q);let x=this.readOptionalFile(m.certPath,"client certificate");x&&(b.cert=x);let v=this.readOptionalFile(m.keyPath,"client private key");v&&(b.key=v);let R=this.readOptionalFile(m.pfxPath,"client pfx");R&&(b.pfx=R),m.passphrase&&(b.passphrase=m.passphrase),m.servername&&(y.servername=m.servername),y.agent=new G0.Agent(b)}return new Promise((m,y)=>{if(i?.aborted){let x=new Error("Request cancelled");x.name="AbortError",y(x);return}let q=(l?G0:jz).request(p,async x=>{let v=x.statusCode||0;if(r.followRedirects&&[301,302,303,307,308].includes(v)){if(n>=r.maxRedirects){y(new Error(`Maximum redirects (${r.maxRedirects}) exceeded`));return}let E=x.headers.location;if(!E){y(new Error("Redirect response missing Location header"));return}let k=new J0.URL(E,e.url).toString(),P=e.method;!r.followOriginalMethod&&[301,302,303].includes(v)&&(P="GET");let M={...e.headers};r.followAuthHeader||(delete M.authorization,delete M.Authorization);try{let j=await this.executeInternal({...e,url:k,method:P,headers:M,body:P==="GET"?void 0:e.body},r,n+1,i),I=Date.now();j.time=I-s,m(j)}catch(j){y(j)}return}let R=[];x.on("data",E=>R.push(E)),x.on("end",()=>{let E=Date.now(),k=Buffer.concat(R),P=x.headers["content-encoding"];if(r.decompress&&P)try{P==="gzip"?k=eg.gunzipSync(k):P==="deflate"&&(k=eg.inflateSync(k))}catch(_){console.warn("[NodeHttpClient] Decompression failed:",_)}let M=k.toString("utf-8"),j={};for(let[_,A]of Object.entries(x.headers))(typeof A=="string"||Array.isArray(A))&&(j[_]=A);let I=this.parseCookies(x.headers["set-cookie"],o.hostname);m({status:x.statusCode||0,statusText:x.statusMessage||"",headers:j,cookies:I,body:M,time:E-s,size:k.length})})});if(i&&i.addEventListener("abort",()=>{q.destroy();let x=new Error("Request cancelled");x.name="AbortError",y(x)}),q.on("error",x=>{y(x)}),q.on("timeout",()=>{q.destroy(),y(new Error("Request timeout"))}),e.body!==void 0&&e.body!==null){let x=typeof e.body=="string"?e.body:JSON.stringify(e.body);q.write(x)}q.end()})}resolveTlsSettings(e,r){let n=r.tls||{};if(!!(n.caPath||n.certPath||n.keyPath||n.pfxPath||n.servername||n.passphrase))return n;let s=this.findCertificateMapping(e,r.certificates||[]);return s?{caPath:s.caPath,certPath:s.certPath,keyPath:s.keyPath,pfxPath:s.pfxPath,passphrase:s.passphrase,servername:s.servername}:n}findCertificateMapping(e,r){if(!Array.isArray(r)||r.length===0)return;let n=e.hostname,i=e.port?Number(e.port):443,s=r.find(o=>this.mappingMatchesHost(o,n,i,!0));return s||r.find(o=>this.mappingMatchesHost(o,n,i,!1))}mappingMatchesHost(e,r,n,i){if(!e||e.enabled===!1)return!1;let s=String(e.host||"").trim().toLowerCase();if(!s||e.port!=null&&Number(e.port)!==n)return!1;let o=r.toLowerCase();if(i)return s!=="*"&&!s.startsWith("*.")&&o===s;if(s==="*")return!0;if(s.startsWith("*.")){let l=s.slice(2);return o===l||o.endsWith(`.${l}`)}return o===s}readOptionalFile(e,r){if(!e)return;let n=Xm.isAbsolute(e)?e:Xm.resolve(this.basePath,e);try{return CP.readFileSync(n)}catch(i){throw new Error(`[NodeHttpClient] Failed to read ${r} file at ${n}: ${i?.message||"Unknown error"}`)}}sanitizeHeaderValue(e){return e?String(e).replace(/[\u201C\u201D\u201E\u201F\u2033\u2036]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032\u2035]/g,"'").replace(/[\x00-\x08\x0A-\x1F\x7F]/g,""):""}sanitizeHeaders(e){let r={};for(let[n,i]of Object.entries(e))r[n]=this.sanitizeHeaderValue(String(i));return r}parseCookies(e,r){return e?e.map(n=>{let i=n.split(";").map(p=>p.trim()),[s,...o]=i,[l,c]=s.split("="),d={name:l.trim(),value:c?.trim()||"",domain:r};for(let p of o){let[m,y]=p.split("=");switch(m.toLowerCase().trim()){case"domain":d.domain=y?.trim();break;case"path":d.path=y?.trim();break;case"expires":d.expires=y?.trim();break;case"httponly":d.httpOnly=!0;break;case"secure":d.secure=!0;break}}return d}):[]}}});var Y0,qo,tg=le(()=>{"use strict";Y0={json:"application/json",xml:"application/xml",html:"text/html",text:"text/plain",javascript:"application/javascript",css:"text/css","x-www-form-urlencoded":"application/x-www-form-urlencoded","form-data":"multipart/form-data",graphql:"application/json"},qo=class{sanitizeHeaderValue(e){return e?String(e).replace(/[\u201C\u201D\u201E\u201F\u2033\u2036]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032\u2035]/g,"'").replace(/[\x00-\x08\x0A-\x1F\x7F]/g,""):""}sanitizeHeaders(e){let r={};for(let[n,i]of Object.entries(e))r[n]=this.sanitizeHeaderValue(String(i));return r}encodeBody(e){if(!e||e.type==="none")return null;let{type:r,content:n}=e;switch(r){case"x-www-form-urlencoded":return this.encodeUrlEncodedBody(n);case"form-data":return n;case"graphql":return this.encodeGraphQLBody(n);case"raw":return n;default:return n}}encodeUrlEncodedBody(e){if(Array.isArray(e)){let r=new URLSearchParams;for(let n of e)n.enabled!==!1&&n.key&&r.append(n.key,n.value||"");return r.toString()}return typeof e=="string"?e:String(e)}encodeGraphQLBody(e){if(typeof e=="string")try{e=JSON.parse(e)}catch{return e}if(typeof e=="object"&&e!==null&&e.query){let r=e.variables;if(typeof r=="string")try{r=r.trim()?JSON.parse(r):void 0}catch{r=void 0}return JSON.stringify({query:e.query,...r!=null?{variables:r}:{},...e.operationName?{operationName:e.operationName}:{}})}return JSON.stringify(e)}setContentTypeHeader(e,r,n){if(Object.keys(e).some(o=>o.toLowerCase()==="content-type"))return;if(n){e["Content-Type"]=n;return}if(!r||r.type==="none")return;let s;switch(r.type){case"x-www-form-urlencoded":s=Y0["x-www-form-urlencoded"];break;case"raw":s=r.format?Y0[r.format]:"text/plain",s||(s="text/plain");break;case"graphql":s=Y0.graphql;break;case"binary":s="application/octet-stream";break}s&&(e["Content-Type"]=s)}}});var Oo,rg=le(()=>{"use strict";Oo=class{parse(e,r){return r.toLowerCase().endsWith(".json")?this.parseJson(e):this.parseCsv(e)}parseJson(e){try{let r=JSON.parse(e);return Array.isArray(r)?r:[r]}catch{throw new Error("Failed to parse JSON data file: Invalid JSON format")}}parseCsv(e){let r=e.split(/\r?\n/).filter(s=>s.trim());if(r.length<2)return[{}];let n=this.parseCsvLine(r[0]),i=[];for(let s=1;s<r.length;s++){let o=this.parseCsvLine(r[s]),l={};n.forEach((c,d)=>{l[c]=o[d]||""}),i.push(l)}return i}parseCsvLine(e){let r=[],n="",i=!1;for(let s=0;s<e.length;s++){let o=e[s],l=e[s+1];o==='"'?i&&l==='"'?(n+='"',s++):i=!i:o===","&&!i?(r.push(n.trim()),n=""):n+=o}return r.push(n.trim()),r}}});var Ku,Lz,Qu,K0=le(()=>{"use strict";Ku=ve(require("crypto")),Lz=3e4,Qu=class{constructor(e,r,n,i,s="henry-huang.http-forge/oauth2/callback"){this.secretStore=e;this.browserService=r;this.envConfigService=n;this.httpService=i;this.callbackPath=s}secretStore;browserService;envConfigService;httpService;callbackPath;tokenCache=new Map;pendingAuthCallback=null;pendingImplicitCallback=null;async getToken(e,r){if(e.accessToken)return{accessToken:this.resolve(e.accessToken,r),tokenType:e.tokenPrefix||"Bearer",raw:{}};let n=this.buildCacheKeyString(e),i=this.tokenCache.get(n);if(i&&!this.isExpired(i))return i;if(i?.refreshToken)try{return await this.refreshToken(e,i.refreshToken,r)}catch{this.tokenCache.delete(n)}if(!i){let o=await this.secretStore.get(`oauth2_refresh_${n}`);if(o)try{return await this.refreshToken(e,o,r)}catch{await this.secretStore.delete(`oauth2_refresh_${n}`)}}let s;switch(e.grantType){case"client_credentials":s=await this.fetchToken(e,r,"client_credentials");break;case"password":s=await this.fetchToken(e,r,"password");break;case"authorization_code":s=await this.authorizationCodeFlow(e,r);break;case"implicit":s=await this.implicitFlow(e,r);break;default:throw new Error(`Unknown OAuth2 grant type: ${e.grantType}`)}return this.tokenCache.set(n,s),s.refreshToken&&await this.storeRefreshToken(n,s.refreshToken),s}async refreshToken(e,r,n){let i=this.resolve(e.tokenUrl||"",n);if(!i)throw new Error("OAuth2 tokenUrl is required for token refresh");let s=this.resolve(e.clientId||"",n),o=this.resolve(e.clientSecret||"",n),l=new URLSearchParams;l.append("grant_type","refresh_token"),l.append("refresh_token",r);let c={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,c,l,s,o,n);let d=await this.httpService.execute({method:"POST",url:i,headers:c,body:l.toString()}),p=this.parseTokenResponse(d.body,e);p.refreshToken||(p.refreshToken=r);let m=this.buildCacheKeyString(e);return this.tokenCache.set(m,p),p.refreshToken&&await this.storeRefreshToken(m,p.refreshToken),p}async authorizationCodeFlow(e,r){let n=this.resolve(e.authUrl||"",r),i=this.resolve(e.tokenUrl||"",r),s=this.resolve(e.clientId||"",r),o=this.resolve(e.clientSecret||"",r),l=e.scope?this.resolve(e.scope,r):void 0;if(!n)throw new Error("OAuth2 authUrl is required for authorization code flow");if(!i)throw new Error("OAuth2 tokenUrl is required for authorization code flow");if(!s)throw new Error("OAuth2 clientId is required for authorization code flow");let c=e.usePkce!==!1,d,p,m;if(c){d=this.generateCodeVerifier();let j=e.pkceMethod||"S256";p=j==="S256"?this.generateCodeChallengeS256(d):d,m=j}let y=e.state||Ku.randomBytes(16).toString("hex"),b=await this.getCallbackUri(),q=new URL(n);if(q.searchParams.set("response_type","code"),q.searchParams.set("client_id",s),q.searchParams.set("redirect_uri",b),l&&q.searchParams.set("scope",l),q.searchParams.set("state",y),p&&(q.searchParams.set("code_challenge",p),q.searchParams.set("code_challenge_method",m)),e.audience&&q.searchParams.set("audience",this.resolve(e.audience,r)),e.resource&&q.searchParams.set("resource",this.resolve(e.resource,r)),e.extraParams)for(let[j,I]of Object.entries(e.extraParams))q.searchParams.set(j,this.resolve(I,r));this.pendingAuthCallback&&(this.pendingAuthCallback.reject(new Error("OAuth2 authorization superseded by a new request")),this.pendingAuthCallback=null);let x=new Promise((j,I)=>{this.pendingAuthCallback={resolve:j,reject:I,state:y}});await this.browserService.openExternal(q.toString());let v;try{v=await Promise.race([x,new Promise((j,I)=>setTimeout(()=>{this.pendingAuthCallback=null,I(new Error("OAuth2 authorization timed out after 2 minutes"))},12e4))])}finally{this.pendingAuthCallback=null}if(v.state&&v.state!==y)throw new Error("OAuth2 state mismatch \u2014 potential CSRF attack");let R=new URLSearchParams;R.append("grant_type","authorization_code"),R.append("code",v.code),R.append("redirect_uri",b),d&&R.append("code_verifier",d);let E={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,E,R,s,o,r);let k=await this.httpService.execute({method:"POST",url:i,headers:E,body:R.toString()}),P=this.parseTokenResponse(k.body,e),M=this.buildCacheKeyString(e);return this.tokenCache.set(M,P),P.refreshToken&&await this.storeRefreshToken(M,P.refreshToken),P}async implicitFlow(e,r){let n=this.resolve(e.authUrl||"",r),i=this.resolve(e.clientId||"",r),s=e.scope?this.resolve(e.scope,r):void 0;if(!n)throw new Error("OAuth2 authUrl is required for implicit flow");if(!i)throw new Error("OAuth2 clientId is required for implicit flow");let o=e.state||Ku.randomBytes(16).toString("hex"),l=await this.getCallbackUri(),c=new URL(n);if(c.searchParams.set("response_type","token"),c.searchParams.set("client_id",i),c.searchParams.set("redirect_uri",l),s&&c.searchParams.set("scope",s),c.searchParams.set("state",o),e.audience&&c.searchParams.set("audience",this.resolve(e.audience,r)),e.resource&&c.searchParams.set("resource",this.resolve(e.resource,r)),e.extraParams)for(let[b,q]of Object.entries(e.extraParams))c.searchParams.set(b,this.resolve(q,r));this.pendingImplicitCallback&&(this.pendingImplicitCallback.reject(new Error("OAuth2 implicit flow superseded by a new request")),this.pendingImplicitCallback=null);let d=new Promise((b,q)=>{this.pendingImplicitCallback={resolve:b,reject:q,state:o}});await this.browserService.openExternal(c.toString());let p;try{p=await Promise.race([d,new Promise((b,q)=>setTimeout(()=>{this.pendingImplicitCallback=null,q(new Error("OAuth2 implicit flow timed out after 2 minutes"))},12e4))])}finally{this.pendingImplicitCallback=null}if(p.state&&p.state!==o)throw new Error("OAuth2 state mismatch \u2014 potential CSRF attack");let m={accessToken:p.accessToken,tokenType:p.tokenType||e.tokenPrefix||"Bearer",expiresAt:p.expiresIn?Date.now()+p.expiresIn*1e3:void 0,raw:{access_token:p.accessToken,token_type:p.tokenType,expires_in:p.expiresIn}},y=this.buildCacheKeyString(e);return this.tokenCache.set(y,m),m}handleAuthorizationCallback(e,r,n){if(n){let i=new Error(`OAuth2 authorization error: ${n}`);this.pendingAuthCallback?.reject(i),this.pendingImplicitCallback?.reject(i),this.pendingAuthCallback=null,this.pendingImplicitCallback=null;return}if(e&&this.pendingAuthCallback){this.pendingAuthCallback.resolve({code:e,state:r}),this.pendingAuthCallback=null;return}!e&&!this.pendingAuthCallback&&this.pendingImplicitCallback&&(this.pendingImplicitCallback.reject(new Error("OAuth2 implicit flow did not receive access_token")),this.pendingImplicitCallback=null)}handleImplicitCallback(e,r,n,i){this.pendingImplicitCallback&&(this.pendingImplicitCallback.resolve({accessToken:e,tokenType:r,expiresIn:n,state:i}),this.pendingImplicitCallback=null)}clearToken(e){let r=`${e.tokenUrl}|${e.clientId}|${e.scope||""}|${e.grantType}`;this.tokenCache.delete(r),this.secretStore.delete(`oauth2_refresh_${r}`)}clearAllTokens(){for(let e of this.tokenCache.keys())this.secretStore.delete(`oauth2_refresh_${e}`);this.tokenCache.clear()}async fetchToken(e,r,n){let i=this.resolve(e.tokenUrl||"",r);if(!i)throw new Error("OAuth2 tokenUrl is required");let s=this.resolve(e.clientId||"",r),o=this.resolve(e.clientSecret||"",r),l=e.scope?this.resolve(e.scope,r):void 0,c=new URLSearchParams;if(c.append("grant_type",n),l&&c.append("scope",l),n==="password"){let m=this.resolve(e.username||"",r),y=this.resolve(e.password||"",r);if(!m)throw new Error("OAuth2 password grant requires username");c.append("username",m),c.append("password",y)}if(e.audience&&c.append("audience",this.resolve(e.audience,r)),e.resource&&c.append("resource",this.resolve(e.resource,r)),e.extraParams)for(let[m,y]of Object.entries(e.extraParams))c.append(m,this.resolve(y,r));let d={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,d,c,s,o,r);let p=await this.httpService.execute({method:"POST",url:i,headers:d,body:c.toString()});return this.parseTokenResponse(p.body,e)}applyClientAuth(e,r,n,i,s,o){if(e.clientAuthentication==="header"){let l=Buffer.from(`${i}:${s}`).toString("base64");r.Authorization=`Basic ${l}`}else i&&n.set("client_id",i),s&&n.set("client_secret",s)}parseTokenResponse(e,r){let n=e;if(typeof n=="string")try{n=JSON.parse(n)}catch{throw new Error("OAuth2 token response is not valid JSON")}if(!n||typeof n!="object")throw new Error("OAuth2 token response is not a valid JSON object");let i=n,s=r.tokenField||"access_token",o=i[s];if(!o)throw new Error(`OAuth2 token fetch failed: '${s}' not present in response`);let l=typeof i.expires_in=="number"?i.expires_in:void 0;return{accessToken:o,tokenType:i.token_type||r.tokenPrefix||"Bearer",expiresAt:l?Date.now()+l*1e3:void 0,refreshToken:i.refresh_token,scope:i.scope,raw:i}}isExpired(e){return e.expiresAt?Date.now()>=e.expiresAt-Lz:!1}buildCacheKeyString(e){return`${e.tokenUrl||""}|${e.clientId||""}|${e.scope||""}|${e.grantType}`}async getCallbackUri(){let e=`${this.browserService.uriScheme}://${this.callbackPath}`;return this.browserService.asExternalUri(e)}resolve(e,r){return this.envConfigService.resolveVariables(e,r)}generateCodeVerifier(){return Ku.randomBytes(32).toString("base64url")}generateCodeChallengeS256(e){return Ku.createHash("sha256").update(e).digest("base64url")}async storeRefreshToken(e,r){try{await this.secretStore.store(`oauth2_refresh_${e}`,r)}catch{}}}});function Ka(t,e={}){let r=[];Object.entries(e).forEach(([n,i])=>{r.push(`${n}=${i}`)}),r.length&&Ya.writeFileSync(t,r.join(`
52
+ `)}function Vu(t,e){return JSON.stringify(t)!==JSON.stringify(e)}function Ja(t){return t.map(e=>{let r=e.args.map(n=>{if(typeof n=="object")try{return JSON.stringify(n,null,2)}catch{return String(n)}return String(n)}).join(" ");return`[${e.level}] ${r}`})}function SP(t){return{log:(...e)=>t.push({level:"log",args:e}),info:(...e)=>t.push({level:"info",args:e}),warn:(...e)=>t.push({level:"warn",args:e}),error:(...e)=>t.push({level:"error",args:e})}}function Km(t){let e=[],r=(n,i)=>{try{let s=i();if(s&&typeof s.then=="function"){let o=s.then(()=>{t.push({name:n,passed:!0})},l=>{t.push({name:n,passed:!1,message:l.message||String(l)})});e.push(o)}else t.push({name:n,passed:!0})}catch(s){t.push({name:n,passed:!1,message:s.message})}};return r.skip=(n,i)=>{t.push({name:n,passed:!0,skipped:!0})},r.fail=n=>{t.push({name:n||"Failed test",passed:!1,message:n||"pm.test.fail()"})},r.index=()=>t.length,r._pendingTests=e,r}function Qm(t){let e={};for(let[r,n]of Object.entries(t))e[r]=Array.isArray(n)?n.join(", "):n;return e}function Zm(t,e,r){let n;if(r)try{n=new URL(r).hostname}catch{n=void 0}let i=_t.parseCookieHeaders(t||{},n);return i.length>0?i:Array.isArray(e)&&e.length>0?e.filter(s=>s&&s.name).map(s=>({name:s.name,value:s.value,domain:s.domain??n,path:s.path,expires:s.expires,maxAge:s.maxAge,httpOnly:s.httpOnly,secure:s.secure,sameSite:s.sameSite})):[]}var hd=le(()=>{"use strict";ka()});function $z(t){let e=null;try{e=new URL(t)}catch{}return{toString(){return t},valueOf(){return t},[Symbol.toPrimitive](n){return n==="number"?NaN:t},getHost(){return e?e.hostname:""},getPath(){return e?e.pathname:t},getPathWithQuery(){return e?e.pathname+e.search:t},getQueryString(){return e?e.search.startsWith("?")?e.search.slice(1):e.search:""},getRemote(){if(!e)return"";let n=e.port||(e.protocol==="https:"?"443":"80");return`${e.hostname}:${n}`},getOAuth1BaseUrl(){return e?`${e.protocol}//${e.host}${e.pathname}`:t},get protocol(){return e?.protocol?.replace(":","")||""},get host(){return e?e.hostname.split("."):[]},get port(){return e?.port||""},get path(){return e?e.pathname.split("/").filter(Boolean):[]},get hash(){return e?.hash?.replace("#","")||""},query:{toObject(){if(!e)return{};let n={};return e.searchParams.forEach((i,s)=>{n[s]=i}),n},has(n){return e?e.searchParams.has(n):!1},get(n){return e?e.searchParams.get(n):void 0},each(n){e&&e.searchParams.forEach((i,s)=>n({key:s,value:i}))}}}}var V0,Wu,W0=le(()=>{"use strict";V0=ve(require("vm"));vP();Ym();hd();Wu=class{constructor(e,r){this.deps=e;this.initialContext=r;this.timerRegistry=yP(n=>{let i=n instanceof Error?n.message:String(n);this.consoleMessages.push({level:"error",args:[`Uncaught error in async callback: ${i}`]})}),this.initializeSession()}deps;initialContext;vmContext=null;ctx=null;modifiedRequest=null;assertions=[];consoleMessages=[];_variables={};_collectionVariables={};_globals={};_environmentVariables={};_liveEnvironmentScope=null;_liveGlobalsScope=null;_liveCollectionScope=null;_nextRequest=void 0;_skipRequest=!1;_visualizerData=void 0;timerRegistry;initializeSession(){this.modifiedRequest={url:this.initialContext.request.url,method:this.initialContext.request.method,headers:{...this.initialContext.request.headers},body:this.initialContext.request.body?{...this.initialContext.request.body}:null,params:this.initialContext.request.params?{...this.initialContext.request.params}:{},query:this.initialContext.request.query?{...this.initialContext.request.query}:{}},this.assertions=[],this.ctx=this.createSharedContext(),this.consoleMessages=[];let e=this,r={log:(...n)=>{e.consoleMessages.push({level:"log",args:n})},info:(...n)=>{e.consoleMessages.push({level:"info",args:n})},warn:(...n)=>{e.consoleMessages.push({level:"warn",args:n})},error:(...n)=>{e.consoleMessages.push({level:"error",args:n})}};this.vmContext=this.deps.createVM(this.ctx,r,this.timerRegistry.timers)}createSharedContext(){let e=this.initialContext,r=this.modifiedRequest,n=this.deps.createCommonContext(e,"prerequest");this._variables={...e.variables},this._collectionVariables={...e.collectionVariables||{}},this._globals={...e.globals||{}},this._environmentVariables={...e.environmentVariables||{}},this._liveEnvironmentScope=n.environment,this._liveGlobalsScope=n.globals,this._liveCollectionScope=n.collectionVariables;let i;try{i=new URL(e.request.url).hostname}catch{}let s={get:l=>e.cookieJar?e.cookieJar.get(l,i)?.value:void 0,set:(l,c)=>{e.cookieJar&&e.cookieJar.set({name:l,value:c,domain:i})},has:l=>e.cookieJar?e.cookieJar.has(l,i):!1,list:()=>e.cookieJar?e.cookieJar.getAll(i).map(l=>({name:l.name,value:l.value})):[],toObject:()=>{if(!e.cookieJar)return{};let l=e.cookieJar.getAll(i),c={};for(let d of l)c[d.name]=d.value;return c},jar:()=>{let l=e.cookieJar,c=d=>{if(d==null)return;let p=typeof d=="string"?d:typeof d=="object"||typeof d=="number"||typeof d=="boolean"?String(d):void 0;if(!p)return;let m=p.trim();if(m)try{return new URL(m).hostname}catch{return m}};return{getAll(d,p){try{if(!l){p(null,[]);return}let m=c(d),y=l.getAll(m).map(b=>({name:b.name,value:b.value,domain:b.domain,path:b.path,httpOnly:b.httpOnly,secure:b.secure}));p(null,y)}catch(m){p(m,[])}},get(d,p,m){try{if(!l){m(null,void 0);return}let y=c(d),b=l.get(p,y);m(null,b?{name:b.name,value:b.value,domain:b.domain}:void 0)}catch(y){m(y,void 0)}},set(d,p,m,y){try{if(!l){(y||m)?.(null);return}let b=c(d);typeof p=="string"&&typeof m=="string"?(l.set({name:p,value:m,domain:b}),y?.(null)):typeof p=="object"&&(l.set({...p,domain:b}),m?.(null))}catch(b){(y||m)?.(b)}},unset(d,p,m){try{if(!l){m?.(null);return}let y=c(d);l.delete(p,y),m?.(null)}catch(y){m?.(y)}},clear(d,p){try{let m=typeof d=="function"?d:p;if(!l){m?.(null);return}let y=typeof d=="function"?void 0:c(d);y&&typeof l.clearDomain=="function"?l.clearDomain(y):l.clear(),m?.(null)}catch(m){(typeof d=="function"?d:p)?.(m)}}}},remove:l=>{e.cookieJar&&e.cookieJar.delete(l,i)},unset:l=>{e.cookieJar&&e.cookieJar.delete(l,i)},clear:()=>{e.cookieJar&&e.cookieJar.clear()}},o=this;return{request:this.createRequestObject(r,e),response:null,test:Km(this.assertions),expect:za,cookies:s,execution:{setNextRequest(l){o._nextRequest=l},skipRequest(){o._skipRequest=!0},runRequest(l,c){let p=(async()=>{if(typeof n.sendRequest!="function")throw new Error("pm.execution.runRequest is not available \u2014 HTTP service not configured.");let m=typeof l=="string"?{url:l,method:"GET"}:l,y=await n.sendRequest(m),b=Array.isArray(y?.cookies)?y.cookies.filter(v=>v?.name):[],q=y?.body,x=0;if(typeof q=="string")x=Buffer.byteLength(q,"utf8");else if(Buffer.isBuffer(q))x=q.length;else if(q!=null)try{x=Buffer.byteLength(JSON.stringify(q),"utf8")}catch{}return dd({executedRequest:null,status:y?.status??0,statusText:y?.statusText??"",headers:y?.headers??{},body:q,cookies:b,responseTime:y?.time,responseSize:x})})();if(typeof c=="function"){p.then(m=>c(null,m),m=>c(m));return}return p},location:{current:n.info?.requestName||"",currentRequestName:n.info?.requestName||"",eventName:"prerequest",toString(){return n.info?.requestName||""}}},setNextRequest(l){o._nextRequest=l},visualizer:{set(l,c){o._visualizerData={template:l,data:c}},clear(){o._visualizerData=void 0}},...n,info:{...n.info||{},eventName:"prerequest",requestName:n.info?.requestName||void 0,requestId:n.info?.requestId||void 0,iteration:e.iteration||0,iterationCount:e.iterationCount||1}}}createRequestObject(e,r){let n=l=>{if(!l)return"none";switch(l){case"raw":return"raw";case"form-data":return"formdata";case"x-www-form-urlencoded":return"urlencoded";case"binary":return"file";case"graphql":return"graphql";case"none":return"none";default:return"raw"}},i=l=>{if(!l)return"none";switch(l){case"raw":return"raw";case"formdata":return"form-data";case"urlencoded":return"x-www-form-urlencoded";case"file":return"binary";case"graphql":return"graphql";case"none":return"none";default:return"raw"}},s={...e.headers,add:l=>{l&&l.key&&(e.headers[l.key]=l.value||"")},get:l=>{for(let[c,d]of Object.entries(e.headers))if(c.toLowerCase()===l.toLowerCase())return d},has:l=>{for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.toLowerCase())return!0;return!1},remove:l=>{for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.toLowerCase()){delete e.headers[c];break}},update:l=>{if(l&&l.key){for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.key.toLowerCase()){e.headers[c]=l.value||"";return}}},upsert:l=>{if(l&&l.key){for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.key.toLowerCase()){e.headers[c]=l.value||"";return}e.headers[l.key]=l.value||""}},toObject:()=>{let l={};for(let[c,d]of Object.entries(e.headers))typeof d=="string"&&(l[c]=d);return l},each:l=>{for(let[c,d]of Object.entries(e.headers))typeof d=="string"&&l({key:c,value:d})}},o={get mode(){return n(e.body?.type)},set mode(l){let c=i(l);e.body?e.body.type=c:e.body={type:c,content:null}},get raw(){let l=e.body?.content;return typeof l=="string"?l:l&&typeof l=="object"?JSON.stringify(l):""},set raw(l){e.body?(e.body.type="raw",e.body.content=l):e.body={type:"raw",content:l}},get formdata(){return e.body?.type==="form-data"&&Array.isArray(e.body.content)?e.body.content:[]},get urlencoded(){return e.body?.type==="x-www-form-urlencoded"&&Array.isArray(e.body.content)?e.body.content:[]},get graphql(){return e.body?.type==="graphql"?e.body.content:null},get file(){return e.body?.type==="binary"?e.body.content:null}};return{get url(){return $z(e.url)},set url(l){e.url=typeof l=="string"?l:String(l)},get method(){return e.method},set method(l){e.method=l},headers:s,get body(){return o},set body(l){if(l==null)e.body=null;else if(typeof l=="string")e.body={type:"raw",content:l};else if(typeof l=="object")if(l.type||l.mode||l.content!==void 0){let c=l.mode?i(l.mode):l.type||"raw";e.body={type:c,format:l.format,content:l.content}}else e.body={type:"raw",content:l}},get params(){return e.params||{}},set params(l){e.params=l||{}},get query(){return e.query||{}},set query(l){e.query=l||{}},get auth(){return r.request?.auth||null},set auth(l){r.request&&(r.request.auth=l)},get certificate(){return r.request?.certificate||null},set certificate(l){r.request&&(r.request.certificate=l)},get description(){return r.request?.description||null},set description(l){r.request&&(r.request.description=l)},get name(){return r.request?.name||null},set name(l){r.request&&(r.request.name=l)},get id(){return r.request?.id||null},get disabled(){return r.request?.disabled||!1},set disabled(l){r.request&&(r.request.disabled=l)},get messages(){return r.request?.messages||[]},get methodPath(){return r.request?.methodPath||null},get metadata(){return r.request?.metadata||[]},getHeaders(l){let c={};for(let[d,p]of Object.entries(e.headers))typeof p=="string"&&(c[d]=p);return c},addQueryParams(l){if(typeof l=="string"){let c=new URLSearchParams(l);for(let[d,p]of c)e.query||(e.query={}),e.query[d]=p}else Array.isArray(l)&&(e.query||(e.query={}),l.forEach(c=>{c.key&&(e.query[c.key]=c.value||"")}))},removeQueryParams(l){e.query&&(typeof l=="string"?delete e.query[l]:Array.isArray(l)&&l.forEach(c=>{let d=typeof c=="string"?c:c.key;d&&delete e.query[d]}))},authorizeUsing(l,c){r.request&&(typeof l=="string"?(r.request.auth||(r.request.auth={}),r.request.auth.type=l,c&&(r.request.auth.parameters=c)):typeof l=="object"&&(r.request.auth=l))},clone(){return{url:e.url,method:e.method,headers:{...e.headers},body:e.body?{...e.body}:null,params:e.params?{...e.params}:{},query:e.query?{...e.query}:{},auth:r.request?.auth,certificate:r.request?.certificate,description:r.request?.description,name:r.request?.name,id:r.request?.id,disabled:r.request?.disabled,metadata:r.request?.metadata,messages:r.request?.messages,methodPath:r.request?.methodPath}},describe(l,c){r.request&&(r.request.description={content:l,type:c||"text/plain"})},setHeader(l,c){e.headers[l]=c},addHeader(l,c){typeof l=="object"&&l!==null?e.headers[l.key]=l.value:e.headers[l]=c},removeHeader(l){delete e.headers[l]},setBody(l,c,d){e.body={type:c||e.body?.type||"raw",format:d||e.body?.format,content:l}}}}injectLegacyGlobals(e,r){let n=this.vmContext;if(!n)return;let i=this.initialContext,s=e==="test"&&r?.executedRequest?r.executedRequest:this.modifiedRequest,o={};for(let[b,q]of Object.entries(s?.headers||{}))typeof q=="string"&&(o[b]=q);let l=s?.body,c=l==null?null:typeof l=="object"&&"content"in l?l.content:l,d=i.request;if(n.request={id:d?.id??"",name:d?.name??"",description:d?.description??"",url:typeof s?.url=="string"?s.url:String(s?.url??""),method:s?.method??"GET",headers:o,data:c},n.environment=this._liveEnvironmentScope?.toObject?.()??{...this._environmentVariables},n.globals=this._liveGlobalsScope?.toObject?.()??{...this._globals},n.data={...i.iterationData||{}},typeof n.iteration!="number"&&(n.iteration=0),e!=="test"||!r)return;let p=r.body;n.responseBody=p==null?"":typeof p=="string"?p:JSON.stringify(p);let m=r.statusText||"";n.responseCode={code:r.status,name:m,detail:m},n.responseHeaders={...r.headers||{}},n.responseTime=r.responseTime??0,n.responseCookies=(r.cookies||[]).map(b=>({...b}));let y=this;n.tests=new Proxy({},{set(b,q,x){return y.assertions.push({name:String(q),passed:!!x,message:x?void 0:`"${String(q)}" was false`}),!0}})}async executePreRequest(e){let r=pd(e,this.deps.isolateScripts);if(!r||!r.trim())return{success:!0};try{this.consoleMessages.length=0,this.injectLegacyGlobals("prerequest");let n=this.ctx.variables.replaceIn(r),i=this.deps.scriptTimeoutMs??5e3,s=V0.runInContext(n,this.vmContext,{timeout:i});this.deps.isolateScripts&&s&&typeof s.then=="function"&&await s,(await this.timerRegistry.drain(i)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${i}ms; pending async work was cancelled.`]});let l=Ja(this.consoleMessages),c=this.initialContext.request.body,d=!this.bodiesEqual(this.modifiedRequest.body,c);return{success:!0,modifiedRequest:{url:this.modifiedRequest.url!==this.initialContext.request.url?this.modifiedRequest.url:void 0,headers:Vu(this.modifiedRequest.headers,this.initialContext.request.headers)?this.modifiedRequest.headers:void 0,body:d?this.modifiedRequest.body:void 0,params:Vu(this.modifiedRequest.params,this.initialContext.request.params||{})?this.modifiedRequest.params:void 0,query:Vu(this.modifiedRequest.query,this.initialContext.request.query||{})?this.modifiedRequest.query:void 0},modifiedVariables:this.ctx.variables.toObject(),localVariables:this.ctx.variables.toLocalObject?.()??{},modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,consoleOutput:l.length>0?l:void 0,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}catch(n){let i=[...Ja(this.consoleMessages),`[error] Script execution failed: ${n.message}`];return{success:!1,error:n.message||"Pre-request script execution failed",consoleOutput:i,modifiedVariables:this.ctx?.variables?.toObject(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}}async executePostResponse(e,r){let n=pd(e,this.deps.isolateScripts);if(!n||!n.trim())return{testResults:[],consoleOutput:[]};try{this.consoleMessages.length=0,this.assertions.length=0,this.ctx.info.eventName="test",this.ctx.response=dd(r),this.ctx.request=this.createRequestObject(r.executedRequest,this.initialContext),this.injectLegacyGlobals("test",r);let i=this.ctx.variables.replaceIn(n),s=this.deps.scriptTimeoutMs??5e3,o=V0.runInContext(i,this.vmContext,{timeout:s});this.deps.isolateScripts&&o&&typeof o.then=="function"&&await o,this.ctx.test._pendingTests?.length>0&&(await Promise.all(this.ctx.test._pendingTests),this.ctx.test._pendingTests.length=0),(await this.timerRegistry.drain(s)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${s}ms; pending async work was cancelled.`]});let c=Ja(this.consoleMessages);return{testResults:[...this.assertions],consoleOutput:c.length>0?c:void 0,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}catch(i){this.assertions.push({name:"Script Execution",passed:!1,message:i.message||"Script execution failed"});let s=[...Ja(this.consoleMessages),`[error] Script execution failed: ${i.message}`];return{testResults:[...this.assertions],consoleOutput:s,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}}bodiesEqual(e,r){return e===r||!e&&!r?!0:!e||!r?!1:e.type===r.type&&e.format===r.format&&JSON.stringify(e.content)===JSON.stringify(r.content)}dispose(){this.timerRegistry.clearAll(),this.vmContext=null,this.ctx=null,this.assertions=[]}}});function RP(t,e){if(t)return t.split(",").map(r=>{let n=r.trim();if(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))return n.slice(1,-1);let i=Number(n);if(!isNaN(i)&&n!=="")return i;if(e&&n in e){let s=e[n],o=Number(s);return!isNaN(o)&&s!==""?o:s}return n})}function xP(t){if(typeof t=="string"&&t.charCodeAt(0)===30)try{return JSON.parse(t.slice(1))}catch{return t}return t}function Mz(t,e){if(t==="@")return"";if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);let r=t.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(r){let n=RP(r[2],e),i=Vi(r[1],n);return i!==null?i:void 0}if(e[t]!==void 0)return xP(e[t]);if(go(t)){let n=mo(t,e),i=ui(t,n);if(i!==void 0)return i}}function wP(t,e,r,n){let i=Buffer.concat([Buffer.from(t,"utf8"),n||Buffer.alloc(0)]),s=[],o=Buffer.alloc(0);for(;Buffer.concat(s).length<e+r;)o=br.createHash("md5").update(Buffer.concat([o,i])).digest(),s.push(o);let l=Buffer.concat(s);return{key:l.subarray(0,e),iv:l.subarray(e,e+r)}}function z0(t,e,r){let n=i=>t==="aes"?`aes-${i*8}-cbc`:t==="des"?"des-cbc":t==="des-ede3"?"des-ede3-cbc":t;return{encrypt(i,s,o){let l=i instanceof Qe?i.toBuffer():Buffer.from(String(i),"utf8");if(typeof s=="string"){let c=br.randomBytes(8),{key:d,iv:p}=wP(s,e,r,c),m=br.createCipheriv(n(e),d,p),y=Buffer.concat([m.update(l),m.final()]),b=Buffer.concat([Buffer.from("Salted__"),c,y]);return{ciphertext:new Qe(y),salt:new Qe(c),toString:q=>q?q.stringify(new Qe(b)):b.toString("base64")}}else{let c=s.toBuffer(),d=o?.iv&&o.iv instanceof Qe?o.iv.toBuffer():Buffer.alloc(r),p=br.createCipheriv(n(c.length),c,d);o?.padding===!1&&p.setAutoPadding(!1);let m=Buffer.concat([p.update(l),p.final()]);return{ciphertext:new Qe(m),toString:y=>y?y.stringify(new Qe(m)):m.toString("base64")}}},decrypt(i,s,o){if(typeof s=="string"){let l=typeof i=="string"?Buffer.from(i,"base64"):i.ciphertext.toBuffer(),c,d;l.subarray(0,8).toString()==="Salted__"?(d=l.subarray(8,16),c=l.subarray(16)):(d=Buffer.alloc(0),c=l);let{key:p,iv:m}=wP(s,e,r,d),y=br.createDecipheriv(n(e),p,m);return new Qe(Buffer.concat([y.update(c),y.final()]))}else{let l=s.toBuffer(),c=o?.iv&&o.iv instanceof Qe?o.iv.toBuffer():Buffer.alloc(r),d=typeof i=="string"?Buffer.from(i,"base64"):i.ciphertext?i.ciphertext.toBuffer():Buffer.from(i),p=br.createDecipheriv(n(l.length),l,c);return o?.padding===!1&&p.setAutoPadding(!1),new Qe(Buffer.concat([p.update(d),p.final()]))}}}}function Fz(){let t=r=>n=>{let i=n instanceof Qe?n.toBuffer():Buffer.from(String(n),"utf8");return new Qe(br.createHash(r).update(i).digest())},e=r=>(n,i)=>{let s=n instanceof Qe?n.toBuffer():Buffer.from(String(n),"utf8"),o=i instanceof Qe?i.toBuffer():Buffer.from(String(i),"utf8");return new Qe(br.createHmac(r,o).update(s).digest())};return{MD5:t("md5"),SHA1:t("sha1"),SHA224:t("sha224"),SHA256:t("sha256"),SHA384:t("sha384"),SHA512:t("sha512"),SHA3:t("sha3-256"),RIPEMD160:t("ripemd160"),HmacMD5:e("md5"),HmacSHA1:e("sha1"),HmacSHA256:e("sha256"),HmacSHA512:e("sha512"),AES:z0("aes",32,16),DES:z0("des",8,8),TripleDES:z0("des-ede3",24,8),PBKDF2(r,n,i){let s=r instanceof Qe?r.toBuffer():Buffer.from(String(r),"utf8"),o=n instanceof Qe?n.toBuffer():Buffer.from(String(n),"utf8"),l=(i?.keySize||4)*4,c=i?.iterations||1;return new Qe(br.pbkdf2Sync(s,o,c,l,"sha1"))},enc:{Base64:{stringify:r=>(r instanceof Qe?r.toBuffer():Buffer.from(String(r))).toString("base64"),parse:r=>Qe.fromBase64(r)},Utf8:{stringify:r=>(r instanceof Qe?r.toBuffer():Buffer.from(String(r))).toString("utf8"),parse:r=>Qe.fromUtf8(r)},Hex:{stringify:r=>(r instanceof Qe?r.toBuffer():Buffer.from(String(r))).toString("hex"),parse:r=>Qe.fromHex(r)},Latin1:{stringify:r=>(r instanceof Qe?r.toBuffer():Buffer.from(String(r))).toString("latin1"),parse:r=>new Qe(Buffer.from(r,"latin1"))},Utf16:{stringify:r=>(r instanceof Qe?r.toBuffer():Buffer.from(String(r))).toString("utf16le"),parse:r=>new Qe(Buffer.from(r,"utf16le"))},Utf16BE:{stringify:r=>(r instanceof Qe?r.toBuffer():Buffer.from(String(r))).swap16().toString("utf16le"),parse:r=>new Qe(Buffer.from(r,"utf16le").swap16())}},lib:{WordArray:{create:r=>r?typeof r=="string"?new Qe(Buffer.from(r,"utf8")):Buffer.isBuffer(r)?new Qe(r):new Qe(Buffer.from(String(r))):new Qe(Buffer.alloc(0)),random:r=>new Qe(br.randomBytes(r))}},pad:{Pkcs7:{_name:"pkcs7"},NoPadding:{_name:"nopadding"},ZeroPadding:{_name:"zeropadding"}},mode:{CBC:{_name:"cbc"},ECB:{_name:"ecb"}}}}var br,Nz,_P,Qe,Ki,md=le(()=>{"use strict";br=ve(require("crypto")),Nz=ve(require("querystring")),_P=ve(require("vm"));om();Pf();um();B0();W0();Ym();Qe=class t{_buffer;constructor(e){this._buffer=typeof e=="string"?Buffer.from(e,"utf8"):e}toString(e){return e?e.stringify(this):this._buffer.toString("hex")}toBuffer(){return this._buffer}static fromHex(e){return new t(Buffer.from(e,"hex"))}static fromBase64(e){return new t(Buffer.from(e,"base64"))}static fromUtf8(e){return new t(Buffer.from(e,"utf8"))}};Ki=class t{constructor(e,r=[],n,i="shared",s=5e3){this.httpService=e;this.secretRegistry=n;this.scopeMode=i;this.scriptTimeoutMs=s;this.moduleLoader=Jm(r)}httpService;secretRegistry;scopeMode;scriptTimeoutMs;moduleLoader;createRequestSession(e){return new Wu({createVM:this.createVM.bind(this),createCommonContext:this.createCommonContext.bind(this),isolateScripts:this.scopeMode==="isolated",scriptTimeoutMs:this.scriptTimeoutMs},e)}createVM(e,r,n){let i=this.moduleLoader.getGlobalSetupExports(),s=this.moduleLoader.createRequireFunction();e.require=s,e.vault=this.createVault();let o={ctx:e,hf:e,pm:e,console:r,...i||{},global:i,setTimeout:n?.setTimeout??setTimeout,setInterval:n?.setInterval??setInterval,clearTimeout:n?.clearTimeout??clearTimeout,clearInterval:n?.clearInterval??clearInterval,URL,URLSearchParams,Buffer,atob:l=>Buffer.from(l,"base64").toString("binary"),btoa:l=>Buffer.from(l,"binary").toString("base64"),TextEncoder,TextDecoder,crypto:br,_:s("lodash"),require:s,moment:fd(),querystring:Nz,CryptoJS:Fz(),tv4:(()=>{try{return s("tv4")}catch{return}})(),postman:{setNextRequest:l=>e.setNextRequest?.(l),setGlobalVariable:(l,c)=>e.globals?.set(l,c),getGlobalVariable:l=>e.globals?.get(l),clearGlobalVariable:l=>e.globals?.unset(l),setEnvironmentVariable:(l,c)=>e.environment?.set(l,c),getEnvironmentVariable:l=>e.environment?.get(l),clearEnvironmentVariable:l=>e.environment?.unset(l),getResponseHeader:l=>{let c=e.response?.headers?.get?.(l);return c===void 0?null:c},getResponseCookie:l=>{let c=e.response?.cookies;if(c&&typeof c[Symbol.iterator]=="function"){for(let d of c)if(d?.name&&d.name.toLowerCase()===l.toLowerCase())return{...d}}return null}},jsonStringify:(l,c,d)=>JSON.stringify(l,c,d),jsonParse:l=>JSON.parse(l),xml2Json:l=>{try{let c=this.moduleLoader.createRequireFunction()("xml2js"),d;return c.parseString(l,{explicitArray:!1},(p,m)=>{if(p)throw p;d=m}),d}catch{throw new Error("xml2Json() requires the xml2js module. Add it to your modules/package.json and run npm install.")}}};return _P.createContext(o)}createCommonContext(e,r){let n={...e.variables},i={...e.collectionVariables||{}},s={...e.globals||{}},o={...e.environmentVariables||{}},l=e.iterationData||{},c=this.createMergedVariableScope(n,o,i,s,l),d=this.createGlobalsScope(s,e.onGlobalsChange),p=this.createVariableScope(i),m=this.createEnvironmentScope(o,e.environmentName,e.onEnvironmentChange,!0),y={...m,set:(x,v)=>{let R=this.serializeValue(v);m.set(x,R),n[x]=R},unset(x){m.unset(x),delete n[x]},clear(){let x=Object.keys(o);m.clear();for(let v of x)delete n[v]}},b={...d,set:(x,v)=>{let R=this.serializeValue(v);d.set(x,R),n[x]=R},unset(x){d.unset(x),delete n[x]},clear(){let x=Object.keys(s);d.clear();for(let v of x)delete n[v]}};return b.replaceIn=c.replaceIn,p.replaceIn=c.replaceIn,y.replaceIn=c.replaceIn,{globals:b,collectionVariables:p,variables:c,environment:y,iterationData:{get:x=>l[x],has:x=>x in l,toObject:()=>({...l}),toJSON:()=>JSON.stringify(l)},sendRequest:this.createSendRequest(),expect:za,info:e.info||{eventName:r,requestName:void 0,requestId:void 0}}}static JSON_TYPE_MARKER="";serializeValue(e){return typeof e=="string"?e:e===void 0?t.JSON_TYPE_MARKER+"undefined":t.JSON_TYPE_MARKER+JSON.stringify(e)}deserializeValue(e){if(e!==void 0){if(typeof e=="string"&&e.charCodeAt(0)===30){let r=e.slice(1);if(r==="undefined")return;try{return JSON.parse(r)}catch{}}return e}}createVariableScope(e){return{get:r=>r in e?this.deserializeValue(e[r]):null,set:(r,n)=>{e[r]=this.serializeValue(n)},has(r){return r in e},unset(r){delete e[r]},clear(){Object.keys(e).forEach(r=>delete e[r])},toObject(){return{...e}}}}createGlobalsScope(e,r){let n=(i,s,o)=>{r&&r(i,s,o)};return{get:i=>i in e?this.deserializeValue(e[i]):null,set:(i,s)=>{let o=this.serializeValue(s);e[i]=o,n("set",i,o)},has(i){return i in e},unset(i){delete e[i],n("unset",i)},clear(){Object.keys(e).forEach(i=>delete e[i]),n("clear")},toObject(){return{...e}}}}createMergedVariableScope(e,r,n,i,s={}){let o={get:l=>l in e?this.deserializeValue(e[l]):l in s?s[l]:l in r?this.deserializeValue(r[l]):l in n?this.deserializeValue(n[l]):l in i?this.deserializeValue(i[l]):null,set:(l,c)=>{e[l]=this.serializeValue(c)},has(l){return l in e||l in s||l in r||l in r||l in n||l in i},unset(l){delete e[l]},clear(){Object.keys(e).forEach(l=>delete e[l])},toObject(){return{...i,...n,...r,...s,...e}},toLocalObject(){return{...n,...r,...s,...e}},replaceIn(l){if(!l||typeof l!="string")return l;let c=o.toObject(),d=20,p=y=>y.replace(/\{\{([^}]+)\}\}/g,(b,q)=>{let x=q.trim(),v=x.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(v)try{let E=RP(v[2],c),k=Vi(v[1],E);return k!==null?String(k):b}catch{return b}let R=xu(x);if(R){let E=Mz(R.input,c);if(E!==void 0){let k=Cu(E,R.filters,c);return k!==void 0?String(k):b}return b}if(o.has(x)){let E=o.get(x);return E===void 0?"":String(E)}if(go(x)){let E={};for(let[M,j]of Object.entries(c))E[M]=xP(j);let k=mo(x,E),P=ui(x,k);if(P!==void 0)return String(P)}return b}),m=l;for(let y=0;y<d;y++){let b=p(m);if(b===m)break;m=b}return m}};return o}createEnvironmentScope(e,r,n,i){let s=(o,l,c)=>{n&&(i?n(o,l,c):n(l||"",o==="set"?c:void 0))};return{name:r||"",get:o=>o in e?this.deserializeValue(e[o]):null,set:(o,l)=>{let c=this.serializeValue(l);e[o]=c,s("set",o,c)},has(o){return o in e},unset(o){delete e[o],s("unset",o)},clear(){Object.keys(e).forEach(o=>delete e[o]),s("clear")},toObject(){return{...e}}}}createVault(){let e=this.secretRegistry,r=()=>{throw new Error("pm.vault is read-only in HTTP Forge. Use environment variables or {{secret:provider/path}} tokens to manage secrets.")};return{async get(n){if(!e)throw new Error('pm.vault is not available \u2014 no secret providers are configured. Configure a provider under "secrets.providers" to use pm.vault.get().');let i=`secret:${n}`;return(await e.resolveSecretTokens(`{{${i}}}`))[i]},set:r,unset:r}}createSendRequest(){return this.httpService?(e,r)=>{let n=typeof e=="string"?{url:e,method:"GET"}:e,i=this.httpService.execute({url:n.url,method:n.method||"GET",headers:n.headers||{},body:n.body,...n});if(r){i.then(s=>r(null,s)).catch(s=>r(s,null));return}return i}:(e,r)=>{let n=new Error("sendRequest not available - HTTP service not configured");if(r){r(n,null);return}return Promise.reject(n)}}}});var CP,jz,G0,Xm,J0,eg,ln,Eo,gd=le(()=>{"use strict";CP=ve(require("fs")),jz=ve(require("http")),G0=ve(require("https")),Xm=ve(require("path")),J0=require("url"),eg=ve(require("zlib")),ln={timeout:3e4,followRedirects:!0,followOriginalMethod:!1,followAuthHeader:!1,maxRedirects:10,strictSSL:!0,decompress:!0,includeCookies:!1,tls:{},certificates:[]},Eo=class{settings;version;basePath;constructor(e,r=process.cwd()){this.settings={...ln,...e},this.basePath=r;try{this.version=require("../../package.json").version||"0.0.0"}catch{this.version="0.0.0"}this.settings.strictSSL===!1&&console.log("[NodeHttpClient] SSL verification disabled (strictSSL: false)")}async send(e){let r=this.mergeSettings(e.settings);return await this.executeInternal(e,r,0)}mergeSettings(e){return{timeout:e?.timeout??this.settings.timeout,followRedirects:e?.followRedirects??this.settings.followRedirects,followOriginalMethod:e?.followOriginalMethod??this.settings.followOriginalMethod,followAuthHeader:e?.followAuthHeader??this.settings.followAuthHeader,maxRedirects:e?.maxRedirects??this.settings.maxRedirects,strictSSL:e?.strictSSL??this.settings.strictSSL,decompress:e?.decompress??this.settings.decompress,includeCookies:e?.includeCookies??this.settings.includeCookies,tls:e?.tls??this.settings.tls??{},certificates:e?.certificates??this.settings.certificates??[]}}async executeInternal(e,r,n,i){let s=Date.now(),o=new J0.URL(e.url),l=o.protocol==="https:",c=this.sanitizeHeaders(e.headers||{});Object.keys(c).some(m=>m.toLowerCase()==="user-agent")||(c["User-Agent"]=`HttpForge/${this.version}`);let p={hostname:o.hostname,port:o.port||(l?443:80),path:o.pathname+o.search,method:e.method,headers:{...c},timeout:r.timeout||void 0};if(r.decompress&&!c["accept-encoding"]&&!c["Accept-Encoding"]&&(p.headers["Accept-Encoding"]="gzip, deflate"),l){let m=this.resolveTlsSettings(o,r),y=p;y.rejectUnauthorized=r.strictSSL;let b={rejectUnauthorized:r.strictSSL},q=this.readOptionalFile(m.caPath,"CA certificate");q&&(b.ca=q);let x=this.readOptionalFile(m.certPath,"client certificate");x&&(b.cert=x);let v=this.readOptionalFile(m.keyPath,"client private key");v&&(b.key=v);let R=this.readOptionalFile(m.pfxPath,"client pfx");R&&(b.pfx=R),m.passphrase&&(b.passphrase=m.passphrase),m.servername&&(y.servername=m.servername),y.agent=new G0.Agent(b)}return new Promise((m,y)=>{if(i?.aborted){let x=new Error("Request cancelled");x.name="AbortError",y(x);return}let q=(l?G0:jz).request(p,async x=>{let v=x.statusCode||0;if(r.followRedirects&&[301,302,303,307,308].includes(v)){if(n>=r.maxRedirects){y(new Error(`Maximum redirects (${r.maxRedirects}) exceeded`));return}let E=x.headers.location;if(!E){y(new Error("Redirect response missing Location header"));return}let k=new J0.URL(E,e.url).toString(),P=e.method;!r.followOriginalMethod&&[301,302,303].includes(v)&&(P="GET");let M={...e.headers};r.followAuthHeader||(delete M.authorization,delete M.Authorization);try{let j=await this.executeInternal({...e,url:k,method:P,headers:M,body:P==="GET"?void 0:e.body},r,n+1,i),I=Date.now();j.time=I-s,m(j)}catch(j){y(j)}return}let R=[];x.on("data",E=>R.push(E)),x.on("end",()=>{let E=Date.now(),k=Buffer.concat(R),P=x.headers["content-encoding"];if(r.decompress&&P)try{P==="gzip"?k=eg.gunzipSync(k):P==="deflate"&&(k=eg.inflateSync(k))}catch(_){console.warn("[NodeHttpClient] Decompression failed:",_)}let M=k.toString("utf-8"),j={};for(let[_,A]of Object.entries(x.headers))(typeof A=="string"||Array.isArray(A))&&(j[_]=A);let I=this.parseCookies(x.headers["set-cookie"],o.hostname);m({status:x.statusCode||0,statusText:x.statusMessage||"",headers:j,cookies:I,body:M,time:E-s,size:k.length})})});if(i&&i.addEventListener("abort",()=>{q.destroy();let x=new Error("Request cancelled");x.name="AbortError",y(x)}),q.on("error",x=>{y(x)}),q.on("timeout",()=>{q.destroy(),y(new Error("Request timeout"))}),e.body!==void 0&&e.body!==null){let x=typeof e.body=="string"?e.body:JSON.stringify(e.body);q.write(x)}q.end()})}resolveTlsSettings(e,r){let n=r.tls||{};if(!!(n.caPath||n.certPath||n.keyPath||n.pfxPath||n.servername||n.passphrase))return n;let s=this.findCertificateMapping(e,r.certificates||[]);return s?{caPath:s.caPath,certPath:s.certPath,keyPath:s.keyPath,pfxPath:s.pfxPath,passphrase:s.passphrase,servername:s.servername}:n}findCertificateMapping(e,r){if(!Array.isArray(r)||r.length===0)return;let n=e.hostname,i=e.port?Number(e.port):443,s=r.find(o=>this.mappingMatchesHost(o,n,i,!0));return s||r.find(o=>this.mappingMatchesHost(o,n,i,!1))}mappingMatchesHost(e,r,n,i){if(!e||e.enabled===!1)return!1;let s=String(e.host||"").trim().toLowerCase();if(!s||e.port!=null&&Number(e.port)!==n)return!1;let o=r.toLowerCase();if(i)return s!=="*"&&!s.startsWith("*.")&&o===s;if(s==="*")return!0;if(s.startsWith("*.")){let l=s.slice(2);return o===l||o.endsWith(`.${l}`)}return o===s}readOptionalFile(e,r){if(!e)return;let n=Xm.isAbsolute(e)?e:Xm.resolve(this.basePath,e);try{return CP.readFileSync(n)}catch(i){throw new Error(`[NodeHttpClient] Failed to read ${r} file at ${n}: ${i?.message||"Unknown error"}`)}}sanitizeHeaderValue(e){return e?String(e).replace(/[\u201C\u201D\u201E\u201F\u2033\u2036]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032\u2035]/g,"'").replace(/[\x00-\x08\x0A-\x1F\x7F]/g,""):""}sanitizeHeaders(e){let r={};for(let[n,i]of Object.entries(e))r[n]=this.sanitizeHeaderValue(String(i));return r}parseCookies(e,r){return e?e.map(n=>{let i=n.split(";").map(p=>p.trim()),[s,...o]=i,[l,c]=s.split("="),d={name:l.trim(),value:c?.trim()||"",domain:r};for(let p of o){let[m,y]=p.split("=");switch(m.toLowerCase().trim()){case"domain":d.domain=y?.trim();break;case"path":d.path=y?.trim();break;case"expires":d.expires=y?.trim();break;case"httponly":d.httpOnly=!0;break;case"secure":d.secure=!0;break}}return d}):[]}}});var Y0,qo,tg=le(()=>{"use strict";Y0={json:"application/json",xml:"application/xml",html:"text/html",text:"text/plain",javascript:"application/javascript",css:"text/css","x-www-form-urlencoded":"application/x-www-form-urlencoded","form-data":"multipart/form-data",graphql:"application/json"},qo=class{sanitizeHeaderValue(e){return e?String(e).replace(/[\u201C\u201D\u201E\u201F\u2033\u2036]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032\u2035]/g,"'").replace(/[\x00-\x08\x0A-\x1F\x7F]/g,""):""}sanitizeHeaders(e){let r={};for(let[n,i]of Object.entries(e))r[n]=this.sanitizeHeaderValue(String(i));return r}encodeBody(e){if(!e||e.type==="none")return null;let{type:r,content:n}=e;switch(r){case"x-www-form-urlencoded":return this.encodeUrlEncodedBody(n);case"form-data":return n;case"graphql":return this.encodeGraphQLBody(n);case"raw":return n;default:return n}}encodeUrlEncodedBody(e){if(Array.isArray(e)){let r=new URLSearchParams;for(let n of e)n.enabled!==!1&&n.key&&r.append(n.key,n.value||"");return r.toString()}return typeof e=="string"?e:String(e)}encodeGraphQLBody(e){if(typeof e=="string")try{e=JSON.parse(e)}catch{return e}if(typeof e=="object"&&e!==null&&e.query){let r=e.variables;if(typeof r=="string")try{r=r.trim()?JSON.parse(r):void 0}catch{r=void 0}return JSON.stringify({query:e.query,...r!=null?{variables:r}:{},...e.operationName?{operationName:e.operationName}:{}})}return JSON.stringify(e)}setContentTypeHeader(e,r,n){if(Object.keys(e).some(o=>o.toLowerCase()==="content-type"))return;if(n){e["Content-Type"]=n;return}if(!r||r.type==="none")return;let s;switch(r.type){case"x-www-form-urlencoded":s=Y0["x-www-form-urlencoded"];break;case"raw":s=r.format?Y0[r.format]:"text/plain",s||(s="text/plain");break;case"graphql":s=Y0.graphql;break;case"binary":s="application/octet-stream";break}s&&(e["Content-Type"]=s)}}});var Oo,rg=le(()=>{"use strict";Oo=class{parse(e,r){return r.toLowerCase().endsWith(".json")?this.parseJson(e):this.parseCsv(e)}parseJson(e){try{let r=JSON.parse(e);return Array.isArray(r)?r:[r]}catch{throw new Error("Failed to parse JSON data file: Invalid JSON format")}}parseCsv(e){let r=e.split(/\r?\n/).filter(s=>s.trim());if(r.length<2)return[{}];let n=this.parseCsvLine(r[0]),i=[];for(let s=1;s<r.length;s++){let o=this.parseCsvLine(r[s]),l={};n.forEach((c,d)=>{l[c]=o[d]||""}),i.push(l)}return i}parseCsvLine(e){let r=[],n="",i=!1;for(let s=0;s<e.length;s++){let o=e[s],l=e[s+1];o==='"'?i&&l==='"'?(n+='"',s++):i=!i:o===","&&!i?(r.push(n.trim()),n=""):n+=o}return r.push(n.trim()),r}}});var Ku,Lz,Qu,K0=le(()=>{"use strict";Ku=ve(require("crypto")),Lz=3e4,Qu=class{constructor(e,r,n,i,s="henry-huang.http-forge/oauth2/callback"){this.secretStore=e;this.browserService=r;this.envConfigService=n;this.httpService=i;this.callbackPath=s}secretStore;browserService;envConfigService;httpService;callbackPath;tokenCache=new Map;pendingAuthCallback=null;pendingImplicitCallback=null;async getToken(e,r){if(e.accessToken)return{accessToken:this.resolve(e.accessToken,r),tokenType:e.tokenPrefix||"Bearer",raw:{}};let n=this.buildCacheKeyString(e),i=this.tokenCache.get(n);if(i&&!this.isExpired(i))return i;if(i?.refreshToken)try{return await this.refreshToken(e,i.refreshToken,r)}catch{this.tokenCache.delete(n)}if(!i){let o=await this.secretStore.get(`oauth2_refresh_${n}`);if(o)try{return await this.refreshToken(e,o,r)}catch{await this.secretStore.delete(`oauth2_refresh_${n}`)}}let s;switch(e.grantType){case"client_credentials":s=await this.fetchToken(e,r,"client_credentials");break;case"password":s=await this.fetchToken(e,r,"password");break;case"authorization_code":s=await this.authorizationCodeFlow(e,r);break;case"implicit":s=await this.implicitFlow(e,r);break;default:throw new Error(`Unknown OAuth2 grant type: ${e.grantType}`)}return this.tokenCache.set(n,s),s.refreshToken&&await this.storeRefreshToken(n,s.refreshToken),s}async refreshToken(e,r,n){let i=this.resolve(e.tokenUrl||"",n);if(!i)throw new Error("OAuth2 tokenUrl is required for token refresh");let s=this.resolve(e.clientId||"",n),o=this.resolve(e.clientSecret||"",n),l=new URLSearchParams;l.append("grant_type","refresh_token"),l.append("refresh_token",r);let c={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,c,l,s,o,n);let d=await this.httpService.execute({method:"POST",url:i,headers:c,body:l.toString()}),p=this.parseTokenResponse(d.body,e);p.refreshToken||(p.refreshToken=r);let m=this.buildCacheKeyString(e);return this.tokenCache.set(m,p),p.refreshToken&&await this.storeRefreshToken(m,p.refreshToken),p}async authorizationCodeFlow(e,r){let n=this.resolve(e.authUrl||"",r),i=this.resolve(e.tokenUrl||"",r),s=this.resolve(e.clientId||"",r),o=this.resolve(e.clientSecret||"",r),l=e.scope?this.resolve(e.scope,r):void 0;if(!n)throw new Error("OAuth2 authUrl is required for authorization code flow");if(!i)throw new Error("OAuth2 tokenUrl is required for authorization code flow");if(!s)throw new Error("OAuth2 clientId is required for authorization code flow");let c=e.usePkce!==!1,d,p,m;if(c){d=this.generateCodeVerifier();let j=e.pkceMethod||"S256";p=j==="S256"?this.generateCodeChallengeS256(d):d,m=j}let y=e.state||Ku.randomBytes(16).toString("hex"),b=await this.getCallbackUri(),q=new URL(n);if(q.searchParams.set("response_type","code"),q.searchParams.set("client_id",s),q.searchParams.set("redirect_uri",b),l&&q.searchParams.set("scope",l),q.searchParams.set("state",y),p&&(q.searchParams.set("code_challenge",p),q.searchParams.set("code_challenge_method",m)),e.audience&&q.searchParams.set("audience",this.resolve(e.audience,r)),e.resource&&q.searchParams.set("resource",this.resolve(e.resource,r)),e.extraParams)for(let[j,I]of Object.entries(e.extraParams))q.searchParams.set(j,this.resolve(I,r));this.pendingAuthCallback&&(this.pendingAuthCallback.reject(new Error("OAuth2 authorization superseded by a new request")),this.pendingAuthCallback=null);let x=new Promise((j,I)=>{this.pendingAuthCallback={resolve:j,reject:I,state:y}});await this.browserService.openExternal(q.toString());let v;try{v=await Promise.race([x,new Promise((j,I)=>setTimeout(()=>{this.pendingAuthCallback=null,I(new Error("OAuth2 authorization timed out after 2 minutes"))},12e4))])}finally{this.pendingAuthCallback=null}if(v.state&&v.state!==y)throw new Error("OAuth2 state mismatch \u2014 potential CSRF attack");let R=new URLSearchParams;R.append("grant_type","authorization_code"),R.append("code",v.code),R.append("redirect_uri",b),d&&R.append("code_verifier",d);let E={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,E,R,s,o,r);let k=await this.httpService.execute({method:"POST",url:i,headers:E,body:R.toString()}),P=this.parseTokenResponse(k.body,e),M=this.buildCacheKeyString(e);return this.tokenCache.set(M,P),P.refreshToken&&await this.storeRefreshToken(M,P.refreshToken),P}async implicitFlow(e,r){let n=this.resolve(e.authUrl||"",r),i=this.resolve(e.clientId||"",r),s=e.scope?this.resolve(e.scope,r):void 0;if(!n)throw new Error("OAuth2 authUrl is required for implicit flow");if(!i)throw new Error("OAuth2 clientId is required for implicit flow");let o=e.state||Ku.randomBytes(16).toString("hex"),l=await this.getCallbackUri(),c=new URL(n);if(c.searchParams.set("response_type","token"),c.searchParams.set("client_id",i),c.searchParams.set("redirect_uri",l),s&&c.searchParams.set("scope",s),c.searchParams.set("state",o),e.audience&&c.searchParams.set("audience",this.resolve(e.audience,r)),e.resource&&c.searchParams.set("resource",this.resolve(e.resource,r)),e.extraParams)for(let[b,q]of Object.entries(e.extraParams))c.searchParams.set(b,this.resolve(q,r));this.pendingImplicitCallback&&(this.pendingImplicitCallback.reject(new Error("OAuth2 implicit flow superseded by a new request")),this.pendingImplicitCallback=null);let d=new Promise((b,q)=>{this.pendingImplicitCallback={resolve:b,reject:q,state:o}});await this.browserService.openExternal(c.toString());let p;try{p=await Promise.race([d,new Promise((b,q)=>setTimeout(()=>{this.pendingImplicitCallback=null,q(new Error("OAuth2 implicit flow timed out after 2 minutes"))},12e4))])}finally{this.pendingImplicitCallback=null}if(p.state&&p.state!==o)throw new Error("OAuth2 state mismatch \u2014 potential CSRF attack");let m={accessToken:p.accessToken,tokenType:p.tokenType||e.tokenPrefix||"Bearer",expiresAt:p.expiresIn?Date.now()+p.expiresIn*1e3:void 0,raw:{access_token:p.accessToken,token_type:p.tokenType,expires_in:p.expiresIn}},y=this.buildCacheKeyString(e);return this.tokenCache.set(y,m),m}handleAuthorizationCallback(e,r,n){if(n){let i=new Error(`OAuth2 authorization error: ${n}`);this.pendingAuthCallback?.reject(i),this.pendingImplicitCallback?.reject(i),this.pendingAuthCallback=null,this.pendingImplicitCallback=null;return}if(e&&this.pendingAuthCallback){this.pendingAuthCallback.resolve({code:e,state:r}),this.pendingAuthCallback=null;return}!e&&!this.pendingAuthCallback&&this.pendingImplicitCallback&&(this.pendingImplicitCallback.reject(new Error("OAuth2 implicit flow did not receive access_token")),this.pendingImplicitCallback=null)}handleImplicitCallback(e,r,n,i){this.pendingImplicitCallback&&(this.pendingImplicitCallback.resolve({accessToken:e,tokenType:r,expiresIn:n,state:i}),this.pendingImplicitCallback=null)}clearToken(e){let r=`${e.tokenUrl}|${e.clientId}|${e.scope||""}|${e.grantType}`;this.tokenCache.delete(r),this.secretStore.delete(`oauth2_refresh_${r}`)}clearAllTokens(){for(let e of this.tokenCache.keys())this.secretStore.delete(`oauth2_refresh_${e}`);this.tokenCache.clear()}async fetchToken(e,r,n){let i=this.resolve(e.tokenUrl||"",r);if(!i)throw new Error("OAuth2 tokenUrl is required");let s=this.resolve(e.clientId||"",r),o=this.resolve(e.clientSecret||"",r),l=e.scope?this.resolve(e.scope,r):void 0,c=new URLSearchParams;if(c.append("grant_type",n),l&&c.append("scope",l),n==="password"){let m=this.resolve(e.username||"",r),y=this.resolve(e.password||"",r);if(!m)throw new Error("OAuth2 password grant requires username");c.append("username",m),c.append("password",y)}if(e.audience&&c.append("audience",this.resolve(e.audience,r)),e.resource&&c.append("resource",this.resolve(e.resource,r)),e.extraParams)for(let[m,y]of Object.entries(e.extraParams))c.append(m,this.resolve(y,r));let d={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,d,c,s,o,r);let p=await this.httpService.execute({method:"POST",url:i,headers:d,body:c.toString()});return this.parseTokenResponse(p.body,e)}applyClientAuth(e,r,n,i,s,o){if(e.clientAuthentication==="header"){let l=Buffer.from(`${i}:${s}`).toString("base64");r.Authorization=`Basic ${l}`}else i&&n.set("client_id",i),s&&n.set("client_secret",s)}parseTokenResponse(e,r){let n=e;if(typeof n=="string")try{n=JSON.parse(n)}catch{throw new Error("OAuth2 token response is not valid JSON")}if(!n||typeof n!="object")throw new Error("OAuth2 token response is not a valid JSON object");let i=n,s=r.tokenField||"access_token",o=i[s];if(!o)throw new Error(`OAuth2 token fetch failed: '${s}' not present in response`);let l=typeof i.expires_in=="number"?i.expires_in:void 0;return{accessToken:o,tokenType:i.token_type||r.tokenPrefix||"Bearer",expiresAt:l?Date.now()+l*1e3:void 0,refreshToken:i.refresh_token,scope:i.scope,raw:i}}isExpired(e){return e.expiresAt?Date.now()>=e.expiresAt-Lz:!1}buildCacheKeyString(e){return`${e.tokenUrl||""}|${e.clientId||""}|${e.scope||""}|${e.grantType}`}async getCallbackUri(){let e=`${this.browserService.uriScheme}://${this.callbackPath}`;return this.browserService.asExternalUri(e)}resolve(e,r){return this.envConfigService.resolveVariables(e,r)}generateCodeVerifier(){return Ku.randomBytes(32).toString("base64url")}generateCodeChallengeS256(e){return Ku.createHash("sha256").update(e).digest("base64url")}async storeRefreshToken(e,r){try{await this.secretStore.store(`oauth2_refresh_${e}`,r)}catch{}}}});function Ka(t,e={}){let r=[];Object.entries(e).forEach(([n,i])=>{r.push(`${n}=${i}`)}),r.length&&Ya.writeFileSync(t,r.join(`
53
53
  `),"utf-8")}function Zu(t,e,r){r&&(r.preRequest&&r.preRequest.trim()&&Ya.writeFileSync(Po.join(t,`${e}.pre.js`),r.preRequest,"utf-8"),r.postResponse&&r.postResponse.trim()&&Ya.writeFileSync(Po.join(t,`${e}.post.js`),r.postResponse,"utf-8"))}function EP(t,e){let n=e&&e.trim()?e.trim():"collections-rest-client";return Po.isAbsolute(n)?n:Po.join(t,n)}async function qP(t,e,r,n,i){await t.exportCollectionAsRestClientFolder(r,n),e.exportEnvironmentsToFolder(n,i)}function yd(t,e,r){t.forEach(n=>{if(n.type==="folder"){let i=Po.join(e,Bt(n.name));Ya.mkdirSync(i,{recursive:!0}),Zu(i,Bt(n.name),n.scripts),yd(n.items||[],i,r)}else if(n.type==="request"){let i=n,s=Bt(i.name)+".http",o=Po.join(e,s),l=Uz(i,r);Ya.writeFileSync(o,l,"utf-8"),Zu(e,Bt(i.name),i.scripts)}})}function Uz(t,e){let r=[];r.push(`### ${e.name} / ${t.name}`),r.push(`# collection env: ${Bt(e.name)}.env`),r.push(`# request scripts: ${Bt(t.name)}.pre.js and .post.js`);let n=Hz(t);return r.push(`${t.method} ${n}`),(t.headers||[]).filter(i=>i.enabled!==!1).forEach(i=>{r.push(`${i.key}: ${i.value}`)}),t.body&&t.body.content&&r.push("",t.body.content),r.join(`
54
54
  `)}function Hz(t){let e=t.url;if(t.query&&t.query.length){let r=t.query.filter(n=>n.enabled!==!1).map(n=>`${encodeURIComponent(n.key)}=${encodeURIComponent(n.value)}`).join("&");r&&(e+=(e.includes("?")?"&":"?")+r)}return e}var Ya,Po,ig=le(()=>{"use strict";Ya=ve(require("fs")),Po=ve(require("path"));Un()});var Or,Q0,Qa,Z0=le(()=>{"use strict";Or=ve(require("fs")),Q0=ve(require("path"));Un();Qa=class{collectionsDir;cache=new Map;constructor(e){this.collectionsDir=e,this.ensureDirectory()}ensureDirectory(){Or.existsSync(this.collectionsDir)||Or.mkdirSync(this.collectionsDir,{recursive:!0})}loadAll(){if(this.cache.clear(),!Or.existsSync(this.collectionsDir))return[];let e=Or.readdirSync(this.collectionsDir),r=[];for(let n of e)if(n.endsWith(".json"))try{let i=Q0.join(this.collectionsDir,n),s=Or.readFileSync(i,"utf-8"),o=JSON.parse(s);o.id&&o.name&&(this.cache.set(o.id,o),r.push(o))}catch(i){console.error(`[JsonCollectionLoader] Failed to load ${n}:`,i)}return r}load(e){if(this.cache.has(e))return this.cache.get(e);let r=this.getCollectionPath(e);if(Or.existsSync(r))try{let n=Or.readFileSync(r,"utf-8"),i=JSON.parse(n);return this.cache.set(e,i),i}catch(n){console.error(`[JsonCollectionLoader] Failed to load collection ${e}:`,n);return}}async save(e){if(this.ensureDirectory(),!e.name)throw new Error("Collection name is required");e.id||(e.id=It(e.name));let r=this.getCollectionPath(e.id),n=JSON.stringify(e,null,2);await Or.promises.writeFile(r,n,"utf-8"),this.cache.set(e.id,e)}async delete(e){let r=this.getCollectionPath(e);if(!Or.existsSync(r))return!1;try{return await Or.promises.unlink(r),this.cache.delete(e),!0}catch(n){return console.error(`[JsonCollectionLoader] Failed to delete collection ${e}:`,n),!1}}exists(e){return Or.existsSync(this.getCollectionPath(e))}getCollectionPath(e){return Q0.join(this.collectionsDir,`${e}.json`)}getItemPath(e,r){}async create(e,r){let n={id:r||It(e),name:e,items:[]};return await this.save(n),n}async saveScripts(e,r,n){let i=this.load(e);if(!i)throw new Error(`Collection ${e} not found`);let s=this.findItemById(i.items,r);s&&(s.scripts=n,await this.save(i))}loadScripts(e,r){let n=this.load(e);return n?this.findItemById(n.items,r)?.scripts:void 0}async updateCollectionMetadata(e,r){let n=this.load(e);if(!n)throw new Error(`Collection ${e} not found`);r.name!==void 0&&(n.name=r.name),r.description!==void 0&&(n.description=r.description),r.version!==void 0&&(n.version=r.version),r.variables!==void 0&&(n.variables=r.variables),r.auth!==void 0&&(n.auth=r.auth),await this.save(n)}async saveItem(e,r,n){let i=this.load(e);if(!i)throw new Error(`Collection ${e} not found`);let s=this.findItemById(i.items,r.id);if(s)Object.assign(s,r);else if(n){let o=this.findItemById(i.items,n);if(o&&o.type==="folder")o.items=o.items||[],o.items.push(r);else throw new Error(`Parent folder ${n} not found`)}else i.items.push(r);await this.save(i)}async deleteItem(e,r){let n=this.load(e);if(!n)return!1;let i=this.deleteItemById(n.items,r);return i&&await this.save(n),i}async updateItem(e,r,n){let i=this.load(e);if(!i)return!1;let s=this.findItemById(i.items,r);if(!s)return!1;let{id:o,type:l,...c}=n;return Object.assign(s,c),await this.save(i),!0}async moveItem(e,r,n){let i=this.load(e);if(!i)return!1;let s=this.findItemById(i.items,r);if(!s)return!1;let o={...s};if(!this.deleteItemById(i.items,r))return!1;if(n){let l=this.findItemById(i.items,n);if(l&&l.type==="folder")l.items=l.items||[],l.items.push(o);else return i.items.push(o),!1}else i.items.push(o);return await this.save(i),!0}async reorderItems(e,r,n){let i=this.load(e);if(!i)return!1;try{let s;if(r){let c=this.findItemById(i.items,r);if(!c||!c.items)return!1;s=c.items}else s=i.items;let o=new Map(s.map(c=>[c.id,c])),l=[];for(let c of n){let d=o.get(c);d&&(l.push(d),o.delete(c))}for(let c of o.values())l.push(c);if(r){let c=this.findItemById(i.items,r);c&&(c.items=l)}else i.items=l;return await this.save(i),!0}catch(s){return console.error("[JsonCollectionLoader] Failed to reorder items:",s),!1}}findItemById(e,r){for(let n of e){if(n.id===r)return n;if(n.type==="folder"&&n.items){let i=this.findItemById(n.items,r);if(i)return i}}}deleteItemById(e,r){for(let n=0;n<e.length;n++){if(e[n].id===r)return e.splice(n,1),!0;let i=e[n];if(i.type==="folder"&&i.items&&this.deleteItemById(i.items,r))return!0}return!1}}});var Xu,X0=le(()=>{"use strict";nm();Z0();Xu=class{static create(e){let r=e.getStorageConfig(),n=e.getCollectionsPath();return r.format==="folder"?new xs(n):new Qa(n)}static createForFormat(e,r){return e==="folder"?new xs(r):new Qa(r)}}});function IP(t){if(typeof t!="string")return"text";let e=t.trim();try{let r=JSON.parse(e);if(typeof r=="object"&&r!==null)return"json"}catch{}return/^<\?xml/.test(e)||/^<([a-zA-Z_][\w\-\.]*)[\s>]/.test(e)?/^<\!DOCTYPE html>/i.test(e)||/^<html[\s>]/i.test(e)?"html":"xml":/^<\!DOCTYPE html>/i.test(e)||/^<html[\s>]/i.test(e)?"html":/^(function\s*\(|\(\)\s*=>|const |let |var |export |import )/.test(e)?"javascript":"text"}function Bz(t){return{info:{name:t.name,_postman_id:t.id,schema:"https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},item:t.items.map(e=>OP(e)),event:e_(t.scripts),variable:t.variables?Object.entries(t.variables).map(([e,r])=>({key:e,value:r})):[]}}function OP(t){if(t.type==="folder")return{name:t.name,item:t.items?t.items.map(OP):[],event:e_(t.scripts)};if(t.type==="request"){let e=t;return{name:e.name,request:{method:e.method,header:(e.headers||[]).map(Vz),url:Wz(e),body:zz(e),auth:Jz(e.auth),description:e.description},event:e_(e.scripts),protocolProfileBehavior:Gz(e.settings)}}}function Vz(t){return{key:t.key,value:t.value,disabled:t.enabled===!1,...t.description!==void 0?{description:t.description}:{},...t.type!==void 0?{type:t.type}:{},...t.required!==void 0?{required:t.required}:{},...t.format!==void 0?{format:t.format}:{},...t.enum!==void 0?{enum:t.enum}:{},...t.deprecated!==void 0?{deprecated:t.deprecated}:{},...t.pattern!==void 0?{pattern:t.pattern}:{},...t.minLength!==void 0?{minLength:t.minLength}:{},...t.maxLength!==void 0?{maxLength:t.maxLength}:{},...t.minimum!==void 0?{minimum:t.minimum}:{},...t.maximum!==void 0?{maximum:t.maximum}:{},...t.exclusiveMinimum!==void 0?{exclusiveMinimum:t.exclusiveMinimum}:{},...t.exclusiveMaximum!==void 0?{exclusiveMaximum:t.exclusiveMaximum}:{},...t.multipleOf!==void 0?{multipleOf:t.multipleOf}:{},...t.minItems!==void 0?{minItems:t.minItems}:{},...t.maxItems!==void 0?{maxItems:t.maxItems}:{},...t.uniqueItems!==void 0?{uniqueItems:t.uniqueItems}:{},...t.nullable!==void 0?{nullable:t.nullable}:{},...t.oneOf!==void 0?{oneOf:t.oneOf}:{}}}function Wz(t){let e=t.url,r=t.url.replace(/^[a-zA-Z]+:\/\//,""),n=[],i=r.match(/^([^\/\?]+)/);if(i){let d=i[1];/^{{.*}}$/.test(d)?n=[d]:n=d.split(".")}let s=[],o=r.match(/^[^\/\?]+(\/[^\?]*)?/);if(o&&o[1]!==void 0){let d=o[1].replace(/^\//,"");d.endsWith("/")?(s=d.slice(0,-1).split("/"),s.push("")):s=d.length>0?d.split("/"):[]}let l;if(Array.isArray(t.query)&&t.query.length>0)l=t.query.map(d=>{let p={key:d.key,value:d.value};return d.enabled===!1&&(p.disabled=!0),d.description!==void 0&&(p.description=d.description),d.type!==void 0&&(p.type=d.type),d.required!==void 0&&(p.required=d.required),d.format!==void 0&&(p.format=d.format),d.enum!==void 0&&(p.enum=d.enum),d.deprecated!==void 0&&(p.deprecated=d.deprecated),d.pattern!==void 0&&(p.pattern=d.pattern),d.minLength!==void 0&&(p.minLength=d.minLength),d.maxLength!==void 0&&(p.maxLength=d.maxLength),d.minimum!==void 0&&(p.minimum=d.minimum),d.maximum!==void 0&&(p.maximum=d.maximum),d.exclusiveMinimum!==void 0&&(p.exclusiveMinimum=d.exclusiveMinimum),d.exclusiveMaximum!==void 0&&(p.exclusiveMaximum=d.exclusiveMaximum),d.multipleOf!==void 0&&(p.multipleOf=d.multipleOf),d.minItems!==void 0&&(p.minItems=d.minItems),d.maxItems!==void 0&&(p.maxItems=d.maxItems),d.uniqueItems!==void 0&&(p.uniqueItems=d.uniqueItems),d.nullable!==void 0&&(p.nullable=d.nullable),d.oneOf!==void 0&&(p.oneOf=d.oneOf),p});else{let d=r.indexOf("?");d!==-1&&(l=r.substring(d+1).split("&").map(m=>{let[y,...b]=m.split("=");return{key:y,value:b.join("=")}}))}let c;return t.params&&typeof t.params=="object"&&(c=Object.entries(t.params).map(([d,p])=>({key:d,value:String(p)}))),{raw:e,host:n.length>0?n:void 0,path:s.length>0?s:void 0,query:l&&l.length>0?l:void 0,variable:c&&c.length>0?c:void 0}}function zz(t){if(!t.body)return;let e=t.body;if(typeof e=="string"){let s=IP(e);return{mode:"raw",raw:e,options:{raw:{language:s}}}}if(e.type==="raw"){let s=e.format||IP(e.content);return{mode:"raw",raw:e.content,options:{raw:{language:s}}}}let r=e.type==="form-data"&&Array.isArray(e.content)?e.content:e.type==="formdata"&&Array.isArray(e.fields)?e.fields:null;if(r)return{mode:"formdata",formdata:r.map(s=>({key:s.key,value:s.value,type:s.type||"text",disabled:s.enabled===!1}))};let n=e.type==="x-www-form-urlencoded"&&Array.isArray(e.content)?e.content:e.type==="urlencoded"&&Array.isArray(e.fields)?e.fields:null;if(n)return{mode:"urlencoded",urlencoded:n.map(s=>({key:s.key,value:s.value,disabled:s.enabled===!1}))};if(e.type==="file"&&e.fileName)return{mode:"file",file:{src:e.fileName}};if(e.type==="binary")return{mode:"binary",file:{}};let i=e.type==="graphql"?e.content??(e.query?e:null):null;if(i){let s=i.query??"",o=i.variables;return{mode:"graphql",graphql:{query:s,variables:o?typeof o=="string"?o:JSON.stringify(o):void 0}}}if(e.content)return{mode:"raw",raw:e.content}}function Jz(t){if(!(!t||!t.type||t.type==="none")){if(t.type==="bearer")return{type:"bearer",bearer:[{key:"token",value:t.bearerToken,type:"string"}]};if(t.type==="basic"&&t.basicAuth)return{type:"basic",basic:[{key:"username",value:t.basicAuth.username,type:"string"},{key:"password",value:t.basicAuth.password,type:"string"}]}}}function Gz(t){if(!t)return;let e={};return t.followRedirects===!1&&(e.followRedirects=!1),t.followOriginalMethod===!0&&(e.followOriginalHttpMethod=!0),t.followAuthHeader===!1&&(e.followAuthorizationHeader=!1),t.maxRedirects!==void 0&&(e.maxRedirects=t.maxRedirects),t.strictSSL===!1&&(e.disableUrlEncoding=!1),t.timeout!==void 0&&(e.requestTimeout=t.timeout),Object.keys(e).length>0?e:void 0}function e_(t){if(!t)return[];let e=[];return t.preRequest&&e.push({listen:"prerequest",script:{type:"text/javascript",exec:[t.preRequest]}}),t.postResponse&&e.push({listen:"test",script:{type:"text/javascript",exec:[t.postResponse]}}),e}var Dt,mi,ec,t_=le(()=>{"use strict";Un();ig();X0();Dt=ve(require("fs")),mi=ve(require("path"));ec=class{constructor(e,r,n){this.workspaceRoot=e;this.configService=r;this.fileWatcherFactory=n;this.collectionsDir=r.getCollectionsPath(),this.loader=Xu.create(r),this.ensureCollectionsDir(),this.loadCollections(),this.setupFileWatcher()}workspaceRoot;configService;fileWatcherFactory;collectionsDir;collections=new Map;fileWatcher;loader;debounceTimer=null;selfWritePending=!1;localCollectionValues=new Map;onCollectionsChanged;ensureCollectionsDir(){Dt.existsSync(this.collectionsDir)||Dt.mkdirSync(this.collectionsDir,{recursive:!0})}loadCollections(){this.collections.clear();let e=this.loader.loadAll();for(let r of e)this.collections.set(r.id,r)}setupFileWatcher(){if(!this.fileWatcherFactory)return;this.fileWatcher=this.fileWatcherFactory.createFileWatcher(this.collectionsDir,"**/*");let e=()=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null;let r=this.selfWritePending;this.selfWritePending=!1,r||this.loadCollections(),this.onCollectionsChanged?.()},300)};this.fileWatcher.onDidChange(e),this.fileWatcher.onDidCreate(e),this.fileWatcher.onDidDelete(e)}getAllCollections(){return Array.from(this.collections.values())}getCollection(e){return this.collections.get(e)}getCollectionById(e){for(let r of this.collections.values())if(r.id===e)return r}getCollectionByName(e){let r=e.toLowerCase();for(let n of this.collections.values())if(n.name.toLowerCase()===r)return n}async saveCollection(e){if(this.ensureCollectionsDir(),!e.name)throw new Error("Collection name is required");e.id||(e.id=It(e.name)),this.selfWritePending=!0,await this.loader.save(e),this.collections.set(e.id,e)}getCollectionVariables(e){let r=this.collections.get(e);return r?.variables?{...r.variables}:{}}getCollectionVariableLocals(e){return{...this.localCollectionValues.get(e)||{}}}setCollectionVariable(e,r,n){this.localCollectionValues.has(e)||this.localCollectionValues.set(e,{}),this.localCollectionValues.get(e)[r]=String(n)}deleteCollectionVariable(e,r){let n=this.localCollectionValues.get(e);n&&delete n[r]}clearCollectionVariables(e){this.localCollectionValues.set(e,{})}async deleteCollection(e){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let n=await this.loader.delete(e);return n&&this.collections.delete(e),n}findRequest(e,r){let n=this.collections.get(e);if(n)return this.findItemRecursive(n.items,r)}findRequestByPath(e,r){let n=this.collections.get(e);if(!n)return;let i=r.split("/").filter(s=>s.trim());return this.findItemByPath(n.items,i)}async updateRequest(e,r,n){let i=this.collections.get(e);if(!i)return!1;this.selfWritePending=!0;let s=await this.loader.updateItem(e,r,n);if(s){let o=this.findItemRecursive(i.items,r);if(o){let{id:l,type:c,...d}=n;Object.assign(o,d)}}return s}async addRequest(e,r,n){if(!this.collections.get(e))return!1;r.id||(r.id=It(r.name)),this.selfWritePending=!0;try{return await this.loader.saveItem(e,r,n),!0}catch(s){return console.error("[CollectionService] Failed to add request:",s),!1}}async deleteRequest(e,r){let n=this.collections.get(e);if(!n)return!1;this.selfWritePending=!0;let i=await this.loader.deleteItem(e,r);return i&&this.deleteItemRecursive(n.items,r),i}getAllRequests(e){let r=this.collections.get(e);if(!r)return[];let n=[];return this.collectRequestsRecursive(r.items,n),n}findItemRecursive(e,r){for(let n of e){if(n.id===r)return n;if(n.type==="folder"&&n.items){let i=this.findItemRecursive(n.items,r);if(i)return i}}}findItemByPath(e,r){if(r.length===0)return;let[n,...i]=r,s=e.find(o=>o.name===n);if(s){if(i.length===0)return s;if(s.type==="folder"&&s.items)return this.findItemByPath(s.items,i)}}updateItemRecursive(e,r,n){for(let i=0;i<e.length;i++){let s=e[i];if(s.id===r)return e[i]={...s,...n},!0;if(s.type==="folder"&&s.items&&this.updateItemRecursive(s.items,r,n))return!0}return!1}deleteItemRecursive(e,r){for(let n=0;n<e.length;n++){let i=e[n];if(i.id===r)return e.splice(n,1),!0;if(i.type==="folder"&&i.items&&this.deleteItemRecursive(i.items,r))return!0}return!1}collectRequestsRecursive(e,r){for(let n of e)n.type==="request"?r.push(n):n.type==="folder"&&n.items&&this.collectRequestsRecursive(n.items,r)}async createCollection(e){let r={id:It(e),name:e,items:[]};return await this.saveCollection(r),r}async renameCollection(e,r){let n=this.collections.get(e);return n?(n.name=r,await this.saveCollection(n),!0):!1}async duplicateCollection(e,r){if(!this.collections.get(e))throw new Error(`Collection not found: ${e}`);this.selfWritePending=!0;let i=It(r),s=this.loader.getCollectionPath(e),o=mi.join(this.collectionsDir,i);if(!Dt.existsSync(s))throw new Error(`Collection directory not found: ${s}`);this.copyDirRecursive(s,o);let l=mi.join(o,"collection.json");if(Dt.existsSync(l)){let d=JSON.parse(Dt.readFileSync(l,"utf-8"));d.id=i,d.name=r,Dt.writeFileSync(l,JSON.stringify(d,null,2))}else Dt.writeFileSync(l,JSON.stringify({id:i,name:r},null,2));this.loadCollections();let c=this.collections.get(i);if(!c)throw new Error("Failed to load duplicated collection");return c}async createFolder(e){if(!this.collections.get(e.collectionId))throw new Error("Collection not found");this.selfWritePending=!0;let n={id:It(e.name),type:"folder",name:e.name,items:[]};await this.loader.saveItem(e.collectionId,n,e.parentId);let i=this.loader.load(e.collectionId);return i&&this.collections.set(e.collectionId,i),n}async deleteFolder(e,r){let n=this.collections.get(e);if(!n)return!1;this.selfWritePending=!0;let i=await this.loader.deleteItem(e,r);return i&&this.deleteItemById(n.items,r),i}async renameFolder(e,r,n){let i=this.collections.get(e);if(!i)return!1;this.selfWritePending=!0;let s=await this.loader.updateItem(e,r,{name:n});if(s){let o=this.findItemById(i.items,r);o&&(o.name=n)}return s}async duplicateFolder(e,r,n){if(!this.collections.get(e))throw new Error("Collection not found");let s=this.loader.getItemPath(e,r);if(!s||!Dt.existsSync(s))throw new Error(`Folder not found on disk: ${r}`);let o=mi.dirname(s),l=It(n),c=mi.join(o,l);this.selfWritePending=!0,this.copyDirRecursive(s,c);let d=mi.join(c,"folder.json");if(Dt.existsSync(d)){let y=JSON.parse(Dt.readFileSync(d,"utf-8"));y.id=l,y.name=n,Dt.writeFileSync(d,JSON.stringify(y,null,2))}else Dt.writeFileSync(d,JSON.stringify({id:l,name:n,type:"folder"},null,2));this.loadCollections();let p=this.collections.get(e),m=p?this.findItemById(p.items,l):void 0;return m||{id:l,type:"folder",name:n,items:[]}}async createRequest(e){if(!this.collections.get(e.collectionId))throw new Error("Collection not found");this.selfWritePending=!0;let n={id:e.id||It(e.name),type:"request",name:e.name,method:e.method||"GET",url:e.url,params:e.params,query:e.query,headers:e.headers,body:e.body,auth:e.auth,settings:e.settings,scripts:e.scripts,deprecated:e.deprecated,description:e.description,doc:e.doc,responseSchema:e.responseSchema,bodySchema:e.bodySchema,operationId:e.operationId,summary:e.summary,tags:e.tags,examples:e.examples,responses:e.responses,security:e.security};await this.loader.saveItem(e.collectionId,n,e.parentId);let i=this.loader.load(e.collectionId);return i&&this.collections.set(e.collectionId,i),n}async renameRequest(e,r,n){let i=this.collections.get(e);if(!i)return!1;this.selfWritePending=!0;let s=await this.loader.updateItem(e,r,{name:n});if(s){let o=this.findItemById(i.items,r);o&&(o.name=n)}return s}async moveItem(e,r,n){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let s=await this.loader.moveItem(e,r,n);return s&&this.loadCollections(),s}async reorderItems(e,r,n){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let s=await this.loader.reorderItems(e,r,n);return s&&this.loadCollections(),s}getRequestScript(e,r,n){let i=this.collections.get(e);if(!i)return;let s=this.findItemById(i.items,r);if(!s||s.type!=="request")return;let o=s;return n==="pre-request"?o.scripts?.preRequest:o.scripts?.postResponse}async setRequestScript(e,r,n,i){let s=this.collections.get(e);if(!s)return!1;let o=this.findItemById(s.items,r);if(!o||o.type!=="request")return!1;let l=o,d={...l.scripts??{},...n==="pre-request"?{preRequest:i}:{postResponse:i}};l.scripts=d,this.selfWritePending=!0;try{return await this.loader.saveScripts(e,r,d),!0}catch{return!1}}findItemById(e,r){for(let n of e){if(n.id===r)return n;if(n.type==="folder"&&n.items){let i=this.findItemById(n.items,r);if(i)return i}}}copyDirRecursive(e,r){Dt.existsSync(r)||Dt.mkdirSync(r,{recursive:!0});for(let n of Dt.readdirSync(e,{withFileTypes:!0})){let i=mi.join(e,n.name),s=mi.join(r,n.name);n.isDirectory()?this.copyDirRecursive(i,s):Dt.copyFileSync(i,s)}}deleteItemById(e,r){for(let n=0;n<e.length;n++){let i=e[n];if(i.id===r)return e.splice(n,1),!0;if(i.type==="folder"&&i.items&&this.deleteItemById(i.items,r))return!0}return!1}async importCollection(e){let r=Dt.readFileSync(e,"utf-8"),n;try{n=JSON.parse(r)}catch{throw new Error("Invalid JSON file")}if(n.info&&n.info._postman_id)return this.importPostmanCollection(n);let i={id:n.id||It(n.name||"Imported Collection"),name:n.name||"Imported Collection",description:n.description,items:n.items||[]};return await this.saveCollection(i),i}async importPostmanCollection(e){let r=p=>{if(!p)return;switch(p.type?.toLowerCase()){case"bearer":return{type:"bearer",bearerToken:p.bearer?.find(E=>E.key==="token")?.value||""};case"basic":let b=p.basic?.find(E=>E.key==="username"),q=p.basic?.find(E=>E.key==="password");return{type:"basic",basicAuth:{username:b?.value||"",password:q?.value||""}};case"apikey":let x=p.apikey?.find(E=>E.key==="key"),v=p.apikey?.find(E=>E.key==="value"),R=p.apikey?.find(E=>E.key==="in");return{type:"apikey",apikey:{key:x?.value||"",value:v?.value||"",in:R?.value||"header"}};case"noauth":return{type:"none"};default:return}},n=p=>{if(!Array.isArray(p)||p.length===0)return;let m={};for(let y of p){let b=y.script?.exec;if(!b)continue;let q=Array.isArray(b)?b.join(`
55
55
  `):b;y.listen==="prerequest"?m.preRequest=q:y.listen==="test"&&(m.postResponse=q)}return m.preRequest||m.postResponse?m:void 0},i=p=>{if(!p||typeof p!="object")return;let m={};return p.followRedirects===!1&&(m.followRedirects=!1),p.followOriginalHttpMethod===!0&&(m.followOriginalMethod=!0),p.followAuthorizationHeader===!1&&(m.followAuthHeader=!1),p.maxRedirects!==void 0&&(m.maxRedirects=p.maxRedirects),p.requestTimeout!==void 0&&(m.timeout=p.requestTimeout),Object.keys(m).length>0?m:void 0},s=p=>{if(!p||typeof p=="string")return;let m=p.query;if(!(!Array.isArray(m)||m.length===0))return m.map(y=>({key:y.key||"",value:y.value||"",enabled:y.disabled!==!0,...y.description!==void 0?{description:y.description}:{},...y.type!==void 0?{type:y.type}:{},...y.required!==void 0?{required:y.required}:{},...y.format!==void 0?{format:y.format}:{},...y.enum!==void 0?{enum:y.enum}:{},...y.deprecated!==void 0?{deprecated:y.deprecated}:{},...y.pattern!==void 0?{pattern:y.pattern}:{},...y.minLength!==void 0?{minLength:y.minLength}:{},...y.maxLength!==void 0?{maxLength:y.maxLength}:{},...y.minimum!==void 0?{minimum:y.minimum}:{},...y.maximum!==void 0?{maximum:y.maximum}:{},...y.exclusiveMinimum!==void 0?{exclusiveMinimum:y.exclusiveMinimum}:{},...y.exclusiveMaximum!==void 0?{exclusiveMaximum:y.exclusiveMaximum}:{},...y.multipleOf!==void 0?{multipleOf:y.multipleOf}:{},...y.minItems!==void 0?{minItems:y.minItems}:{},...y.maxItems!==void 0?{maxItems:y.maxItems}:{},...y.uniqueItems!==void 0?{uniqueItems:y.uniqueItems}:{},...y.nullable!==void 0?{nullable:y.nullable}:{},...y.oneOf!==void 0?{oneOf:y.oneOf}:{}}))},o=p=>{if(typeof p=="string")return p;if(!p)return"";let m=new Set;if(Array.isArray(p.variable))for(let b of p.variable)b.key&&m.add(b.key);if(m.size===0&&p.raw)return p.raw;let y="";if(p.protocol&&(y+=p.protocol+"://"),p.host&&(y+=Array.isArray(p.host)?p.host.join("."):p.host),p.port&&(y+=":"+p.port),p.path){let q=(Array.isArray(p.path)?p.path:[p.path]).map(x=>{let v=x.startsWith(":")?x.substring(1):x;return m.has(v)?":"+v:(x.startsWith(":"),x)});y+="/"+q.join("/")}return!y&&p.raw?p.raw:y},l=p=>{if(!Array.isArray(p)||p.length===0)return;let m={responses:{}};for(let y of p){let b=String(y.code||200),q,x={};if(Array.isArray(y.header))for(let P of y.header)!P.key||P.disabled||(P.key.toLowerCase()==="content-type"?q=P.value?.split(";")[0]?.trim():x[P.key]={description:String(P.value??""),schema:{type:"string"}});let v=y.body;if(typeof y.body=="string"&&y.body)try{v=JSON.parse(y.body)}catch{}let R=y.originalRequest,E;if(R){let P=typeof R.url=="string"?R.url:R.url?.raw??"";E=`${R.method||""} ${P}`.trim()||void 0}let k=y.name?y.name.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toLowerCase()||`example_${b}`:`example_${b}`;if(m.responses[b]){let P=m.responses[b];P.examples=P.examples??{},P.examples[k]={summary:E,value:v}}else m.responses[b]={description:y.name,contentType:q,examples:{[k]:{summary:E,value:v}},...Object.keys(x).length>0?{headers:x}:{}}}return Object.keys(m.responses).length>0?m:void 0},c=p=>p.map(m=>{if(m.item)return{id:It(m.name),type:"folder",name:m.name,description:m.description,auth:r(m.auth),scripts:n(m.event),items:c(m.item)};{let y=m.request||{};return{id:It(m.name),type:"request",name:m.name,description:m.description||y.description,method:typeof y.method=="string"?y.method:"GET",url:o(y.url),query:s(y.url),headers:Array.isArray(y.header)?y.header.map(b=>({key:b.key||b.name||"",value:b.value||b.value||"",enabled:b.disabled!==!0,...b.description!==void 0?{description:b.description}:{},...b.type!==void 0?{type:b.type}:{},...b.required!==void 0?{required:b.required}:{},...b.format!==void 0?{format:b.format}:{},...b.enum!==void 0?{enum:b.enum}:{},...b.deprecated!==void 0?{deprecated:b.deprecated}:{},...b.pattern!==void 0?{pattern:b.pattern}:{},...b.minLength!==void 0?{minLength:b.minLength}:{},...b.maxLength!==void 0?{maxLength:b.maxLength}:{},...b.minimum!==void 0?{minimum:b.minimum}:{},...b.maximum!==void 0?{maximum:b.maximum}:{},...b.exclusiveMinimum!==void 0?{exclusiveMinimum:b.exclusiveMinimum}:{},...b.exclusiveMaximum!==void 0?{exclusiveMaximum:b.exclusiveMaximum}:{},...b.multipleOf!==void 0?{multipleOf:b.multipleOf}:{},...b.minItems!==void 0?{minItems:b.minItems}:{},...b.maxItems!==void 0?{maxItems:b.maxItems}:{},...b.uniqueItems!==void 0?{uniqueItems:b.uniqueItems}:{},...b.nullable!==void 0?{nullable:b.nullable}:{},...b.oneOf!==void 0?{oneOf:b.oneOf}:{}})):[],body:(()=>{let b=y.body;if(b){if(b.mode==="raw"&&b.raw){let q=b.options?.raw?.language;return{type:"raw",format:q==="xml"?"xml":q==="html"?"html":q==="javascript"?"javascript":q==="text"?"text":"json",content:b.raw}}if(b.mode==="urlencoded"&&Array.isArray(b.urlencoded))return{type:"x-www-form-urlencoded",content:b.urlencoded.map(q=>({key:q.key||"",value:q.value||"",enabled:q.disabled!==!0}))};if(b.mode==="formdata"&&Array.isArray(b.formdata))return{type:"form-data",content:b.formdata.map(q=>({key:q.key||"",value:q.value||"",type:q.type||"text",enabled:q.disabled!==!0}))};if(b.mode==="graphql"&&b.graphql){let q;if(b.graphql.variables)try{q=JSON.parse(b.graphql.variables)}catch{q=void 0}return{type:"graphql",content:{query:b.graphql.query||"",variables:q}}}if(b.mode==="binary")return{type:"binary",content:""}}})(),auth:r(y.auth),scripts:n(m.event),settings:i(m.protocolProfileBehavior),responseSchema:l(m.response)}}}),d={id:It(e.info?.name||"Imported Postman Collection"),name:e.info?.name||"Imported Postman Collection",description:e.info?.description,auth:r(e.auth),scripts:n(e.event),variables:Array.isArray(e.variable)?Object.fromEntries(e.variable.filter(p=>p&&p.key).map(p=>[p.key,String(p.value??"")])):typeof e.variable=="object"&&e.variable!==null?Object.fromEntries(Object.entries(e.variable).map(([p,m])=>[p,String(m??"")])):void 0,items:c(e.item||[])};return await this.saveCollection(d),d}async exportCollection(e,r){let n=this.collections.get(e);if(!n)throw new Error("Collection not found");let i=Bz(n),s=JSON.stringify(i,null,2);Dt.writeFileSync(r,s,"utf-8")}async exportCollectionAsRestClientFolder(e,r){let n=this.collections.get(e);if(!n)throw new Error("Collection not found");let i=mi.join(r,Bt(n.name));Dt.mkdirSync(i,{recursive:!0});let s=n.variables||{};Ka(mi.join(i,`${Bt(n.name)}.env`),s),Zu(i,Bt(n.name),n.scripts),yd(n.items,i,n)}dispose(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.fileWatcher?.dispose()}}});var rr,ko,Ps,r_=le(()=>{"use strict";rr={version:"1.0",storage:{format:"folder",root:"./.http-forge/assets",history:"./.http-forge/.cache/histories",results:"./.http-forge/.cache/results"},request:{timeout:3e4,followRedirects:!0,maxRedirects:10,strictSSL:!0,tls:{},certificates:[]},scripts:{modulePaths:["./.http-forge/assets/src","./.http-forge/assets/lib"],scope:"shared",timeout:5e3},runner:{resultsRetentionDays:7,indexPageSize:1e3,recentErrorsLimit:20},environments:{default:"dev"},restClientExport:{path:"collections-rest-client",mergeGlobals:!0},mcp:{port:3100,excludedCollections:[],excludedSuites:[],toolPrefix:"",maxRequestsPerCall:500,toolMode:"auto",drilldownThreshold:100,toolPageSize:200,cors:{allowedOrigins:["http://localhost","http://127.0.0.1"]}},proxy:null,secrets:{providers:{aws:{provider:"aws"},azure:{provider:"azure",vaultUrl:""},gcp:{provider:"gcp"},vault:{provider:"vault"},op:{provider:"1password"},doppler:{provider:"doppler"}}}},ko={preferred:".http-forge/http-forge.config.json",legacy:"http-forge.config.json"},Ps={collections:"collections",environments:"environments",flows:"flows",suites:"suites"}});var Vt,Jt,ks,sg=le(()=>{"use strict";Vt=ve(require("fs")),Jt=ve(require("path"));r_();ks=class{constructor(e,r,n){this.workspacePath=e;this.fileWatcherFactory=r;this.notifications=n;this.configPath=this.resolveConfigPath(),this.config=this.loadConfig(),this.setupFileWatcher()}workspacePath;fileWatcherFactory;notifications;config;configPath;fileWatchers=[];resolveConfigPath(){let e=Jt.join(this.workspacePath,ko.preferred);if(Vt.existsSync(e))return e;let r=Jt.join(this.workspacePath,ko.legacy);return Vt.existsSync(r)?r:e}loadConfig(){if(this.configPath=this.resolveConfigPath(),!Vt.existsSync(this.configPath))return{...rr};try{let e=Vt.readFileSync(this.configPath,"utf-8"),r=JSON.parse(e);return this.mergeWithDefaults(r)}catch(e){return console.error("[ConfigService] Failed to load config:",e),this.notifications?.showWarning(`Failed to parse ${Jt.relative(this.workspacePath,this.configPath)}. Using default configuration.`),{...rr}}}mergeWithDefaults(e){return{version:e.version??rr.version,storage:{...rr.storage,...e.storage},request:{...rr.request,...e.request},scripts:{...rr.scripts,...e.scripts},runner:{...rr.runner,...e.runner},environments:{...rr.environments,...e.environments},restClientExport:{...rr.restClientExport,...e.restClientExport},proxy:e.proxy!==void 0?e.proxy:rr.proxy,mcp:{...rr.mcp,...e.mcp,cors:{...rr.mcp.cors,...e.mcp?.cors}},secrets:{...rr.secrets,...e.secrets,providers:{...rr.secrets?.providers,...e.secrets?.providers}}}}setupFileWatcher(){if(!this.fileWatcherFactory)return;let e=()=>{this.reload()};for(let r of[ko.preferred,ko.legacy]){let n=this.fileWatcherFactory.createFileWatcher(this.workspacePath,r);n.onDidChange(e),n.onDidCreate(e),n.onDidDelete(e),this.fileWatchers.push(n)}}getConfig(){return this.config}getStorageConfig(){return this.config.storage}getRequestConfig(){return this.config.request}getScriptsConfig(){return this.config.scripts}getRunnerConfig(){return this.config.runner}getEnvironmentsConfig(){return this.config.environments}getRestClientExportPath(){let e=this.config.restClientExport?.path||"collections-rest-client";return Jt.isAbsolute(e)?e:this.resolvePath(e)}getRestClientMergeGlobals(){return this.config.restClientExport?.mergeGlobals??!0}getProxyConfig(){return this.config.proxy??null}getMcpConfig(){let e=this.config.mcp??rr.mcp,r=["flat","drilldown","auto"];return{...e,port:Math.min(65535,Math.max(1,Math.floor(e.port??3100))),toolMode:r.includes(e.toolMode)?e.toolMode:"auto",drilldownThreshold:Math.min(500,Math.max(10,e.drilldownThreshold??100)),toolPageSize:e.toolPageSize===0?0:Math.min(1e3,Math.max(10,e.toolPageSize??200)),maxRequestsPerCall:Math.min(1e4,Math.max(1,e.maxRequestsPerCall??500))}}resolvePath(e){let r=e.startsWith("./")?e.slice(2):e;return Jt.join(this.workspacePath,...r.split("/"))}hasFolderCollectionsAtRoot(e){let r=Jt.join(e,Ps.collections);if(!Vt.existsSync(r))return!1;let n;try{n=Vt.readdirSync(r,{withFileTypes:!0})}catch{return!1}return n.some(i=>{if(!i.isDirectory())return!1;let s=Jt.join(r,i.name,"collection.json");return Vt.existsSync(s)})}hasAnyEntries(e){if(!Vt.existsSync(e))return!1;try{return Vt.readdirSync(e).length>0}catch{return!1}}resolveStorageRootPath(){let e=this.resolvePath(this.config.storage.root);return this.configExists()||this.hasFolderCollectionsAtRoot(e)?e:[Jt.join(this.workspacePath,"http-forge-assets")].find(i=>this.hasFolderCollectionsAtRoot(i))||e}getRootPath(){return this.resolveStorageRootPath()}getCollectionsPath(){return Jt.join(this.getRootPath(),Ps.collections)}getEnvironmentsPath(){return Jt.join(this.getRootPath(),Ps.environments)}getFlowsPath(){return Jt.join(this.getRootPath(),Ps.flows)}getHistoryPath(){let e=this.resolvePath(this.config.storage.history);if(this.configExists()||this.hasAnyEntries(e))return e;let r=Jt.join(this.workspacePath,".http-forge-cache","histories");return this.hasAnyEntries(r)?r:e}getResultsPath(){let e=this.resolvePath(this.config.storage.results);if(this.configExists()||this.hasAnyEntries(e))return e;let r=Jt.join(this.workspacePath,".http-forge-cache","results");return this.hasAnyEntries(r)?r:e}getSuitesPath(){return Jt.join(this.getRootPath(),Ps.suites)}getModulePaths(){return this.config.scripts.modulePaths.map(e=>this.resolvePath(e))}getScriptScope(){return this.config.scripts.scope??"shared"}getScriptTimeout(){return this.config.scripts.timeout??5e3}getWorkspacePath(){return this.workspacePath}reload(){this.configPath=this.resolveConfigPath(),this.config=this.loadConfig()}configExists(){return Vt.existsSync(this.resolveConfigPath())}async createDefaultConfig(){await Vt.promises.mkdir(Jt.dirname(this.configPath),{recursive:!0});let e=JSON.stringify(rr,null,2);await Vt.promises.writeFile(this.configPath,e,"utf-8");let r=[this.getCollectionsPath(),this.getEnvironmentsPath(),this.getFlowsPath(),this.getSuitesPath()];for(let i of r)Vt.existsSync(i)||await Vt.promises.mkdir(i,{recursive:!0});let n=[this.getHistoryPath(),this.getResultsPath()];for(let i of n)Vt.existsSync(i)||await Vt.promises.mkdir(i,{recursive:!0});await this.createSampleEnvironments()}async createSampleEnvironments(){let e=this.getEnvironmentsPath(),r={id:"globals",name:"Global Variables",variables:{appName:"HTTP Forge"}};await Vt.promises.writeFile(Jt.join(e,"globals.json"),JSON.stringify(r,null,2),"utf-8");let n={id:"env_dev",name:"Development",variables:{baseUrl:"http://localhost:3000",apiVersion:"v1"}};await Vt.promises.writeFile(Jt.join(e,"dev.json"),JSON.stringify(n,null,2),"utf-8");let i={id:"default_headers",name:"Default Headers",headers:{"Content-Type":"application/json",Accept:"application/json"}};await Vt.promises.writeFile(Jt.join(e,"default-headers.json"),JSON.stringify(i,null,2),"utf-8")}dispose(){for(let e of this.fileWatchers)e.dispose();this.fileWatchers=[]}}});var Yz,tc,n_=le(()=>{"use strict";ka();Yz="httpForge.cookies",tc=class{constructor(e,r=Yz){this.store=e;this.storeKey=r;this.loadCookies()}store;storeKey;cookies=new Map;loadCookies(){try{let e=this.store.get(this.storeKey);e&&(this.cookies=new Map(Object.entries(e)),this.cleanExpiredCookies())}catch(e){console.error("[CookieService] Failed to load cookies:",e)}}async saveCookies(){try{let e={};this.cookies.forEach((r,n)=>{e[n]=r}),await this.store.update(this.storeKey,e)}catch(e){console.error("[CookieService] Failed to save cookies:",e)}}getCookieKey(e,r,n){return`${r||"*"}|${n||"/"}|${e}`}get(e,r){if(r){let s=this.getCookieKey(e,r),o=this.cookies.get(s);if(o&&!this.isExpired(o))return o}let n=this.getCookieKey(e,"*"),i=this.cookies.get(n);if(i&&!this.isExpired(i))return i;for(let s of this.cookies.values())if(s.name===e&&!this.isExpired(s))if(r&&s.domain){if(this.domainMatches(r,s.domain))return s}else return s}async set(e){let r=this.getCookieKey(e.name,e.domain,e.path);this.cookies.set(r,e),await this.saveCookies()}async setFromResponse(e){for(let r of e){let n=this.getCookieKey(r.name,r.domain,r.path);this.cookies.set(n,r)}await this.saveCookies()}has(e,r){return this.get(e,r)!==void 0}async delete(e,r,n){let i=this.getCookieKey(e,r,n),s=this.cookies.delete(i);return s&&await this.saveCookies(),s}getAll(e){let r=[];for(let n of this.cookies.values())this.isExpired(n)||(e?(!n.domain||this.domainMatches(e,n.domain))&&r.push(n):r.push(n));return r}getCookieHeader(e){let r=this.getAll(e);return _t.formatCookieHeader(r)}async clear(){this.cookies.clear(),await this.saveCookies()}async clearDomain(e){let r=[];for(let[n,i]of this.cookies.entries())i.domain&&this.domainMatches(e,i.domain)&&r.push(n);for(let n of r)this.cookies.delete(n);await this.saveCookies()}parseCookieHeaders(e,r){return _t.parseCookieHeaders(e,r)}isExpired(e){return _t.isExpired(e)}cleanExpiredCookies(){let e=[];for(let[r,n]of this.cookies.entries())this.isExpired(n)&&e.push(r);for(let r of e)this.cookies.delete(r);e.length>0&&this.saveCookies()}domainMatches(e,r){return _t.domainMatches(e,r)}get count(){return this.cookies.size}}});var rc,i_=le(()=>{"use strict";ka();rc=class{constructor(e){this.cookieService=e;this.localCache=[...e.getAll()]}cookieService;localCache=[];pendingOperations=[];get(e,r){return r?this.localCache.find(n=>n.name===e&&(!n.domain||n.domain===r||r.endsWith(n.domain))):this.localCache.find(n=>n.name===e)}has(e,r){return this.get(e,r)!==void 0}set(e){let r=this.localCache.findIndex(n=>n.name===e.name&&(!e.domain||n.domain===e.domain));r>=0?this.localCache[r]=e:this.localCache.push(e),this.pendingOperations.push({type:"set",cookie:e})}delete(e,r,n){let i=this.localCache.findIndex(s=>s.name===e&&(!r||s.domain===r||s.domain&&r.endsWith(s.domain)));return i>=0&&this.localCache.splice(i,1),this.pendingOperations.push({type:"delete",name:e,domain:r,path:n}),!0}getAll(e){return e?this.localCache.filter(r=>{let n=r.domain||"";return n===e||e.endsWith(n)}):[...this.localCache]}getCookiesForDomain(e){return this.localCache.filter(r=>{let n=r.domain||"";return n===e||e.endsWith(n)})}async setCookiesFromResponse(e,r){let n=new URL(e).hostname,i=this.cookieService.parseCookieHeaders(r,n);i.length>0&&(i.forEach(s=>{let o=this.localCache.findIndex(l=>l.name===s.name&&l.domain===(s.domain||n));o>=0?this.localCache[o]=s:this.localCache.push(s)}),await this.cookieService.setFromResponse(i))}getCookieHeader(e){let r=new URL(e).hostname,n=new URL(e).pathname,i=this.localCache.filter(s=>!(_t.isExpired(s)||s.domain&&!_t.domainMatches(r,s.domain)||!s.domain||s.path&&!n.startsWith(s.path)));if(i.length!==0)return _t.formatCookieHeader(i)}clear(){this.localCache=[],this.pendingOperations.push({type:"clear"})}async flush(){for(let e of this.pendingOperations)switch(e.type){case"set":e.cookie&&await this.cookieService.set(e.cookie);break;case"delete":e.name&&await this.cookieService.delete(e.name,e.domain,e.path);break;case"clear":await this.cookieService.clear();break}this.pendingOperations=[]}}});function vd(t){try{let e=JSON.parse(typeof t=="string"?t:t.toString("utf-8"));if(!e)return null;let r=e.environment||e,n=r.name||e.name||"imported-environment",i=r.values||r.variables||e.values||e.variables||[],s={};if(Array.isArray(i))for(let l of i){if(!l)continue;let c=l.key??l.name,d=typeof l.enabled=="boolean"?l.enabled:!0;c&&d!==!1&&(s[c]=l.value??l.initial??"")}else if(typeof i=="object"&&i!==null)for(let[l,c]of Object.entries(i))s[l]=String(c??"");let o=r._postman_exported_at?"Imported from Postman export":r.description||"";return{name:n,variables:s,description:o}}catch{return null}}async function PP(t,e){try{let r=await e.readFile(t);return vd(r)}catch{return null}}var s_=le(()=>{"use strict"});var ur,Cn,bd,nc,o_=le(()=>{"use strict";ur=ve(require("fs")),Cn=ve(require("path"));Un();s_();ig();sm();Af();bd={SELECTED_ENVIRONMENT:"httpForge.selectedEnvironment",ENV_OVERRIDES_PREFIX:"httpForge.envOverrides."},nc=class{constructor(e,r,n,i,s,o=!0){this.workspaceFolder=e;this.workspaceStore=r;this.configService=n;this.fileWatcherFactory=i;this.secretStore=s;this.persistOverrides=o;let l=n.getEnvironmentsPath();this.environmentsPath=l,this.sharedConfigPath=Cn.join(l,"_global.json"),this.localConfigPath=Cn.join(l,"_global.local.json"),this.historiesPath=n.getHistoryPath(),this.selectedEnvironment=r?.get(bd.SELECTED_ENVIRONMENT,"dev")??"dev",this.localGlobalValues={},this.localEnvironmentValues=new Map,this.persistOverrides&&this.loadPersistedEnvironmentOverrides(),this.loadSecretVariables(this.selectedEnvironment).catch(()=>{}),this.setupFileWatcher()}workspaceFolder;workspaceStore;configService;fileWatcherFactory;secretStore;persistOverrides;environmentsPath;sharedConfigPath;localConfigPath;historiesPath;sharedConfig=null;localConfig=null;selectedEnvironment="dev";fileWatcher;localGlobalValues={};localEnvironmentValues=new Map;secretValuesCache=new Map;onEnvironmentsChanged;setupFileWatcher(){if(!this.fileWatcherFactory||!ur.existsSync(this.environmentsPath))return;this.fileWatcher=this.fileWatcherFactory.createFileWatcher(this.environmentsPath,"**/*.json");let e=()=>{this.reload(),this.onEnvironmentsChanged?.()};this.fileWatcher.onDidChange(e),this.fileWatcher.onDidCreate(e),this.fileWatcher.onDidDelete(e)}dispose(){this.fileWatcher?.dispose()}getWorkspaceFolder(){return this.workspaceFolder}getRootPath(){return this.configService.getRootPath()}loadConfigs(){if(!ur.existsSync(this.environmentsPath)){this.sharedConfig={environments:{},globalVariables:{},defaultHeaders:{}},this.localConfig={credentials:{},variables:{}};return}this.loadFolderConfigs()}getSharedConfig(){return this.sharedConfig||this.loadConfigs(),this.sharedConfig}getLocalConfig(){return this.localConfig||this.loadConfigs(),this.localConfig}getEnvironmentNames(){let e=this.getSharedConfig();return e?.environments?Object.keys(e.environments):[]}getSelectedEnvironment(){return this.selectedEnvironment}async setSelectedEnvironment(e){if(this.selectedEnvironment=e,await this.workspaceStore?.update(bd.SELECTED_ENVIRONMENT,e),!this.localEnvironmentValues.has(e)){let r=this.getEnvOverridesStateKey(e),n=this.workspaceStore?.get(r,{});n&&Object.keys(n).length>0&&this.localEnvironmentValues.set(e,{...n})}await this.loadSecretVariables(e)}getEnvOverridesStateKey(e){return`${bd.ENV_OVERRIDES_PREFIX}${e||this.selectedEnvironment}`}loadPersistedEnvironmentOverrides(){let e=this.getEnvOverridesStateKey(),r=this.workspaceStore?.get(e,{});r&&Object.keys(r).length>0&&this.localEnvironmentValues.set(this.selectedEnvironment,{...r})}persistEnvironmentOverrides(e){if(!this.persistOverrides)return;let r=this.getEnvOverridesStateKey(e),n=this.localEnvironmentValues.get(e)||{};this.workspaceStore?.update(r,n)}setEnvironmentVariable(e,r,n){let i=n??this.selectedEnvironment;this.localEnvironmentValues.has(i)||this.localEnvironmentValues.set(i,{}),this.localEnvironmentValues.get(i)[e]=String(r),this.persistEnvironmentOverrides(i)}deleteEnvironmentVariable(e,r){let n=r??this.selectedEnvironment,i=this.localEnvironmentValues.get(n);i&&(delete i[e],this.persistEnvironmentOverrides(n))}clearEnvironmentVariables(e){let r=e??this.selectedEnvironment;this.localEnvironmentValues.set(r,{}),this.persistEnvironmentOverrides(r)}async resetEnvironmentOverrides(e){let r=e||this.selectedEnvironment;this.localEnvironmentValues.delete(r),await this.workspaceStore?.update(this.getEnvOverridesStateKey(r),void 0)}getEnvironmentVariableLocal(e){return this.localEnvironmentValues.get(this.selectedEnvironment)?.[e]}getEnvironmentVariableLocals(){return{...this.localEnvironmentValues.get(this.selectedEnvironment)||{}}}setGlobalVariable(e,r){this.localGlobalValues[e]=String(r)}getGlobalVariable(e){return this.getSharedConfig()?.globalVariables?.[e]}getGlobalVariableLocal(e){return this.localGlobalValues[e]}getGlobalVariables(){return{...this.getSharedConfig()?.globalVariables||{},...this.getLocalConfig()?.variables||{},...this.localGlobalValues}}getGlobalVariableLocals(){return{...this.localGlobalValues}}deleteGlobalVariable(e){delete this.localGlobalValues[e]}clearGlobalVariables(){this.localGlobalValues={}}getResolvedEnvironment(e){let r=e||this.selectedEnvironment,n=this.getSharedConfig(),i=this.getLocalConfig();if(!n?.environments?.[r])return null;let s=n.environments[r],o=i?.credentials?.[r],l=i?.variables||{},c=o?.variables||{},d=o&&o.headers||{},p=gu(n.defaultHeaders||{},d),m=this.localEnvironmentValues.get(r)||{},y=this.secretValuesCache.get(r)||{},b={...s.variables||{},...c,...m,...y};return{name:r,description:s.description,requiresConfirmation:s.requiresConfirmation,headers:p,variables:b}}async getSecretVariable(e,r){return this.secretStore?.get(`${e}:${r}`)}async setSecretVariable(e,r,n){await this.secretStore?.store(`${e}:${r}`,n),this.secretValuesCache.has(e)||this.secretValuesCache.set(e,{}),this.secretValuesCache.get(e)[r]=n}async deleteSecretVariable(e,r){await this.secretStore?.delete(`${e}:${r}`),this.secretValuesCache.get(e)&&delete this.secretValuesCache.get(e)[r]}async loadSecretVariables(e){if(!this.secretStore)return;let r=e||this.selectedEnvironment,n=this.getSharedConfig()?.environments?.[r]?.secretVariables??[];if(n.length===0)return;let i={};await Promise.all(n.map(async s=>{let o=await this.secretStore.get(`${r}:${s}`);o!==void 0&&(i[s]=o)})),this.secretValuesCache.set(r,i)}resolveVariables(e,r){return this.createResolver(r).resolveString(e,!0)}exportEnvironmentsToFolder(e,r=!0){let n=this.getEnvironmentNames(),i=this.getSharedConfig(),s=i?.globalVariables?{...i.globalVariables}:{};if(!r&&Object.keys(s).length){let o=Cn.join(e,"globals.env");Ka(o,s)}n.forEach(o=>{let l=i?.environments?.[o];if(!l)return;let c={...l.variables||{}};r&&(c={...s,...c});let d=Cn.join(e,`${Bt(o)}.env`);Ka(d,c)})}resolveVariablesWithExtra(e,r,n){return this.createResolver(n,r).resolveString(e,!0)}resolveVariablesInObject(e,r){return this.createResolver(r).resolveObject(e,!0)}resolveVariablesInObjectWithExtra(e,r,n){return this.createResolver(n,r).resolveObject(e,!0)}getHistoriesPath(){return this.historiesPath}getSharedConfigPath(){return this.sharedConfigPath}getLocalConfigPath(){return this.localConfigPath}getEnvironmentConfigPath(e){return Cn.join(this.environmentsPath,`${e}.json`)}localConfigExists(){return ur.existsSync(this.localConfigPath)}saveSharedConfig(e){this.saveFolderSharedConfig(e),this.sharedConfig=e}saveLocalConfig(e){let r={variables:e.variables||{}};this.saveJsonFile(this.localConfigPath,r);for(let[n,i]of Object.entries(e.credentials||{})){let s=this.getEnvLocalConfigPath(n),o={variables:i.variables||{}};this.saveJsonFile(s,o)}this.localConfig=e}importPostmanEnvironmentFile(e){try{let r=ur.readFileSync(e,"utf-8"),n=vd(r);if(!n)throw new Error("Failed to parse Postman environment file");this.sharedConfig||this.loadConfigs(),this.sharedConfig||(this.sharedConfig={environments:{},globalVariables:{},defaultHeaders:{}});let i=n.name||`imported-${Date.now()}`;return this.sharedConfig.environments=this.sharedConfig.environments||{},this.sharedConfig.environments[i]=this.sharedConfig.environments[i]||{},this.sharedConfig.environments[i].variables=n.variables,n.description&&(this.sharedConfig.environments[i].description=n.description),this.saveSharedConfig(this.sharedConfig),n}catch(r){throw console.error("[EnvironmentConfigService] importPostmanEnvironmentFile failed:",r),r}}saveEnvLocalConfig(e,r){let n=this.getEnvLocalConfigPath(e),i={variables:r};this.saveJsonFile(n,i),this.localConfig||(this.localConfig={credentials:{},variables:{}}),this.localConfig.credentials||(this.localConfig.credentials={}),this.localConfig.credentials[e]={variables:r}}getEnvLocalPath(e){return this.getEnvLocalConfigPath(e)}getEnvLocalConfigPath(e){return Cn.join(this.environmentsPath,`${e}.local.json`)}loadFolderConfigs(){let e=wu(this.environmentsPath);this.sharedConfig={environments:e.environments,globalVariables:e.globalVariables,defaultHeaders:e.defaultHeaders},this.localConfig={credentials:e.localCredentials,variables:e.localVariables}}createResolver(e,r){let i=this.getResolvedEnvironment(e)?.variables||{},s=this.getGlobalVariables(),o=this.getGlobalVariableLocals();return new yo({globals:s,collectionVariables:{},environmentVariables:i,variables:{...o,...r||{}}})}saveFolderSharedConfig(e){ur.existsSync(this.environmentsPath)||ur.mkdirSync(this.environmentsPath,{recursive:!0});let r={variables:e.globalVariables||{},defaultHeaders:e.defaultHeaders||{}};this.saveJsonFile(this.sharedConfigPath,r);let n=ur.readdirSync(this.environmentsPath).filter(s=>s.endsWith(".json")).filter(s=>!Of(s)),i=new Set(Object.keys(e.environments||{}));for(let s of n){let o=Cn.basename(s,".json");if(!i.has(o))try{ur.unlinkSync(Cn.join(this.environmentsPath,s))}catch{}}for(let[s,o]of Object.entries(e.environments||{})){let l={name:s,description:o.description,requiresConfirmation:o.requiresConfirmation,variables:o.variables||{}};this.saveJsonFile(Cn.join(this.environmentsPath,`${s}.json`),l)}}reload(){this.sharedConfig=null,this.localConfig=null,this.loadConfigs()}getAllEnvironments(){return this.loadConfigs(),this.sharedConfig?Object.entries(this.sharedConfig.environments).map(([e,r])=>({id:e,name:e,active:e===this.selectedEnvironment,variables:r.variables||{}})):[]}async setActiveEnvironment(e){await this.setSelectedEnvironment(e)}async createEnvironment(e){if(this.loadConfigs(),this.sharedConfig||(this.sharedConfig={environments:{},globalVariables:{}}),this.sharedConfig.environments[e])throw new Error(`Environment "${e}" already exists`);this.sharedConfig.environments[e]={description:`Created ${new Date().toISOString()}`,variables:{}},this.saveSharedConfig(this.sharedConfig)}async deleteEnvironment(e){if(this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentExists(e),delete this.sharedConfig.environments[e],this.selectedEnvironment===e){let r=Object.keys(this.sharedConfig.environments);this.selectedEnvironment=r.length>0?r[0]:"dev",await this.workspaceStore?.update(bd.SELECTED_ENVIRONMENT,this.selectedEnvironment)}this.saveSharedConfig(this.sharedConfig)}async duplicateEnvironment(e,r){this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentName(r),this.validateEnvironmentExists(e),this.validateEnvironmentNameNotTaken(r);let n=this.sharedConfig.environments[e];this.sharedConfig.environments[r]=JSON.parse(JSON.stringify(n)),this.sharedConfig.environments[r].description=`Copied from ${e}`,this.saveSharedConfig(this.sharedConfig)}async renameEnvironment(e,r){this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentName(r),this.validateEnvironmentExists(e),r!==e&&(this.validateEnvironmentNameNotTaken(r),this.sharedConfig.environments[r]=this.sharedConfig.environments[e],delete this.sharedConfig.environments[e],this.selectedEnvironment===e&&(this.selectedEnvironment=r,await this.workspaceStore?.update(bd.SELECTED_ENVIRONMENT,r)),this.saveSharedConfig(this.sharedConfig))}validateEnvironmentName(e){if(!e||e.trim().length===0)throw new Error("Environment name cannot be empty");if(e.length>128)throw new Error("Environment name cannot exceed 128 characters");if(!/^[a-zA-Z0-9_\-\.]+$/.test(e))throw new Error("Environment name can only contain letters, numbers, hyphens, underscores, and dots")}validateEnvironmentExists(e){if(!this.sharedConfig?.environments?.[e])throw new Error(`Environment "${e}" not found`)}validateEnvironmentNameNotTaken(e){if(this.sharedConfig?.environments?.[e])throw new Error(`Environment "${e}" already exists`)}validateConfigLoaded(){if(!this.sharedConfig)throw new Error("No environment configuration loaded")}async updateEnvironmentVariables(e,r){if(this.loadConfigs(),!this.sharedConfig)throw new Error("No configuration loaded");let n=this.sharedConfig.environments[e];if(!n)throw new Error(`Environment "${e}" not found`);n.variables=r,this.saveSharedConfig(this.sharedConfig)}loadJsonFile(e){try{if(!ur.existsSync(e))return null;let r=ur.readFileSync(e,"utf-8");return JSON.parse(r)}catch(r){return console.error(`Failed to load JSON from ${e}:`,r),null}}saveJsonFile(e,r){try{let n=Cn.dirname(e);ur.existsSync(n)||ur.mkdirSync(n,{recursive:!0}),ur.writeFileSync(e,JSON.stringify(r,null,2),"utf-8")}catch(n){throw console.error(`Failed to save JSON to ${e}:`,n),n}}}});var As,og=le(()=>{"use strict";hd();As=class t{constructor(e,r,n,i,s,o,l,c,d,p,m,y,b){this.httpService=e;this.scriptExecutor=r;this.envConfigService=n;this.requestPreparer=i;this.environment=s;this.cookieJar=o;this.collectionScripts=l;this.folderScriptsChain=c;this.onConsoleOutput=d;this.collectionName=p;this.collectionAuth=m;this.iteration=y;this.iterationCount=b}httpService;scriptExecutor;envConfigService;requestPreparer;environment;cookieJar;collectionScripts;folderScriptsChain;onConsoleOutput;collectionName;collectionAuth;iteration;iterationCount;async execute(e,r,n){let i=Date.now();return this.executeWithSession(e,r,n,i)}async executeWithSession(e,r,n,i){let s=this.collectPreRequestScripts(e),o=this.collectPostResponseScripts(e),l=this.envConfigService.getResolvedEnvironment(this.environment);if(!l)throw new Error(`Environment "${this.environment}" not found or not configured`);let c=this.envConfigService.getGlobalVariables(),d={request:e,variables:{...r},environmentVariables:l.variables||{},globals:{...c},environmentName:this.environment,cookieJar:this.cookieJar,info:{eventName:"prerequest",requestName:e.name,requestId:e.id,collectionName:this.collectionName,iteration:this.iteration,iterationCount:this.iterationCount},onEnvironmentChange:async(y,b,q)=>{y==="set"&&b&&q!==void 0?this.envConfigService.setEnvironmentVariable(b,q,this.environment):y==="unset"&&b?this.envConfigService.deleteEnvironmentVariable(b,this.environment):y==="clear"&&this.envConfigService.clearEnvironmentVariables(this.environment)},onGlobalsChange:(y,b,q)=>{y==="set"&&b&&q!==void 0?this.envConfigService.setGlobalVariable(b,q):y==="unset"&&b?this.envConfigService.deleteGlobalVariable(b):y==="clear"&&this.envConfigService.clearGlobalVariables()}},p=this.scriptExecutor.createRequestSession(d),m=null;try{let y={...r},b={...e},q;if((!b.auth||b.auth.type==="inherit")&&(b.auth=this.collectionAuth&&this.collectionAuth.type!=="inherit"?this.collectionAuth:void 0),s.length>0){let D=await p.executePreRequest(s);if(D.consoleOutput&&D.consoleOutput.length>0&&this.onConsoleOutput?.(D.consoleOutput,{requestName:e.name||"",phase:"pre-request"}),D.nextRequest!==void 0&&(q=D.nextRequest),D.skipRequest){let J={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:{url:e.url||"",method:e.method||"GET",headers:{},body:J,params:{},query:{}},response:{status:0,statusText:"Skipped",headers:{},body:null,time:0,cookies:[]},duration:Date.now()-i,timestamp:Date.now(),passed:!0,assertions:[],modifiedVariables:y,nextRequest:q}}D.success&&(D.modifiedRequest&&(D.modifiedRequest.url&&(b.url=D.modifiedRequest.url),D.modifiedRequest.headers&&(b.headers=D.modifiedRequest.headers),D.modifiedRequest.params&&(b.params=D.modifiedRequest.params),D.modifiedRequest.query&&(b.query=D.modifiedRequest.query),D.modifiedRequest.body!==void 0&&(b.body=D.modifiedRequest.body)),(D.localVariables??D.modifiedVariables)&&(y=D.localVariables??D.modifiedVariables))}m=await this.requestPreparer.prepareRequest(b,this.environment,l,y);let{url:x,headers:v,body:R,method:E}=m,k={};for(let D in v)Object.prototype.hasOwnProperty.call(v,D)&&(k[D.toUpperCase()]=v[D]);if(!k.COOKIE&&b.settings?.includeCookies!==!1&&this.cookieJar){let J=this.cookieJar.getCookieHeader(x);J&&(k.COOKIE=J)}let P={method:E,url:x,headers:k,body:R.content,signal:n,settings:b.settings?{...b.settings}:void 0},M=await this.httpService.execute(P);this.cookieJar&&M.headers&&await this.cookieJar.setCookiesFromResponse(x,M.headers);let j=Date.now()-i,I=[],_={},A;if(o.length>0){let D=0;if(M.body)if(typeof M.body=="string")D=Buffer.byteLength(M.body,"utf8");else if(Buffer.isBuffer(M.body))D=M.body.length;else try{D=Buffer.byteLength(JSON.stringify(M.body),"utf8")}catch{D=0}let J=Zm(M.headers,M.cookies,m.url),Q={executedRequest:m,status:M.status,statusText:M.statusText,headers:Qm(M.headers||{}),body:M.body,cookies:J,responseTime:M.time,responseSize:D},se=await p.executePostResponse(o,Q);I=se.testResults,_=se.modifiedEnvironmentVariables||{},A=se.visualizerData,(se.localVariables??se.modifiedVariables)&&(y=se.localVariables??se.modifiedVariables),se.nextRequest!==void 0&&(q=se.nextRequest),se.consoleOutput&&se.consoleOutput.length>0&&this.onConsoleOutput?.(se.consoleOutput,{requestName:e.name||"",phase:"post-response"})}let F=I.length===0||I.every(D=>D.passed),U=I.length>0?F:M.status>=200&&M.status<=302;return{requestId:e.id,name:e.name,executedRequest:{...m,headers:k},response:{status:M.status,statusText:M.statusText,headers:M.headers||{},body:M.body,time:M.time||j,cookies:M.cookies||[]},duration:j,timestamp:Date.now(),passed:U,assertions:I,modifiedVariables:y,modifiedEnvironmentVariables:_,nextRequest:q,visualizerData:A}}catch(y){return this.handleError(e,m,y,i)}finally{p.dispose?.()}}collectPreRequestScripts(e){let r=[];if(this.collectionScripts?.preRequest&&r.push(this.collectionScripts.preRequest),this.folderScriptsChain)if(Array.isArray(this.folderScriptsChain))for(let n of this.folderScriptsChain)n?.preRequest&&r.push(n.preRequest);else this.folderScriptsChain.preRequest&&r.push(this.folderScriptsChain.preRequest);return e.scripts?.preRequest&&r.push(e.scripts.preRequest),r}collectPostResponseScripts(e){let r=[];if(e.scripts?.postResponse&&r.push(e.scripts.postResponse),this.folderScriptsChain)if(Array.isArray(this.folderScriptsChain)){let n=[...this.folderScriptsChain].reverse();for(let i of n)i?.postResponse&&r.push(i.postResponse)}else this.folderScriptsChain.postResponse&&r.push(this.folderScriptsChain.postResponse);return this.collectionScripts?.postResponse&&r.push(this.collectionScripts.postResponse),r}handleError(e,r,n,i){let s=Date.now()-i,o=r?.method||e.method,l=r?.url||e.url;this.onConsoleOutput?.([`${n.message||n}`],{requestName:e.name||"",phase:"error"});let c=String(n.name==="AbortError"?"Request was aborted":n.message||n),d=n?.stack?String(n.stack):"",p=this.errorBodyFormat,m,y;p==="html"||p==="both"?(m=t.formatErrorAsHtml(c,d),y={"content-type":"text/html; charset=utf-8"}):(m=c,y={});let b={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:{url:l||"",method:o||"GET",headers:r?.headers||{},body:r?.body||b,params:r?.params||{},query:r?.query||{}},response:{status:0,statusText:n.name==="AbortError"?"Aborted":n.code||n.message||"Request Error",headers:y,cookies:[],body:m,time:0},duration:s,timestamp:Date.now(),passed:!1,assertions:[],error:c}}get errorBodyFormat(){return"text"}static formatErrorAsHtml(e,r){let n=i=>i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");return`<!doctype html>
package/dist/index.mjs CHANGED
@@ -49,7 +49,7 @@ ${i}
49
49
 
50
50
  // --- Next Script ---
51
51
 
52
- `)}function Uf(t,e){return JSON.stringify(t)!==JSON.stringify(e)}function Su(t){return t.map(e=>{let r=e.args.map(n=>{if(typeof n=="object")try{return JSON.stringify(n,null,2)}catch{return String(n)}return String(n)}).join(" ");return`[${e.level}] ${r}`})}function fz(t){return{log:(...e)=>t.push({level:"log",args:e}),info:(...e)=>t.push({level:"info",args:e}),warn:(...e)=>t.push({level:"warn",args:e}),error:(...e)=>t.push({level:"error",args:e})}}function r0(t){let e=[],r=(n,i)=>{try{let s=i();if(s&&typeof s.then=="function"){let o=s.then(()=>{t.push({name:n,passed:!0})},l=>{t.push({name:n,passed:!1,message:l.message||String(l)})});e.push(o)}else t.push({name:n,passed:!0})}catch(s){t.push({name:n,passed:!1,message:s.message})}};return r.skip=(n,i)=>{t.push({name:n,passed:!0,skipped:!0})},r.fail=n=>{t.push({name:n||"Failed test",passed:!1,message:n||"pm.test.fail()"})},r.index=()=>t.length,r._pendingTests=e,r}function n0(t){let e={};for(let[r,n]of Object.entries(t))e[r]=Array.isArray(n)?n.join(", "):n;return e}function xm(t,e,r){let n;if(r)try{n=new URL(r).hostname}catch{n=void 0}let i=Ct.parseCookieHeaders(t||{},n);return i.length>0?i:Array.isArray(e)&&e.length>0?e.filter(s=>s&&s.name).map(s=>({name:s.name,value:s.value,domain:s.domain??n,path:s.path,expires:s.expires,maxAge:s.maxAge,httpOnly:s.httpOnly,secure:s.secure,sameSite:s.sameSite})):[]}var Hf=le(()=>{"use strict";ga()});import*as i0 from"vm";function dz(t){let e=null;try{e=new URL(t)}catch{}return{toString(){return t},valueOf(){return t},[Symbol.toPrimitive](n){return n==="number"?NaN:t},getHost(){return e?e.hostname:""},getPath(){return e?e.pathname:t},getPathWithQuery(){return e?e.pathname+e.search:t},getQueryString(){return e?e.search.startsWith("?")?e.search.slice(1):e.search:""},getRemote(){if(!e)return"";let n=e.port||(e.protocol==="https:"?"443":"80");return`${e.hostname}:${n}`},getOAuth1BaseUrl(){return e?`${e.protocol}//${e.host}${e.pathname}`:t},get protocol(){return e?.protocol?.replace(":","")||""},get host(){return e?e.hostname.split("."):[]},get port(){return e?.port||""},get path(){return e?e.pathname.split("/").filter(Boolean):[]},get hash(){return e?.hash?.replace("#","")||""},query:{toObject(){if(!e)return{};let n={};return e.searchParams.forEach((i,s)=>{n[s]=i}),n},has(n){return e?e.searchParams.has(n):!1},get(n){return e?e.searchParams.get(n):void 0},each(n){e&&e.searchParams.forEach((i,s)=>n({key:s,value:i}))}}}}var Bf,s0=le(()=>{"use strict";aP();_m();Hf();Bf=class{constructor(e,r){this.deps=e;this.initialContext=r;this.timerRegistry=oP(n=>{let i=n instanceof Error?n.message:String(n);this.consoleMessages.push({level:"error",args:[`Uncaught error in async callback: ${i}`]})}),this.initializeSession()}deps;initialContext;vmContext=null;ctx=null;modifiedRequest=null;assertions=[];consoleMessages=[];_variables={};_collectionVariables={};_globals={};_environmentVariables={};_liveEnvironmentScope=null;_liveGlobalsScope=null;_liveCollectionScope=null;_nextRequest=void 0;_skipRequest=!1;_visualizerData=void 0;timerRegistry;initializeSession(){this.modifiedRequest={url:this.initialContext.request.url,method:this.initialContext.request.method,headers:{...this.initialContext.request.headers},body:this.initialContext.request.body?{...this.initialContext.request.body}:null,params:this.initialContext.request.params?{...this.initialContext.request.params}:{},query:this.initialContext.request.query?{...this.initialContext.request.query}:{}},this.assertions=[],this.ctx=this.createSharedContext(),this.consoleMessages=[];let e=this,r={log:(...n)=>{e.consoleMessages.push({level:"log",args:n})},info:(...n)=>{e.consoleMessages.push({level:"info",args:n})},warn:(...n)=>{e.consoleMessages.push({level:"warn",args:n})},error:(...n)=>{e.consoleMessages.push({level:"error",args:n})}};this.vmContext=this.deps.createVM(this.ctx,r,this.timerRegistry.timers)}createSharedContext(){let e=this.initialContext,r=this.modifiedRequest,n=this.deps.createCommonContext(e,"prerequest");this._variables={...e.variables},this._collectionVariables={...e.collectionVariables||{}},this._globals={...e.globals||{}},this._environmentVariables={...e.environmentVariables||{}},this._liveEnvironmentScope=n.environment,this._liveGlobalsScope=n.globals,this._liveCollectionScope=n.collectionVariables;let i;try{i=new URL(e.request.url).hostname}catch{}let s={get:l=>e.cookieJar?e.cookieJar.get(l,i)?.value:void 0,set:(l,c)=>{e.cookieJar&&e.cookieJar.set({name:l,value:c,domain:i})},has:l=>e.cookieJar?e.cookieJar.has(l,i):!1,list:()=>e.cookieJar?e.cookieJar.getAll(i).map(l=>({name:l.name,value:l.value})):[],toObject:()=>{if(!e.cookieJar)return{};let l=e.cookieJar.getAll(i),c={};for(let d of l)c[d.name]=d.value;return c},jar:()=>{let l=e.cookieJar,c=d=>{if(d==null)return;let p=typeof d=="string"?d:typeof d=="object"||typeof d=="number"||typeof d=="boolean"?String(d):void 0;if(!p)return;let m=p.trim();if(m)try{return new URL(m).hostname}catch{return m}};return{getAll(d,p){try{if(!l){p(null,[]);return}let m=c(d),y=l.getAll(m).map(b=>({name:b.name,value:b.value,domain:b.domain,path:b.path,httpOnly:b.httpOnly,secure:b.secure}));p(null,y)}catch(m){p(m,[])}},get(d,p,m){try{if(!l){m(null,void 0);return}let y=c(d),b=l.get(p,y);m(null,b?{name:b.name,value:b.value,domain:b.domain}:void 0)}catch(y){m(y,void 0)}},set(d,p,m,y){try{if(!l){(y||m)?.(null);return}let b=c(d);typeof p=="string"&&typeof m=="string"?(l.set({name:p,value:m,domain:b}),y?.(null)):typeof p=="object"&&(l.set({...p,domain:b}),m?.(null))}catch(b){(y||m)?.(b)}},unset(d,p,m){try{if(!l){m?.(null);return}let y=c(d);l.delete(p,y),m?.(null)}catch(y){m?.(y)}},clear(d,p){try{let m=typeof d=="function"?d:p;if(!l){m?.(null);return}let y=typeof d=="function"?void 0:c(d);y&&typeof l.clearDomain=="function"?l.clearDomain(y):l.clear(),m?.(null)}catch(m){(typeof d=="function"?d:p)?.(m)}}}},remove:l=>{e.cookieJar&&e.cookieJar.delete(l,i)},unset:l=>{e.cookieJar&&e.cookieJar.delete(l,i)},clear:()=>{e.cookieJar&&e.cookieJar.clear()}},o=this;return{request:this.createRequestObject(r,e),response:null,test:r0(this.assertions),expect:bu,cookies:s,execution:{setNextRequest(l){o._nextRequest=l},skipRequest(){o._skipRequest=!0},runRequest(l,c){let p=(async()=>{if(typeof n.sendRequest!="function")throw new Error("pm.execution.runRequest is not available \u2014 HTTP service not configured.");let m=typeof l=="string"?{url:l,method:"GET"}:l,y=await n.sendRequest(m),b=Array.isArray(y?.cookies)?y.cookies.filter(v=>v?.name):[],q=y?.body,x=0;if(typeof q=="string")x=Buffer.byteLength(q,"utf8");else if(Buffer.isBuffer(q))x=q.length;else if(q!=null)try{x=Buffer.byteLength(JSON.stringify(q),"utf8")}catch{}return wm({executedRequest:null,status:y?.status??0,statusText:y?.statusText??"",headers:y?.headers??{},body:q,cookies:b,responseTime:y?.time,responseSize:x})})();if(typeof c=="function"){p.then(m=>c(null,m),m=>c(m));return}return p},location:{current:n.info?.requestName||"",currentRequestName:n.info?.requestName||"",eventName:"prerequest",toString(){return n.info?.requestName||""}}},setNextRequest(l){o._nextRequest=l},visualizer:{set(l,c){o._visualizerData={template:l,data:c}},clear(){o._visualizerData=void 0}},...n,info:{...n.info||{},eventName:"prerequest",requestName:n.info?.requestName||void 0,requestId:n.info?.requestId||void 0,iteration:e.iteration||0,iterationCount:e.iterationCount||1}}}createRequestObject(e,r){let n=l=>{if(!l)return"none";switch(l){case"raw":return"raw";case"form-data":return"formdata";case"x-www-form-urlencoded":return"urlencoded";case"binary":return"file";case"graphql":return"graphql";case"none":return"none";default:return"raw"}},i=l=>{if(!l)return"none";switch(l){case"raw":return"raw";case"formdata":return"form-data";case"urlencoded":return"x-www-form-urlencoded";case"file":return"binary";case"graphql":return"graphql";case"none":return"none";default:return"raw"}},s={...e.headers,add:l=>{l&&l.key&&(e.headers[l.key]=l.value||"")},get:l=>{for(let[c,d]of Object.entries(e.headers))if(c.toLowerCase()===l.toLowerCase())return d},has:l=>{for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.toLowerCase())return!0;return!1},remove:l=>{for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.toLowerCase()){delete e.headers[c];break}},update:l=>{if(l&&l.key){for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.key.toLowerCase()){e.headers[c]=l.value||"";return}}},upsert:l=>{if(l&&l.key){for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.key.toLowerCase()){e.headers[c]=l.value||"";return}e.headers[l.key]=l.value||""}},toObject:()=>{let l={};for(let[c,d]of Object.entries(e.headers))typeof d=="string"&&(l[c]=d);return l},each:l=>{for(let[c,d]of Object.entries(e.headers))typeof d=="string"&&l({key:c,value:d})}},o={get mode(){return n(e.body?.type)},set mode(l){let c=i(l);e.body?e.body.type=c:e.body={type:c,content:null}},get raw(){let l=e.body?.content;return typeof l=="string"?l:l&&typeof l=="object"?JSON.stringify(l):""},set raw(l){e.body?(e.body.type="raw",e.body.content=l):e.body={type:"raw",content:l}},get formdata(){return e.body?.type==="form-data"&&Array.isArray(e.body.content)?e.body.content:[]},get urlencoded(){return e.body?.type==="x-www-form-urlencoded"&&Array.isArray(e.body.content)?e.body.content:[]},get graphql(){return e.body?.type==="graphql"?e.body.content:null},get file(){return e.body?.type==="binary"?e.body.content:null}};return{get url(){return dz(e.url)},set url(l){e.url=typeof l=="string"?l:String(l)},get method(){return e.method},set method(l){e.method=l},headers:s,get body(){return o},set body(l){if(l==null)e.body=null;else if(typeof l=="string")e.body={type:"raw",content:l};else if(typeof l=="object")if(l.type||l.mode||l.content!==void 0){let c=l.mode?i(l.mode):l.type||"raw";e.body={type:c,format:l.format,content:l.content}}else e.body={type:"raw",content:l}},get params(){return e.params||{}},set params(l){e.params=l||{}},get query(){return e.query||{}},set query(l){e.query=l||{}},get auth(){return r.request?.auth||null},set auth(l){r.request&&(r.request.auth=l)},get certificate(){return r.request?.certificate||null},set certificate(l){r.request&&(r.request.certificate=l)},get description(){return r.request?.description||null},set description(l){r.request&&(r.request.description=l)},get name(){return r.request?.name||null},set name(l){r.request&&(r.request.name=l)},get id(){return r.request?.id||null},get disabled(){return r.request?.disabled||!1},set disabled(l){r.request&&(r.request.disabled=l)},get messages(){return r.request?.messages||[]},get methodPath(){return r.request?.methodPath||null},get metadata(){return r.request?.metadata||[]},getHeaders(l){let c={};for(let[d,p]of Object.entries(e.headers))typeof p=="string"&&(c[d]=p);return c},addQueryParams(l){if(typeof l=="string"){let c=new URLSearchParams(l);for(let[d,p]of c)e.query||(e.query={}),e.query[d]=p}else Array.isArray(l)&&(e.query||(e.query={}),l.forEach(c=>{c.key&&(e.query[c.key]=c.value||"")}))},removeQueryParams(l){e.query&&(typeof l=="string"?delete e.query[l]:Array.isArray(l)&&l.forEach(c=>{let d=typeof c=="string"?c:c.key;d&&delete e.query[d]}))},authorizeUsing(l,c){r.request&&(typeof l=="string"?(r.request.auth||(r.request.auth={}),r.request.auth.type=l,c&&(r.request.auth.parameters=c)):typeof l=="object"&&(r.request.auth=l))},clone(){return{url:e.url,method:e.method,headers:{...e.headers},body:e.body?{...e.body}:null,params:e.params?{...e.params}:{},query:e.query?{...e.query}:{},auth:r.request?.auth,certificate:r.request?.certificate,description:r.request?.description,name:r.request?.name,id:r.request?.id,disabled:r.request?.disabled,metadata:r.request?.metadata,messages:r.request?.messages,methodPath:r.request?.methodPath}},describe(l,c){r.request&&(r.request.description={content:l,type:c||"text/plain"})},setHeader(l,c){e.headers[l]=c},addHeader(l,c){typeof l=="object"&&l!==null?e.headers[l.key]=l.value:e.headers[l]=c},removeHeader(l){delete e.headers[l]},setBody(l,c,d){e.body={type:c||e.body?.type||"raw",format:d||e.body?.format,content:l}}}}injectLegacyGlobals(e,r){let n=this.vmContext;if(!n)return;let i=this.initialContext,s=e==="test"&&r?.executedRequest?r.executedRequest:this.modifiedRequest,o={};for(let[b,q]of Object.entries(s?.headers||{}))typeof q=="string"&&(o[b]=q);let l=s?.body,c=l==null?null:typeof l=="object"&&"content"in l?l.content:l,d=i.request;if(n.request={id:d?.id??"",name:d?.name??"",description:d?.description??"",url:typeof s?.url=="string"?s.url:String(s?.url??""),method:s?.method??"GET",headers:o,data:c},n.environment=this._liveEnvironmentScope?.toObject?.()??{...this._environmentVariables},n.globals=this._liveGlobalsScope?.toObject?.()??{...this._globals},n.data={...i.iterationData||{}},typeof n.iteration!="number"&&(n.iteration=0),e!=="test"||!r)return;let p=r.body;n.responseBody=p==null?"":typeof p=="string"?p:JSON.stringify(p);let m=r.statusText||"";n.responseCode={code:r.status,name:m,detail:m},n.responseHeaders={...r.headers||{}},n.responseTime=r.responseTime??0,n.responseCookies=(r.cookies||[]).map(b=>({...b}));let y=this;n.tests=new Proxy({},{set(b,q,x){return y.assertions.push({name:String(q),passed:!!x,message:x?void 0:`"${String(q)}" was false`}),!0}})}async executePreRequest(e){let r=Rm(e,this.deps.isolateScripts);if(!r||!r.trim())return{success:!0};try{this.consoleMessages.length=0,this.injectLegacyGlobals("prerequest");let n=this.ctx.variables.replaceIn(r),i=this.deps.scriptTimeoutMs??5e3,s=i0.runInContext(n,this.vmContext,{timeout:i});this.deps.isolateScripts&&s&&typeof s.then=="function"&&await s,(await this.timerRegistry.drain(i)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${i}ms; pending async work was cancelled.`]});let l=Su(this.consoleMessages),c=this.initialContext.request.body,d=!this.bodiesEqual(this.modifiedRequest.body,c);return{success:!0,modifiedRequest:{url:this.modifiedRequest.url!==this.initialContext.request.url?this.modifiedRequest.url:void 0,headers:Uf(this.modifiedRequest.headers,this.initialContext.request.headers)?this.modifiedRequest.headers:void 0,body:d?this.modifiedRequest.body:void 0,params:Uf(this.modifiedRequest.params,this.initialContext.request.params||{})?this.modifiedRequest.params:void 0,query:Uf(this.modifiedRequest.query,this.initialContext.request.query||{})?this.modifiedRequest.query:void 0},modifiedVariables:this.ctx.variables.toObject(),localVariables:this.ctx.variables.toLocalObject?.()??{},modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,consoleOutput:l.length>0?l:void 0,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}catch(n){let i=[...Su(this.consoleMessages),`[error] Script execution failed: ${n.message}`];return{success:!1,error:n.message||"Pre-request script execution failed",consoleOutput:i,modifiedVariables:this.ctx?.variables?.toObject(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}}async executePostResponse(e,r){let n=Rm(e,this.deps.isolateScripts);if(!n||!n.trim())return{testResults:[],consoleOutput:[]};try{this.consoleMessages.length=0,this.assertions.length=0,this.ctx.info.eventName="test",this.ctx.response=wm(r),this.ctx.request=this.createRequestObject(r.executedRequest,this.initialContext),this.injectLegacyGlobals("test",r);let i=this.ctx.variables.replaceIn(n),s=this.deps.scriptTimeoutMs??5e3,o=i0.runInContext(i,this.vmContext,{timeout:s});this.deps.isolateScripts&&o&&typeof o.then=="function"&&await o,this.ctx.test._pendingTests?.length>0&&(await Promise.all(this.ctx.test._pendingTests),this.ctx.test._pendingTests.length=0),(await this.timerRegistry.drain(s)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${s}ms; pending async work was cancelled.`]});let c=Su(this.consoleMessages);return{testResults:[...this.assertions],consoleOutput:c.length>0?c:void 0,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}catch(i){this.assertions.push({name:"Script Execution",passed:!1,message:i.message||"Script execution failed"});let s=[...Su(this.consoleMessages),`[error] Script execution failed: ${i.message}`];return{testResults:[...this.assertions],consoleOutput:s,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}}bodiesEqual(e,r){return e===r||!e&&!r?!0:!e||!r?!1:e.type===r.type&&e.format===r.format&&JSON.stringify(e.content)===JSON.stringify(r.content)}dispose(){this.timerRegistry.clearAll(),this.vmContext=null,this.ctx=null,this.assertions=[]}}});import*as vr from"crypto";import*as pz from"querystring";import*as cP from"vm";function fP(t,e){if(t)return t.split(",").map(r=>{let n=r.trim();if(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))return n.slice(1,-1);let i=Number(n);if(!isNaN(i)&&n!=="")return i;if(e&&n in e){let s=e[n],o=Number(s);return!isNaN(o)&&s!==""?o:s}return n})}function dP(t){if(typeof t=="string"&&t.charCodeAt(0)===30)try{return JSON.parse(t.slice(1))}catch{return t}return t}function hz(t,e){if(t==="@")return"";if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);let r=t.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(r){let n=fP(r[2],e),i=ys(r[1],n);return i!==null?i:void 0}if(e[t]!==void 0)return dP(e[t]);if(ba(t)){let n=va(t,e),i=Ui(t,n);if(i!==void 0)return i}}function uP(t,e,r,n){let i=Buffer.concat([Buffer.from(t,"utf8"),n||Buffer.alloc(0)]),s=[],o=Buffer.alloc(0);for(;Buffer.concat(s).length<e+r;)o=vr.createHash("md5").update(Buffer.concat([o,i])).digest(),s.push(o);let l=Buffer.concat(s);return{key:l.subarray(0,e),iv:l.subarray(e,e+r)}}function o0(t,e,r){let n=i=>t==="aes"?`aes-${i*8}-cbc`:t==="des"?"des-cbc":t==="des-ede3"?"des-ede3-cbc":t;return{encrypt(i,s,o){let l=i instanceof Ke?i.toBuffer():Buffer.from(String(i),"utf8");if(typeof s=="string"){let c=vr.randomBytes(8),{key:d,iv:p}=uP(s,e,r,c),m=vr.createCipheriv(n(e),d,p),y=Buffer.concat([m.update(l),m.final()]),b=Buffer.concat([Buffer.from("Salted__"),c,y]);return{ciphertext:new Ke(y),salt:new Ke(c),toString:q=>q?q.stringify(new Ke(b)):b.toString("base64")}}else{let c=s.toBuffer(),d=o?.iv&&o.iv instanceof Ke?o.iv.toBuffer():Buffer.alloc(r),p=vr.createCipheriv(n(c.length),c,d);o?.padding===!1&&p.setAutoPadding(!1);let m=Buffer.concat([p.update(l),p.final()]);return{ciphertext:new Ke(m),toString:y=>y?y.stringify(new Ke(m)):m.toString("base64")}}},decrypt(i,s,o){if(typeof s=="string"){let l=typeof i=="string"?Buffer.from(i,"base64"):i.ciphertext.toBuffer(),c,d;l.subarray(0,8).toString()==="Salted__"?(d=l.subarray(8,16),c=l.subarray(16)):(d=Buffer.alloc(0),c=l);let{key:p,iv:m}=uP(s,e,r,d),y=vr.createDecipheriv(n(e),p,m);return new Ke(Buffer.concat([y.update(c),y.final()]))}else{let l=s.toBuffer(),c=o?.iv&&o.iv instanceof Ke?o.iv.toBuffer():Buffer.alloc(r),d=typeof i=="string"?Buffer.from(i,"base64"):i.ciphertext?i.ciphertext.toBuffer():Buffer.from(i),p=vr.createDecipheriv(n(l.length),l,c);return o?.padding===!1&&p.setAutoPadding(!1),new Ke(Buffer.concat([p.update(d),p.final()]))}}}}function mz(){let t=r=>n=>{let i=n instanceof Ke?n.toBuffer():Buffer.from(String(n),"utf8");return new Ke(vr.createHash(r).update(i).digest())},e=r=>(n,i)=>{let s=n instanceof Ke?n.toBuffer():Buffer.from(String(n),"utf8"),o=i instanceof Ke?i.toBuffer():Buffer.from(String(i),"utf8");return new Ke(vr.createHmac(r,o).update(s).digest())};return{MD5:t("md5"),SHA1:t("sha1"),SHA224:t("sha224"),SHA256:t("sha256"),SHA384:t("sha384"),SHA512:t("sha512"),SHA3:t("sha3-256"),RIPEMD160:t("ripemd160"),HmacMD5:e("md5"),HmacSHA1:e("sha1"),HmacSHA256:e("sha256"),HmacSHA512:e("sha512"),AES:o0("aes",32,16),DES:o0("des",8,8),TripleDES:o0("des-ede3",24,8),PBKDF2(r,n,i){let s=r instanceof Ke?r.toBuffer():Buffer.from(String(r),"utf8"),o=n instanceof Ke?n.toBuffer():Buffer.from(String(n),"utf8"),l=(i?.keySize||4)*4,c=i?.iterations||1;return new Ke(vr.pbkdf2Sync(s,o,c,l,"sha1"))},enc:{Base64:{stringify:r=>(r instanceof Ke?r.toBuffer():Buffer.from(String(r))).toString("base64"),parse:r=>Ke.fromBase64(r)},Utf8:{stringify:r=>(r instanceof Ke?r.toBuffer():Buffer.from(String(r))).toString("utf8"),parse:r=>Ke.fromUtf8(r)},Hex:{stringify:r=>(r instanceof Ke?r.toBuffer():Buffer.from(String(r))).toString("hex"),parse:r=>Ke.fromHex(r)},Latin1:{stringify:r=>(r instanceof Ke?r.toBuffer():Buffer.from(String(r))).toString("latin1"),parse:r=>new Ke(Buffer.from(r,"latin1"))},Utf16:{stringify:r=>(r instanceof Ke?r.toBuffer():Buffer.from(String(r))).toString("utf16le"),parse:r=>new Ke(Buffer.from(r,"utf16le"))},Utf16BE:{stringify:r=>(r instanceof Ke?r.toBuffer():Buffer.from(String(r))).swap16().toString("utf16le"),parse:r=>new Ke(Buffer.from(r,"utf16le").swap16())}},lib:{WordArray:{create:r=>r?typeof r=="string"?new Ke(Buffer.from(r,"utf8")):Buffer.isBuffer(r)?new Ke(r):new Ke(Buffer.from(String(r))):new Ke(Buffer.alloc(0)),random:r=>new Ke(vr.randomBytes(r))}},pad:{Pkcs7:{_name:"pkcs7"},NoPadding:{_name:"nopadding"},ZeroPadding:{_name:"zeropadding"}},mode:{CBC:{_name:"cbc"},ECB:{_name:"ecb"}}}}var Ke,xs,Vf=le(()=>{"use strict";$h();sf();Fh();t0();s0();_m();Ke=class t{_buffer;constructor(e){this._buffer=typeof e=="string"?Buffer.from(e,"utf8"):e}toString(e){return e?e.stringify(this):this._buffer.toString("hex")}toBuffer(){return this._buffer}static fromHex(e){return new t(Buffer.from(e,"hex"))}static fromBase64(e){return new t(Buffer.from(e,"base64"))}static fromUtf8(e){return new t(Buffer.from(e,"utf8"))}};xs=class t{constructor(e,r=[],n,i="shared",s=5e3){this.httpService=e;this.secretRegistry=n;this.scopeMode=i;this.scriptTimeoutMs=s;this.moduleLoader=e0(r)}httpService;secretRegistry;scopeMode;scriptTimeoutMs;moduleLoader;createRequestSession(e){return new Bf({createVM:this.createVM.bind(this),createCommonContext:this.createCommonContext.bind(this),isolateScripts:this.scopeMode==="isolated",scriptTimeoutMs:this.scriptTimeoutMs},e)}createVM(e,r,n){let i=this.moduleLoader.getGlobalSetupExports(),s=this.moduleLoader.createRequireFunction();e.require=s,e.vault=this.createVault();let o={ctx:e,hf:e,pm:e,console:r,...i||{},global:i,setTimeout:n?.setTimeout??setTimeout,setInterval:n?.setInterval??setInterval,clearTimeout:n?.clearTimeout??clearTimeout,clearInterval:n?.clearInterval??clearInterval,URL,URLSearchParams,Buffer,atob:l=>Buffer.from(l,"base64").toString("binary"),btoa:l=>Buffer.from(l,"binary").toString("base64"),TextEncoder,TextDecoder,crypto:vr,_:s("lodash"),require:s,moment:bm(),querystring:pz,CryptoJS:mz(),tv4:(()=>{try{return s("tv4")}catch{return}})(),postman:{setNextRequest:l=>e.setNextRequest?.(l),setGlobalVariable:(l,c)=>e.globals?.set(l,c),getGlobalVariable:l=>e.globals?.get(l),clearGlobalVariable:l=>e.globals?.unset(l),setEnvironmentVariable:(l,c)=>e.environment?.set(l,c),getEnvironmentVariable:l=>e.environment?.get(l),clearEnvironmentVariable:l=>e.environment?.unset(l),getResponseHeader:l=>{let c=e.response?.headers?.get?.(l);return c===void 0?null:c},getResponseCookie:l=>{let c=e.response?.cookies;if(c&&typeof c[Symbol.iterator]=="function"){for(let d of c)if(d?.name&&d.name.toLowerCase()===l.toLowerCase())return{...d}}return null}},jsonStringify:(l,c,d)=>JSON.stringify(l,c,d),jsonParse:l=>JSON.parse(l),xml2Json:l=>{try{let c=this.moduleLoader.createRequireFunction()("xml2js"),d;return c.parseString(l,{explicitArray:!1},(p,m)=>{if(p)throw p;d=m}),d}catch{throw new Error("xml2Json() requires the xml2js module. Add it to your modules/package.json and run npm install.")}}};return cP.createContext(o)}createCommonContext(e,r){let n={...e.variables},i={...e.collectionVariables||{}},s={...e.globals||{}},o={...e.environmentVariables||{}},l=e.iterationData||{},c=this.createMergedVariableScope(n,o,i,s,l),d=this.createGlobalsScope(s,e.onGlobalsChange),p=this.createVariableScope(i),m=this.createEnvironmentScope(o,e.environmentName,e.onEnvironmentChange,!0),y={...m,set:(x,v)=>{let R=this.serializeValue(v);m.set(x,R),n[x]=R},unset(x){m.unset(x),delete n[x]},clear(){let x=Object.keys(o);m.clear();for(let v of x)delete n[v]}},b={...d,set:(x,v)=>{let R=this.serializeValue(v);d.set(x,R),n[x]=R},unset(x){d.unset(x),delete n[x]},clear(){let x=Object.keys(s);d.clear();for(let v of x)delete n[v]}};return b.replaceIn=c.replaceIn,p.replaceIn=c.replaceIn,y.replaceIn=c.replaceIn,{globals:b,collectionVariables:p,variables:c,environment:y,iterationData:{get:x=>l[x],has:x=>x in l,toObject:()=>({...l}),toJSON:()=>JSON.stringify(l)},sendRequest:this.createSendRequest(),expect:bu,info:e.info||{eventName:r,requestName:void 0,requestId:void 0}}}static JSON_TYPE_MARKER="";serializeValue(e){return typeof e=="string"?e:e===void 0?t.JSON_TYPE_MARKER+"undefined":t.JSON_TYPE_MARKER+JSON.stringify(e)}deserializeValue(e){if(e!==void 0){if(typeof e=="string"&&e.charCodeAt(0)===30){let r=e.slice(1);if(r==="undefined")return;try{return JSON.parse(r)}catch{}}return e}}createVariableScope(e){return{get:r=>this.deserializeValue(e[r]),set:(r,n)=>{e[r]=this.serializeValue(n)},has(r){return r in e},unset(r){delete e[r]},clear(){Object.keys(e).forEach(r=>delete e[r])},toObject(){return{...e}}}}createGlobalsScope(e,r){let n=(i,s,o)=>{r&&r(i,s,o)};return{get:i=>this.deserializeValue(e[i]),set:(i,s)=>{let o=this.serializeValue(s);e[i]=o,n("set",i,o)},has(i){return i in e},unset(i){delete e[i],n("unset",i)},clear(){Object.keys(e).forEach(i=>delete e[i]),n("clear")},toObject(){return{...e}}}}createMergedVariableScope(e,r,n,i,s={}){let o={get:l=>l in e?this.deserializeValue(e[l]):l in s?s[l]:l in r?this.deserializeValue(r[l]):l in n?this.deserializeValue(n[l]):this.deserializeValue(i[l]),set:(l,c)=>{e[l]=this.serializeValue(c)},has(l){return l in e||l in s||l in r||l in r||l in n||l in i},unset(l){delete e[l]},clear(){Object.keys(e).forEach(l=>delete e[l])},toObject(){return{...i,...n,...r,...s,...e}},toLocalObject(){return{...n,...r,...s,...e}},replaceIn(l){if(!l||typeof l!="string")return l;let c=o.toObject(),d=20,p=y=>y.replace(/\{\{([^}]+)\}\}/g,(b,q)=>{let x=q.trim(),v=x.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(v)try{let E=fP(v[2],c),k=ys(v[1],E);return k!==null?String(k):b}catch{return b}let R=af(x);if(R){let E=hz(R.input,c);if(E!==void 0){let k=lf(E,R.filters,c);return k!==void 0?String(k):b}return b}if(o.has(x)){let E=o.get(x);return E===void 0?"":String(E)}if(ba(x)){let E={};for(let[M,j]of Object.entries(c))E[M]=dP(j);let k=va(x,E),P=Ui(x,k);if(P!==void 0)return String(P)}return b}),m=l;for(let y=0;y<d;y++){let b=p(m);if(b===m)break;m=b}return m}};return o}createEnvironmentScope(e,r,n,i){let s=(o,l,c)=>{n&&(i?n(o,l,c):n(l||"",o==="set"?c:void 0))};return{name:r||"",get:o=>this.deserializeValue(e[o]),set:(o,l)=>{let c=this.serializeValue(l);e[o]=c,s("set",o,c)},has(o){return o in e},unset(o){delete e[o],s("unset",o)},clear(){Object.keys(e).forEach(o=>delete e[o]),s("clear")},toObject(){return{...e}}}}createVault(){let e=this.secretRegistry,r=()=>{throw new Error("pm.vault is read-only in HTTP Forge. Use environment variables or {{secret:provider/path}} tokens to manage secrets.")};return{async get(n){if(!e)throw new Error('pm.vault is not available \u2014 no secret providers are configured. Configure a provider under "secrets.providers" to use pm.vault.get().');let i=`secret:${n}`;return(await e.resolveSecretTokens(`{{${i}}}`))[i]},set:r,unset:r}}createSendRequest(){return this.httpService?(e,r)=>{let n=typeof e=="string"?{url:e,method:"GET"}:e,i=this.httpService.execute({url:n.url,method:n.method||"GET",headers:n.headers||{},body:n.body,...n});if(r){i.then(s=>r(null,s)).catch(s=>r(s,null));return}return i}:(e,r)=>{let n=new Error("sendRequest not available - HTTP service not configured");if(r){r(n,null);return}return Promise.reject(n)}}}});import*as hP from"fs";import*as yz from"http";import*as a0 from"https";import*as Cm from"path";import{URL as pP}from"url";import*as Em from"zlib";var _n,Na,Jf=le(()=>{"use strict";_n={timeout:3e4,followRedirects:!0,followOriginalMethod:!1,followAuthHeader:!1,maxRedirects:10,strictSSL:!0,decompress:!0,includeCookies:!1,tls:{},certificates:[]},Na=class{settings;version;basePath;constructor(e,r=process.cwd()){this.settings={..._n,...e},this.basePath=r;try{this.version=wt("../../package.json").version||"0.0.0"}catch{this.version="0.0.0"}this.settings.strictSSL===!1&&console.log("[NodeHttpClient] SSL verification disabled (strictSSL: false)")}async send(e){let r=this.mergeSettings(e.settings);return await this.executeInternal(e,r,0)}mergeSettings(e){return{timeout:e?.timeout??this.settings.timeout,followRedirects:e?.followRedirects??this.settings.followRedirects,followOriginalMethod:e?.followOriginalMethod??this.settings.followOriginalMethod,followAuthHeader:e?.followAuthHeader??this.settings.followAuthHeader,maxRedirects:e?.maxRedirects??this.settings.maxRedirects,strictSSL:e?.strictSSL??this.settings.strictSSL,decompress:e?.decompress??this.settings.decompress,includeCookies:e?.includeCookies??this.settings.includeCookies,tls:e?.tls??this.settings.tls??{},certificates:e?.certificates??this.settings.certificates??[]}}async executeInternal(e,r,n,i){let s=Date.now(),o=new pP(e.url),l=o.protocol==="https:",c=this.sanitizeHeaders(e.headers||{});Object.keys(c).some(m=>m.toLowerCase()==="user-agent")||(c["User-Agent"]=`HttpForge/${this.version}`);let p={hostname:o.hostname,port:o.port||(l?443:80),path:o.pathname+o.search,method:e.method,headers:{...c},timeout:r.timeout||void 0};if(r.decompress&&!c["accept-encoding"]&&!c["Accept-Encoding"]&&(p.headers["Accept-Encoding"]="gzip, deflate"),l){let m=this.resolveTlsSettings(o,r),y=p;y.rejectUnauthorized=r.strictSSL;let b={rejectUnauthorized:r.strictSSL},q=this.readOptionalFile(m.caPath,"CA certificate");q&&(b.ca=q);let x=this.readOptionalFile(m.certPath,"client certificate");x&&(b.cert=x);let v=this.readOptionalFile(m.keyPath,"client private key");v&&(b.key=v);let R=this.readOptionalFile(m.pfxPath,"client pfx");R&&(b.pfx=R),m.passphrase&&(b.passphrase=m.passphrase),m.servername&&(y.servername=m.servername),y.agent=new a0.Agent(b)}return new Promise((m,y)=>{if(i?.aborted){let x=new Error("Request cancelled");x.name="AbortError",y(x);return}let q=(l?a0:yz).request(p,async x=>{let v=x.statusCode||0;if(r.followRedirects&&[301,302,303,307,308].includes(v)){if(n>=r.maxRedirects){y(new Error(`Maximum redirects (${r.maxRedirects}) exceeded`));return}let E=x.headers.location;if(!E){y(new Error("Redirect response missing Location header"));return}let k=new pP(E,e.url).toString(),P=e.method;!r.followOriginalMethod&&[301,302,303].includes(v)&&(P="GET");let M={...e.headers};r.followAuthHeader||(delete M.authorization,delete M.Authorization);try{let j=await this.executeInternal({...e,url:k,method:P,headers:M,body:P==="GET"?void 0:e.body},r,n+1,i),I=Date.now();j.time=I-s,m(j)}catch(j){y(j)}return}let R=[];x.on("data",E=>R.push(E)),x.on("end",()=>{let E=Date.now(),k=Buffer.concat(R),P=x.headers["content-encoding"];if(r.decompress&&P)try{P==="gzip"?k=Em.gunzipSync(k):P==="deflate"&&(k=Em.inflateSync(k))}catch(_){console.warn("[NodeHttpClient] Decompression failed:",_)}let M=k.toString("utf-8"),j={};for(let[_,A]of Object.entries(x.headers))(typeof A=="string"||Array.isArray(A))&&(j[_]=A);let I=this.parseCookies(x.headers["set-cookie"],o.hostname);m({status:x.statusCode||0,statusText:x.statusMessage||"",headers:j,cookies:I,body:M,time:E-s,size:k.length})})});if(i&&i.addEventListener("abort",()=>{q.destroy();let x=new Error("Request cancelled");x.name="AbortError",y(x)}),q.on("error",x=>{y(x)}),q.on("timeout",()=>{q.destroy(),y(new Error("Request timeout"))}),e.body!==void 0&&e.body!==null){let x=typeof e.body=="string"?e.body:JSON.stringify(e.body);q.write(x)}q.end()})}resolveTlsSettings(e,r){let n=r.tls||{};if(!!(n.caPath||n.certPath||n.keyPath||n.pfxPath||n.servername||n.passphrase))return n;let s=this.findCertificateMapping(e,r.certificates||[]);return s?{caPath:s.caPath,certPath:s.certPath,keyPath:s.keyPath,pfxPath:s.pfxPath,passphrase:s.passphrase,servername:s.servername}:n}findCertificateMapping(e,r){if(!Array.isArray(r)||r.length===0)return;let n=e.hostname,i=e.port?Number(e.port):443,s=r.find(o=>this.mappingMatchesHost(o,n,i,!0));return s||r.find(o=>this.mappingMatchesHost(o,n,i,!1))}mappingMatchesHost(e,r,n,i){if(!e||e.enabled===!1)return!1;let s=String(e.host||"").trim().toLowerCase();if(!s||e.port!=null&&Number(e.port)!==n)return!1;let o=r.toLowerCase();if(i)return s!=="*"&&!s.startsWith("*.")&&o===s;if(s==="*")return!0;if(s.startsWith("*.")){let l=s.slice(2);return o===l||o.endsWith(`.${l}`)}return o===s}readOptionalFile(e,r){if(!e)return;let n=Cm.isAbsolute(e)?e:Cm.resolve(this.basePath,e);try{return hP.readFileSync(n)}catch(i){throw new Error(`[NodeHttpClient] Failed to read ${r} file at ${n}: ${i?.message||"Unknown error"}`)}}sanitizeHeaderValue(e){return e?String(e).replace(/[\u201C\u201D\u201E\u201F\u2033\u2036]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032\u2035]/g,"'").replace(/[\x00-\x08\x0A-\x1F\x7F]/g,""):""}sanitizeHeaders(e){let r={};for(let[n,i]of Object.entries(e))r[n]=this.sanitizeHeaderValue(String(i));return r}parseCookies(e,r){return e?e.map(n=>{let i=n.split(";").map(p=>p.trim()),[s,...o]=i,[l,c]=s.split("="),d={name:l.trim(),value:c?.trim()||"",domain:r};for(let p of o){let[m,y]=p.split("=");switch(m.toLowerCase().trim()){case"domain":d.domain=y?.trim();break;case"path":d.path=y?.trim();break;case"expires":d.expires=y?.trim();break;case"httponly":d.httpOnly=!0;break;case"secure":d.secure=!0;break}}return d}):[]}}});var l0,Ma,qm=le(()=>{"use strict";l0={json:"application/json",xml:"application/xml",html:"text/html",text:"text/plain",javascript:"application/javascript",css:"text/css","x-www-form-urlencoded":"application/x-www-form-urlencoded","form-data":"multipart/form-data",graphql:"application/json"},Ma=class{sanitizeHeaderValue(e){return e?String(e).replace(/[\u201C\u201D\u201E\u201F\u2033\u2036]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032\u2035]/g,"'").replace(/[\x00-\x08\x0A-\x1F\x7F]/g,""):""}sanitizeHeaders(e){let r={};for(let[n,i]of Object.entries(e))r[n]=this.sanitizeHeaderValue(String(i));return r}encodeBody(e){if(!e||e.type==="none")return null;let{type:r,content:n}=e;switch(r){case"x-www-form-urlencoded":return this.encodeUrlEncodedBody(n);case"form-data":return n;case"graphql":return this.encodeGraphQLBody(n);case"raw":return n;default:return n}}encodeUrlEncodedBody(e){if(Array.isArray(e)){let r=new URLSearchParams;for(let n of e)n.enabled!==!1&&n.key&&r.append(n.key,n.value||"");return r.toString()}return typeof e=="string"?e:String(e)}encodeGraphQLBody(e){if(typeof e=="string")try{e=JSON.parse(e)}catch{return e}if(typeof e=="object"&&e!==null&&e.query){let r=e.variables;if(typeof r=="string")try{r=r.trim()?JSON.parse(r):void 0}catch{r=void 0}return JSON.stringify({query:e.query,...r!=null?{variables:r}:{},...e.operationName?{operationName:e.operationName}:{}})}return JSON.stringify(e)}setContentTypeHeader(e,r,n){if(Object.keys(e).some(o=>o.toLowerCase()==="content-type"))return;if(n){e["Content-Type"]=n;return}if(!r||r.type==="none")return;let s;switch(r.type){case"x-www-form-urlencoded":s=l0["x-www-form-urlencoded"];break;case"raw":s=r.format?l0[r.format]:"text/plain",s||(s="text/plain");break;case"graphql":s=l0.graphql;break;case"binary":s="application/octet-stream";break}s&&(e["Content-Type"]=s)}}});var Da,Im=le(()=>{"use strict";Da=class{parse(e,r){return r.toLowerCase().endsWith(".json")?this.parseJson(e):this.parseCsv(e)}parseJson(e){try{let r=JSON.parse(e);return Array.isArray(r)?r:[r]}catch{throw new Error("Failed to parse JSON data file: Invalid JSON format")}}parseCsv(e){let r=e.split(/\r?\n/).filter(s=>s.trim());if(r.length<2)return[{}];let n=this.parseCsvLine(r[0]),i=[];for(let s=1;s<r.length;s++){let o=this.parseCsvLine(r[s]),l={};n.forEach((c,d)=>{l[c]=o[d]||""}),i.push(l)}return i}parseCsvLine(e){let r=[],n="",i=!1;for(let s=0;s<e.length;s++){let o=e[s],l=e[s+1];o==='"'?i&&l==='"'?(n+='"',s++):i=!i:o===","&&!i?(r.push(n.trim()),n=""):n+=o}return r.push(n.trim()),r}}});import*as Ru from"crypto";var vz,Yf,c0=le(()=>{"use strict";vz=3e4,Yf=class{constructor(e,r,n,i,s="henry-huang.http-forge/oauth2/callback"){this.secretStore=e;this.browserService=r;this.envConfigService=n;this.httpService=i;this.callbackPath=s}secretStore;browserService;envConfigService;httpService;callbackPath;tokenCache=new Map;pendingAuthCallback=null;pendingImplicitCallback=null;async getToken(e,r){if(e.accessToken)return{accessToken:this.resolve(e.accessToken,r),tokenType:e.tokenPrefix||"Bearer",raw:{}};let n=this.buildCacheKeyString(e),i=this.tokenCache.get(n);if(i&&!this.isExpired(i))return i;if(i?.refreshToken)try{return await this.refreshToken(e,i.refreshToken,r)}catch{this.tokenCache.delete(n)}if(!i){let o=await this.secretStore.get(`oauth2_refresh_${n}`);if(o)try{return await this.refreshToken(e,o,r)}catch{await this.secretStore.delete(`oauth2_refresh_${n}`)}}let s;switch(e.grantType){case"client_credentials":s=await this.fetchToken(e,r,"client_credentials");break;case"password":s=await this.fetchToken(e,r,"password");break;case"authorization_code":s=await this.authorizationCodeFlow(e,r);break;case"implicit":s=await this.implicitFlow(e,r);break;default:throw new Error(`Unknown OAuth2 grant type: ${e.grantType}`)}return this.tokenCache.set(n,s),s.refreshToken&&await this.storeRefreshToken(n,s.refreshToken),s}async refreshToken(e,r,n){let i=this.resolve(e.tokenUrl||"",n);if(!i)throw new Error("OAuth2 tokenUrl is required for token refresh");let s=this.resolve(e.clientId||"",n),o=this.resolve(e.clientSecret||"",n),l=new URLSearchParams;l.append("grant_type","refresh_token"),l.append("refresh_token",r);let c={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,c,l,s,o,n);let d=await this.httpService.execute({method:"POST",url:i,headers:c,body:l.toString()}),p=this.parseTokenResponse(d.body,e);p.refreshToken||(p.refreshToken=r);let m=this.buildCacheKeyString(e);return this.tokenCache.set(m,p),p.refreshToken&&await this.storeRefreshToken(m,p.refreshToken),p}async authorizationCodeFlow(e,r){let n=this.resolve(e.authUrl||"",r),i=this.resolve(e.tokenUrl||"",r),s=this.resolve(e.clientId||"",r),o=this.resolve(e.clientSecret||"",r),l=e.scope?this.resolve(e.scope,r):void 0;if(!n)throw new Error("OAuth2 authUrl is required for authorization code flow");if(!i)throw new Error("OAuth2 tokenUrl is required for authorization code flow");if(!s)throw new Error("OAuth2 clientId is required for authorization code flow");let c=e.usePkce!==!1,d,p,m;if(c){d=this.generateCodeVerifier();let j=e.pkceMethod||"S256";p=j==="S256"?this.generateCodeChallengeS256(d):d,m=j}let y=e.state||Ru.randomBytes(16).toString("hex"),b=await this.getCallbackUri(),q=new URL(n);if(q.searchParams.set("response_type","code"),q.searchParams.set("client_id",s),q.searchParams.set("redirect_uri",b),l&&q.searchParams.set("scope",l),q.searchParams.set("state",y),p&&(q.searchParams.set("code_challenge",p),q.searchParams.set("code_challenge_method",m)),e.audience&&q.searchParams.set("audience",this.resolve(e.audience,r)),e.resource&&q.searchParams.set("resource",this.resolve(e.resource,r)),e.extraParams)for(let[j,I]of Object.entries(e.extraParams))q.searchParams.set(j,this.resolve(I,r));this.pendingAuthCallback&&(this.pendingAuthCallback.reject(new Error("OAuth2 authorization superseded by a new request")),this.pendingAuthCallback=null);let x=new Promise((j,I)=>{this.pendingAuthCallback={resolve:j,reject:I,state:y}});await this.browserService.openExternal(q.toString());let v;try{v=await Promise.race([x,new Promise((j,I)=>setTimeout(()=>{this.pendingAuthCallback=null,I(new Error("OAuth2 authorization timed out after 2 minutes"))},12e4))])}finally{this.pendingAuthCallback=null}if(v.state&&v.state!==y)throw new Error("OAuth2 state mismatch \u2014 potential CSRF attack");let R=new URLSearchParams;R.append("grant_type","authorization_code"),R.append("code",v.code),R.append("redirect_uri",b),d&&R.append("code_verifier",d);let E={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,E,R,s,o,r);let k=await this.httpService.execute({method:"POST",url:i,headers:E,body:R.toString()}),P=this.parseTokenResponse(k.body,e),M=this.buildCacheKeyString(e);return this.tokenCache.set(M,P),P.refreshToken&&await this.storeRefreshToken(M,P.refreshToken),P}async implicitFlow(e,r){let n=this.resolve(e.authUrl||"",r),i=this.resolve(e.clientId||"",r),s=e.scope?this.resolve(e.scope,r):void 0;if(!n)throw new Error("OAuth2 authUrl is required for implicit flow");if(!i)throw new Error("OAuth2 clientId is required for implicit flow");let o=e.state||Ru.randomBytes(16).toString("hex"),l=await this.getCallbackUri(),c=new URL(n);if(c.searchParams.set("response_type","token"),c.searchParams.set("client_id",i),c.searchParams.set("redirect_uri",l),s&&c.searchParams.set("scope",s),c.searchParams.set("state",o),e.audience&&c.searchParams.set("audience",this.resolve(e.audience,r)),e.resource&&c.searchParams.set("resource",this.resolve(e.resource,r)),e.extraParams)for(let[b,q]of Object.entries(e.extraParams))c.searchParams.set(b,this.resolve(q,r));this.pendingImplicitCallback&&(this.pendingImplicitCallback.reject(new Error("OAuth2 implicit flow superseded by a new request")),this.pendingImplicitCallback=null);let d=new Promise((b,q)=>{this.pendingImplicitCallback={resolve:b,reject:q,state:o}});await this.browserService.openExternal(c.toString());let p;try{p=await Promise.race([d,new Promise((b,q)=>setTimeout(()=>{this.pendingImplicitCallback=null,q(new Error("OAuth2 implicit flow timed out after 2 minutes"))},12e4))])}finally{this.pendingImplicitCallback=null}if(p.state&&p.state!==o)throw new Error("OAuth2 state mismatch \u2014 potential CSRF attack");let m={accessToken:p.accessToken,tokenType:p.tokenType||e.tokenPrefix||"Bearer",expiresAt:p.expiresIn?Date.now()+p.expiresIn*1e3:void 0,raw:{access_token:p.accessToken,token_type:p.tokenType,expires_in:p.expiresIn}},y=this.buildCacheKeyString(e);return this.tokenCache.set(y,m),m}handleAuthorizationCallback(e,r,n){if(n){let i=new Error(`OAuth2 authorization error: ${n}`);this.pendingAuthCallback?.reject(i),this.pendingImplicitCallback?.reject(i),this.pendingAuthCallback=null,this.pendingImplicitCallback=null;return}if(e&&this.pendingAuthCallback){this.pendingAuthCallback.resolve({code:e,state:r}),this.pendingAuthCallback=null;return}!e&&!this.pendingAuthCallback&&this.pendingImplicitCallback&&(this.pendingImplicitCallback.reject(new Error("OAuth2 implicit flow did not receive access_token")),this.pendingImplicitCallback=null)}handleImplicitCallback(e,r,n,i){this.pendingImplicitCallback&&(this.pendingImplicitCallback.resolve({accessToken:e,tokenType:r,expiresIn:n,state:i}),this.pendingImplicitCallback=null)}clearToken(e){let r=`${e.tokenUrl}|${e.clientId}|${e.scope||""}|${e.grantType}`;this.tokenCache.delete(r),this.secretStore.delete(`oauth2_refresh_${r}`)}clearAllTokens(){for(let e of this.tokenCache.keys())this.secretStore.delete(`oauth2_refresh_${e}`);this.tokenCache.clear()}async fetchToken(e,r,n){let i=this.resolve(e.tokenUrl||"",r);if(!i)throw new Error("OAuth2 tokenUrl is required");let s=this.resolve(e.clientId||"",r),o=this.resolve(e.clientSecret||"",r),l=e.scope?this.resolve(e.scope,r):void 0,c=new URLSearchParams;if(c.append("grant_type",n),l&&c.append("scope",l),n==="password"){let m=this.resolve(e.username||"",r),y=this.resolve(e.password||"",r);if(!m)throw new Error("OAuth2 password grant requires username");c.append("username",m),c.append("password",y)}if(e.audience&&c.append("audience",this.resolve(e.audience,r)),e.resource&&c.append("resource",this.resolve(e.resource,r)),e.extraParams)for(let[m,y]of Object.entries(e.extraParams))c.append(m,this.resolve(y,r));let d={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,d,c,s,o,r);let p=await this.httpService.execute({method:"POST",url:i,headers:d,body:c.toString()});return this.parseTokenResponse(p.body,e)}applyClientAuth(e,r,n,i,s,o){if(e.clientAuthentication==="header"){let l=Buffer.from(`${i}:${s}`).toString("base64");r.Authorization=`Basic ${l}`}else i&&n.set("client_id",i),s&&n.set("client_secret",s)}parseTokenResponse(e,r){let n=e;if(typeof n=="string")try{n=JSON.parse(n)}catch{throw new Error("OAuth2 token response is not valid JSON")}if(!n||typeof n!="object")throw new Error("OAuth2 token response is not a valid JSON object");let i=n,s=r.tokenField||"access_token",o=i[s];if(!o)throw new Error(`OAuth2 token fetch failed: '${s}' not present in response`);let l=typeof i.expires_in=="number"?i.expires_in:void 0;return{accessToken:o,tokenType:i.token_type||r.tokenPrefix||"Bearer",expiresAt:l?Date.now()+l*1e3:void 0,refreshToken:i.refresh_token,scope:i.scope,raw:i}}isExpired(e){return e.expiresAt?Date.now()>=e.expiresAt-vz:!1}buildCacheKeyString(e){return`${e.tokenUrl||""}|${e.clientId||""}|${e.scope||""}|${e.grantType}`}async getCallbackUri(){let e=`${this.browserService.uriScheme}://${this.callbackPath}`;return this.browserService.asExternalUri(e)}resolve(e,r){return this.envConfigService.resolveVariables(e,r)}generateCodeVerifier(){return Ru.randomBytes(32).toString("base64url")}generateCodeChallengeS256(e){return Ru.createHash("sha256").update(e).digest("base64url")}async storeRefreshToken(e,r){try{await this.secretStore.store(`oauth2_refresh_${e}`,r)}catch{}}}});import*as ja from"fs";import*as go from"path";function xu(t,e={}){let r=[];Object.entries(e).forEach(([n,i])=>{r.push(`${n}=${i}`)}),r.length&&ja.writeFileSync(t,r.join(`
52
+ `)}function Uf(t,e){return JSON.stringify(t)!==JSON.stringify(e)}function Su(t){return t.map(e=>{let r=e.args.map(n=>{if(typeof n=="object")try{return JSON.stringify(n,null,2)}catch{return String(n)}return String(n)}).join(" ");return`[${e.level}] ${r}`})}function fz(t){return{log:(...e)=>t.push({level:"log",args:e}),info:(...e)=>t.push({level:"info",args:e}),warn:(...e)=>t.push({level:"warn",args:e}),error:(...e)=>t.push({level:"error",args:e})}}function r0(t){let e=[],r=(n,i)=>{try{let s=i();if(s&&typeof s.then=="function"){let o=s.then(()=>{t.push({name:n,passed:!0})},l=>{t.push({name:n,passed:!1,message:l.message||String(l)})});e.push(o)}else t.push({name:n,passed:!0})}catch(s){t.push({name:n,passed:!1,message:s.message})}};return r.skip=(n,i)=>{t.push({name:n,passed:!0,skipped:!0})},r.fail=n=>{t.push({name:n||"Failed test",passed:!1,message:n||"pm.test.fail()"})},r.index=()=>t.length,r._pendingTests=e,r}function n0(t){let e={};for(let[r,n]of Object.entries(t))e[r]=Array.isArray(n)?n.join(", "):n;return e}function xm(t,e,r){let n;if(r)try{n=new URL(r).hostname}catch{n=void 0}let i=Ct.parseCookieHeaders(t||{},n);return i.length>0?i:Array.isArray(e)&&e.length>0?e.filter(s=>s&&s.name).map(s=>({name:s.name,value:s.value,domain:s.domain??n,path:s.path,expires:s.expires,maxAge:s.maxAge,httpOnly:s.httpOnly,secure:s.secure,sameSite:s.sameSite})):[]}var Hf=le(()=>{"use strict";ga()});import*as i0 from"vm";function dz(t){let e=null;try{e=new URL(t)}catch{}return{toString(){return t},valueOf(){return t},[Symbol.toPrimitive](n){return n==="number"?NaN:t},getHost(){return e?e.hostname:""},getPath(){return e?e.pathname:t},getPathWithQuery(){return e?e.pathname+e.search:t},getQueryString(){return e?e.search.startsWith("?")?e.search.slice(1):e.search:""},getRemote(){if(!e)return"";let n=e.port||(e.protocol==="https:"?"443":"80");return`${e.hostname}:${n}`},getOAuth1BaseUrl(){return e?`${e.protocol}//${e.host}${e.pathname}`:t},get protocol(){return e?.protocol?.replace(":","")||""},get host(){return e?e.hostname.split("."):[]},get port(){return e?.port||""},get path(){return e?e.pathname.split("/").filter(Boolean):[]},get hash(){return e?.hash?.replace("#","")||""},query:{toObject(){if(!e)return{};let n={};return e.searchParams.forEach((i,s)=>{n[s]=i}),n},has(n){return e?e.searchParams.has(n):!1},get(n){return e?e.searchParams.get(n):void 0},each(n){e&&e.searchParams.forEach((i,s)=>n({key:s,value:i}))}}}}var Bf,s0=le(()=>{"use strict";aP();_m();Hf();Bf=class{constructor(e,r){this.deps=e;this.initialContext=r;this.timerRegistry=oP(n=>{let i=n instanceof Error?n.message:String(n);this.consoleMessages.push({level:"error",args:[`Uncaught error in async callback: ${i}`]})}),this.initializeSession()}deps;initialContext;vmContext=null;ctx=null;modifiedRequest=null;assertions=[];consoleMessages=[];_variables={};_collectionVariables={};_globals={};_environmentVariables={};_liveEnvironmentScope=null;_liveGlobalsScope=null;_liveCollectionScope=null;_nextRequest=void 0;_skipRequest=!1;_visualizerData=void 0;timerRegistry;initializeSession(){this.modifiedRequest={url:this.initialContext.request.url,method:this.initialContext.request.method,headers:{...this.initialContext.request.headers},body:this.initialContext.request.body?{...this.initialContext.request.body}:null,params:this.initialContext.request.params?{...this.initialContext.request.params}:{},query:this.initialContext.request.query?{...this.initialContext.request.query}:{}},this.assertions=[],this.ctx=this.createSharedContext(),this.consoleMessages=[];let e=this,r={log:(...n)=>{e.consoleMessages.push({level:"log",args:n})},info:(...n)=>{e.consoleMessages.push({level:"info",args:n})},warn:(...n)=>{e.consoleMessages.push({level:"warn",args:n})},error:(...n)=>{e.consoleMessages.push({level:"error",args:n})}};this.vmContext=this.deps.createVM(this.ctx,r,this.timerRegistry.timers)}createSharedContext(){let e=this.initialContext,r=this.modifiedRequest,n=this.deps.createCommonContext(e,"prerequest");this._variables={...e.variables},this._collectionVariables={...e.collectionVariables||{}},this._globals={...e.globals||{}},this._environmentVariables={...e.environmentVariables||{}},this._liveEnvironmentScope=n.environment,this._liveGlobalsScope=n.globals,this._liveCollectionScope=n.collectionVariables;let i;try{i=new URL(e.request.url).hostname}catch{}let s={get:l=>e.cookieJar?e.cookieJar.get(l,i)?.value:void 0,set:(l,c)=>{e.cookieJar&&e.cookieJar.set({name:l,value:c,domain:i})},has:l=>e.cookieJar?e.cookieJar.has(l,i):!1,list:()=>e.cookieJar?e.cookieJar.getAll(i).map(l=>({name:l.name,value:l.value})):[],toObject:()=>{if(!e.cookieJar)return{};let l=e.cookieJar.getAll(i),c={};for(let d of l)c[d.name]=d.value;return c},jar:()=>{let l=e.cookieJar,c=d=>{if(d==null)return;let p=typeof d=="string"?d:typeof d=="object"||typeof d=="number"||typeof d=="boolean"?String(d):void 0;if(!p)return;let m=p.trim();if(m)try{return new URL(m).hostname}catch{return m}};return{getAll(d,p){try{if(!l){p(null,[]);return}let m=c(d),y=l.getAll(m).map(b=>({name:b.name,value:b.value,domain:b.domain,path:b.path,httpOnly:b.httpOnly,secure:b.secure}));p(null,y)}catch(m){p(m,[])}},get(d,p,m){try{if(!l){m(null,void 0);return}let y=c(d),b=l.get(p,y);m(null,b?{name:b.name,value:b.value,domain:b.domain}:void 0)}catch(y){m(y,void 0)}},set(d,p,m,y){try{if(!l){(y||m)?.(null);return}let b=c(d);typeof p=="string"&&typeof m=="string"?(l.set({name:p,value:m,domain:b}),y?.(null)):typeof p=="object"&&(l.set({...p,domain:b}),m?.(null))}catch(b){(y||m)?.(b)}},unset(d,p,m){try{if(!l){m?.(null);return}let y=c(d);l.delete(p,y),m?.(null)}catch(y){m?.(y)}},clear(d,p){try{let m=typeof d=="function"?d:p;if(!l){m?.(null);return}let y=typeof d=="function"?void 0:c(d);y&&typeof l.clearDomain=="function"?l.clearDomain(y):l.clear(),m?.(null)}catch(m){(typeof d=="function"?d:p)?.(m)}}}},remove:l=>{e.cookieJar&&e.cookieJar.delete(l,i)},unset:l=>{e.cookieJar&&e.cookieJar.delete(l,i)},clear:()=>{e.cookieJar&&e.cookieJar.clear()}},o=this;return{request:this.createRequestObject(r,e),response:null,test:r0(this.assertions),expect:bu,cookies:s,execution:{setNextRequest(l){o._nextRequest=l},skipRequest(){o._skipRequest=!0},runRequest(l,c){let p=(async()=>{if(typeof n.sendRequest!="function")throw new Error("pm.execution.runRequest is not available \u2014 HTTP service not configured.");let m=typeof l=="string"?{url:l,method:"GET"}:l,y=await n.sendRequest(m),b=Array.isArray(y?.cookies)?y.cookies.filter(v=>v?.name):[],q=y?.body,x=0;if(typeof q=="string")x=Buffer.byteLength(q,"utf8");else if(Buffer.isBuffer(q))x=q.length;else if(q!=null)try{x=Buffer.byteLength(JSON.stringify(q),"utf8")}catch{}return wm({executedRequest:null,status:y?.status??0,statusText:y?.statusText??"",headers:y?.headers??{},body:q,cookies:b,responseTime:y?.time,responseSize:x})})();if(typeof c=="function"){p.then(m=>c(null,m),m=>c(m));return}return p},location:{current:n.info?.requestName||"",currentRequestName:n.info?.requestName||"",eventName:"prerequest",toString(){return n.info?.requestName||""}}},setNextRequest(l){o._nextRequest=l},visualizer:{set(l,c){o._visualizerData={template:l,data:c}},clear(){o._visualizerData=void 0}},...n,info:{...n.info||{},eventName:"prerequest",requestName:n.info?.requestName||void 0,requestId:n.info?.requestId||void 0,iteration:e.iteration||0,iterationCount:e.iterationCount||1}}}createRequestObject(e,r){let n=l=>{if(!l)return"none";switch(l){case"raw":return"raw";case"form-data":return"formdata";case"x-www-form-urlencoded":return"urlencoded";case"binary":return"file";case"graphql":return"graphql";case"none":return"none";default:return"raw"}},i=l=>{if(!l)return"none";switch(l){case"raw":return"raw";case"formdata":return"form-data";case"urlencoded":return"x-www-form-urlencoded";case"file":return"binary";case"graphql":return"graphql";case"none":return"none";default:return"raw"}},s={...e.headers,add:l=>{l&&l.key&&(e.headers[l.key]=l.value||"")},get:l=>{for(let[c,d]of Object.entries(e.headers))if(c.toLowerCase()===l.toLowerCase())return d},has:l=>{for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.toLowerCase())return!0;return!1},remove:l=>{for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.toLowerCase()){delete e.headers[c];break}},update:l=>{if(l&&l.key){for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.key.toLowerCase()){e.headers[c]=l.value||"";return}}},upsert:l=>{if(l&&l.key){for(let c of Object.keys(e.headers))if(c.toLowerCase()===l.key.toLowerCase()){e.headers[c]=l.value||"";return}e.headers[l.key]=l.value||""}},toObject:()=>{let l={};for(let[c,d]of Object.entries(e.headers))typeof d=="string"&&(l[c]=d);return l},each:l=>{for(let[c,d]of Object.entries(e.headers))typeof d=="string"&&l({key:c,value:d})}},o={get mode(){return n(e.body?.type)},set mode(l){let c=i(l);e.body?e.body.type=c:e.body={type:c,content:null}},get raw(){let l=e.body?.content;return typeof l=="string"?l:l&&typeof l=="object"?JSON.stringify(l):""},set raw(l){e.body?(e.body.type="raw",e.body.content=l):e.body={type:"raw",content:l}},get formdata(){return e.body?.type==="form-data"&&Array.isArray(e.body.content)?e.body.content:[]},get urlencoded(){return e.body?.type==="x-www-form-urlencoded"&&Array.isArray(e.body.content)?e.body.content:[]},get graphql(){return e.body?.type==="graphql"?e.body.content:null},get file(){return e.body?.type==="binary"?e.body.content:null}};return{get url(){return dz(e.url)},set url(l){e.url=typeof l=="string"?l:String(l)},get method(){return e.method},set method(l){e.method=l},headers:s,get body(){return o},set body(l){if(l==null)e.body=null;else if(typeof l=="string")e.body={type:"raw",content:l};else if(typeof l=="object")if(l.type||l.mode||l.content!==void 0){let c=l.mode?i(l.mode):l.type||"raw";e.body={type:c,format:l.format,content:l.content}}else e.body={type:"raw",content:l}},get params(){return e.params||{}},set params(l){e.params=l||{}},get query(){return e.query||{}},set query(l){e.query=l||{}},get auth(){return r.request?.auth||null},set auth(l){r.request&&(r.request.auth=l)},get certificate(){return r.request?.certificate||null},set certificate(l){r.request&&(r.request.certificate=l)},get description(){return r.request?.description||null},set description(l){r.request&&(r.request.description=l)},get name(){return r.request?.name||null},set name(l){r.request&&(r.request.name=l)},get id(){return r.request?.id||null},get disabled(){return r.request?.disabled||!1},set disabled(l){r.request&&(r.request.disabled=l)},get messages(){return r.request?.messages||[]},get methodPath(){return r.request?.methodPath||null},get metadata(){return r.request?.metadata||[]},getHeaders(l){let c={};for(let[d,p]of Object.entries(e.headers))typeof p=="string"&&(c[d]=p);return c},addQueryParams(l){if(typeof l=="string"){let c=new URLSearchParams(l);for(let[d,p]of c)e.query||(e.query={}),e.query[d]=p}else Array.isArray(l)&&(e.query||(e.query={}),l.forEach(c=>{c.key&&(e.query[c.key]=c.value||"")}))},removeQueryParams(l){e.query&&(typeof l=="string"?delete e.query[l]:Array.isArray(l)&&l.forEach(c=>{let d=typeof c=="string"?c:c.key;d&&delete e.query[d]}))},authorizeUsing(l,c){r.request&&(typeof l=="string"?(r.request.auth||(r.request.auth={}),r.request.auth.type=l,c&&(r.request.auth.parameters=c)):typeof l=="object"&&(r.request.auth=l))},clone(){return{url:e.url,method:e.method,headers:{...e.headers},body:e.body?{...e.body}:null,params:e.params?{...e.params}:{},query:e.query?{...e.query}:{},auth:r.request?.auth,certificate:r.request?.certificate,description:r.request?.description,name:r.request?.name,id:r.request?.id,disabled:r.request?.disabled,metadata:r.request?.metadata,messages:r.request?.messages,methodPath:r.request?.methodPath}},describe(l,c){r.request&&(r.request.description={content:l,type:c||"text/plain"})},setHeader(l,c){e.headers[l]=c},addHeader(l,c){typeof l=="object"&&l!==null?e.headers[l.key]=l.value:e.headers[l]=c},removeHeader(l){delete e.headers[l]},setBody(l,c,d){e.body={type:c||e.body?.type||"raw",format:d||e.body?.format,content:l}}}}injectLegacyGlobals(e,r){let n=this.vmContext;if(!n)return;let i=this.initialContext,s=e==="test"&&r?.executedRequest?r.executedRequest:this.modifiedRequest,o={};for(let[b,q]of Object.entries(s?.headers||{}))typeof q=="string"&&(o[b]=q);let l=s?.body,c=l==null?null:typeof l=="object"&&"content"in l?l.content:l,d=i.request;if(n.request={id:d?.id??"",name:d?.name??"",description:d?.description??"",url:typeof s?.url=="string"?s.url:String(s?.url??""),method:s?.method??"GET",headers:o,data:c},n.environment=this._liveEnvironmentScope?.toObject?.()??{...this._environmentVariables},n.globals=this._liveGlobalsScope?.toObject?.()??{...this._globals},n.data={...i.iterationData||{}},typeof n.iteration!="number"&&(n.iteration=0),e!=="test"||!r)return;let p=r.body;n.responseBody=p==null?"":typeof p=="string"?p:JSON.stringify(p);let m=r.statusText||"";n.responseCode={code:r.status,name:m,detail:m},n.responseHeaders={...r.headers||{}},n.responseTime=r.responseTime??0,n.responseCookies=(r.cookies||[]).map(b=>({...b}));let y=this;n.tests=new Proxy({},{set(b,q,x){return y.assertions.push({name:String(q),passed:!!x,message:x?void 0:`"${String(q)}" was false`}),!0}})}async executePreRequest(e){let r=Rm(e,this.deps.isolateScripts);if(!r||!r.trim())return{success:!0};try{this.consoleMessages.length=0,this.injectLegacyGlobals("prerequest");let n=this.ctx.variables.replaceIn(r),i=this.deps.scriptTimeoutMs??5e3,s=i0.runInContext(n,this.vmContext,{timeout:i});this.deps.isolateScripts&&s&&typeof s.then=="function"&&await s,(await this.timerRegistry.drain(i)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${i}ms; pending async work was cancelled.`]});let l=Su(this.consoleMessages),c=this.initialContext.request.body,d=!this.bodiesEqual(this.modifiedRequest.body,c);return{success:!0,modifiedRequest:{url:this.modifiedRequest.url!==this.initialContext.request.url?this.modifiedRequest.url:void 0,headers:Uf(this.modifiedRequest.headers,this.initialContext.request.headers)?this.modifiedRequest.headers:void 0,body:d?this.modifiedRequest.body:void 0,params:Uf(this.modifiedRequest.params,this.initialContext.request.params||{})?this.modifiedRequest.params:void 0,query:Uf(this.modifiedRequest.query,this.initialContext.request.query||{})?this.modifiedRequest.query:void 0},modifiedVariables:this.ctx.variables.toObject(),localVariables:this.ctx.variables.toLocalObject?.()??{},modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,consoleOutput:l.length>0?l:void 0,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}catch(n){let i=[...Su(this.consoleMessages),`[error] Script execution failed: ${n.message}`];return{success:!1,error:n.message||"Pre-request script execution failed",consoleOutput:i,modifiedVariables:this.ctx?.variables?.toObject(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}}async executePostResponse(e,r){let n=Rm(e,this.deps.isolateScripts);if(!n||!n.trim())return{testResults:[],consoleOutput:[]};try{this.consoleMessages.length=0,this.assertions.length=0,this.ctx.info.eventName="test",this.ctx.response=wm(r),this.ctx.request=this.createRequestObject(r.executedRequest,this.initialContext),this.injectLegacyGlobals("test",r);let i=this.ctx.variables.replaceIn(n),s=this.deps.scriptTimeoutMs??5e3,o=i0.runInContext(i,this.vmContext,{timeout:s});this.deps.isolateScripts&&o&&typeof o.then=="function"&&await o,this.ctx.test._pendingTests?.length>0&&(await Promise.all(this.ctx.test._pendingTests),this.ctx.test._pendingTests.length=0),(await this.timerRegistry.drain(s)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${s}ms; pending async work was cancelled.`]});let c=Su(this.consoleMessages);return{testResults:[...this.assertions],consoleOutput:c.length>0?c:void 0,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}catch(i){this.assertions.push({name:"Script Execution",passed:!1,message:i.message||"Script execution failed"});let s=[...Su(this.consoleMessages),`[error] Script execution failed: ${i.message}`];return{testResults:[...this.assertions],consoleOutput:s,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}}bodiesEqual(e,r){return e===r||!e&&!r?!0:!e||!r?!1:e.type===r.type&&e.format===r.format&&JSON.stringify(e.content)===JSON.stringify(r.content)}dispose(){this.timerRegistry.clearAll(),this.vmContext=null,this.ctx=null,this.assertions=[]}}});import*as vr from"crypto";import*as pz from"querystring";import*as cP from"vm";function fP(t,e){if(t)return t.split(",").map(r=>{let n=r.trim();if(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))return n.slice(1,-1);let i=Number(n);if(!isNaN(i)&&n!=="")return i;if(e&&n in e){let s=e[n],o=Number(s);return!isNaN(o)&&s!==""?o:s}return n})}function dP(t){if(typeof t=="string"&&t.charCodeAt(0)===30)try{return JSON.parse(t.slice(1))}catch{return t}return t}function hz(t,e){if(t==="@")return"";if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);let r=t.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(r){let n=fP(r[2],e),i=ys(r[1],n);return i!==null?i:void 0}if(e[t]!==void 0)return dP(e[t]);if(ba(t)){let n=va(t,e),i=Ui(t,n);if(i!==void 0)return i}}function uP(t,e,r,n){let i=Buffer.concat([Buffer.from(t,"utf8"),n||Buffer.alloc(0)]),s=[],o=Buffer.alloc(0);for(;Buffer.concat(s).length<e+r;)o=vr.createHash("md5").update(Buffer.concat([o,i])).digest(),s.push(o);let l=Buffer.concat(s);return{key:l.subarray(0,e),iv:l.subarray(e,e+r)}}function o0(t,e,r){let n=i=>t==="aes"?`aes-${i*8}-cbc`:t==="des"?"des-cbc":t==="des-ede3"?"des-ede3-cbc":t;return{encrypt(i,s,o){let l=i instanceof Ke?i.toBuffer():Buffer.from(String(i),"utf8");if(typeof s=="string"){let c=vr.randomBytes(8),{key:d,iv:p}=uP(s,e,r,c),m=vr.createCipheriv(n(e),d,p),y=Buffer.concat([m.update(l),m.final()]),b=Buffer.concat([Buffer.from("Salted__"),c,y]);return{ciphertext:new Ke(y),salt:new Ke(c),toString:q=>q?q.stringify(new Ke(b)):b.toString("base64")}}else{let c=s.toBuffer(),d=o?.iv&&o.iv instanceof Ke?o.iv.toBuffer():Buffer.alloc(r),p=vr.createCipheriv(n(c.length),c,d);o?.padding===!1&&p.setAutoPadding(!1);let m=Buffer.concat([p.update(l),p.final()]);return{ciphertext:new Ke(m),toString:y=>y?y.stringify(new Ke(m)):m.toString("base64")}}},decrypt(i,s,o){if(typeof s=="string"){let l=typeof i=="string"?Buffer.from(i,"base64"):i.ciphertext.toBuffer(),c,d;l.subarray(0,8).toString()==="Salted__"?(d=l.subarray(8,16),c=l.subarray(16)):(d=Buffer.alloc(0),c=l);let{key:p,iv:m}=uP(s,e,r,d),y=vr.createDecipheriv(n(e),p,m);return new Ke(Buffer.concat([y.update(c),y.final()]))}else{let l=s.toBuffer(),c=o?.iv&&o.iv instanceof Ke?o.iv.toBuffer():Buffer.alloc(r),d=typeof i=="string"?Buffer.from(i,"base64"):i.ciphertext?i.ciphertext.toBuffer():Buffer.from(i),p=vr.createDecipheriv(n(l.length),l,c);return o?.padding===!1&&p.setAutoPadding(!1),new Ke(Buffer.concat([p.update(d),p.final()]))}}}}function mz(){let t=r=>n=>{let i=n instanceof Ke?n.toBuffer():Buffer.from(String(n),"utf8");return new Ke(vr.createHash(r).update(i).digest())},e=r=>(n,i)=>{let s=n instanceof Ke?n.toBuffer():Buffer.from(String(n),"utf8"),o=i instanceof Ke?i.toBuffer():Buffer.from(String(i),"utf8");return new Ke(vr.createHmac(r,o).update(s).digest())};return{MD5:t("md5"),SHA1:t("sha1"),SHA224:t("sha224"),SHA256:t("sha256"),SHA384:t("sha384"),SHA512:t("sha512"),SHA3:t("sha3-256"),RIPEMD160:t("ripemd160"),HmacMD5:e("md5"),HmacSHA1:e("sha1"),HmacSHA256:e("sha256"),HmacSHA512:e("sha512"),AES:o0("aes",32,16),DES:o0("des",8,8),TripleDES:o0("des-ede3",24,8),PBKDF2(r,n,i){let s=r instanceof Ke?r.toBuffer():Buffer.from(String(r),"utf8"),o=n instanceof Ke?n.toBuffer():Buffer.from(String(n),"utf8"),l=(i?.keySize||4)*4,c=i?.iterations||1;return new Ke(vr.pbkdf2Sync(s,o,c,l,"sha1"))},enc:{Base64:{stringify:r=>(r instanceof Ke?r.toBuffer():Buffer.from(String(r))).toString("base64"),parse:r=>Ke.fromBase64(r)},Utf8:{stringify:r=>(r instanceof Ke?r.toBuffer():Buffer.from(String(r))).toString("utf8"),parse:r=>Ke.fromUtf8(r)},Hex:{stringify:r=>(r instanceof Ke?r.toBuffer():Buffer.from(String(r))).toString("hex"),parse:r=>Ke.fromHex(r)},Latin1:{stringify:r=>(r instanceof Ke?r.toBuffer():Buffer.from(String(r))).toString("latin1"),parse:r=>new Ke(Buffer.from(r,"latin1"))},Utf16:{stringify:r=>(r instanceof Ke?r.toBuffer():Buffer.from(String(r))).toString("utf16le"),parse:r=>new Ke(Buffer.from(r,"utf16le"))},Utf16BE:{stringify:r=>(r instanceof Ke?r.toBuffer():Buffer.from(String(r))).swap16().toString("utf16le"),parse:r=>new Ke(Buffer.from(r,"utf16le").swap16())}},lib:{WordArray:{create:r=>r?typeof r=="string"?new Ke(Buffer.from(r,"utf8")):Buffer.isBuffer(r)?new Ke(r):new Ke(Buffer.from(String(r))):new Ke(Buffer.alloc(0)),random:r=>new Ke(vr.randomBytes(r))}},pad:{Pkcs7:{_name:"pkcs7"},NoPadding:{_name:"nopadding"},ZeroPadding:{_name:"zeropadding"}},mode:{CBC:{_name:"cbc"},ECB:{_name:"ecb"}}}}var Ke,xs,Vf=le(()=>{"use strict";$h();sf();Fh();t0();s0();_m();Ke=class t{_buffer;constructor(e){this._buffer=typeof e=="string"?Buffer.from(e,"utf8"):e}toString(e){return e?e.stringify(this):this._buffer.toString("hex")}toBuffer(){return this._buffer}static fromHex(e){return new t(Buffer.from(e,"hex"))}static fromBase64(e){return new t(Buffer.from(e,"base64"))}static fromUtf8(e){return new t(Buffer.from(e,"utf8"))}};xs=class t{constructor(e,r=[],n,i="shared",s=5e3){this.httpService=e;this.secretRegistry=n;this.scopeMode=i;this.scriptTimeoutMs=s;this.moduleLoader=e0(r)}httpService;secretRegistry;scopeMode;scriptTimeoutMs;moduleLoader;createRequestSession(e){return new Bf({createVM:this.createVM.bind(this),createCommonContext:this.createCommonContext.bind(this),isolateScripts:this.scopeMode==="isolated",scriptTimeoutMs:this.scriptTimeoutMs},e)}createVM(e,r,n){let i=this.moduleLoader.getGlobalSetupExports(),s=this.moduleLoader.createRequireFunction();e.require=s,e.vault=this.createVault();let o={ctx:e,hf:e,pm:e,console:r,...i||{},global:i,setTimeout:n?.setTimeout??setTimeout,setInterval:n?.setInterval??setInterval,clearTimeout:n?.clearTimeout??clearTimeout,clearInterval:n?.clearInterval??clearInterval,URL,URLSearchParams,Buffer,atob:l=>Buffer.from(l,"base64").toString("binary"),btoa:l=>Buffer.from(l,"binary").toString("base64"),TextEncoder,TextDecoder,crypto:vr,_:s("lodash"),require:s,moment:bm(),querystring:pz,CryptoJS:mz(),tv4:(()=>{try{return s("tv4")}catch{return}})(),postman:{setNextRequest:l=>e.setNextRequest?.(l),setGlobalVariable:(l,c)=>e.globals?.set(l,c),getGlobalVariable:l=>e.globals?.get(l),clearGlobalVariable:l=>e.globals?.unset(l),setEnvironmentVariable:(l,c)=>e.environment?.set(l,c),getEnvironmentVariable:l=>e.environment?.get(l),clearEnvironmentVariable:l=>e.environment?.unset(l),getResponseHeader:l=>{let c=e.response?.headers?.get?.(l);return c===void 0?null:c},getResponseCookie:l=>{let c=e.response?.cookies;if(c&&typeof c[Symbol.iterator]=="function"){for(let d of c)if(d?.name&&d.name.toLowerCase()===l.toLowerCase())return{...d}}return null}},jsonStringify:(l,c,d)=>JSON.stringify(l,c,d),jsonParse:l=>JSON.parse(l),xml2Json:l=>{try{let c=this.moduleLoader.createRequireFunction()("xml2js"),d;return c.parseString(l,{explicitArray:!1},(p,m)=>{if(p)throw p;d=m}),d}catch{throw new Error("xml2Json() requires the xml2js module. Add it to your modules/package.json and run npm install.")}}};return cP.createContext(o)}createCommonContext(e,r){let n={...e.variables},i={...e.collectionVariables||{}},s={...e.globals||{}},o={...e.environmentVariables||{}},l=e.iterationData||{},c=this.createMergedVariableScope(n,o,i,s,l),d=this.createGlobalsScope(s,e.onGlobalsChange),p=this.createVariableScope(i),m=this.createEnvironmentScope(o,e.environmentName,e.onEnvironmentChange,!0),y={...m,set:(x,v)=>{let R=this.serializeValue(v);m.set(x,R),n[x]=R},unset(x){m.unset(x),delete n[x]},clear(){let x=Object.keys(o);m.clear();for(let v of x)delete n[v]}},b={...d,set:(x,v)=>{let R=this.serializeValue(v);d.set(x,R),n[x]=R},unset(x){d.unset(x),delete n[x]},clear(){let x=Object.keys(s);d.clear();for(let v of x)delete n[v]}};return b.replaceIn=c.replaceIn,p.replaceIn=c.replaceIn,y.replaceIn=c.replaceIn,{globals:b,collectionVariables:p,variables:c,environment:y,iterationData:{get:x=>l[x],has:x=>x in l,toObject:()=>({...l}),toJSON:()=>JSON.stringify(l)},sendRequest:this.createSendRequest(),expect:bu,info:e.info||{eventName:r,requestName:void 0,requestId:void 0}}}static JSON_TYPE_MARKER="";serializeValue(e){return typeof e=="string"?e:e===void 0?t.JSON_TYPE_MARKER+"undefined":t.JSON_TYPE_MARKER+JSON.stringify(e)}deserializeValue(e){if(e!==void 0){if(typeof e=="string"&&e.charCodeAt(0)===30){let r=e.slice(1);if(r==="undefined")return;try{return JSON.parse(r)}catch{}}return e}}createVariableScope(e){return{get:r=>r in e?this.deserializeValue(e[r]):null,set:(r,n)=>{e[r]=this.serializeValue(n)},has(r){return r in e},unset(r){delete e[r]},clear(){Object.keys(e).forEach(r=>delete e[r])},toObject(){return{...e}}}}createGlobalsScope(e,r){let n=(i,s,o)=>{r&&r(i,s,o)};return{get:i=>i in e?this.deserializeValue(e[i]):null,set:(i,s)=>{let o=this.serializeValue(s);e[i]=o,n("set",i,o)},has(i){return i in e},unset(i){delete e[i],n("unset",i)},clear(){Object.keys(e).forEach(i=>delete e[i]),n("clear")},toObject(){return{...e}}}}createMergedVariableScope(e,r,n,i,s={}){let o={get:l=>l in e?this.deserializeValue(e[l]):l in s?s[l]:l in r?this.deserializeValue(r[l]):l in n?this.deserializeValue(n[l]):l in i?this.deserializeValue(i[l]):null,set:(l,c)=>{e[l]=this.serializeValue(c)},has(l){return l in e||l in s||l in r||l in r||l in n||l in i},unset(l){delete e[l]},clear(){Object.keys(e).forEach(l=>delete e[l])},toObject(){return{...i,...n,...r,...s,...e}},toLocalObject(){return{...n,...r,...s,...e}},replaceIn(l){if(!l||typeof l!="string")return l;let c=o.toObject(),d=20,p=y=>y.replace(/\{\{([^}]+)\}\}/g,(b,q)=>{let x=q.trim(),v=x.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(v)try{let E=fP(v[2],c),k=ys(v[1],E);return k!==null?String(k):b}catch{return b}let R=af(x);if(R){let E=hz(R.input,c);if(E!==void 0){let k=lf(E,R.filters,c);return k!==void 0?String(k):b}return b}if(o.has(x)){let E=o.get(x);return E===void 0?"":String(E)}if(ba(x)){let E={};for(let[M,j]of Object.entries(c))E[M]=dP(j);let k=va(x,E),P=Ui(x,k);if(P!==void 0)return String(P)}return b}),m=l;for(let y=0;y<d;y++){let b=p(m);if(b===m)break;m=b}return m}};return o}createEnvironmentScope(e,r,n,i){let s=(o,l,c)=>{n&&(i?n(o,l,c):n(l||"",o==="set"?c:void 0))};return{name:r||"",get:o=>o in e?this.deserializeValue(e[o]):null,set:(o,l)=>{let c=this.serializeValue(l);e[o]=c,s("set",o,c)},has(o){return o in e},unset(o){delete e[o],s("unset",o)},clear(){Object.keys(e).forEach(o=>delete e[o]),s("clear")},toObject(){return{...e}}}}createVault(){let e=this.secretRegistry,r=()=>{throw new Error("pm.vault is read-only in HTTP Forge. Use environment variables or {{secret:provider/path}} tokens to manage secrets.")};return{async get(n){if(!e)throw new Error('pm.vault is not available \u2014 no secret providers are configured. Configure a provider under "secrets.providers" to use pm.vault.get().');let i=`secret:${n}`;return(await e.resolveSecretTokens(`{{${i}}}`))[i]},set:r,unset:r}}createSendRequest(){return this.httpService?(e,r)=>{let n=typeof e=="string"?{url:e,method:"GET"}:e,i=this.httpService.execute({url:n.url,method:n.method||"GET",headers:n.headers||{},body:n.body,...n});if(r){i.then(s=>r(null,s)).catch(s=>r(s,null));return}return i}:(e,r)=>{let n=new Error("sendRequest not available - HTTP service not configured");if(r){r(n,null);return}return Promise.reject(n)}}}});import*as hP from"fs";import*as yz from"http";import*as a0 from"https";import*as Cm from"path";import{URL as pP}from"url";import*as Em from"zlib";var _n,Na,Jf=le(()=>{"use strict";_n={timeout:3e4,followRedirects:!0,followOriginalMethod:!1,followAuthHeader:!1,maxRedirects:10,strictSSL:!0,decompress:!0,includeCookies:!1,tls:{},certificates:[]},Na=class{settings;version;basePath;constructor(e,r=process.cwd()){this.settings={..._n,...e},this.basePath=r;try{this.version=wt("../../package.json").version||"0.0.0"}catch{this.version="0.0.0"}this.settings.strictSSL===!1&&console.log("[NodeHttpClient] SSL verification disabled (strictSSL: false)")}async send(e){let r=this.mergeSettings(e.settings);return await this.executeInternal(e,r,0)}mergeSettings(e){return{timeout:e?.timeout??this.settings.timeout,followRedirects:e?.followRedirects??this.settings.followRedirects,followOriginalMethod:e?.followOriginalMethod??this.settings.followOriginalMethod,followAuthHeader:e?.followAuthHeader??this.settings.followAuthHeader,maxRedirects:e?.maxRedirects??this.settings.maxRedirects,strictSSL:e?.strictSSL??this.settings.strictSSL,decompress:e?.decompress??this.settings.decompress,includeCookies:e?.includeCookies??this.settings.includeCookies,tls:e?.tls??this.settings.tls??{},certificates:e?.certificates??this.settings.certificates??[]}}async executeInternal(e,r,n,i){let s=Date.now(),o=new pP(e.url),l=o.protocol==="https:",c=this.sanitizeHeaders(e.headers||{});Object.keys(c).some(m=>m.toLowerCase()==="user-agent")||(c["User-Agent"]=`HttpForge/${this.version}`);let p={hostname:o.hostname,port:o.port||(l?443:80),path:o.pathname+o.search,method:e.method,headers:{...c},timeout:r.timeout||void 0};if(r.decompress&&!c["accept-encoding"]&&!c["Accept-Encoding"]&&(p.headers["Accept-Encoding"]="gzip, deflate"),l){let m=this.resolveTlsSettings(o,r),y=p;y.rejectUnauthorized=r.strictSSL;let b={rejectUnauthorized:r.strictSSL},q=this.readOptionalFile(m.caPath,"CA certificate");q&&(b.ca=q);let x=this.readOptionalFile(m.certPath,"client certificate");x&&(b.cert=x);let v=this.readOptionalFile(m.keyPath,"client private key");v&&(b.key=v);let R=this.readOptionalFile(m.pfxPath,"client pfx");R&&(b.pfx=R),m.passphrase&&(b.passphrase=m.passphrase),m.servername&&(y.servername=m.servername),y.agent=new a0.Agent(b)}return new Promise((m,y)=>{if(i?.aborted){let x=new Error("Request cancelled");x.name="AbortError",y(x);return}let q=(l?a0:yz).request(p,async x=>{let v=x.statusCode||0;if(r.followRedirects&&[301,302,303,307,308].includes(v)){if(n>=r.maxRedirects){y(new Error(`Maximum redirects (${r.maxRedirects}) exceeded`));return}let E=x.headers.location;if(!E){y(new Error("Redirect response missing Location header"));return}let k=new pP(E,e.url).toString(),P=e.method;!r.followOriginalMethod&&[301,302,303].includes(v)&&(P="GET");let M={...e.headers};r.followAuthHeader||(delete M.authorization,delete M.Authorization);try{let j=await this.executeInternal({...e,url:k,method:P,headers:M,body:P==="GET"?void 0:e.body},r,n+1,i),I=Date.now();j.time=I-s,m(j)}catch(j){y(j)}return}let R=[];x.on("data",E=>R.push(E)),x.on("end",()=>{let E=Date.now(),k=Buffer.concat(R),P=x.headers["content-encoding"];if(r.decompress&&P)try{P==="gzip"?k=Em.gunzipSync(k):P==="deflate"&&(k=Em.inflateSync(k))}catch(_){console.warn("[NodeHttpClient] Decompression failed:",_)}let M=k.toString("utf-8"),j={};for(let[_,A]of Object.entries(x.headers))(typeof A=="string"||Array.isArray(A))&&(j[_]=A);let I=this.parseCookies(x.headers["set-cookie"],o.hostname);m({status:x.statusCode||0,statusText:x.statusMessage||"",headers:j,cookies:I,body:M,time:E-s,size:k.length})})});if(i&&i.addEventListener("abort",()=>{q.destroy();let x=new Error("Request cancelled");x.name="AbortError",y(x)}),q.on("error",x=>{y(x)}),q.on("timeout",()=>{q.destroy(),y(new Error("Request timeout"))}),e.body!==void 0&&e.body!==null){let x=typeof e.body=="string"?e.body:JSON.stringify(e.body);q.write(x)}q.end()})}resolveTlsSettings(e,r){let n=r.tls||{};if(!!(n.caPath||n.certPath||n.keyPath||n.pfxPath||n.servername||n.passphrase))return n;let s=this.findCertificateMapping(e,r.certificates||[]);return s?{caPath:s.caPath,certPath:s.certPath,keyPath:s.keyPath,pfxPath:s.pfxPath,passphrase:s.passphrase,servername:s.servername}:n}findCertificateMapping(e,r){if(!Array.isArray(r)||r.length===0)return;let n=e.hostname,i=e.port?Number(e.port):443,s=r.find(o=>this.mappingMatchesHost(o,n,i,!0));return s||r.find(o=>this.mappingMatchesHost(o,n,i,!1))}mappingMatchesHost(e,r,n,i){if(!e||e.enabled===!1)return!1;let s=String(e.host||"").trim().toLowerCase();if(!s||e.port!=null&&Number(e.port)!==n)return!1;let o=r.toLowerCase();if(i)return s!=="*"&&!s.startsWith("*.")&&o===s;if(s==="*")return!0;if(s.startsWith("*.")){let l=s.slice(2);return o===l||o.endsWith(`.${l}`)}return o===s}readOptionalFile(e,r){if(!e)return;let n=Cm.isAbsolute(e)?e:Cm.resolve(this.basePath,e);try{return hP.readFileSync(n)}catch(i){throw new Error(`[NodeHttpClient] Failed to read ${r} file at ${n}: ${i?.message||"Unknown error"}`)}}sanitizeHeaderValue(e){return e?String(e).replace(/[\u201C\u201D\u201E\u201F\u2033\u2036]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032\u2035]/g,"'").replace(/[\x00-\x08\x0A-\x1F\x7F]/g,""):""}sanitizeHeaders(e){let r={};for(let[n,i]of Object.entries(e))r[n]=this.sanitizeHeaderValue(String(i));return r}parseCookies(e,r){return e?e.map(n=>{let i=n.split(";").map(p=>p.trim()),[s,...o]=i,[l,c]=s.split("="),d={name:l.trim(),value:c?.trim()||"",domain:r};for(let p of o){let[m,y]=p.split("=");switch(m.toLowerCase().trim()){case"domain":d.domain=y?.trim();break;case"path":d.path=y?.trim();break;case"expires":d.expires=y?.trim();break;case"httponly":d.httpOnly=!0;break;case"secure":d.secure=!0;break}}return d}):[]}}});var l0,Ma,qm=le(()=>{"use strict";l0={json:"application/json",xml:"application/xml",html:"text/html",text:"text/plain",javascript:"application/javascript",css:"text/css","x-www-form-urlencoded":"application/x-www-form-urlencoded","form-data":"multipart/form-data",graphql:"application/json"},Ma=class{sanitizeHeaderValue(e){return e?String(e).replace(/[\u201C\u201D\u201E\u201F\u2033\u2036]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032\u2035]/g,"'").replace(/[\x00-\x08\x0A-\x1F\x7F]/g,""):""}sanitizeHeaders(e){let r={};for(let[n,i]of Object.entries(e))r[n]=this.sanitizeHeaderValue(String(i));return r}encodeBody(e){if(!e||e.type==="none")return null;let{type:r,content:n}=e;switch(r){case"x-www-form-urlencoded":return this.encodeUrlEncodedBody(n);case"form-data":return n;case"graphql":return this.encodeGraphQLBody(n);case"raw":return n;default:return n}}encodeUrlEncodedBody(e){if(Array.isArray(e)){let r=new URLSearchParams;for(let n of e)n.enabled!==!1&&n.key&&r.append(n.key,n.value||"");return r.toString()}return typeof e=="string"?e:String(e)}encodeGraphQLBody(e){if(typeof e=="string")try{e=JSON.parse(e)}catch{return e}if(typeof e=="object"&&e!==null&&e.query){let r=e.variables;if(typeof r=="string")try{r=r.trim()?JSON.parse(r):void 0}catch{r=void 0}return JSON.stringify({query:e.query,...r!=null?{variables:r}:{},...e.operationName?{operationName:e.operationName}:{}})}return JSON.stringify(e)}setContentTypeHeader(e,r,n){if(Object.keys(e).some(o=>o.toLowerCase()==="content-type"))return;if(n){e["Content-Type"]=n;return}if(!r||r.type==="none")return;let s;switch(r.type){case"x-www-form-urlencoded":s=l0["x-www-form-urlencoded"];break;case"raw":s=r.format?l0[r.format]:"text/plain",s||(s="text/plain");break;case"graphql":s=l0.graphql;break;case"binary":s="application/octet-stream";break}s&&(e["Content-Type"]=s)}}});var Da,Im=le(()=>{"use strict";Da=class{parse(e,r){return r.toLowerCase().endsWith(".json")?this.parseJson(e):this.parseCsv(e)}parseJson(e){try{let r=JSON.parse(e);return Array.isArray(r)?r:[r]}catch{throw new Error("Failed to parse JSON data file: Invalid JSON format")}}parseCsv(e){let r=e.split(/\r?\n/).filter(s=>s.trim());if(r.length<2)return[{}];let n=this.parseCsvLine(r[0]),i=[];for(let s=1;s<r.length;s++){let o=this.parseCsvLine(r[s]),l={};n.forEach((c,d)=>{l[c]=o[d]||""}),i.push(l)}return i}parseCsvLine(e){let r=[],n="",i=!1;for(let s=0;s<e.length;s++){let o=e[s],l=e[s+1];o==='"'?i&&l==='"'?(n+='"',s++):i=!i:o===","&&!i?(r.push(n.trim()),n=""):n+=o}return r.push(n.trim()),r}}});import*as Ru from"crypto";var vz,Yf,c0=le(()=>{"use strict";vz=3e4,Yf=class{constructor(e,r,n,i,s="henry-huang.http-forge/oauth2/callback"){this.secretStore=e;this.browserService=r;this.envConfigService=n;this.httpService=i;this.callbackPath=s}secretStore;browserService;envConfigService;httpService;callbackPath;tokenCache=new Map;pendingAuthCallback=null;pendingImplicitCallback=null;async getToken(e,r){if(e.accessToken)return{accessToken:this.resolve(e.accessToken,r),tokenType:e.tokenPrefix||"Bearer",raw:{}};let n=this.buildCacheKeyString(e),i=this.tokenCache.get(n);if(i&&!this.isExpired(i))return i;if(i?.refreshToken)try{return await this.refreshToken(e,i.refreshToken,r)}catch{this.tokenCache.delete(n)}if(!i){let o=await this.secretStore.get(`oauth2_refresh_${n}`);if(o)try{return await this.refreshToken(e,o,r)}catch{await this.secretStore.delete(`oauth2_refresh_${n}`)}}let s;switch(e.grantType){case"client_credentials":s=await this.fetchToken(e,r,"client_credentials");break;case"password":s=await this.fetchToken(e,r,"password");break;case"authorization_code":s=await this.authorizationCodeFlow(e,r);break;case"implicit":s=await this.implicitFlow(e,r);break;default:throw new Error(`Unknown OAuth2 grant type: ${e.grantType}`)}return this.tokenCache.set(n,s),s.refreshToken&&await this.storeRefreshToken(n,s.refreshToken),s}async refreshToken(e,r,n){let i=this.resolve(e.tokenUrl||"",n);if(!i)throw new Error("OAuth2 tokenUrl is required for token refresh");let s=this.resolve(e.clientId||"",n),o=this.resolve(e.clientSecret||"",n),l=new URLSearchParams;l.append("grant_type","refresh_token"),l.append("refresh_token",r);let c={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,c,l,s,o,n);let d=await this.httpService.execute({method:"POST",url:i,headers:c,body:l.toString()}),p=this.parseTokenResponse(d.body,e);p.refreshToken||(p.refreshToken=r);let m=this.buildCacheKeyString(e);return this.tokenCache.set(m,p),p.refreshToken&&await this.storeRefreshToken(m,p.refreshToken),p}async authorizationCodeFlow(e,r){let n=this.resolve(e.authUrl||"",r),i=this.resolve(e.tokenUrl||"",r),s=this.resolve(e.clientId||"",r),o=this.resolve(e.clientSecret||"",r),l=e.scope?this.resolve(e.scope,r):void 0;if(!n)throw new Error("OAuth2 authUrl is required for authorization code flow");if(!i)throw new Error("OAuth2 tokenUrl is required for authorization code flow");if(!s)throw new Error("OAuth2 clientId is required for authorization code flow");let c=e.usePkce!==!1,d,p,m;if(c){d=this.generateCodeVerifier();let j=e.pkceMethod||"S256";p=j==="S256"?this.generateCodeChallengeS256(d):d,m=j}let y=e.state||Ru.randomBytes(16).toString("hex"),b=await this.getCallbackUri(),q=new URL(n);if(q.searchParams.set("response_type","code"),q.searchParams.set("client_id",s),q.searchParams.set("redirect_uri",b),l&&q.searchParams.set("scope",l),q.searchParams.set("state",y),p&&(q.searchParams.set("code_challenge",p),q.searchParams.set("code_challenge_method",m)),e.audience&&q.searchParams.set("audience",this.resolve(e.audience,r)),e.resource&&q.searchParams.set("resource",this.resolve(e.resource,r)),e.extraParams)for(let[j,I]of Object.entries(e.extraParams))q.searchParams.set(j,this.resolve(I,r));this.pendingAuthCallback&&(this.pendingAuthCallback.reject(new Error("OAuth2 authorization superseded by a new request")),this.pendingAuthCallback=null);let x=new Promise((j,I)=>{this.pendingAuthCallback={resolve:j,reject:I,state:y}});await this.browserService.openExternal(q.toString());let v;try{v=await Promise.race([x,new Promise((j,I)=>setTimeout(()=>{this.pendingAuthCallback=null,I(new Error("OAuth2 authorization timed out after 2 minutes"))},12e4))])}finally{this.pendingAuthCallback=null}if(v.state&&v.state!==y)throw new Error("OAuth2 state mismatch \u2014 potential CSRF attack");let R=new URLSearchParams;R.append("grant_type","authorization_code"),R.append("code",v.code),R.append("redirect_uri",b),d&&R.append("code_verifier",d);let E={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,E,R,s,o,r);let k=await this.httpService.execute({method:"POST",url:i,headers:E,body:R.toString()}),P=this.parseTokenResponse(k.body,e),M=this.buildCacheKeyString(e);return this.tokenCache.set(M,P),P.refreshToken&&await this.storeRefreshToken(M,P.refreshToken),P}async implicitFlow(e,r){let n=this.resolve(e.authUrl||"",r),i=this.resolve(e.clientId||"",r),s=e.scope?this.resolve(e.scope,r):void 0;if(!n)throw new Error("OAuth2 authUrl is required for implicit flow");if(!i)throw new Error("OAuth2 clientId is required for implicit flow");let o=e.state||Ru.randomBytes(16).toString("hex"),l=await this.getCallbackUri(),c=new URL(n);if(c.searchParams.set("response_type","token"),c.searchParams.set("client_id",i),c.searchParams.set("redirect_uri",l),s&&c.searchParams.set("scope",s),c.searchParams.set("state",o),e.audience&&c.searchParams.set("audience",this.resolve(e.audience,r)),e.resource&&c.searchParams.set("resource",this.resolve(e.resource,r)),e.extraParams)for(let[b,q]of Object.entries(e.extraParams))c.searchParams.set(b,this.resolve(q,r));this.pendingImplicitCallback&&(this.pendingImplicitCallback.reject(new Error("OAuth2 implicit flow superseded by a new request")),this.pendingImplicitCallback=null);let d=new Promise((b,q)=>{this.pendingImplicitCallback={resolve:b,reject:q,state:o}});await this.browserService.openExternal(c.toString());let p;try{p=await Promise.race([d,new Promise((b,q)=>setTimeout(()=>{this.pendingImplicitCallback=null,q(new Error("OAuth2 implicit flow timed out after 2 minutes"))},12e4))])}finally{this.pendingImplicitCallback=null}if(p.state&&p.state!==o)throw new Error("OAuth2 state mismatch \u2014 potential CSRF attack");let m={accessToken:p.accessToken,tokenType:p.tokenType||e.tokenPrefix||"Bearer",expiresAt:p.expiresIn?Date.now()+p.expiresIn*1e3:void 0,raw:{access_token:p.accessToken,token_type:p.tokenType,expires_in:p.expiresIn}},y=this.buildCacheKeyString(e);return this.tokenCache.set(y,m),m}handleAuthorizationCallback(e,r,n){if(n){let i=new Error(`OAuth2 authorization error: ${n}`);this.pendingAuthCallback?.reject(i),this.pendingImplicitCallback?.reject(i),this.pendingAuthCallback=null,this.pendingImplicitCallback=null;return}if(e&&this.pendingAuthCallback){this.pendingAuthCallback.resolve({code:e,state:r}),this.pendingAuthCallback=null;return}!e&&!this.pendingAuthCallback&&this.pendingImplicitCallback&&(this.pendingImplicitCallback.reject(new Error("OAuth2 implicit flow did not receive access_token")),this.pendingImplicitCallback=null)}handleImplicitCallback(e,r,n,i){this.pendingImplicitCallback&&(this.pendingImplicitCallback.resolve({accessToken:e,tokenType:r,expiresIn:n,state:i}),this.pendingImplicitCallback=null)}clearToken(e){let r=`${e.tokenUrl}|${e.clientId}|${e.scope||""}|${e.grantType}`;this.tokenCache.delete(r),this.secretStore.delete(`oauth2_refresh_${r}`)}clearAllTokens(){for(let e of this.tokenCache.keys())this.secretStore.delete(`oauth2_refresh_${e}`);this.tokenCache.clear()}async fetchToken(e,r,n){let i=this.resolve(e.tokenUrl||"",r);if(!i)throw new Error("OAuth2 tokenUrl is required");let s=this.resolve(e.clientId||"",r),o=this.resolve(e.clientSecret||"",r),l=e.scope?this.resolve(e.scope,r):void 0,c=new URLSearchParams;if(c.append("grant_type",n),l&&c.append("scope",l),n==="password"){let m=this.resolve(e.username||"",r),y=this.resolve(e.password||"",r);if(!m)throw new Error("OAuth2 password grant requires username");c.append("username",m),c.append("password",y)}if(e.audience&&c.append("audience",this.resolve(e.audience,r)),e.resource&&c.append("resource",this.resolve(e.resource,r)),e.extraParams)for(let[m,y]of Object.entries(e.extraParams))c.append(m,this.resolve(y,r));let d={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,d,c,s,o,r);let p=await this.httpService.execute({method:"POST",url:i,headers:d,body:c.toString()});return this.parseTokenResponse(p.body,e)}applyClientAuth(e,r,n,i,s,o){if(e.clientAuthentication==="header"){let l=Buffer.from(`${i}:${s}`).toString("base64");r.Authorization=`Basic ${l}`}else i&&n.set("client_id",i),s&&n.set("client_secret",s)}parseTokenResponse(e,r){let n=e;if(typeof n=="string")try{n=JSON.parse(n)}catch{throw new Error("OAuth2 token response is not valid JSON")}if(!n||typeof n!="object")throw new Error("OAuth2 token response is not a valid JSON object");let i=n,s=r.tokenField||"access_token",o=i[s];if(!o)throw new Error(`OAuth2 token fetch failed: '${s}' not present in response`);let l=typeof i.expires_in=="number"?i.expires_in:void 0;return{accessToken:o,tokenType:i.token_type||r.tokenPrefix||"Bearer",expiresAt:l?Date.now()+l*1e3:void 0,refreshToken:i.refresh_token,scope:i.scope,raw:i}}isExpired(e){return e.expiresAt?Date.now()>=e.expiresAt-vz:!1}buildCacheKeyString(e){return`${e.tokenUrl||""}|${e.clientId||""}|${e.scope||""}|${e.grantType}`}async getCallbackUri(){let e=`${this.browserService.uriScheme}://${this.callbackPath}`;return this.browserService.asExternalUri(e)}resolve(e,r){return this.envConfigService.resolveVariables(e,r)}generateCodeVerifier(){return Ru.randomBytes(32).toString("base64url")}generateCodeChallengeS256(e){return Ru.createHash("sha256").update(e).digest("base64url")}async storeRefreshToken(e,r){try{await this.secretStore.store(`oauth2_refresh_${e}`,r)}catch{}}}});import*as ja from"fs";import*as go from"path";function xu(t,e={}){let r=[];Object.entries(e).forEach(([n,i])=>{r.push(`${n}=${i}`)}),r.length&&ja.writeFileSync(t,r.join(`
53
53
  `),"utf-8")}function Kf(t,e,r){r&&(r.preRequest&&r.preRequest.trim()&&ja.writeFileSync(go.join(t,`${e}.pre.js`),r.preRequest,"utf-8"),r.postResponse&&r.postResponse.trim()&&ja.writeFileSync(go.join(t,`${e}.post.js`),r.postResponse,"utf-8"))}function bz(t,e){let n=e&&e.trim()?e.trim():"collections-rest-client";return go.isAbsolute(n)?n:go.join(t,n)}async function Sz(t,e,r,n,i){await t.exportCollectionAsRestClientFolder(r,n),e.exportEnvironmentsToFolder(n,i)}function Om(t,e,r){t.forEach(n=>{if(n.type==="folder"){let i=go.join(e,Wt(n.name));ja.mkdirSync(i,{recursive:!0}),Kf(i,Wt(n.name),n.scripts),Om(n.items||[],i,r)}else if(n.type==="request"){let i=n,s=Wt(i.name)+".http",o=go.join(e,s),l=wz(i,r);ja.writeFileSync(o,l,"utf-8"),Kf(e,Wt(i.name),i.scripts)}})}function wz(t,e){let r=[];r.push(`### ${e.name} / ${t.name}`),r.push(`# collection env: ${Wt(e.name)}.env`),r.push(`# request scripts: ${Wt(t.name)}.pre.js and .post.js`);let n=_z(t);return r.push(`${t.method} ${n}`),(t.headers||[]).filter(i=>i.enabled!==!1).forEach(i=>{r.push(`${i.key}: ${i.value}`)}),t.body&&t.body.content&&r.push("",t.body.content),r.join(`
54
54
  `)}function _z(t){let e=t.url;if(t.query&&t.query.length){let r=t.query.filter(n=>n.enabled!==!1).map(n=>`${encodeURIComponent(n.key)}=${encodeURIComponent(n.value)}`).join("&");r&&(e+=(e.includes("?")?"&":"?")+r)}return e}var Pm=le(()=>{"use strict";jn()});import*as Ir from"fs";import*as f0 from"path";var Cu,d0=le(()=>{"use strict";jn();Cu=class{collectionsDir;cache=new Map;constructor(e){this.collectionsDir=e,this.ensureDirectory()}ensureDirectory(){Ir.existsSync(this.collectionsDir)||Ir.mkdirSync(this.collectionsDir,{recursive:!0})}loadAll(){if(this.cache.clear(),!Ir.existsSync(this.collectionsDir))return[];let e=Ir.readdirSync(this.collectionsDir),r=[];for(let n of e)if(n.endsWith(".json"))try{let i=f0.join(this.collectionsDir,n),s=Ir.readFileSync(i,"utf-8"),o=JSON.parse(s);o.id&&o.name&&(this.cache.set(o.id,o),r.push(o))}catch(i){console.error(`[JsonCollectionLoader] Failed to load ${n}:`,i)}return r}load(e){if(this.cache.has(e))return this.cache.get(e);let r=this.getCollectionPath(e);if(Ir.existsSync(r))try{let n=Ir.readFileSync(r,"utf-8"),i=JSON.parse(n);return this.cache.set(e,i),i}catch(n){console.error(`[JsonCollectionLoader] Failed to load collection ${e}:`,n);return}}async save(e){if(this.ensureDirectory(),!e.name)throw new Error("Collection name is required");e.id||(e.id=Pt(e.name));let r=this.getCollectionPath(e.id),n=JSON.stringify(e,null,2);await Ir.promises.writeFile(r,n,"utf-8"),this.cache.set(e.id,e)}async delete(e){let r=this.getCollectionPath(e);if(!Ir.existsSync(r))return!1;try{return await Ir.promises.unlink(r),this.cache.delete(e),!0}catch(n){return console.error(`[JsonCollectionLoader] Failed to delete collection ${e}:`,n),!1}}exists(e){return Ir.existsSync(this.getCollectionPath(e))}getCollectionPath(e){return f0.join(this.collectionsDir,`${e}.json`)}getItemPath(e,r){}async create(e,r){let n={id:r||Pt(e),name:e,items:[]};return await this.save(n),n}async saveScripts(e,r,n){let i=this.load(e);if(!i)throw new Error(`Collection ${e} not found`);let s=this.findItemById(i.items,r);s&&(s.scripts=n,await this.save(i))}loadScripts(e,r){let n=this.load(e);return n?this.findItemById(n.items,r)?.scripts:void 0}async updateCollectionMetadata(e,r){let n=this.load(e);if(!n)throw new Error(`Collection ${e} not found`);r.name!==void 0&&(n.name=r.name),r.description!==void 0&&(n.description=r.description),r.version!==void 0&&(n.version=r.version),r.variables!==void 0&&(n.variables=r.variables),r.auth!==void 0&&(n.auth=r.auth),await this.save(n)}async saveItem(e,r,n){let i=this.load(e);if(!i)throw new Error(`Collection ${e} not found`);let s=this.findItemById(i.items,r.id);if(s)Object.assign(s,r);else if(n){let o=this.findItemById(i.items,n);if(o&&o.type==="folder")o.items=o.items||[],o.items.push(r);else throw new Error(`Parent folder ${n} not found`)}else i.items.push(r);await this.save(i)}async deleteItem(e,r){let n=this.load(e);if(!n)return!1;let i=this.deleteItemById(n.items,r);return i&&await this.save(n),i}async updateItem(e,r,n){let i=this.load(e);if(!i)return!1;let s=this.findItemById(i.items,r);if(!s)return!1;let{id:o,type:l,...c}=n;return Object.assign(s,c),await this.save(i),!0}async moveItem(e,r,n){let i=this.load(e);if(!i)return!1;let s=this.findItemById(i.items,r);if(!s)return!1;let o={...s};if(!this.deleteItemById(i.items,r))return!1;if(n){let l=this.findItemById(i.items,n);if(l&&l.type==="folder")l.items=l.items||[],l.items.push(o);else return i.items.push(o),!1}else i.items.push(o);return await this.save(i),!0}async reorderItems(e,r,n){let i=this.load(e);if(!i)return!1;try{let s;if(r){let c=this.findItemById(i.items,r);if(!c||!c.items)return!1;s=c.items}else s=i.items;let o=new Map(s.map(c=>[c.id,c])),l=[];for(let c of n){let d=o.get(c);d&&(l.push(d),o.delete(c))}for(let c of o.values())l.push(c);if(r){let c=this.findItemById(i.items,r);c&&(c.items=l)}else i.items=l;return await this.save(i),!0}catch(s){return console.error("[JsonCollectionLoader] Failed to reorder items:",s),!1}}findItemById(e,r){for(let n of e){if(n.id===r)return n;if(n.type==="folder"&&n.items){let i=this.findItemById(n.items,r);if(i)return i}}}deleteItemById(e,r){for(let n=0;n<e.length;n++){if(e[n].id===r)return e.splice(n,1),!0;let i=e[n];if(i.type==="folder"&&i.items&&this.deleteItemById(i.items,r))return!0}return!1}}});var Qf,p0=le(()=>{"use strict";Ph();d0();Qf=class{static create(e){let r=e.getStorageConfig(),n=e.getCollectionsPath();return r.format==="folder"?new so(n):new Cu(n)}static createForFormat(e,r){return e==="folder"?new so(r):new Cu(r)}}});import*as Dt from"fs";import*as hi from"path";function mP(t){if(typeof t!="string")return"text";let e=t.trim();try{let r=JSON.parse(e);if(typeof r=="object"&&r!==null)return"json"}catch{}return/^<\?xml/.test(e)||/^<([a-zA-Z_][\w\-\.]*)[\s>]/.test(e)?/^<\!DOCTYPE html>/i.test(e)||/^<html[\s>]/i.test(e)?"html":"xml":/^<\!DOCTYPE html>/i.test(e)||/^<html[\s>]/i.test(e)?"html":/^(function\s*\(|\(\)\s*=>|const |let |var |export |import )/.test(e)?"javascript":"text"}function Rz(t){return{info:{name:t.name,_postman_id:t.id,schema:"https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},item:t.items.map(e=>gP(e)),event:h0(t.scripts),variable:t.variables?Object.entries(t.variables).map(([e,r])=>({key:e,value:r})):[]}}function gP(t){if(t.type==="folder")return{name:t.name,item:t.items?t.items.map(gP):[],event:h0(t.scripts)};if(t.type==="request"){let e=t;return{name:e.name,request:{method:e.method,header:(e.headers||[]).map(xz),url:Cz(e),body:Ez(e),auth:qz(e.auth),description:e.description},event:h0(e.scripts),protocolProfileBehavior:Iz(e.settings)}}}function xz(t){return{key:t.key,value:t.value,disabled:t.enabled===!1,...t.description!==void 0?{description:t.description}:{},...t.type!==void 0?{type:t.type}:{},...t.required!==void 0?{required:t.required}:{},...t.format!==void 0?{format:t.format}:{},...t.enum!==void 0?{enum:t.enum}:{},...t.deprecated!==void 0?{deprecated:t.deprecated}:{},...t.pattern!==void 0?{pattern:t.pattern}:{},...t.minLength!==void 0?{minLength:t.minLength}:{},...t.maxLength!==void 0?{maxLength:t.maxLength}:{},...t.minimum!==void 0?{minimum:t.minimum}:{},...t.maximum!==void 0?{maximum:t.maximum}:{},...t.exclusiveMinimum!==void 0?{exclusiveMinimum:t.exclusiveMinimum}:{},...t.exclusiveMaximum!==void 0?{exclusiveMaximum:t.exclusiveMaximum}:{},...t.multipleOf!==void 0?{multipleOf:t.multipleOf}:{},...t.minItems!==void 0?{minItems:t.minItems}:{},...t.maxItems!==void 0?{maxItems:t.maxItems}:{},...t.uniqueItems!==void 0?{uniqueItems:t.uniqueItems}:{},...t.nullable!==void 0?{nullable:t.nullable}:{},...t.oneOf!==void 0?{oneOf:t.oneOf}:{}}}function Cz(t){let e=t.url,r=t.url.replace(/^[a-zA-Z]+:\/\//,""),n=[],i=r.match(/^([^\/\?]+)/);if(i){let d=i[1];/^{{.*}}$/.test(d)?n=[d]:n=d.split(".")}let s=[],o=r.match(/^[^\/\?]+(\/[^\?]*)?/);if(o&&o[1]!==void 0){let d=o[1].replace(/^\//,"");d.endsWith("/")?(s=d.slice(0,-1).split("/"),s.push("")):s=d.length>0?d.split("/"):[]}let l;if(Array.isArray(t.query)&&t.query.length>0)l=t.query.map(d=>{let p={key:d.key,value:d.value};return d.enabled===!1&&(p.disabled=!0),d.description!==void 0&&(p.description=d.description),d.type!==void 0&&(p.type=d.type),d.required!==void 0&&(p.required=d.required),d.format!==void 0&&(p.format=d.format),d.enum!==void 0&&(p.enum=d.enum),d.deprecated!==void 0&&(p.deprecated=d.deprecated),d.pattern!==void 0&&(p.pattern=d.pattern),d.minLength!==void 0&&(p.minLength=d.minLength),d.maxLength!==void 0&&(p.maxLength=d.maxLength),d.minimum!==void 0&&(p.minimum=d.minimum),d.maximum!==void 0&&(p.maximum=d.maximum),d.exclusiveMinimum!==void 0&&(p.exclusiveMinimum=d.exclusiveMinimum),d.exclusiveMaximum!==void 0&&(p.exclusiveMaximum=d.exclusiveMaximum),d.multipleOf!==void 0&&(p.multipleOf=d.multipleOf),d.minItems!==void 0&&(p.minItems=d.minItems),d.maxItems!==void 0&&(p.maxItems=d.maxItems),d.uniqueItems!==void 0&&(p.uniqueItems=d.uniqueItems),d.nullable!==void 0&&(p.nullable=d.nullable),d.oneOf!==void 0&&(p.oneOf=d.oneOf),p});else{let d=r.indexOf("?");d!==-1&&(l=r.substring(d+1).split("&").map(m=>{let[y,...b]=m.split("=");return{key:y,value:b.join("=")}}))}let c;return t.params&&typeof t.params=="object"&&(c=Object.entries(t.params).map(([d,p])=>({key:d,value:String(p)}))),{raw:e,host:n.length>0?n:void 0,path:s.length>0?s:void 0,query:l&&l.length>0?l:void 0,variable:c&&c.length>0?c:void 0}}function Ez(t){if(!t.body)return;let e=t.body;if(typeof e=="string"){let s=mP(e);return{mode:"raw",raw:e,options:{raw:{language:s}}}}if(e.type==="raw"){let s=e.format||mP(e.content);return{mode:"raw",raw:e.content,options:{raw:{language:s}}}}let r=e.type==="form-data"&&Array.isArray(e.content)?e.content:e.type==="formdata"&&Array.isArray(e.fields)?e.fields:null;if(r)return{mode:"formdata",formdata:r.map(s=>({key:s.key,value:s.value,type:s.type||"text",disabled:s.enabled===!1}))};let n=e.type==="x-www-form-urlencoded"&&Array.isArray(e.content)?e.content:e.type==="urlencoded"&&Array.isArray(e.fields)?e.fields:null;if(n)return{mode:"urlencoded",urlencoded:n.map(s=>({key:s.key,value:s.value,disabled:s.enabled===!1}))};if(e.type==="file"&&e.fileName)return{mode:"file",file:{src:e.fileName}};if(e.type==="binary")return{mode:"binary",file:{}};let i=e.type==="graphql"?e.content??(e.query?e:null):null;if(i){let s=i.query??"",o=i.variables;return{mode:"graphql",graphql:{query:s,variables:o?typeof o=="string"?o:JSON.stringify(o):void 0}}}if(e.content)return{mode:"raw",raw:e.content}}function qz(t){if(!(!t||!t.type||t.type==="none")){if(t.type==="bearer")return{type:"bearer",bearer:[{key:"token",value:t.bearerToken,type:"string"}]};if(t.type==="basic"&&t.basicAuth)return{type:"basic",basic:[{key:"username",value:t.basicAuth.username,type:"string"},{key:"password",value:t.basicAuth.password,type:"string"}]}}}function Iz(t){if(!t)return;let e={};return t.followRedirects===!1&&(e.followRedirects=!1),t.followOriginalMethod===!0&&(e.followOriginalHttpMethod=!0),t.followAuthHeader===!1&&(e.followAuthorizationHeader=!1),t.maxRedirects!==void 0&&(e.maxRedirects=t.maxRedirects),t.strictSSL===!1&&(e.disableUrlEncoding=!1),t.timeout!==void 0&&(e.requestTimeout=t.timeout),Object.keys(e).length>0?e:void 0}function h0(t){if(!t)return[];let e=[];return t.preRequest&&e.push({listen:"prerequest",script:{type:"text/javascript",exec:[t.preRequest]}}),t.postResponse&&e.push({listen:"test",script:{type:"text/javascript",exec:[t.postResponse]}}),e}var Zf,m0=le(()=>{"use strict";jn();Pm();p0();Zf=class{constructor(e,r,n){this.workspaceRoot=e;this.configService=r;this.fileWatcherFactory=n;this.collectionsDir=r.getCollectionsPath(),this.loader=Qf.create(r),this.ensureCollectionsDir(),this.loadCollections(),this.setupFileWatcher()}workspaceRoot;configService;fileWatcherFactory;collectionsDir;collections=new Map;fileWatcher;loader;debounceTimer=null;selfWritePending=!1;localCollectionValues=new Map;onCollectionsChanged;ensureCollectionsDir(){Dt.existsSync(this.collectionsDir)||Dt.mkdirSync(this.collectionsDir,{recursive:!0})}loadCollections(){this.collections.clear();let e=this.loader.loadAll();for(let r of e)this.collections.set(r.id,r)}setupFileWatcher(){if(!this.fileWatcherFactory)return;this.fileWatcher=this.fileWatcherFactory.createFileWatcher(this.collectionsDir,"**/*");let e=()=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null;let r=this.selfWritePending;this.selfWritePending=!1,r||this.loadCollections(),this.onCollectionsChanged?.()},300)};this.fileWatcher.onDidChange(e),this.fileWatcher.onDidCreate(e),this.fileWatcher.onDidDelete(e)}getAllCollections(){return Array.from(this.collections.values())}getCollection(e){return this.collections.get(e)}getCollectionById(e){for(let r of this.collections.values())if(r.id===e)return r}getCollectionByName(e){let r=e.toLowerCase();for(let n of this.collections.values())if(n.name.toLowerCase()===r)return n}async saveCollection(e){if(this.ensureCollectionsDir(),!e.name)throw new Error("Collection name is required");e.id||(e.id=Pt(e.name)),this.selfWritePending=!0,await this.loader.save(e),this.collections.set(e.id,e)}getCollectionVariables(e){let r=this.collections.get(e);return r?.variables?{...r.variables}:{}}getCollectionVariableLocals(e){return{...this.localCollectionValues.get(e)||{}}}setCollectionVariable(e,r,n){this.localCollectionValues.has(e)||this.localCollectionValues.set(e,{}),this.localCollectionValues.get(e)[r]=String(n)}deleteCollectionVariable(e,r){let n=this.localCollectionValues.get(e);n&&delete n[r]}clearCollectionVariables(e){this.localCollectionValues.set(e,{})}async deleteCollection(e){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let n=await this.loader.delete(e);return n&&this.collections.delete(e),n}findRequest(e,r){let n=this.collections.get(e);if(n)return this.findItemRecursive(n.items,r)}findRequestByPath(e,r){let n=this.collections.get(e);if(!n)return;let i=r.split("/").filter(s=>s.trim());return this.findItemByPath(n.items,i)}async updateRequest(e,r,n){let i=this.collections.get(e);if(!i)return!1;this.selfWritePending=!0;let s=await this.loader.updateItem(e,r,n);if(s){let o=this.findItemRecursive(i.items,r);if(o){let{id:l,type:c,...d}=n;Object.assign(o,d)}}return s}async addRequest(e,r,n){if(!this.collections.get(e))return!1;r.id||(r.id=Pt(r.name)),this.selfWritePending=!0;try{return await this.loader.saveItem(e,r,n),!0}catch(s){return console.error("[CollectionService] Failed to add request:",s),!1}}async deleteRequest(e,r){let n=this.collections.get(e);if(!n)return!1;this.selfWritePending=!0;let i=await this.loader.deleteItem(e,r);return i&&this.deleteItemRecursive(n.items,r),i}getAllRequests(e){let r=this.collections.get(e);if(!r)return[];let n=[];return this.collectRequestsRecursive(r.items,n),n}findItemRecursive(e,r){for(let n of e){if(n.id===r)return n;if(n.type==="folder"&&n.items){let i=this.findItemRecursive(n.items,r);if(i)return i}}}findItemByPath(e,r){if(r.length===0)return;let[n,...i]=r,s=e.find(o=>o.name===n);if(s){if(i.length===0)return s;if(s.type==="folder"&&s.items)return this.findItemByPath(s.items,i)}}updateItemRecursive(e,r,n){for(let i=0;i<e.length;i++){let s=e[i];if(s.id===r)return e[i]={...s,...n},!0;if(s.type==="folder"&&s.items&&this.updateItemRecursive(s.items,r,n))return!0}return!1}deleteItemRecursive(e,r){for(let n=0;n<e.length;n++){let i=e[n];if(i.id===r)return e.splice(n,1),!0;if(i.type==="folder"&&i.items&&this.deleteItemRecursive(i.items,r))return!0}return!1}collectRequestsRecursive(e,r){for(let n of e)n.type==="request"?r.push(n):n.type==="folder"&&n.items&&this.collectRequestsRecursive(n.items,r)}async createCollection(e){let r={id:Pt(e),name:e,items:[]};return await this.saveCollection(r),r}async renameCollection(e,r){let n=this.collections.get(e);return n?(n.name=r,await this.saveCollection(n),!0):!1}async duplicateCollection(e,r){if(!this.collections.get(e))throw new Error(`Collection not found: ${e}`);this.selfWritePending=!0;let i=Pt(r),s=this.loader.getCollectionPath(e),o=hi.join(this.collectionsDir,i);if(!Dt.existsSync(s))throw new Error(`Collection directory not found: ${s}`);this.copyDirRecursive(s,o);let l=hi.join(o,"collection.json");if(Dt.existsSync(l)){let d=JSON.parse(Dt.readFileSync(l,"utf-8"));d.id=i,d.name=r,Dt.writeFileSync(l,JSON.stringify(d,null,2))}else Dt.writeFileSync(l,JSON.stringify({id:i,name:r},null,2));this.loadCollections();let c=this.collections.get(i);if(!c)throw new Error("Failed to load duplicated collection");return c}async createFolder(e){if(!this.collections.get(e.collectionId))throw new Error("Collection not found");this.selfWritePending=!0;let n={id:Pt(e.name),type:"folder",name:e.name,items:[]};await this.loader.saveItem(e.collectionId,n,e.parentId);let i=this.loader.load(e.collectionId);return i&&this.collections.set(e.collectionId,i),n}async deleteFolder(e,r){let n=this.collections.get(e);if(!n)return!1;this.selfWritePending=!0;let i=await this.loader.deleteItem(e,r);return i&&this.deleteItemById(n.items,r),i}async renameFolder(e,r,n){let i=this.collections.get(e);if(!i)return!1;this.selfWritePending=!0;let s=await this.loader.updateItem(e,r,{name:n});if(s){let o=this.findItemById(i.items,r);o&&(o.name=n)}return s}async duplicateFolder(e,r,n){if(!this.collections.get(e))throw new Error("Collection not found");let s=this.loader.getItemPath(e,r);if(!s||!Dt.existsSync(s))throw new Error(`Folder not found on disk: ${r}`);let o=hi.dirname(s),l=Pt(n),c=hi.join(o,l);this.selfWritePending=!0,this.copyDirRecursive(s,c);let d=hi.join(c,"folder.json");if(Dt.existsSync(d)){let y=JSON.parse(Dt.readFileSync(d,"utf-8"));y.id=l,y.name=n,Dt.writeFileSync(d,JSON.stringify(y,null,2))}else Dt.writeFileSync(d,JSON.stringify({id:l,name:n,type:"folder"},null,2));this.loadCollections();let p=this.collections.get(e),m=p?this.findItemById(p.items,l):void 0;return m||{id:l,type:"folder",name:n,items:[]}}async createRequest(e){if(!this.collections.get(e.collectionId))throw new Error("Collection not found");this.selfWritePending=!0;let n={id:e.id||Pt(e.name),type:"request",name:e.name,method:e.method||"GET",url:e.url,params:e.params,query:e.query,headers:e.headers,body:e.body,auth:e.auth,settings:e.settings,scripts:e.scripts,deprecated:e.deprecated,description:e.description,doc:e.doc,responseSchema:e.responseSchema,bodySchema:e.bodySchema,operationId:e.operationId,summary:e.summary,tags:e.tags,examples:e.examples,responses:e.responses,security:e.security};await this.loader.saveItem(e.collectionId,n,e.parentId);let i=this.loader.load(e.collectionId);return i&&this.collections.set(e.collectionId,i),n}async renameRequest(e,r,n){let i=this.collections.get(e);if(!i)return!1;this.selfWritePending=!0;let s=await this.loader.updateItem(e,r,{name:n});if(s){let o=this.findItemById(i.items,r);o&&(o.name=n)}return s}async moveItem(e,r,n){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let s=await this.loader.moveItem(e,r,n);return s&&this.loadCollections(),s}async reorderItems(e,r,n){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let s=await this.loader.reorderItems(e,r,n);return s&&this.loadCollections(),s}getRequestScript(e,r,n){let i=this.collections.get(e);if(!i)return;let s=this.findItemById(i.items,r);if(!s||s.type!=="request")return;let o=s;return n==="pre-request"?o.scripts?.preRequest:o.scripts?.postResponse}async setRequestScript(e,r,n,i){let s=this.collections.get(e);if(!s)return!1;let o=this.findItemById(s.items,r);if(!o||o.type!=="request")return!1;let l=o,d={...l.scripts??{},...n==="pre-request"?{preRequest:i}:{postResponse:i}};l.scripts=d,this.selfWritePending=!0;try{return await this.loader.saveScripts(e,r,d),!0}catch{return!1}}findItemById(e,r){for(let n of e){if(n.id===r)return n;if(n.type==="folder"&&n.items){let i=this.findItemById(n.items,r);if(i)return i}}}copyDirRecursive(e,r){Dt.existsSync(r)||Dt.mkdirSync(r,{recursive:!0});for(let n of Dt.readdirSync(e,{withFileTypes:!0})){let i=hi.join(e,n.name),s=hi.join(r,n.name);n.isDirectory()?this.copyDirRecursive(i,s):Dt.copyFileSync(i,s)}}deleteItemById(e,r){for(let n=0;n<e.length;n++){let i=e[n];if(i.id===r)return e.splice(n,1),!0;if(i.type==="folder"&&i.items&&this.deleteItemById(i.items,r))return!0}return!1}async importCollection(e){let r=Dt.readFileSync(e,"utf-8"),n;try{n=JSON.parse(r)}catch{throw new Error("Invalid JSON file")}if(n.info&&n.info._postman_id)return this.importPostmanCollection(n);let i={id:n.id||Pt(n.name||"Imported Collection"),name:n.name||"Imported Collection",description:n.description,items:n.items||[]};return await this.saveCollection(i),i}async importPostmanCollection(e){let r=p=>{if(!p)return;switch(p.type?.toLowerCase()){case"bearer":return{type:"bearer",bearerToken:p.bearer?.find(E=>E.key==="token")?.value||""};case"basic":let b=p.basic?.find(E=>E.key==="username"),q=p.basic?.find(E=>E.key==="password");return{type:"basic",basicAuth:{username:b?.value||"",password:q?.value||""}};case"apikey":let x=p.apikey?.find(E=>E.key==="key"),v=p.apikey?.find(E=>E.key==="value"),R=p.apikey?.find(E=>E.key==="in");return{type:"apikey",apikey:{key:x?.value||"",value:v?.value||"",in:R?.value||"header"}};case"noauth":return{type:"none"};default:return}},n=p=>{if(!Array.isArray(p)||p.length===0)return;let m={};for(let y of p){let b=y.script?.exec;if(!b)continue;let q=Array.isArray(b)?b.join(`
55
55
  `):b;y.listen==="prerequest"?m.preRequest=q:y.listen==="test"&&(m.postResponse=q)}return m.preRequest||m.postResponse?m:void 0},i=p=>{if(!p||typeof p!="object")return;let m={};return p.followRedirects===!1&&(m.followRedirects=!1),p.followOriginalHttpMethod===!0&&(m.followOriginalMethod=!0),p.followAuthorizationHeader===!1&&(m.followAuthHeader=!1),p.maxRedirects!==void 0&&(m.maxRedirects=p.maxRedirects),p.requestTimeout!==void 0&&(m.timeout=p.requestTimeout),Object.keys(m).length>0?m:void 0},s=p=>{if(!p||typeof p=="string")return;let m=p.query;if(!(!Array.isArray(m)||m.length===0))return m.map(y=>({key:y.key||"",value:y.value||"",enabled:y.disabled!==!0,...y.description!==void 0?{description:y.description}:{},...y.type!==void 0?{type:y.type}:{},...y.required!==void 0?{required:y.required}:{},...y.format!==void 0?{format:y.format}:{},...y.enum!==void 0?{enum:y.enum}:{},...y.deprecated!==void 0?{deprecated:y.deprecated}:{},...y.pattern!==void 0?{pattern:y.pattern}:{},...y.minLength!==void 0?{minLength:y.minLength}:{},...y.maxLength!==void 0?{maxLength:y.maxLength}:{},...y.minimum!==void 0?{minimum:y.minimum}:{},...y.maximum!==void 0?{maximum:y.maximum}:{},...y.exclusiveMinimum!==void 0?{exclusiveMinimum:y.exclusiveMinimum}:{},...y.exclusiveMaximum!==void 0?{exclusiveMaximum:y.exclusiveMaximum}:{},...y.multipleOf!==void 0?{multipleOf:y.multipleOf}:{},...y.minItems!==void 0?{minItems:y.minItems}:{},...y.maxItems!==void 0?{maxItems:y.maxItems}:{},...y.uniqueItems!==void 0?{uniqueItems:y.uniqueItems}:{},...y.nullable!==void 0?{nullable:y.nullable}:{},...y.oneOf!==void 0?{oneOf:y.oneOf}:{}}))},o=p=>{if(typeof p=="string")return p;if(!p)return"";let m=new Set;if(Array.isArray(p.variable))for(let b of p.variable)b.key&&m.add(b.key);if(m.size===0&&p.raw)return p.raw;let y="";if(p.protocol&&(y+=p.protocol+"://"),p.host&&(y+=Array.isArray(p.host)?p.host.join("."):p.host),p.port&&(y+=":"+p.port),p.path){let q=(Array.isArray(p.path)?p.path:[p.path]).map(x=>{let v=x.startsWith(":")?x.substring(1):x;return m.has(v)?":"+v:(x.startsWith(":"),x)});y+="/"+q.join("/")}return!y&&p.raw?p.raw:y},l=p=>{if(!Array.isArray(p)||p.length===0)return;let m={responses:{}};for(let y of p){let b=String(y.code||200),q,x={};if(Array.isArray(y.header))for(let P of y.header)!P.key||P.disabled||(P.key.toLowerCase()==="content-type"?q=P.value?.split(";")[0]?.trim():x[P.key]={description:String(P.value??""),schema:{type:"string"}});let v=y.body;if(typeof y.body=="string"&&y.body)try{v=JSON.parse(y.body)}catch{}let R=y.originalRequest,E;if(R){let P=typeof R.url=="string"?R.url:R.url?.raw??"";E=`${R.method||""} ${P}`.trim()||void 0}let k=y.name?y.name.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toLowerCase()||`example_${b}`:`example_${b}`;if(m.responses[b]){let P=m.responses[b];P.examples=P.examples??{},P.examples[k]={summary:E,value:v}}else m.responses[b]={description:y.name,contentType:q,examples:{[k]:{summary:E,value:v}},...Object.keys(x).length>0?{headers:x}:{}}}return Object.keys(m.responses).length>0?m:void 0},c=p=>p.map(m=>{if(m.item)return{id:Pt(m.name),type:"folder",name:m.name,description:m.description,auth:r(m.auth),scripts:n(m.event),items:c(m.item)};{let y=m.request||{};return{id:Pt(m.name),type:"request",name:m.name,description:m.description||y.description,method:typeof y.method=="string"?y.method:"GET",url:o(y.url),query:s(y.url),headers:Array.isArray(y.header)?y.header.map(b=>({key:b.key||b.name||"",value:b.value||b.value||"",enabled:b.disabled!==!0,...b.description!==void 0?{description:b.description}:{},...b.type!==void 0?{type:b.type}:{},...b.required!==void 0?{required:b.required}:{},...b.format!==void 0?{format:b.format}:{},...b.enum!==void 0?{enum:b.enum}:{},...b.deprecated!==void 0?{deprecated:b.deprecated}:{},...b.pattern!==void 0?{pattern:b.pattern}:{},...b.minLength!==void 0?{minLength:b.minLength}:{},...b.maxLength!==void 0?{maxLength:b.maxLength}:{},...b.minimum!==void 0?{minimum:b.minimum}:{},...b.maximum!==void 0?{maximum:b.maximum}:{},...b.exclusiveMinimum!==void 0?{exclusiveMinimum:b.exclusiveMinimum}:{},...b.exclusiveMaximum!==void 0?{exclusiveMaximum:b.exclusiveMaximum}:{},...b.multipleOf!==void 0?{multipleOf:b.multipleOf}:{},...b.minItems!==void 0?{minItems:b.minItems}:{},...b.maxItems!==void 0?{maxItems:b.maxItems}:{},...b.uniqueItems!==void 0?{uniqueItems:b.uniqueItems}:{},...b.nullable!==void 0?{nullable:b.nullable}:{},...b.oneOf!==void 0?{oneOf:b.oneOf}:{}})):[],body:(()=>{let b=y.body;if(b){if(b.mode==="raw"&&b.raw){let q=b.options?.raw?.language;return{type:"raw",format:q==="xml"?"xml":q==="html"?"html":q==="javascript"?"javascript":q==="text"?"text":"json",content:b.raw}}if(b.mode==="urlencoded"&&Array.isArray(b.urlencoded))return{type:"x-www-form-urlencoded",content:b.urlencoded.map(q=>({key:q.key||"",value:q.value||"",enabled:q.disabled!==!0}))};if(b.mode==="formdata"&&Array.isArray(b.formdata))return{type:"form-data",content:b.formdata.map(q=>({key:q.key||"",value:q.value||"",type:q.type||"text",enabled:q.disabled!==!0}))};if(b.mode==="graphql"&&b.graphql){let q;if(b.graphql.variables)try{q=JSON.parse(b.graphql.variables)}catch{q=void 0}return{type:"graphql",content:{query:b.graphql.query||"",variables:q}}}if(b.mode==="binary")return{type:"binary",content:""}}})(),auth:r(y.auth),scripts:n(m.event),settings:i(m.protocolProfileBehavior),responseSchema:l(m.response)}}}),d={id:Pt(e.info?.name||"Imported Postman Collection"),name:e.info?.name||"Imported Postman Collection",description:e.info?.description,auth:r(e.auth),scripts:n(e.event),variables:Array.isArray(e.variable)?Object.fromEntries(e.variable.filter(p=>p&&p.key).map(p=>[p.key,String(p.value??"")])):typeof e.variable=="object"&&e.variable!==null?Object.fromEntries(Object.entries(e.variable).map(([p,m])=>[p,String(m??"")])):void 0,items:c(e.item||[])};return await this.saveCollection(d),d}async exportCollection(e,r){let n=this.collections.get(e);if(!n)throw new Error("Collection not found");let i=Rz(n),s=JSON.stringify(i,null,2);Dt.writeFileSync(r,s,"utf-8")}async exportCollectionAsRestClientFolder(e,r){let n=this.collections.get(e);if(!n)throw new Error("Collection not found");let i=hi.join(r,Wt(n.name));Dt.mkdirSync(i,{recursive:!0});let s=n.variables||{};xu(hi.join(i,`${Wt(n.name)}.env`),s),Kf(i,Wt(n.name),n.scripts),Om(n.items,i,n)}dispose(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.fileWatcher?.dispose()}}});var lr,La,yo,g0=le(()=>{"use strict";lr={version:"1.0",storage:{format:"folder",root:"./.http-forge/assets",history:"./.http-forge/.cache/histories",results:"./.http-forge/.cache/results"},request:{timeout:3e4,followRedirects:!0,maxRedirects:10,strictSSL:!0,tls:{},certificates:[]},scripts:{modulePaths:["./.http-forge/assets/src","./.http-forge/assets/lib"],scope:"shared",timeout:5e3},runner:{resultsRetentionDays:7,indexPageSize:1e3,recentErrorsLimit:20},environments:{default:"dev"},restClientExport:{path:"collections-rest-client",mergeGlobals:!0},mcp:{port:3100,excludedCollections:[],excludedSuites:[],toolPrefix:"",maxRequestsPerCall:500,toolMode:"auto",drilldownThreshold:100,toolPageSize:200,cors:{allowedOrigins:["http://localhost","http://127.0.0.1"]}},proxy:null,secrets:{providers:{aws:{provider:"aws"},azure:{provider:"azure",vaultUrl:""},gcp:{provider:"gcp"},vault:{provider:"vault"},op:{provider:"1password"},doppler:{provider:"doppler"}}}},La={preferred:".http-forge/http-forge.config.json",legacy:"http-forge.config.json"},yo={collections:"collections",environments:"environments",flows:"flows",suites:"suites"}});import*as Bt from"fs";import*as Jt from"path";var vo,km=le(()=>{"use strict";g0();vo=class{constructor(e,r,n){this.workspacePath=e;this.fileWatcherFactory=r;this.notifications=n;this.configPath=this.resolveConfigPath(),this.config=this.loadConfig(),this.setupFileWatcher()}workspacePath;fileWatcherFactory;notifications;config;configPath;fileWatchers=[];resolveConfigPath(){let e=Jt.join(this.workspacePath,La.preferred);if(Bt.existsSync(e))return e;let r=Jt.join(this.workspacePath,La.legacy);return Bt.existsSync(r)?r:e}loadConfig(){if(this.configPath=this.resolveConfigPath(),!Bt.existsSync(this.configPath))return{...lr};try{let e=Bt.readFileSync(this.configPath,"utf-8"),r=JSON.parse(e);return this.mergeWithDefaults(r)}catch(e){return console.error("[ConfigService] Failed to load config:",e),this.notifications?.showWarning(`Failed to parse ${Jt.relative(this.workspacePath,this.configPath)}. Using default configuration.`),{...lr}}}mergeWithDefaults(e){return{version:e.version??lr.version,storage:{...lr.storage,...e.storage},request:{...lr.request,...e.request},scripts:{...lr.scripts,...e.scripts},runner:{...lr.runner,...e.runner},environments:{...lr.environments,...e.environments},restClientExport:{...lr.restClientExport,...e.restClientExport},proxy:e.proxy!==void 0?e.proxy:lr.proxy,mcp:{...lr.mcp,...e.mcp,cors:{...lr.mcp.cors,...e.mcp?.cors}},secrets:{...lr.secrets,...e.secrets,providers:{...lr.secrets?.providers,...e.secrets?.providers}}}}setupFileWatcher(){if(!this.fileWatcherFactory)return;let e=()=>{this.reload()};for(let r of[La.preferred,La.legacy]){let n=this.fileWatcherFactory.createFileWatcher(this.workspacePath,r);n.onDidChange(e),n.onDidCreate(e),n.onDidDelete(e),this.fileWatchers.push(n)}}getConfig(){return this.config}getStorageConfig(){return this.config.storage}getRequestConfig(){return this.config.request}getScriptsConfig(){return this.config.scripts}getRunnerConfig(){return this.config.runner}getEnvironmentsConfig(){return this.config.environments}getRestClientExportPath(){let e=this.config.restClientExport?.path||"collections-rest-client";return Jt.isAbsolute(e)?e:this.resolvePath(e)}getRestClientMergeGlobals(){return this.config.restClientExport?.mergeGlobals??!0}getProxyConfig(){return this.config.proxy??null}getMcpConfig(){let e=this.config.mcp??lr.mcp,r=["flat","drilldown","auto"];return{...e,port:Math.min(65535,Math.max(1,Math.floor(e.port??3100))),toolMode:r.includes(e.toolMode)?e.toolMode:"auto",drilldownThreshold:Math.min(500,Math.max(10,e.drilldownThreshold??100)),toolPageSize:e.toolPageSize===0?0:Math.min(1e3,Math.max(10,e.toolPageSize??200)),maxRequestsPerCall:Math.min(1e4,Math.max(1,e.maxRequestsPerCall??500))}}resolvePath(e){let r=e.startsWith("./")?e.slice(2):e;return Jt.join(this.workspacePath,...r.split("/"))}hasFolderCollectionsAtRoot(e){let r=Jt.join(e,yo.collections);if(!Bt.existsSync(r))return!1;let n;try{n=Bt.readdirSync(r,{withFileTypes:!0})}catch{return!1}return n.some(i=>{if(!i.isDirectory())return!1;let s=Jt.join(r,i.name,"collection.json");return Bt.existsSync(s)})}hasAnyEntries(e){if(!Bt.existsSync(e))return!1;try{return Bt.readdirSync(e).length>0}catch{return!1}}resolveStorageRootPath(){let e=this.resolvePath(this.config.storage.root);return this.configExists()||this.hasFolderCollectionsAtRoot(e)?e:[Jt.join(this.workspacePath,"http-forge-assets")].find(i=>this.hasFolderCollectionsAtRoot(i))||e}getRootPath(){return this.resolveStorageRootPath()}getCollectionsPath(){return Jt.join(this.getRootPath(),yo.collections)}getEnvironmentsPath(){return Jt.join(this.getRootPath(),yo.environments)}getFlowsPath(){return Jt.join(this.getRootPath(),yo.flows)}getHistoryPath(){let e=this.resolvePath(this.config.storage.history);if(this.configExists()||this.hasAnyEntries(e))return e;let r=Jt.join(this.workspacePath,".http-forge-cache","histories");return this.hasAnyEntries(r)?r:e}getResultsPath(){let e=this.resolvePath(this.config.storage.results);if(this.configExists()||this.hasAnyEntries(e))return e;let r=Jt.join(this.workspacePath,".http-forge-cache","results");return this.hasAnyEntries(r)?r:e}getSuitesPath(){return Jt.join(this.getRootPath(),yo.suites)}getModulePaths(){return this.config.scripts.modulePaths.map(e=>this.resolvePath(e))}getScriptScope(){return this.config.scripts.scope??"shared"}getScriptTimeout(){return this.config.scripts.timeout??5e3}getWorkspacePath(){return this.workspacePath}reload(){this.configPath=this.resolveConfigPath(),this.config=this.loadConfig()}configExists(){return Bt.existsSync(this.resolveConfigPath())}async createDefaultConfig(){await Bt.promises.mkdir(Jt.dirname(this.configPath),{recursive:!0});let e=JSON.stringify(lr,null,2);await Bt.promises.writeFile(this.configPath,e,"utf-8");let r=[this.getCollectionsPath(),this.getEnvironmentsPath(),this.getFlowsPath(),this.getSuitesPath()];for(let i of r)Bt.existsSync(i)||await Bt.promises.mkdir(i,{recursive:!0});let n=[this.getHistoryPath(),this.getResultsPath()];for(let i of n)Bt.existsSync(i)||await Bt.promises.mkdir(i,{recursive:!0});await this.createSampleEnvironments()}async createSampleEnvironments(){let e=this.getEnvironmentsPath(),r={id:"globals",name:"Global Variables",variables:{appName:"HTTP Forge"}};await Bt.promises.writeFile(Jt.join(e,"globals.json"),JSON.stringify(r,null,2),"utf-8");let n={id:"env_dev",name:"Development",variables:{baseUrl:"http://localhost:3000",apiVersion:"v1"}};await Bt.promises.writeFile(Jt.join(e,"dev.json"),JSON.stringify(n,null,2),"utf-8");let i={id:"default_headers",name:"Default Headers",headers:{"Content-Type":"application/json",Accept:"application/json"}};await Bt.promises.writeFile(Jt.join(e,"default-headers.json"),JSON.stringify(i,null,2),"utf-8")}dispose(){for(let e of this.fileWatchers)e.dispose();this.fileWatchers=[]}}});var Oz,Xf,y0=le(()=>{"use strict";ga();Oz="httpForge.cookies",Xf=class{constructor(e,r=Oz){this.store=e;this.storeKey=r;this.loadCookies()}store;storeKey;cookies=new Map;loadCookies(){try{let e=this.store.get(this.storeKey);e&&(this.cookies=new Map(Object.entries(e)),this.cleanExpiredCookies())}catch(e){console.error("[CookieService] Failed to load cookies:",e)}}async saveCookies(){try{let e={};this.cookies.forEach((r,n)=>{e[n]=r}),await this.store.update(this.storeKey,e)}catch(e){console.error("[CookieService] Failed to save cookies:",e)}}getCookieKey(e,r,n){return`${r||"*"}|${n||"/"}|${e}`}get(e,r){if(r){let s=this.getCookieKey(e,r),o=this.cookies.get(s);if(o&&!this.isExpired(o))return o}let n=this.getCookieKey(e,"*"),i=this.cookies.get(n);if(i&&!this.isExpired(i))return i;for(let s of this.cookies.values())if(s.name===e&&!this.isExpired(s))if(r&&s.domain){if(this.domainMatches(r,s.domain))return s}else return s}async set(e){let r=this.getCookieKey(e.name,e.domain,e.path);this.cookies.set(r,e),await this.saveCookies()}async setFromResponse(e){for(let r of e){let n=this.getCookieKey(r.name,r.domain,r.path);this.cookies.set(n,r)}await this.saveCookies()}has(e,r){return this.get(e,r)!==void 0}async delete(e,r,n){let i=this.getCookieKey(e,r,n),s=this.cookies.delete(i);return s&&await this.saveCookies(),s}getAll(e){let r=[];for(let n of this.cookies.values())this.isExpired(n)||(e?(!n.domain||this.domainMatches(e,n.domain))&&r.push(n):r.push(n));return r}getCookieHeader(e){let r=this.getAll(e);return Ct.formatCookieHeader(r)}async clear(){this.cookies.clear(),await this.saveCookies()}async clearDomain(e){let r=[];for(let[n,i]of this.cookies.entries())i.domain&&this.domainMatches(e,i.domain)&&r.push(n);for(let n of r)this.cookies.delete(n);await this.saveCookies()}parseCookieHeaders(e,r){return Ct.parseCookieHeaders(e,r)}isExpired(e){return Ct.isExpired(e)}cleanExpiredCookies(){let e=[];for(let[r,n]of this.cookies.entries())this.isExpired(n)&&e.push(r);for(let r of e)this.cookies.delete(r);e.length>0&&this.saveCookies()}domainMatches(e,r){return Ct.domainMatches(e,r)}get count(){return this.cookies.size}}});var ed,v0=le(()=>{"use strict";ga();ed=class{constructor(e){this.cookieService=e;this.localCache=[...e.getAll()]}cookieService;localCache=[];pendingOperations=[];get(e,r){return r?this.localCache.find(n=>n.name===e&&(!n.domain||n.domain===r||r.endsWith(n.domain))):this.localCache.find(n=>n.name===e)}has(e,r){return this.get(e,r)!==void 0}set(e){let r=this.localCache.findIndex(n=>n.name===e.name&&(!e.domain||n.domain===e.domain));r>=0?this.localCache[r]=e:this.localCache.push(e),this.pendingOperations.push({type:"set",cookie:e})}delete(e,r,n){let i=this.localCache.findIndex(s=>s.name===e&&(!r||s.domain===r||s.domain&&r.endsWith(s.domain)));return i>=0&&this.localCache.splice(i,1),this.pendingOperations.push({type:"delete",name:e,domain:r,path:n}),!0}getAll(e){return e?this.localCache.filter(r=>{let n=r.domain||"";return n===e||e.endsWith(n)}):[...this.localCache]}getCookiesForDomain(e){return this.localCache.filter(r=>{let n=r.domain||"";return n===e||e.endsWith(n)})}async setCookiesFromResponse(e,r){let n=new URL(e).hostname,i=this.cookieService.parseCookieHeaders(r,n);i.length>0&&(i.forEach(s=>{let o=this.localCache.findIndex(l=>l.name===s.name&&l.domain===(s.domain||n));o>=0?this.localCache[o]=s:this.localCache.push(s)}),await this.cookieService.setFromResponse(i))}getCookieHeader(e){let r=new URL(e).hostname,n=new URL(e).pathname,i=this.localCache.filter(s=>!(Ct.isExpired(s)||s.domain&&!Ct.domainMatches(r,s.domain)||!s.domain||s.path&&!n.startsWith(s.path)));if(i.length!==0)return Ct.formatCookieHeader(i)}clear(){this.localCache=[],this.pendingOperations.push({type:"clear"})}async flush(){for(let e of this.pendingOperations)switch(e.type){case"set":e.cookie&&await this.cookieService.set(e.cookie);break;case"delete":e.name&&await this.cookieService.delete(e.name,e.domain,e.path);break;case"clear":await this.cookieService.clear();break}this.pendingOperations=[]}}});function Am(t){try{let e=JSON.parse(typeof t=="string"?t:t.toString("utf-8"));if(!e)return null;let r=e.environment||e,n=r.name||e.name||"imported-environment",i=r.values||r.variables||e.values||e.variables||[],s={};if(Array.isArray(i))for(let l of i){if(!l)continue;let c=l.key??l.name,d=typeof l.enabled=="boolean"?l.enabled:!0;c&&d!==!1&&(s[c]=l.value??l.initial??"")}else if(typeof i=="object"&&i!==null)for(let[l,c]of Object.entries(i))s[l]=String(c??"");let o=r._postman_exported_at?"Imported from Postman export":r.description||"";return{name:n,variables:s,description:o}}catch{return null}}async function Pz(t,e){try{let r=await e.readFile(t);return Am(r)}catch{return null}}var b0=le(()=>{"use strict"});import*as ur from"fs";import*as xn from"path";var td,rd,S0=le(()=>{"use strict";jn();b0();Pm();Th();uf();td={SELECTED_ENVIRONMENT:"httpForge.selectedEnvironment",ENV_OVERRIDES_PREFIX:"httpForge.envOverrides."},rd=class{constructor(e,r,n,i,s,o=!0){this.workspaceFolder=e;this.workspaceStore=r;this.configService=n;this.fileWatcherFactory=i;this.secretStore=s;this.persistOverrides=o;let l=n.getEnvironmentsPath();this.environmentsPath=l,this.sharedConfigPath=xn.join(l,"_global.json"),this.localConfigPath=xn.join(l,"_global.local.json"),this.historiesPath=n.getHistoryPath(),this.selectedEnvironment=r?.get(td.SELECTED_ENVIRONMENT,"dev")??"dev",this.localGlobalValues={},this.localEnvironmentValues=new Map,this.persistOverrides&&this.loadPersistedEnvironmentOverrides(),this.loadSecretVariables(this.selectedEnvironment).catch(()=>{}),this.setupFileWatcher()}workspaceFolder;workspaceStore;configService;fileWatcherFactory;secretStore;persistOverrides;environmentsPath;sharedConfigPath;localConfigPath;historiesPath;sharedConfig=null;localConfig=null;selectedEnvironment="dev";fileWatcher;localGlobalValues={};localEnvironmentValues=new Map;secretValuesCache=new Map;onEnvironmentsChanged;setupFileWatcher(){if(!this.fileWatcherFactory||!ur.existsSync(this.environmentsPath))return;this.fileWatcher=this.fileWatcherFactory.createFileWatcher(this.environmentsPath,"**/*.json");let e=()=>{this.reload(),this.onEnvironmentsChanged?.()};this.fileWatcher.onDidChange(e),this.fileWatcher.onDidCreate(e),this.fileWatcher.onDidDelete(e)}dispose(){this.fileWatcher?.dispose()}getWorkspaceFolder(){return this.workspaceFolder}getRootPath(){return this.configService.getRootPath()}loadConfigs(){if(!ur.existsSync(this.environmentsPath)){this.sharedConfig={environments:{},globalVariables:{},defaultHeaders:{}},this.localConfig={credentials:{},variables:{}};return}this.loadFolderConfigs()}getSharedConfig(){return this.sharedConfig||this.loadConfigs(),this.sharedConfig}getLocalConfig(){return this.localConfig||this.loadConfigs(),this.localConfig}getEnvironmentNames(){let e=this.getSharedConfig();return e?.environments?Object.keys(e.environments):[]}getSelectedEnvironment(){return this.selectedEnvironment}async setSelectedEnvironment(e){if(this.selectedEnvironment=e,await this.workspaceStore?.update(td.SELECTED_ENVIRONMENT,e),!this.localEnvironmentValues.has(e)){let r=this.getEnvOverridesStateKey(e),n=this.workspaceStore?.get(r,{});n&&Object.keys(n).length>0&&this.localEnvironmentValues.set(e,{...n})}await this.loadSecretVariables(e)}getEnvOverridesStateKey(e){return`${td.ENV_OVERRIDES_PREFIX}${e||this.selectedEnvironment}`}loadPersistedEnvironmentOverrides(){let e=this.getEnvOverridesStateKey(),r=this.workspaceStore?.get(e,{});r&&Object.keys(r).length>0&&this.localEnvironmentValues.set(this.selectedEnvironment,{...r})}persistEnvironmentOverrides(e){if(!this.persistOverrides)return;let r=this.getEnvOverridesStateKey(e),n=this.localEnvironmentValues.get(e)||{};this.workspaceStore?.update(r,n)}setEnvironmentVariable(e,r,n){let i=n??this.selectedEnvironment;this.localEnvironmentValues.has(i)||this.localEnvironmentValues.set(i,{}),this.localEnvironmentValues.get(i)[e]=String(r),this.persistEnvironmentOverrides(i)}deleteEnvironmentVariable(e,r){let n=r??this.selectedEnvironment,i=this.localEnvironmentValues.get(n);i&&(delete i[e],this.persistEnvironmentOverrides(n))}clearEnvironmentVariables(e){let r=e??this.selectedEnvironment;this.localEnvironmentValues.set(r,{}),this.persistEnvironmentOverrides(r)}async resetEnvironmentOverrides(e){let r=e||this.selectedEnvironment;this.localEnvironmentValues.delete(r),await this.workspaceStore?.update(this.getEnvOverridesStateKey(r),void 0)}getEnvironmentVariableLocal(e){return this.localEnvironmentValues.get(this.selectedEnvironment)?.[e]}getEnvironmentVariableLocals(){return{...this.localEnvironmentValues.get(this.selectedEnvironment)||{}}}setGlobalVariable(e,r){this.localGlobalValues[e]=String(r)}getGlobalVariable(e){return this.getSharedConfig()?.globalVariables?.[e]}getGlobalVariableLocal(e){return this.localGlobalValues[e]}getGlobalVariables(){return{...this.getSharedConfig()?.globalVariables||{},...this.getLocalConfig()?.variables||{},...this.localGlobalValues}}getGlobalVariableLocals(){return{...this.localGlobalValues}}deleteGlobalVariable(e){delete this.localGlobalValues[e]}clearGlobalVariables(){this.localGlobalValues={}}getResolvedEnvironment(e){let r=e||this.selectedEnvironment,n=this.getSharedConfig(),i=this.getLocalConfig();if(!n?.environments?.[r])return null;let s=n.environments[r],o=i?.credentials?.[r],l=i?.variables||{},c=o?.variables||{},d=o&&o.headers||{},p=Zc(n.defaultHeaders||{},d),m=this.localEnvironmentValues.get(r)||{},y=this.secretValuesCache.get(r)||{},b={...s.variables||{},...c,...m,...y};return{name:r,description:s.description,requiresConfirmation:s.requiresConfirmation,headers:p,variables:b}}async getSecretVariable(e,r){return this.secretStore?.get(`${e}:${r}`)}async setSecretVariable(e,r,n){await this.secretStore?.store(`${e}:${r}`,n),this.secretValuesCache.has(e)||this.secretValuesCache.set(e,{}),this.secretValuesCache.get(e)[r]=n}async deleteSecretVariable(e,r){await this.secretStore?.delete(`${e}:${r}`),this.secretValuesCache.get(e)&&delete this.secretValuesCache.get(e)[r]}async loadSecretVariables(e){if(!this.secretStore)return;let r=e||this.selectedEnvironment,n=this.getSharedConfig()?.environments?.[r]?.secretVariables??[];if(n.length===0)return;let i={};await Promise.all(n.map(async s=>{let o=await this.secretStore.get(`${r}:${s}`);o!==void 0&&(i[s]=o)})),this.secretValuesCache.set(r,i)}resolveVariables(e,r){return this.createResolver(r).resolveString(e,!0)}exportEnvironmentsToFolder(e,r=!0){let n=this.getEnvironmentNames(),i=this.getSharedConfig(),s=i?.globalVariables?{...i.globalVariables}:{};if(!r&&Object.keys(s).length){let o=xn.join(e,"globals.env");xu(o,s)}n.forEach(o=>{let l=i?.environments?.[o];if(!l)return;let c={...l.variables||{}};r&&(c={...s,...c});let d=xn.join(e,`${Wt(o)}.env`);xu(d,c)})}resolveVariablesWithExtra(e,r,n){return this.createResolver(n,r).resolveString(e,!0)}resolveVariablesInObject(e,r){return this.createResolver(r).resolveObject(e,!0)}resolveVariablesInObjectWithExtra(e,r,n){return this.createResolver(n,r).resolveObject(e,!0)}getHistoriesPath(){return this.historiesPath}getSharedConfigPath(){return this.sharedConfigPath}getLocalConfigPath(){return this.localConfigPath}getEnvironmentConfigPath(e){return xn.join(this.environmentsPath,`${e}.json`)}localConfigExists(){return ur.existsSync(this.localConfigPath)}saveSharedConfig(e){this.saveFolderSharedConfig(e),this.sharedConfig=e}saveLocalConfig(e){let r={variables:e.variables||{}};this.saveJsonFile(this.localConfigPath,r);for(let[n,i]of Object.entries(e.credentials||{})){let s=this.getEnvLocalConfigPath(n),o={variables:i.variables||{}};this.saveJsonFile(s,o)}this.localConfig=e}importPostmanEnvironmentFile(e){try{let r=ur.readFileSync(e,"utf-8"),n=Am(r);if(!n)throw new Error("Failed to parse Postman environment file");this.sharedConfig||this.loadConfigs(),this.sharedConfig||(this.sharedConfig={environments:{},globalVariables:{},defaultHeaders:{}});let i=n.name||`imported-${Date.now()}`;return this.sharedConfig.environments=this.sharedConfig.environments||{},this.sharedConfig.environments[i]=this.sharedConfig.environments[i]||{},this.sharedConfig.environments[i].variables=n.variables,n.description&&(this.sharedConfig.environments[i].description=n.description),this.saveSharedConfig(this.sharedConfig),n}catch(r){throw console.error("[EnvironmentConfigService] importPostmanEnvironmentFile failed:",r),r}}saveEnvLocalConfig(e,r){let n=this.getEnvLocalConfigPath(e),i={variables:r};this.saveJsonFile(n,i),this.localConfig||(this.localConfig={credentials:{},variables:{}}),this.localConfig.credentials||(this.localConfig.credentials={}),this.localConfig.credentials[e]={variables:r}}getEnvLocalPath(e){return this.getEnvLocalConfigPath(e)}getEnvLocalConfigPath(e){return xn.join(this.environmentsPath,`${e}.local.json`)}loadFolderConfigs(){let e=nf(this.environmentsPath);this.sharedConfig={environments:e.environments,globalVariables:e.globalVariables,defaultHeaders:e.defaultHeaders},this.localConfig={credentials:e.localCredentials,variables:e.localVariables}}createResolver(e,r){let i=this.getResolvedEnvironment(e)?.variables||{},s=this.getGlobalVariables(),o=this.getGlobalVariableLocals();return new Sa({globals:s,collectionVariables:{},environmentVariables:i,variables:{...o,...r||{}}})}saveFolderSharedConfig(e){ur.existsSync(this.environmentsPath)||ur.mkdirSync(this.environmentsPath,{recursive:!0});let r={variables:e.globalVariables||{},defaultHeaders:e.defaultHeaders||{}};this.saveJsonFile(this.sharedConfigPath,r);let n=ur.readdirSync(this.environmentsPath).filter(s=>s.endsWith(".json")).filter(s=>!Ah(s)),i=new Set(Object.keys(e.environments||{}));for(let s of n){let o=xn.basename(s,".json");if(!i.has(o))try{ur.unlinkSync(xn.join(this.environmentsPath,s))}catch{}}for(let[s,o]of Object.entries(e.environments||{})){let l={name:s,description:o.description,requiresConfirmation:o.requiresConfirmation,variables:o.variables||{}};this.saveJsonFile(xn.join(this.environmentsPath,`${s}.json`),l)}}reload(){this.sharedConfig=null,this.localConfig=null,this.loadConfigs()}getAllEnvironments(){return this.loadConfigs(),this.sharedConfig?Object.entries(this.sharedConfig.environments).map(([e,r])=>({id:e,name:e,active:e===this.selectedEnvironment,variables:r.variables||{}})):[]}async setActiveEnvironment(e){await this.setSelectedEnvironment(e)}async createEnvironment(e){if(this.loadConfigs(),this.sharedConfig||(this.sharedConfig={environments:{},globalVariables:{}}),this.sharedConfig.environments[e])throw new Error(`Environment "${e}" already exists`);this.sharedConfig.environments[e]={description:`Created ${new Date().toISOString()}`,variables:{}},this.saveSharedConfig(this.sharedConfig)}async deleteEnvironment(e){if(this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentExists(e),delete this.sharedConfig.environments[e],this.selectedEnvironment===e){let r=Object.keys(this.sharedConfig.environments);this.selectedEnvironment=r.length>0?r[0]:"dev",await this.workspaceStore?.update(td.SELECTED_ENVIRONMENT,this.selectedEnvironment)}this.saveSharedConfig(this.sharedConfig)}async duplicateEnvironment(e,r){this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentName(r),this.validateEnvironmentExists(e),this.validateEnvironmentNameNotTaken(r);let n=this.sharedConfig.environments[e];this.sharedConfig.environments[r]=JSON.parse(JSON.stringify(n)),this.sharedConfig.environments[r].description=`Copied from ${e}`,this.saveSharedConfig(this.sharedConfig)}async renameEnvironment(e,r){this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentName(r),this.validateEnvironmentExists(e),r!==e&&(this.validateEnvironmentNameNotTaken(r),this.sharedConfig.environments[r]=this.sharedConfig.environments[e],delete this.sharedConfig.environments[e],this.selectedEnvironment===e&&(this.selectedEnvironment=r,await this.workspaceStore?.update(td.SELECTED_ENVIRONMENT,r)),this.saveSharedConfig(this.sharedConfig))}validateEnvironmentName(e){if(!e||e.trim().length===0)throw new Error("Environment name cannot be empty");if(e.length>128)throw new Error("Environment name cannot exceed 128 characters");if(!/^[a-zA-Z0-9_\-\.]+$/.test(e))throw new Error("Environment name can only contain letters, numbers, hyphens, underscores, and dots")}validateEnvironmentExists(e){if(!this.sharedConfig?.environments?.[e])throw new Error(`Environment "${e}" not found`)}validateEnvironmentNameNotTaken(e){if(this.sharedConfig?.environments?.[e])throw new Error(`Environment "${e}" already exists`)}validateConfigLoaded(){if(!this.sharedConfig)throw new Error("No environment configuration loaded")}async updateEnvironmentVariables(e,r){if(this.loadConfigs(),!this.sharedConfig)throw new Error("No configuration loaded");let n=this.sharedConfig.environments[e];if(!n)throw new Error(`Environment "${e}" not found`);n.variables=r,this.saveSharedConfig(this.sharedConfig)}loadJsonFile(e){try{if(!ur.existsSync(e))return null;let r=ur.readFileSync(e,"utf-8");return JSON.parse(r)}catch(r){return console.error(`Failed to load JSON from ${e}:`,r),null}}saveJsonFile(e,r){try{let n=xn.dirname(e);ur.existsSync(n)||ur.mkdirSync(n,{recursive:!0}),ur.writeFileSync(e,JSON.stringify(r,null,2),"utf-8")}catch(n){throw console.error(`Failed to save JSON to ${e}:`,n),n}}}});var bo,Tm=le(()=>{"use strict";Hf();bo=class t{constructor(e,r,n,i,s,o,l,c,d,p,m,y,b){this.httpService=e;this.scriptExecutor=r;this.envConfigService=n;this.requestPreparer=i;this.environment=s;this.cookieJar=o;this.collectionScripts=l;this.folderScriptsChain=c;this.onConsoleOutput=d;this.collectionName=p;this.collectionAuth=m;this.iteration=y;this.iterationCount=b}httpService;scriptExecutor;envConfigService;requestPreparer;environment;cookieJar;collectionScripts;folderScriptsChain;onConsoleOutput;collectionName;collectionAuth;iteration;iterationCount;async execute(e,r,n){let i=Date.now();return this.executeWithSession(e,r,n,i)}async executeWithSession(e,r,n,i){let s=this.collectPreRequestScripts(e),o=this.collectPostResponseScripts(e),l=this.envConfigService.getResolvedEnvironment(this.environment);if(!l)throw new Error(`Environment "${this.environment}" not found or not configured`);let c=this.envConfigService.getGlobalVariables(),d={request:e,variables:{...r},environmentVariables:l.variables||{},globals:{...c},environmentName:this.environment,cookieJar:this.cookieJar,info:{eventName:"prerequest",requestName:e.name,requestId:e.id,collectionName:this.collectionName,iteration:this.iteration,iterationCount:this.iterationCount},onEnvironmentChange:async(y,b,q)=>{y==="set"&&b&&q!==void 0?this.envConfigService.setEnvironmentVariable(b,q,this.environment):y==="unset"&&b?this.envConfigService.deleteEnvironmentVariable(b,this.environment):y==="clear"&&this.envConfigService.clearEnvironmentVariables(this.environment)},onGlobalsChange:(y,b,q)=>{y==="set"&&b&&q!==void 0?this.envConfigService.setGlobalVariable(b,q):y==="unset"&&b?this.envConfigService.deleteGlobalVariable(b):y==="clear"&&this.envConfigService.clearGlobalVariables()}},p=this.scriptExecutor.createRequestSession(d),m=null;try{let y={...r},b={...e},q;if((!b.auth||b.auth.type==="inherit")&&(b.auth=this.collectionAuth&&this.collectionAuth.type!=="inherit"?this.collectionAuth:void 0),s.length>0){let D=await p.executePreRequest(s);if(D.consoleOutput&&D.consoleOutput.length>0&&this.onConsoleOutput?.(D.consoleOutput,{requestName:e.name||"",phase:"pre-request"}),D.nextRequest!==void 0&&(q=D.nextRequest),D.skipRequest){let J={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:{url:e.url||"",method:e.method||"GET",headers:{},body:J,params:{},query:{}},response:{status:0,statusText:"Skipped",headers:{},body:null,time:0,cookies:[]},duration:Date.now()-i,timestamp:Date.now(),passed:!0,assertions:[],modifiedVariables:y,nextRequest:q}}D.success&&(D.modifiedRequest&&(D.modifiedRequest.url&&(b.url=D.modifiedRequest.url),D.modifiedRequest.headers&&(b.headers=D.modifiedRequest.headers),D.modifiedRequest.params&&(b.params=D.modifiedRequest.params),D.modifiedRequest.query&&(b.query=D.modifiedRequest.query),D.modifiedRequest.body!==void 0&&(b.body=D.modifiedRequest.body)),(D.localVariables??D.modifiedVariables)&&(y=D.localVariables??D.modifiedVariables))}m=await this.requestPreparer.prepareRequest(b,this.environment,l,y);let{url:x,headers:v,body:R,method:E}=m,k={};for(let D in v)Object.prototype.hasOwnProperty.call(v,D)&&(k[D.toUpperCase()]=v[D]);if(!k.COOKIE&&b.settings?.includeCookies!==!1&&this.cookieJar){let J=this.cookieJar.getCookieHeader(x);J&&(k.COOKIE=J)}let P={method:E,url:x,headers:k,body:R.content,signal:n,settings:b.settings?{...b.settings}:void 0},M=await this.httpService.execute(P);this.cookieJar&&M.headers&&await this.cookieJar.setCookiesFromResponse(x,M.headers);let j=Date.now()-i,I=[],_={},A;if(o.length>0){let D=0;if(M.body)if(typeof M.body=="string")D=Buffer.byteLength(M.body,"utf8");else if(Buffer.isBuffer(M.body))D=M.body.length;else try{D=Buffer.byteLength(JSON.stringify(M.body),"utf8")}catch{D=0}let J=xm(M.headers,M.cookies,m.url),Q={executedRequest:m,status:M.status,statusText:M.statusText,headers:n0(M.headers||{}),body:M.body,cookies:J,responseTime:M.time,responseSize:D},se=await p.executePostResponse(o,Q);I=se.testResults,_=se.modifiedEnvironmentVariables||{},A=se.visualizerData,(se.localVariables??se.modifiedVariables)&&(y=se.localVariables??se.modifiedVariables),se.nextRequest!==void 0&&(q=se.nextRequest),se.consoleOutput&&se.consoleOutput.length>0&&this.onConsoleOutput?.(se.consoleOutput,{requestName:e.name||"",phase:"post-response"})}let F=I.length===0||I.every(D=>D.passed),U=I.length>0?F:M.status>=200&&M.status<=302;return{requestId:e.id,name:e.name,executedRequest:{...m,headers:k},response:{status:M.status,statusText:M.statusText,headers:M.headers||{},body:M.body,time:M.time||j,cookies:M.cookies||[]},duration:j,timestamp:Date.now(),passed:U,assertions:I,modifiedVariables:y,modifiedEnvironmentVariables:_,nextRequest:q,visualizerData:A}}catch(y){return this.handleError(e,m,y,i)}finally{p.dispose?.()}}collectPreRequestScripts(e){let r=[];if(this.collectionScripts?.preRequest&&r.push(this.collectionScripts.preRequest),this.folderScriptsChain)if(Array.isArray(this.folderScriptsChain))for(let n of this.folderScriptsChain)n?.preRequest&&r.push(n.preRequest);else this.folderScriptsChain.preRequest&&r.push(this.folderScriptsChain.preRequest);return e.scripts?.preRequest&&r.push(e.scripts.preRequest),r}collectPostResponseScripts(e){let r=[];if(e.scripts?.postResponse&&r.push(e.scripts.postResponse),this.folderScriptsChain)if(Array.isArray(this.folderScriptsChain)){let n=[...this.folderScriptsChain].reverse();for(let i of n)i?.postResponse&&r.push(i.postResponse)}else this.folderScriptsChain.postResponse&&r.push(this.folderScriptsChain.postResponse);return this.collectionScripts?.postResponse&&r.push(this.collectionScripts.postResponse),r}handleError(e,r,n,i){let s=Date.now()-i,o=r?.method||e.method,l=r?.url||e.url;this.onConsoleOutput?.([`${n.message||n}`],{requestName:e.name||"",phase:"error"});let c=String(n.name==="AbortError"?"Request was aborted":n.message||n),d=n?.stack?String(n.stack):"",p=this.errorBodyFormat,m,y;p==="html"||p==="both"?(m=t.formatErrorAsHtml(c,d),y={"content-type":"text/html; charset=utf-8"}):(m=c,y={});let b={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:{url:l||"",method:o||"GET",headers:r?.headers||{},body:r?.body||b,params:r?.params||{},query:r?.query||{}},response:{status:0,statusText:n.name==="AbortError"?"Aborted":n.code||n.message||"Request Error",headers:y,cookies:[],body:m,time:0},duration:s,timestamp:Date.now(),passed:!1,assertions:[],error:c}}get errorBodyFormat(){return"text"}static formatErrorAsHtml(e,r){let n=i=>i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");return`<!doctype html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@http-forge/core",
3
- "version": "0.6.24",
3
+ "version": "0.6.25",
4
4
  "description": "Headless Postman-compatible API testing engine for Node.js, CI/CD, OpenAPI workflows, and HTTP Forge automation",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",