@http-forge/core 1.0.1 → 1.0.2
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/README.md +1 -0
- package/dist/index.js +52 -52
- package/dist/index.mjs +52 -52
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -600,8 +600,8 @@ ${s}
|
|
|
600
600
|
`);let f="";p.once("data",h=>{if(f+=h.toString(),!f.includes("200")){d(new Error(`Proxy CONNECT failed: ${f.split(`\r
|
|
601
601
|
`)[0]}`)),p.destroy();return}let g=Dd.connect({...s,socket:p,servername:t});g.once("error",v=>d(v)),g.once("secureConnect",()=>d(null,g))})}),p.once("error",m=>d(m))},l}hostMatchesBypass(e,t){let n=t.toLowerCase().trim(),s=e.toLowerCase();return n==="*"?!0:n.startsWith("*.")?s===n.slice(2)||s.endsWith(`.${n.slice(2)}`):s===n}resolveTlsSettings(e,t){let n=t.tls||{};if(!!(n.caPath||n.certPath||n.keyPath||n.pfxPath||n.servername||n.passphrase))return n;let i=this.findCertificateMapping(e,t.certificates||[]);return i?{caPath:i.caPath,certPath:i.certPath,keyPath:i.keyPath,pfxPath:i.pfxPath,passphrase:i.passphrase,servername:i.servername}:n}findCertificateMapping(e,t){if(!Array.isArray(t)||t.length===0)return;let n=e.hostname,s=e.port?Number(e.port):443,i=t.find(o=>this.mappingMatchesHost(o,n,s,!0));return i||t.find(o=>this.mappingMatchesHost(o,n,s,!1))}mappingMatchesHost(e,t,n,s){if(!e||e.enabled===!1)return!1;let i=String(e.host||"").trim().toLowerCase();if(!i||e.port!=null&&Number(e.port)!==n)return!1;let o=t.toLowerCase();if(s)return i!=="*"&&!i.startsWith("*.")&&o===i;if(i==="*")return!0;if(i.startsWith("*.")){let a=i.slice(2);return o===a||o.endsWith(`.${a}`)}return o===i}readOptionalFile(e,t){if(!e)return;let n=uo.isAbsolute(e)?e:uo.resolve(this.basePath,e);try{return _d.readFileSync(n)}catch(s){throw new Error(`[NodeHttpClient] Failed to read ${t} file at ${n}: ${s?.message||"Unknown error"}`)}}parseCookies(e,t){return e?e.map(n=>{let s=n.split(";").map(u=>u.trim()),[i,...o]=s,[a,c]=i.split("="),l={name:a.trim(),value:c?.trim()||"",domain:t};for(let u of o){let[d,p]=u.split("=");switch(d.toLowerCase().trim()){case"domain":l.domain=p?.trim();break;case"path":l.path=p?.trim();break;case"expires":l.expires=p?.trim();break;case"httponly":l.httpOnly=!0;break;case"secure":l.secure=!0;break}}return l}):[]}}});var qc,Un,fo=k(()=>{"use strict";Cc();qc={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"},Un=class{sanitizeHeaderValue(e){return Rc(e)}sanitizeHeaders(e){return lo(e)}encodeBody(e){if(!e||e.type==="none")return null;let{type:t,content:n}=e;switch(t){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 t=new URLSearchParams;for(let n of e)n.enabled!==!1&&n.key&&t.append(n.key,n.value||"");return t.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 t=e.variables;if(typeof t=="string")try{t=t.trim()?JSON.parse(t):void 0}catch{t=void 0}return JSON.stringify({query:e.query,...t!=null?{variables:t}:{},...e.operationName?{operationName:e.operationName}:{}})}return JSON.stringify(e)}setContentTypeHeader(e,t,n){if(Object.keys(e).some(o=>o.toLowerCase()==="content-type"))return;if(n){e["Content-Type"]=n;return}if(!t||t.type==="none")return;let i;switch(t.type){case"x-www-form-urlencoded":i=qc["x-www-form-urlencoded"];break;case"raw":i=t.format?qc[t.format]:"text/plain",i||(i="text/plain");break;case"graphql":i=qc.graphql;break;case"binary":i="application/octet-stream";break}i&&(e["Content-Type"]=i)}}});var zn,mo=k(()=>{"use strict";zn=class{parse(e,t){return t.toLowerCase().endsWith(".json")?this.parseJson(e):this.parseCsv(e)}parseJson(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[t]}catch{throw new Error("Failed to parse JSON data file: Invalid JSON format")}}parseCsv(e){let t=e.split(/\r?\n/).filter(i=>i.trim());if(t.length<2)return[{}];let n=this.parseCsvLine(t[0]),s=[];for(let i=1;i<t.length;i++){let o=this.parseCsvLine(t[i]),a={};n.forEach((c,l)=>{a[c]=o[l]||""}),s.push(a)}return s}parseCsvLine(e){let t=[],n="",s=!1;for(let i=0;i<e.length;i++){let o=e[i],a=e[i+1];o==='"'?s&&a==='"'?(n+='"',i++):s=!s:o===","&&!s?(t.push(n.trim()),n=""):n+=o}return t.push(n.trim()),t}}});import*as $r from"crypto";var ag,Ds,Pc=k(()=>{"use strict";ag=3e4,Ds=class{constructor(e,t,n,s,i="henry-huang.http-forge/oauth2/callback"){this.secretStore=e;this.browserService=t;this.envConfigService=n;this.httpService=s;this.callbackPath=i}secretStore;browserService;envConfigService;httpService;callbackPath;tokenCache=new Map;pendingAuthCallback=null;pendingImplicitCallback=null;async getToken(e,t){if(e.accessToken)return{accessToken:this.resolve(e.accessToken,t),tokenType:e.tokenPrefix||"Bearer",raw:{}};let n=this.buildCacheKeyString(e),s=this.tokenCache.get(n);if(s&&!this.isExpired(s))return s;if(s?.refreshToken)try{return await this.refreshToken(e,s.refreshToken,t)}catch{this.tokenCache.delete(n)}if(!s){let o=await this.secretStore.get(`oauth2_refresh_${n}`);if(o)try{return await this.refreshToken(e,o,t)}catch{await this.secretStore.delete(`oauth2_refresh_${n}`)}}let i;switch(e.grantType){case"client_credentials":i=await this.fetchToken(e,t,"client_credentials");break;case"password":i=await this.fetchToken(e,t,"password");break;case"authorization_code":i=await this.authorizationCodeFlow(e,t);break;case"implicit":i=await this.implicitFlow(e,t);break;default:throw new Error(`Unknown OAuth2 grant type: ${e.grantType}`)}return this.tokenCache.set(n,i),i.refreshToken&&await this.storeRefreshToken(n,i.refreshToken),i}async refreshToken(e,t,n){let s=this.resolve(e.tokenUrl||"",n);if(!s)throw new Error("OAuth2 tokenUrl is required for token refresh");let i=this.resolve(e.clientId||"",n),o=this.resolve(e.clientSecret||"",n),a=new URLSearchParams;a.append("grant_type","refresh_token"),a.append("refresh_token",t);let c={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,c,a,i,o,n);let l=await this.httpService.execute({method:"POST",url:s,headers:c,body:a.toString()}),u=this.parseTokenResponse(l.body,e);u.refreshToken||(u.refreshToken=t);let d=this.buildCacheKeyString(e);return this.tokenCache.set(d,u),u.refreshToken&&await this.storeRefreshToken(d,u.refreshToken),u}async authorizationCodeFlow(e,t){let n=this.resolve(e.authUrl||"",t),s=this.resolve(e.tokenUrl||"",t),i=this.resolve(e.clientId||"",t),o=this.resolve(e.clientSecret||"",t),a=e.scope?this.resolve(e.scope,t):void 0;if(!n)throw new Error("OAuth2 authUrl is required for authorization code flow");if(!s)throw new Error("OAuth2 tokenUrl is required for authorization code flow");if(!i)throw new Error("OAuth2 clientId is required for authorization code flow");let c=e.usePkce!==!1,l,u,d;if(c){l=this.generateCodeVerifier();let w=e.pkceMethod||"S256";u=w==="S256"?this.generateCodeChallengeS256(l):l,d=w}let p=e.state||$r.randomBytes(16).toString("hex"),m=await this.getCallbackUri(),f=new URL(n);if(f.searchParams.set("response_type","code"),f.searchParams.set("client_id",i),f.searchParams.set("redirect_uri",m),a&&f.searchParams.set("scope",a),f.searchParams.set("state",p),u&&(f.searchParams.set("code_challenge",u),f.searchParams.set("code_challenge_method",d)),e.audience&&f.searchParams.set("audience",this.resolve(e.audience,t)),e.resource&&f.searchParams.set("resource",this.resolve(e.resource,t)),e.extraParams)for(let[w,E]of Object.entries(e.extraParams))f.searchParams.set(w,this.resolve(E,t));this.pendingAuthCallback&&(this.pendingAuthCallback.reject(new Error("OAuth2 authorization superseded by a new request")),this.pendingAuthCallback=null);let h=new Promise((w,E)=>{this.pendingAuthCallback={resolve:w,reject:E,state:p}});await this.browserService.openExternal(f.toString());let g;try{g=await Promise.race([h,new Promise((w,E)=>setTimeout(()=>{this.pendingAuthCallback=null,E(new Error("OAuth2 authorization timed out after 2 minutes"))},12e4))])}finally{this.pendingAuthCallback=null}if(g.state&&g.state!==p)throw new Error("OAuth2 state mismatch \u2014 potential CSRF attack");let v=new URLSearchParams;v.append("grant_type","authorization_code"),v.append("code",g.code),v.append("redirect_uri",m),l&&v.append("code_verifier",l);let y={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,y,v,i,o,t);let S=await this.httpService.execute({method:"POST",url:s,headers:y,body:v.toString()}),b=this.parseTokenResponse(S.body,e),C=this.buildCacheKeyString(e);return this.tokenCache.set(C,b),b.refreshToken&&await this.storeRefreshToken(C,b.refreshToken),b}async implicitFlow(e,t){let n=this.resolve(e.authUrl||"",t),s=this.resolve(e.clientId||"",t),i=e.scope?this.resolve(e.scope,t):void 0;if(!n)throw new Error("OAuth2 authUrl is required for implicit flow");if(!s)throw new Error("OAuth2 clientId is required for implicit flow");let o=e.state||$r.randomBytes(16).toString("hex"),a=await this.getCallbackUri(),c=new URL(n);if(c.searchParams.set("response_type","token"),c.searchParams.set("client_id",s),c.searchParams.set("redirect_uri",a),i&&c.searchParams.set("scope",i),c.searchParams.set("state",o),e.audience&&c.searchParams.set("audience",this.resolve(e.audience,t)),e.resource&&c.searchParams.set("resource",this.resolve(e.resource,t)),e.extraParams)for(let[m,f]of Object.entries(e.extraParams))c.searchParams.set(m,this.resolve(f,t));this.pendingImplicitCallback&&(this.pendingImplicitCallback.reject(new Error("OAuth2 implicit flow superseded by a new request")),this.pendingImplicitCallback=null);let l=new Promise((m,f)=>{this.pendingImplicitCallback={resolve:m,reject:f,state:o}});await this.browserService.openExternal(c.toString());let u;try{u=await Promise.race([l,new Promise((m,f)=>setTimeout(()=>{this.pendingImplicitCallback=null,f(new Error("OAuth2 implicit flow timed out after 2 minutes"))},12e4))])}finally{this.pendingImplicitCallback=null}if(u.state&&u.state!==o)throw new Error("OAuth2 state mismatch \u2014 potential CSRF attack");let d={accessToken:u.accessToken,tokenType:u.tokenType||e.tokenPrefix||"Bearer",expiresAt:u.expiresIn?Date.now()+u.expiresIn*1e3:void 0,raw:{access_token:u.accessToken,token_type:u.tokenType,expires_in:u.expiresIn}},p=this.buildCacheKeyString(e);return this.tokenCache.set(p,d),d}handleAuthorizationCallback(e,t,n){if(n){let s=new Error(`OAuth2 authorization error: ${n}`);this.pendingAuthCallback?.reject(s),this.pendingImplicitCallback?.reject(s),this.pendingAuthCallback=null,this.pendingImplicitCallback=null;return}if(e&&this.pendingAuthCallback){this.pendingAuthCallback.resolve({code:e,state:t}),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,t,n,s){this.pendingImplicitCallback&&(this.pendingImplicitCallback.resolve({accessToken:e,tokenType:t,expiresIn:n,state:s}),this.pendingImplicitCallback=null)}clearToken(e){let t=`${e.tokenUrl}|${e.clientId}|${e.scope||""}|${e.grantType}`;this.tokenCache.delete(t),this.secretStore.delete(`oauth2_refresh_${t}`)}clearAllTokens(){for(let e of this.tokenCache.keys())this.secretStore.delete(`oauth2_refresh_${e}`);this.tokenCache.clear()}async fetchToken(e,t,n){let s=this.resolve(e.tokenUrl||"",t);if(!s)throw new Error("OAuth2 tokenUrl is required");let i=this.resolve(e.clientId||"",t),o=this.resolve(e.clientSecret||"",t),a=e.scope?this.resolve(e.scope,t):void 0,c=new URLSearchParams;if(c.append("grant_type",n),a&&c.append("scope",a),n==="password"){let d=this.resolve(e.username||"",t),p=this.resolve(e.password||"",t);if(!d)throw new Error("OAuth2 password grant requires username");c.append("username",d),c.append("password",p)}if(e.audience&&c.append("audience",this.resolve(e.audience,t)),e.resource&&c.append("resource",this.resolve(e.resource,t)),e.extraParams)for(let[d,p]of Object.entries(e.extraParams))c.append(d,this.resolve(p,t));let l={"Content-Type":"application/x-www-form-urlencoded"};this.applyClientAuth(e,l,c,i,o,t);let u=await this.httpService.execute({method:"POST",url:s,headers:l,body:c.toString()});return this.parseTokenResponse(u.body,e)}applyClientAuth(e,t,n,s,i,o){if(e.clientAuthentication==="header"){let a=Buffer.from(`${s}:${i}`).toString("base64");t.Authorization=`Basic ${a}`}else s&&n.set("client_id",s),i&&n.set("client_secret",i)}parseTokenResponse(e,t){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 s=n,i=t.tokenField||"access_token",o=s[i];if(!o)throw new Error(`OAuth2 token fetch failed: '${i}' not present in response`);let a=typeof s.expires_in=="number"?s.expires_in:void 0;return{accessToken:o,tokenType:s.token_type||t.tokenPrefix||"Bearer",expiresAt:a?Date.now()+a*1e3:void 0,refreshToken:s.refresh_token,scope:s.scope,raw:s}}isExpired(e){return e.expiresAt?Date.now()>=e.expiresAt-ag:!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,t){return this.envConfigService.resolveVariables(e,t)}generateCodeVerifier(){return $r.randomBytes(32).toString("base64url")}generateCodeChallengeS256(e){return $r.createHash("sha256").update(e).digest("base64url")}async storeRefreshToken(e,t){try{await this.secretStore.store(`oauth2_refresh_${e}`,t)}catch{}}}});import*as Jn from"fs";import*as Fr from"path";function Nr(r,e={}){let t=[];Object.entries(e).forEach(([n,s])=>{t.push(`${n}=${s}`)}),t.length&&Jn.writeFileSync(r,t.join(`
|
|
602
602
|
`),"utf-8")}function Ms(r,e,t){t&&(t.preRequest&&t.preRequest.trim()&&Jn.writeFileSync(Fr.join(r,`${e}.pre.js`),t.preRequest,"utf-8"),t.postResponse&&t.postResponse.trim()&&Jn.writeFileSync(Fr.join(r,`${e}.post.js`),t.postResponse,"utf-8"))}async function cg(r,e,t,n,s){await r.exportCollectionAsRestClientFolder(t,n),e.exportEnvironmentsToFolder(n,s)}function ho(r,e,t){r.forEach(n=>{if(n.type==="folder"){let s=Fr.join(e,xe(n.name));Jn.mkdirSync(s,{recursive:!0}),Ms(s,xe(n.name),n.scripts),ho(n.items||[],s,t)}else if(n.type==="request"){let s=n,i=xe(s.name)+".http",o=Fr.join(e,i),a=lg(s,t);Jn.writeFileSync(o,a,"utf-8"),Ms(e,xe(s.name),s.scripts)}})}function lg(r,e){let t=[];t.push(`### ${e.name} / ${r.name}`),t.push(`# collection env: ${xe(e.name)}.env`),t.push(`# request scripts: ${xe(r.name)}.pre.js and .post.js`);let n=ug(r);return t.push(`${r.method} ${n}`),(r.headers||[]).filter(s=>s.enabled!==!1).forEach(s=>{t.push(`${s.key}: ${s.value}`)}),r.body&&r.body.content&&t.push("",r.body.content),t.join(`
|
|
603
|
-
`)}function ug(r){let e=r.url;if(r.query&&r.query.length){let t=r.query.filter(n=>n.enabled!==!1).map(n=>`${encodeURIComponent(n.key)}=${encodeURIComponent(n.value)}`).join("&");t&&(e+=(e.includes("?")?"&":"?")+t)}return e}var go=k(()=>{"use strict";Ze()});import*as Le from"fs";import*as Ic from"path";var _r,Tc=k(()=>{"use strict";Ze();tn();_r=class{collectionsDir;cache=new Map;constructor(e){this.collectionsDir=e}ensureDirectory(){Le.existsSync(this.collectionsDir)||Le.mkdirSync(this.collectionsDir,{recursive:!0})}loadAll(){if(this.cache.clear(),!Le.existsSync(this.collectionsDir))return[];let e=Le.readdirSync(this.collectionsDir),t=[];for(let n of e)if(n.endsWith(".json"))try{let s=Ic.join(this.collectionsDir,n),i=Le.readFileSync(s,"utf-8"),o=JSON.parse(i);o.id&&o.name&&(this.cache.set(o.id,o),t.push(o))}catch(s){console.error(`[JsonCollectionLoader] Failed to load ${n}:`,s)}return t}load(e){if(this.cache.has(e))return this.cache.get(e);let t=this.getCollectionPath(e);if(Le.existsSync(t))try{let n=Le.readFileSync(t,"utf-8"),s=JSON.parse(n);return this.cache.set(e,s),s}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=le(e.name));let t=this.getCollectionPath(e.id),n=JSON.stringify(e,null,2);await Le.promises.writeFile(t,n,"utf-8"),this.cache.set(e.id,e)}async delete(e){let t=this.getCollectionPath(e);if(!Le.existsSync(t))return!1;try{return await Le.promises.unlink(t),this.cache.delete(e),!0}catch(n){return console.error(`[JsonCollectionLoader] Failed to delete collection ${e}:`,n),!1}}exists(e){return Le.existsSync(this.getCollectionPath(e))}getCollectionPath(e){return Ic.join(this.collectionsDir,`${e}.json`)}getItemPath(e,t){}async create(e,t){let n={id:t||le(e),name:e,items:[]};return await this.save(n),n}async saveScripts(e,t,n){let s=this.load(e);if(!s)throw new Error(`Collection ${e} not found`);let i=Ee(s.items,t);i&&(i.scripts=n,await this.save(s))}loadScripts(e,t){let n=this.load(e);return n?Ee(n.items,t)?.scripts:void 0}async updateCollectionMetadata(e,t){let n=this.load(e);if(!n)throw new Error(`Collection ${e} not found`);t.name!==void 0&&(n.name=t.name),t.description!==void 0&&(n.description=t.description),t.version!==void 0&&(n.version=t.version),t.variables!==void 0&&(n.variables=t.variables),t.auth!==void 0&&(n.auth=t.auth),await this.save(n)}async saveItem(e,t,n){let s=this.load(e);if(!s)throw new Error(`Collection ${e} not found`);let i=Ee(s.items,t.id);if(i)Object.assign(i,t);else if(n){let o=Ee(s.items,n);if(o&&o.type==="folder")o.items=o.items||[],o.items.push(t);else throw new Error(`Parent folder ${n} not found`)}else s.items.push(t);await this.save(s)}async deleteItem(e,t){let n=this.load(e);if(!n)return!1;let s=en(n.items,t);return s&&await this.save(n),s}async updateItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=Ee(s.items,t);if(!i)return!1;let{id:o,type:a,...c}=n;return Object.assign(i,c),await this.save(s),!0}async moveItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=Ee(s.items,t);if(!i)return!1;let o={...i};if(!en(s.items,t))return!1;if(n){let a=Ee(s.items,n);if(a&&a.type==="folder")a.items=a.items||[],a.items.push(o);else return s.items.push(o),!1}else s.items.push(o);return await this.save(s),!0}async reorderItems(e,t,n){let s=this.load(e);if(!s)return!1;try{let i;if(t){let c=Ee(s.items,t);if(!c||!c.items)return!1;i=c.items}else i=s.items;let o=new Map(i.map(c=>[c.id,c])),a=[];for(let c of n){let l=o.get(c);l&&(a.push(l),o.delete(c))}for(let c of o.values())a.push(c);if(t){let c=Ee(s.items,t);c&&(c.items=a)}else s.items=a;return await this.save(s),!0}catch(i){return console.error("[JsonCollectionLoader] Failed to reorder items:",i),!1}}}});var js,Oc=k(()=>{"use strict";Qi();Tc();js=class{static create(e){let t=e.getStorageConfig(),n=e.getCollectionsPath();return t.format==="folder"?new nn(n):new _r(n)}static createForFormat(e,t){return e==="folder"?new nn(t):new _r(t)}}});import*as he from"fs";import*as bt from"path";function Md(r){if(typeof r!="string")return"text";let e=r.trim();try{let t=JSON.parse(e);if(typeof t=="object"&&t!==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 dg(r){return{info:{name:r.name,_postman_id:r.id,schema:"https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},item:r.items.map(e=>jd(e)),event:$c(r.scripts),variable:r.variables?Object.entries(r.variables).map(([e,t])=>({key:e,value:t})):[]}}function jd(r){if(r.type==="folder")return{name:r.name,item:r.items?r.items.map(jd):[],event:$c(r.scripts)};if(r.type==="request"){let e=r;return{name:e.name,request:{method:e.method,header:(e.headers||[]).map(pg),url:fg(e),body:mg(e),auth:hg(e.auth),description:e.description},event:$c(e.scripts),protocolProfileBehavior:gg(e.settings)}}}function pg(r){return{key:r.key,value:r.value,disabled:r.enabled===!1,...r.description!==void 0?{description:r.description}:{},...r.type!==void 0?{type:r.type}:{},...r.required!==void 0?{required:r.required}:{},...r.format!==void 0?{format:r.format}:{},...r.enum!==void 0?{enum:r.enum}:{},...r.deprecated!==void 0?{deprecated:r.deprecated}:{},...r.pattern!==void 0?{pattern:r.pattern}:{},...r.minLength!==void 0?{minLength:r.minLength}:{},...r.maxLength!==void 0?{maxLength:r.maxLength}:{},...r.minimum!==void 0?{minimum:r.minimum}:{},...r.maximum!==void 0?{maximum:r.maximum}:{},...r.exclusiveMinimum!==void 0?{exclusiveMinimum:r.exclusiveMinimum}:{},...r.exclusiveMaximum!==void 0?{exclusiveMaximum:r.exclusiveMaximum}:{},...r.multipleOf!==void 0?{multipleOf:r.multipleOf}:{},...r.minItems!==void 0?{minItems:r.minItems}:{},...r.maxItems!==void 0?{maxItems:r.maxItems}:{},...r.uniqueItems!==void 0?{uniqueItems:r.uniqueItems}:{},...r.nullable!==void 0?{nullable:r.nullable}:{},...r.oneOf!==void 0?{oneOf:r.oneOf}:{}}}function fg(r){let e=r.url,t=r.url.replace(/^[a-zA-Z]+:\/\//,""),n=[],s=t.match(/^([^\/\?]+)/);if(s){let l=s[1];/^{{.*}}$/.test(l)?n=[l]:n=l.split(".")}let i=[],o=t.match(/^[^\/\?]+(\/[^\?]*)?/);if(o&&o[1]!==void 0){let l=o[1].replace(/^\//,"");l.endsWith("/")?(i=l.slice(0,-1).split("/"),i.push("")):i=l.length>0?l.split("/"):[]}let a;if(Array.isArray(r.query)&&r.query.length>0)a=r.query.map(l=>{let u={key:l.key,value:l.value};return l.enabled===!1&&(u.disabled=!0),l.description!==void 0&&(u.description=l.description),l.type!==void 0&&(u.type=l.type),l.required!==void 0&&(u.required=l.required),l.format!==void 0&&(u.format=l.format),l.enum!==void 0&&(u.enum=l.enum),l.deprecated!==void 0&&(u.deprecated=l.deprecated),l.pattern!==void 0&&(u.pattern=l.pattern),l.minLength!==void 0&&(u.minLength=l.minLength),l.maxLength!==void 0&&(u.maxLength=l.maxLength),l.minimum!==void 0&&(u.minimum=l.minimum),l.maximum!==void 0&&(u.maximum=l.maximum),l.exclusiveMinimum!==void 0&&(u.exclusiveMinimum=l.exclusiveMinimum),l.exclusiveMaximum!==void 0&&(u.exclusiveMaximum=l.exclusiveMaximum),l.multipleOf!==void 0&&(u.multipleOf=l.multipleOf),l.minItems!==void 0&&(u.minItems=l.minItems),l.maxItems!==void 0&&(u.maxItems=l.maxItems),l.uniqueItems!==void 0&&(u.uniqueItems=l.uniqueItems),l.nullable!==void 0&&(u.nullable=l.nullable),l.oneOf!==void 0&&(u.oneOf=l.oneOf),u});else{let l=t.indexOf("?");l!==-1&&(a=t.substring(l+1).split("&").map(d=>{let[p,...m]=d.split("=");return{key:p,value:m.join("=")}}))}let c;return r.params&&typeof r.params=="object"&&(c=Object.entries(r.params).map(([l,u])=>({key:l,value:String(u)}))),{raw:e,host:n.length>0?n:void 0,path:i.length>0?i:void 0,query:a&&a.length>0?a:void 0,variable:c&&c.length>0?c:void 0}}function mg(r){if(!r.body)return;let e=r.body;if(typeof e=="string"){let i=Md(e);return{mode:"raw",raw:e,options:{raw:{language:i}}}}if(e.type==="raw"){let i=e.format||Md(e.content);return{mode:"raw",raw:e.content,options:{raw:{language:i}}}}let t=e.type==="form-data"&&Array.isArray(e.content)?e.content:e.type==="formdata"&&Array.isArray(e.fields)?e.fields:null;if(t)return{mode:"formdata",formdata:t.map(i=>({key:i.key,value:i.value,type:i.type||"text",disabled:i.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(i=>({key:i.key,value:i.value,disabled:i.enabled===!1}))};if(e.type==="file"&&e.fileName)return{mode:"file",file:{src:e.fileName}};if(e.type==="binary")return{mode:"binary",file:{}};let s=e.type==="graphql"?e.content??(e.query?e:null):null;if(s){let i=s.query??"",o=s.variables;return{mode:"graphql",graphql:{query:i,variables:o?typeof o=="string"?o:JSON.stringify(o):void 0}}}if(e.content)return{mode:"raw",raw:e.content}}function hg(r){if(!(!r||!r.type||r.type==="none")){if(r.type==="bearer")return{type:"bearer",bearer:[{key:"token",value:r.bearerToken,type:"string"}]};if(r.type==="basic"&&r.basicAuth)return{type:"basic",basic:[{key:"username",value:r.basicAuth.username,type:"string"},{key:"password",value:r.basicAuth.password,type:"string"}]}}}function gg(r){if(!r)return;let e={};return r.followRedirects===!1&&(e.followRedirects=!1),r.followOriginalMethod===!0&&(e.followOriginalHttpMethod=!0),r.followAuthHeader===!1&&(e.followAuthorizationHeader=!1),r.maxRedirects!==void 0&&(e.maxRedirects=r.maxRedirects),r.strictSSL===!1&&(e.disableUrlEncoding=!1),r.timeout!==void 0&&(e.requestTimeout=r.timeout),Object.keys(e).length>0?e:void 0}function $c(r){if(!r)return[];let e=[];return r.preRequest&&e.push({listen:"prerequest",script:{type:"text/javascript",exec:[r.preRequest]}}),r.postResponse&&e.push({listen:"test",script:{type:"text/javascript",exec:[r.postResponse]}}),e}var Ls,Fc=k(()=>{"use strict";Ze();go();Oc();rc();tn();Ls=class{constructor(e,t){this.configService=e;this.fileWatcherFactory=t;this.collectionsDir=e.getCollectionsPath(),this.loader=js.create(e),this.loadCollections(),this.setupFileWatcher()}configService;fileWatcherFactory;collectionsDir;collections=new Map;fileWatcher;loader;debounceTimer=null;selfWritePending=!1;localCollectionValues=new Map;onCollectionsChanged;ensureCollectionsDir(){he.existsSync(this.collectionsDir)||he.mkdirSync(this.collectionsDir,{recursive:!0})}loadCollections(){this.collections.clear();let e=this.loader.loadAllLight?.()??this.loader.loadAll();for(let t of e)this.collections.set(t.id,t)}getRequestDetail(e,t){let n=this.loader.loadRequestDetail?.(e,t);return n||this.findRequest(e,t)}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 t=this.selfWritePending;this.selfWritePending=!1,t||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 t of this.collections.values())if(t.id===e)return t}getCollectionByName(e){let t=e.toLowerCase();for(let n of this.collections.values())if(n.name.toLowerCase()===t)return n}async saveCollection(e){if(this.ensureCollectionsDir(),!e.name)throw new Error("Collection name is required");e.id||(e.id=le(e.name)),this.selfWritePending=!0,await this.loader.save(e),this.collections.set(e.id,e)}getCollectionVariables(e){let t=this.collections.get(e);return t?.variables?{...t.variables}:{}}getCollectionVariableLocals(e){return{...this.localCollectionValues.get(e)||{}}}setCollectionVariable(e,t,n){this.localCollectionValues.has(e)||this.localCollectionValues.set(e,{}),this.localCollectionValues.get(e)[t]=String(n)}deleteCollectionVariable(e,t){let n=this.localCollectionValues.get(e);n&&delete n[t]}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,t){let n=this.collections.get(e);if(!n)return;let s=this.findItemRecursive(n.items,t);if(s){if(Tn(s)){let i=this.loader.loadRequestDetail?.(e,t);if(zi(i??s),i)return i}return s}}findRequestByPath(e,t){let n=this.collections.get(e);if(!n)return;let s=t.split("/").filter(i=>i.trim());return this.findItemByPath(n.items,s)}async updateRequest(e,t,n){let s=this.collections.get(e);if(!s)return!1;this.selfWritePending=!0;let i=await this.loader.updateItem(e,t,n);if(i){let o=this.findItemRecursive(s.items,t);if(o){let{id:a,type:c,...l}=n;Object.assign(o,l)}}return i}async addRequest(e,t,n){if(!this.collections.get(e))return!1;t.id||(t.id=le(t.name)),this.selfWritePending=!0;try{return await this.loader.saveItem(e,t,n),!0}catch(i){return console.error("[CollectionService] Failed to add request:",i),!1}}async deleteRequest(e,t){let n=this.collections.get(e);if(!n)return!1;this.selfWritePending=!0;let s=await this.loader.deleteItem(e,t);return s&&this.deleteItemRecursive(n.items,t),s}getAllRequests(e){let t=this.collections.get(e);if(!t)return[];let n=[];return this.collectRequestsRecursive(t.items,n),n}findItemRecursive(e,t){for(let n of e){if(n.id===t)return n;if(n.type==="folder"&&n.items){let s=this.findItemRecursive(n.items,t);if(s)return s}}}findItemByPath(e,t){if(t.length===0)return;let[n,...s]=t,i=e.find(o=>o.name===n);if(i){if(s.length===0)return i;if(i.type==="folder"&&i.items)return this.findItemByPath(i.items,s)}}deleteItemRecursive(e,t){for(let n=0;n<e.length;n++){let s=e[n];if(s.id===t)return e.splice(n,1),!0;if(s.type==="folder"&&s.items&&this.deleteItemRecursive(s.items,t))return!0}return!1}collectRequestsRecursive(e,t){for(let n of e)n.type==="request"?t.push(n):n.type==="folder"&&n.items&&this.collectRequestsRecursive(n.items,t)}async createCollection(e){let t={id:le(e),name:e,items:[]};return await this.saveCollection(t),t}async renameCollection(e,t){let n=this.collections.get(e);return n?(n.name=t,await this.saveCollection(n),!0):!1}async duplicateCollection(e,t){if(!this.collections.get(e))throw new Error(`Collection not found: ${e}`);this.selfWritePending=!0;let s=le(t),i=this.loader.getCollectionPath(e),o=bt.join(this.collectionsDir,s);if(!he.existsSync(i))throw new Error(`Collection directory not found: ${i}`);this.copyDirRecursive(i,o);let a=bt.join(o,"collection.json");if(he.existsSync(a)){let l=JSON.parse(he.readFileSync(a,"utf-8"));l.id=s,l.name=t,he.writeFileSync(a,JSON.stringify(l,null,2))}else he.writeFileSync(a,JSON.stringify({id:s,name:t},null,2));this.loadCollections();let c=this.collections.get(s);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:le(e.name),type:"folder",name:e.name,items:[]};await this.loader.saveItem(e.collectionId,n,e.parentId);let s=this.loader.load(e.collectionId);return s&&this.collections.set(e.collectionId,s),n}async deleteFolder(e,t){let n=this.collections.get(e);if(!n)return!1;this.selfWritePending=!0;let s=await this.loader.deleteItem(e,t);return s&&en(n.items,t),s}async renameFolder(e,t,n){let s=this.collections.get(e);if(!s)return!1;this.selfWritePending=!0;let i=await this.loader.updateItem(e,t,{name:n});if(i){let o=Ee(s.items,t);o&&(o.name=n)}return i}async duplicateFolder(e,t,n){if(!this.collections.get(e))throw new Error("Collection not found");let i=this.loader.getItemPath(e,t);if(!i||!he.existsSync(i))throw new Error(`Folder not found on disk: ${t}`);let o=bt.dirname(i),a=le(n),c=bt.join(o,a);this.selfWritePending=!0,this.copyDirRecursive(i,c);let l=bt.join(c,"folder.json");if(he.existsSync(l)){let p=JSON.parse(he.readFileSync(l,"utf-8"));p.id=a,p.name=n,he.writeFileSync(l,JSON.stringify(p,null,2))}else he.writeFileSync(l,JSON.stringify({id:a,name:n,type:"folder"},null,2));this.loadCollections();let u=this.collections.get(e),d=u?Ee(u.items,a):void 0;return d||{id:a,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||le(e.name),type:"request",name:e.name,requestType:e.requestType,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,websocket:e.websocket,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 s=this.loader.load(e.collectionId);return s&&this.collections.set(e.collectionId,s),n}async renameRequest(e,t,n){let s=this.collections.get(e);if(!s)return!1;this.selfWritePending=!0;let i=await this.loader.updateItem(e,t,{name:n});if(i){let o=Ee(s.items,t);o&&(o.name=n)}return i}async moveItem(e,t,n){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let i=await this.loader.moveItem(e,t,n);return i&&this.loadCollections(),i}async reorderItems(e,t,n){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let i=await this.loader.reorderItems(e,t,n);return i&&this.loadCollections(),i}getRequestScript(e,t,n){let s=this.findRequest(e,t);if(s)return n==="pre-request"?s.scripts?.preRequest:s.scripts?.postResponse}async setRequestScript(e,t,n,s){let i=this.collections.get(e);if(!i)return!1;let o=Ee(i.items,t);if(!o||o.type!=="request")return!1;let a=o,l={...a.scripts??{},...n==="pre-request"?{preRequest:s}:{postResponse:s}};a.scripts=l,this.selfWritePending=!0;try{return await this.loader.saveScripts(e,t,l),!0}catch{return!1}}copyDirRecursive(e,t){he.existsSync(t)||he.mkdirSync(t,{recursive:!0});for(let n of he.readdirSync(e,{withFileTypes:!0})){let s=bt.join(e,n.name),i=bt.join(t,n.name);n.isDirectory()?this.copyDirRecursive(s,i):he.copyFileSync(s,i)}}async importCollection(e){let t=he.readFileSync(e,"utf-8"),n;try{n=JSON.parse(t)}catch{throw new Error("Invalid JSON file")}if(n.info&&n.info._postman_id)return this.importPostmanCollection(n);let s={id:n.id||le(n.name||"Imported Collection"),name:n.name||"Imported Collection",description:n.description,items:n.items||[]};return await this.saveCollection(s),s}async importPostmanCollection(e){let t=p=>{if(!p)return;switch(p.type?.toLowerCase()){case"bearer":return{type:"bearer",bearerToken:p.bearer?.find(b=>b.key==="token")?.value||""};case"basic":let h=p.basic?.find(b=>b.key==="username"),g=p.basic?.find(b=>b.key==="password");return{type:"basic",basicAuth:{username:h?.value||"",password:g?.value||""}};case"apikey":let v=p.apikey?.find(b=>b.key==="key"),y=p.apikey?.find(b=>b.key==="value"),S=p.apikey?.find(b=>b.key==="in");return{type:"apikey",apikey:{key:v?.value||"",value:y?.value||"",in:S?.value||"header"}};case"noauth":return{type:"none"};default:return}},n=p=>{if(!Array.isArray(p)||p.length===0)return;let m={};for(let f of p){let h=f.script?.exec;if(!h)continue;let g=Array.isArray(h)?h.join(`
|
|
604
|
-
`):h;f.listen==="prerequest"?m.preRequest=g:f.listen==="test"&&(m.postResponse=g)}return m.preRequest||m.postResponse?m:void 0},s=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},i=p=>{if(!p||typeof p=="string")return;let m=p.query;if(!(!Array.isArray(m)||m.length===0))return m.map(f=>({key:f.key||"",value:f.value||"",enabled:f.disabled!==!0,...f.description!==void 0?{description:f.description}:{},...f.type!==void 0?{type:f.type}:{},...f.required!==void 0?{required:f.required}:{},...f.format!==void 0?{format:f.format}:{},...f.enum!==void 0?{enum:f.enum}:{},...f.deprecated!==void 0?{deprecated:f.deprecated}:{},...f.pattern!==void 0?{pattern:f.pattern}:{},...f.minLength!==void 0?{minLength:f.minLength}:{},...f.maxLength!==void 0?{maxLength:f.maxLength}:{},...f.minimum!==void 0?{minimum:f.minimum}:{},...f.maximum!==void 0?{maximum:f.maximum}:{},...f.exclusiveMinimum!==void 0?{exclusiveMinimum:f.exclusiveMinimum}:{},...f.exclusiveMaximum!==void 0?{exclusiveMaximum:f.exclusiveMaximum}:{},...f.multipleOf!==void 0?{multipleOf:f.multipleOf}:{},...f.minItems!==void 0?{minItems:f.minItems}:{},...f.maxItems!==void 0?{maxItems:f.maxItems}:{},...f.uniqueItems!==void 0?{uniqueItems:f.uniqueItems}:{},...f.nullable!==void 0?{nullable:f.nullable}:{},...f.oneOf!==void 0?{oneOf:f.oneOf}:{}}))},o=p=>{if(typeof p=="string")return p;if(!p)return"";let m=new Set;if(Array.isArray(p.variable))for(let h of p.variable)h.key&&m.add(h.key);if(m.size===0&&p.raw)return p.raw;let f="";if(p.protocol&&(f+=p.protocol+"://"),p.host&&(f+=Array.isArray(p.host)?p.host.join("."):p.host),p.port&&(f+=":"+p.port),p.path){let g=(Array.isArray(p.path)?p.path:[p.path]).map(v=>{let y=v.startsWith(":")?v.substring(1):v;return m.has(y)?":"+y:(v.startsWith(":"),v)});f+="/"+g.join("/")}return!f&&p.raw?p.raw:f},a=p=>{if(!Array.isArray(p)||p.length===0)return;let m={responses:{}};for(let f of p){let h=String(f.code||200),g,v={};if(Array.isArray(f.header))for(let w of f.header)!w.key||w.disabled||(w.key.toLowerCase()==="content-type"?g=w.value?.split(";")[0]?.trim():v[w.key]={description:String(w.value??""),schema:{type:"string"}});let y=f.body;if(typeof f.body=="string"&&f.body)try{y=JSON.parse(f.body)}catch{}let S=f.originalRequest,b;if(S){let w=typeof S.url=="string"?S.url:S.url?.raw??"";b=`${S.method||""} ${w}`.trim()||void 0}let C=f.name?f.name.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toLowerCase()||`example_${h}`:`example_${h}`;if(m.responses[h]){let w=m.responses[h];w.examples=w.examples??{},w.examples[C]={summary:b,value:y}}else m.responses[h]={description:f.name,contentType:g,examples:{[C]:{summary:b,value:y}},...Object.keys(v).length>0?{headers:v}:{}}}return Object.keys(m.responses).length>0?m:void 0},c=p=>!(!p||typeof p!="object"||p.item===void 0&&p.request===void 0&&(p.listen!==void 0||p.script!==void 0)),l=p=>p.filter(c).map(m=>{if(m.item)return{id:le(m.name),type:"folder",name:m.name||"Folder",description:m.description,auth:t(m.auth),scripts:n(m.event),items:l(m.item)};{let f=m.request||{};return{id:le(m.name),type:"request",name:m.name||f.method||"Request",description:m.description||f.description,method:typeof f.method=="string"?f.method:"GET",url:o(f.url),query:i(f.url),headers:Array.isArray(f.header)?f.header.map(h=>({key:h.key||h.name||"",value:h.value||h.value||"",enabled:h.disabled!==!0,...h.description!==void 0?{description:h.description}:{},...h.type!==void 0?{type:h.type}:{},...h.required!==void 0?{required:h.required}:{},...h.format!==void 0?{format:h.format}:{},...h.enum!==void 0?{enum:h.enum}:{},...h.deprecated!==void 0?{deprecated:h.deprecated}:{},...h.pattern!==void 0?{pattern:h.pattern}:{},...h.minLength!==void 0?{minLength:h.minLength}:{},...h.maxLength!==void 0?{maxLength:h.maxLength}:{},...h.minimum!==void 0?{minimum:h.minimum}:{},...h.maximum!==void 0?{maximum:h.maximum}:{},...h.exclusiveMinimum!==void 0?{exclusiveMinimum:h.exclusiveMinimum}:{},...h.exclusiveMaximum!==void 0?{exclusiveMaximum:h.exclusiveMaximum}:{},...h.multipleOf!==void 0?{multipleOf:h.multipleOf}:{},...h.minItems!==void 0?{minItems:h.minItems}:{},...h.maxItems!==void 0?{maxItems:h.maxItems}:{},...h.uniqueItems!==void 0?{uniqueItems:h.uniqueItems}:{},...h.nullable!==void 0?{nullable:h.nullable}:{},...h.oneOf!==void 0?{oneOf:h.oneOf}:{}})):[],body:(()=>{let h=f.body;if(h){if(h.mode==="raw"&&h.raw){let g=h.options?.raw?.language;return{type:"raw",format:g==="xml"?"xml":g==="html"?"html":g==="javascript"?"javascript":g==="text"?"text":"json",content:h.raw}}if(h.mode==="urlencoded"&&Array.isArray(h.urlencoded))return{type:"x-www-form-urlencoded",content:h.urlencoded.map(g=>({key:g.key||"",value:g.value||"",enabled:g.disabled!==!0}))};if(h.mode==="formdata"&&Array.isArray(h.formdata))return{type:"form-data",content:h.formdata.map(g=>({key:g.key||"",value:g.value||"",type:g.type||"text",enabled:g.disabled!==!0}))};if(h.mode==="graphql"&&h.graphql){let g;if(h.graphql.variables)try{g=JSON.parse(h.graphql.variables)}catch{g=void 0}return{type:"graphql",content:{query:h.graphql.query||"",variables:g}}}if(h.mode==="binary")return{type:"binary",content:""}}})(),auth:t(f.auth),scripts:n(m.event),settings:s(m.protocolProfileBehavior),responseSchema:a(m.response)}}}),u=l(e.item||[]),d={id:le(e.info?.name||"Imported Postman Collection"),name:e.info?.name||"Imported Postman Collection",description:e.info?.description,auth:t(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:u};return await this.saveCollection(d),d}async exportCollection(e,t){let n=this.collections.get(e);if(!n)throw new Error("Collection not found");let s=dg(n),i=JSON.stringify(s,null,2);he.writeFileSync(t,i,"utf-8")}async exportCollectionAsRestClientFolder(e,t){let n=this.collections.get(e);if(!n)throw new Error("Collection not found");let s=bt.join(t,xe(n.name));he.mkdirSync(s,{recursive:!0});let i=n.variables||{};Nr(bt.join(s,`${xe(n.name)}.env`),i),Ms(s,xe(n.name),n.scripts),ho(n.items,s,n)}dispose(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.fileWatcher?.dispose()}}});var se,Wn,on,Nc=k(()=>{"use strict";se={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,report:{maxBodyChars:1e5,embedBodies:"failed"}},environments:{default:"dev"},restClientExport:{path:"collections-rest-client",mergeGlobals:!0},discovery:{customSeedLoaderModulePath:void 0,frameworks:["auto"],contextProperties:["locals"],skipComponentAnalysis:!1},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"}}}},Wn={preferred:".http-forge/http-forge.config.json",legacy:"http-forge.config.json"},on={collections:"collections",environments:"environments",flows:"flows",suites:"suites"}});import*as ee from"fs";import*as L from"path";var an,yo=k(()=>{"use strict";Nc();an=class{constructor(e,t,n){this.workspacePath=e;this.fileWatcherFactory=t;this.notifications=n;this.workspacePath=this.normalizeWorkspacePath(e),this.configPath=this.resolveConfigPath(),this.configDir=L.dirname(this.configPath),this.config=this.loadConfig(),this.setupFileWatcher()}workspacePath;fileWatcherFactory;notifications;config;configPath;configDir;fileWatchers=[];_standaloneProbeCache;_cachedWorkspaceNormalization;isStandaloneLayoutCached(){let e=Date.now();if(this._standaloneProbeCache&&e-this._standaloneProbeCache.ts<5e3)return this._standaloneProbeCache.value;let t=ee.existsSync(L.join(this.workspacePath,"assets")),n=ee.existsSync(L.join(this.workspacePath,".http-forge")),s=t&&!n;return this._standaloneProbeCache={key:this.workspacePath,value:s,ts:e},s}normalizeWorkspacePath(e){if(this._cachedWorkspaceNormalization&&this._cachedWorkspaceNormalization.input===e)return this._cachedWorkspaceNormalization.result;let t=L.resolve(e),n=L.basename(t),s=a=>ee.existsSync(L.join(a,"assets","collections"))||ee.existsSync(L.join(a,"collections"))||ee.existsSync(L.join(a,"environments"))||ee.existsSync(L.join(a,"http-forge.config.json"))?!0:ee.existsSync(L.join(a,".http-forge","http-forge.config.json"))?!1:ee.existsSync(L.join(a,"assets")),i=a=>!!(ee.existsSync(L.join(a,"collections"))||ee.existsSync(L.join(a,"environments"))||ee.existsSync(L.join(a,"suites"))),o;if(n===".http-forge")o=s(t)?t:L.dirname(t);else if(n==="assets")if(!i(t))o=t;else{let a=L.dirname(t);L.basename(a)===".http-forge"?o=L.dirname(a):o=a}else o=t;return this._cachedWorkspaceNormalization={input:e,result:o},o}resolveConfigPath(){let e=L.join(this.workspacePath,Wn.legacy),t=L.join(this.workspacePath,Wn.preferred);return ee.existsSync(e)?e:ee.existsSync(t)||ee.existsSync(L.join(this.workspacePath,".http-forge"))?t:this.hasFolderCollectionsAtRoot(L.join(this.workspacePath,"assets"))||ee.existsSync(L.join(this.workspacePath,"assets"))||this.hasFolderCollectionsAtRoot(this.workspacePath)?e:t}loadConfig(){if(this.configPath=this.resolveConfigPath(),this.configDir=L.dirname(this.configPath),!ee.existsSync(this.configPath))return{...se};try{let e=ee.readFileSync(this.configPath,"utf-8"),t=JSON.parse(e);return this.mergeWithDefaults(t)}catch(e){return console.error("[ConfigService] Failed to load config:",e),this.notifications?.showWarning(`Failed to parse ${L.relative(this.workspacePath,this.configPath)}. Using default configuration.`),{...se}}}mergeWithDefaults(e){return{version:e.version??se.version,storage:{...se.storage,...e.storage},request:{...se.request,...e.request},scripts:{...se.scripts,...e.scripts},runner:{...se.runner,...e.runner,report:{...se.runner.report,...e.runner?.report}},environments:{...se.environments,...e.environments},restClientExport:{...se.restClientExport,...e.restClientExport},proxy:e.proxy!==void 0?e.proxy:se.proxy,discovery:{...se.discovery,...e.discovery},mcp:{...se.mcp,...e.mcp,cors:{...se.mcp.cors,...e.mcp?.cors}},secrets:{...se.secrets,...e.secrets,providers:{...se.secrets?.providers,...e.secrets?.providers}}}}setupFileWatcher(){if(!this.fileWatcherFactory)return;let e=()=>{this.reload()};for(let t of[Wn.preferred,Wn.legacy]){let n=this.fileWatcherFactory.createFileWatcher(this.workspacePath,t);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(){let e=this.config.runner,t=e.report??se.runner.report,n=["all","failed","none"];return{...e,report:{maxBodyChars:Math.max(1e3,Math.floor(t.maxBodyChars??se.runner.report.maxBodyChars)),embedBodies:n.includes(t.embedBodies)?t.embedBodies:se.runner.report.embedBodies}}}getEnvironmentsConfig(){return this.config.environments}getRestClientExportPath(){let e=this.config.restClientExport?.path||"collections-rest-client";return L.isAbsolute(e)?e:this.resolvePath(e)}getRestClientMergeGlobals(){return this.config.restClientExport?.mergeGlobals??!0}getProxyConfig(){return this.config.proxy??null}getDiscoveryConfig(){let e=this.config.discovery??se.discovery;return{customSeedLoaderModulePath:e.customSeedLoaderModulePath,frameworks:e.frameworks??se.discovery.frameworks,contextProperties:e.contextProperties??se.discovery.contextProperties,skipComponentAnalysis:e.skipComponentAnalysis??se.discovery.skipComponentAnalysis}}getMcpConfig(){let e=this.config.mcp??se.mcp,t=["flat","drilldown","auto","execution-only"];return{...e,port:Math.min(65535,Math.max(1,Math.floor(e.port??3100))),toolMode:t.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){if(L.isAbsolute(e))return e;let t=e.startsWith("./")?e.slice(2):e,n=this.configExists()?this.configDir:this.workspacePath,s=t;return L.basename(n)===".http-forge"?(s===".http-forge"||s.startsWith(".http-forge/"))&&(s=s.slice(12)):n===this.workspacePath&&s.startsWith(".http-forge/")&&this.isStandaloneLayoutCached()&&(s=s.slice(12)),s?L.join(n,...s.split("/").filter(i=>i!==""&&i!==".")):n}hasFolderCollectionsAtRoot(e){let t=L.join(e,on.collections);if(!ee.existsSync(t))return!1;let n;try{n=ee.readdirSync(t,{withFileTypes:!0})}catch{return!1}return n.some(s=>{if(!s.isDirectory())return!1;let i=L.join(t,s.name,"collection.json");return ee.existsSync(i)})}hasAnyEntries(e){if(!ee.existsSync(e))return!1;try{return ee.readdirSync(e).length>0}catch{return!1}}resolveStorageRootPath(){let e=this.resolvePath(this.config.storage.root);if(this.configExists()||this.hasFolderCollectionsAtRoot(e))return e;let n=[L.join(this.workspacePath,".http-forge","assets"),L.join(this.workspacePath,"assets"),L.join(this.workspacePath,"http-forge-assets"),this.workspacePath].find(i=>this.hasFolderCollectionsAtRoot(i));if(n)return n;let s=L.join(this.workspacePath,"assets");return this.hasFolderCollectionsAtRoot(s)?s:e}getRootPath(){return this.resolveStorageRootPath()}getCollectionsPath(){return L.join(this.getRootPath(),on.collections)}getEnvironmentsPath(){return L.join(this.getRootPath(),on.environments)}getFlowsPath(){return L.join(this.getRootPath(),on.flows)}getHistoryPath(){let e=this.resolvePath(this.config.storage.history);return this.configExists()||this.hasAnyEntries(e)?e:[L.join(this.workspacePath,".http-forge",".cache","histories"),L.join(this.workspacePath,".cache","histories"),L.join(this.workspacePath,".http-forge-cache","histories"),L.join(this.getRootPath(),".cache","histories")].find(s=>this.hasAnyEntries(s))||e}getResultsPath(){let e=this.resolvePath(this.config.storage.results);return this.configExists()||this.hasAnyEntries(e)?e:[L.join(this.workspacePath,".http-forge",".cache","results"),L.join(this.workspacePath,".cache","results"),L.join(this.workspacePath,".http-forge-cache","results"),L.join(this.getRootPath(),".cache","results")].find(s=>this.hasAnyEntries(s))||e}getSuitesPath(){return L.join(this.getRootPath(),on.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}onConfigReloaded;reload(){this.configPath=this.resolveConfigPath(),this.configDir=L.dirname(this.configPath),this.config=this.loadConfig(),this.onConfigReloaded?.()}configExists(){return ee.existsSync(this.configPath)||ee.existsSync(this.resolveConfigPath())}getDefaultConfigForCurrentLocation(){if(L.basename(this.configDir)===".http-forge")return{...se,storage:{...se.storage,root:"./assets",history:"./.cache/histories",results:"./.cache/results"},scripts:{...se.scripts,modulePaths:["./assets/src","./assets/lib"]}};let e=ee.existsSync(L.join(this.workspacePath,"assets")),t=ee.existsSync(L.join(this.workspacePath,".http-forge"));return e&&!t?{...se,storage:{...se.storage,root:"./assets",history:"./.cache/histories",results:"./.cache/results"},scripts:{...se.scripts,modulePaths:["./assets/src","./assets/lib"]}}:{...se}}async createDefaultConfig(){this.configPath=this.resolveConfigPath(),this.configDir=L.dirname(this.configPath),await ee.promises.mkdir(L.dirname(this.configPath),{recursive:!0});let e=this.getDefaultConfigForCurrentLocation(),t=JSON.stringify(e,null,2);await ee.promises.writeFile(this.configPath,t,"utf-8");let n=[this.getCollectionsPath(),this.getEnvironmentsPath(),this.getFlowsPath(),this.getSuitesPath()];for(let i of n)ee.existsSync(i)||await ee.promises.mkdir(i,{recursive:!0});let s=[this.getHistoryPath(),this.getResultsPath()];for(let i of s)ee.existsSync(i)||await ee.promises.mkdir(i,{recursive:!0});await this.createSampleEnvironments()}async createSampleEnvironments(){let e=this.getEnvironmentsPath(),t={id:"globals",name:"Global Variables",variables:{appName:"HTTP Forge"}};await ee.promises.writeFile(L.join(e,"globals.json"),JSON.stringify(t,null,2),"utf-8");let n={id:"env_dev",name:"Development",variables:{baseUrl:"http://localhost:3000",apiVersion:"v1"}};await ee.promises.writeFile(L.join(e,"dev.json"),JSON.stringify(n,null,2),"utf-8");let s={id:"default_headers",name:"Default Headers",headers:{"Content-Type":"application/json",Accept:"application/json"}};await ee.promises.writeFile(L.join(e,"default-headers.json"),JSON.stringify(s,null,2),"utf-8")}dispose(){for(let e of this.fileWatchers)e.dispose();this.fileWatchers=[]}}});var yg,Hs,_c=k(()=>{"use strict";$n();yg="httpForge.cookies",Hs=class{constructor(e,t=yg){this.store=e;this.storeKey=t;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((t,n)=>{e[n]=t}),await this.store.update(this.storeKey,e)}catch(e){console.error("[CookieService] Failed to save cookies:",e)}}getCookieKey(e,t,n){return oe.cookieKey(e,t,n)}get(e,t){if(t){let i=this.getCookieKey(e,t),o=this.cookies.get(i);if(o&&!this.isExpired(o))return o}let n=this.getCookieKey(e,"*"),s=this.cookies.get(n);if(s&&!this.isExpired(s))return s;for(let i of this.cookies.values())if(i.name===e&&!this.isExpired(i))if(t&&i.domain){if(this.domainMatches(t,i.domain))return i}else return i}async set(e){let t=this.getCookieKey(e.name,e.domain,e.path);this.cookies.set(t,e),await this.saveCookies()}async setFromResponse(e){for(let t of e){let n=this.getCookieKey(t.name,t.domain,t.path);this.cookies.set(n,t)}await this.saveCookies()}has(e,t){return this.get(e,t)!==void 0}async delete(e,t,n){let s=this.getCookieKey(e,t,n),i=this.cookies.delete(s);return i&&await this.saveCookies(),i}getAll(e){let t=[];for(let n of this.cookies.values())this.isExpired(n)||(e?(!n.domain||this.domainMatches(e,n.domain))&&t.push(n):t.push(n));return t}getCookieHeader(e){let t=this.getAll(e);return oe.formatCookieHeader(t)}async clear(){this.cookies.clear(),await this.saveCookies()}async clearDomain(e){let t=[];for(let[n,s]of this.cookies.entries())s.domain&&this.domainMatches(e,s.domain)&&t.push(n);for(let n of t)this.cookies.delete(n);await this.saveCookies()}parseCookieHeaders(e,t){return oe.parseCookieHeaders(e,t)}isExpired(e){return oe.isExpired(e)}cleanExpiredCookies(){let e=[];for(let[t,n]of this.cookies.entries())this.isExpired(n)&&e.push(t);for(let t of e)this.cookies.delete(t);e.length>0&&this.saveCookies()}domainMatches(e,t){return oe.domainMatches(e,t)}get count(){return this.cookies.size}}});var Bs,Dc=k(()=>{"use strict";$n();Bs=class{constructor(e){this.cookieService=e;this.localCache=[...e.getAll()]}cookieService;localCache=[];pendingOperations=[];get(e,t){return t?this.localCache.find(n=>n.name===e&&(!n.domain||n.domain===t||t.endsWith(n.domain))):this.localCache.find(n=>n.name===e)}has(e,t){return this.get(e,t)!==void 0}set(e){let t=this.localCache.findIndex(n=>n.name===e.name&&(!e.domain||n.domain===e.domain));t>=0?this.localCache[t]=e:this.localCache.push(e),this.pendingOperations.push({type:"set",cookie:e})}delete(e,t,n){let s=this.localCache.findIndex(i=>i.name===e&&(!t||i.domain===t||i.domain&&t.endsWith(i.domain)));return s>=0&&this.localCache.splice(s,1),this.pendingOperations.push({type:"delete",name:e,domain:t,path:n}),!0}getAll(e){return e?this.localCache.filter(t=>{let n=t.domain||"";return n===e||e.endsWith(n)}):[...this.localCache]}getCookiesForDomain(e){return this.localCache.filter(t=>{let n=t.domain||"";return n===e||e.endsWith(n)})}async setCookiesFromResponse(e,t){let n=new URL(e).hostname,s=this.cookieService.parseCookieHeaders(t,n);s.length>0&&(s.forEach(i=>{let o=this.localCache.findIndex(a=>a.name===i.name&&a.domain===(i.domain||n));o>=0?this.localCache[o]=i:this.localCache.push(i)}),await this.cookieService.setFromResponse(s))}getCookieHeader(e){let t=new URL(e).hostname,n=new URL(e).pathname,s=this.localCache.filter(i=>!(oe.isExpired(i)||i.domain&&!oe.domainMatches(t,i.domain)||!i.domain||i.path&&!n.startsWith(i.path)));if(s.length!==0)return oe.formatCookieHeader(s)}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 Mc(r){try{let e=JSON.parse(typeof r=="string"?r:r.toString("utf-8"));if(!e)return null;let t=e.environment||e,n=t.name||e.name||"imported-environment",s=t.values||t.variables||e.values||e.variables||[],i={};if(Array.isArray(s))for(let a of s){if(!a)continue;let c=a.key??a.name,l=typeof a.enabled=="boolean"?a.enabled:!0;c&&l!==!1&&(i[c]=a.value??a.initial??"")}else if(typeof s=="object"&&s!==null)for(let[a,c]of Object.entries(s))i[a]=String(c??"");let o=t._postman_exported_at?"Imported from Postman export":t.description||"";return{name:n,variables:i,description:o}}catch{return null}}var jc=k(()=>{"use strict"});import*as Oe from"fs";import*as et from"path";var Us,Vs,Lc=k(()=>{"use strict";Ze();jc();go();Xi();Ar();Us={SELECTED_ENVIRONMENT:"httpForge.selectedEnvironment",ENV_OVERRIDES_PREFIX:"httpForge.envOverrides."},Vs=class{constructor(e,t,n,s,i,o=!0){this.workspaceFolder=e;this.workspaceStore=t;this.configService=n;this.fileWatcherFactory=s;this.secretStore=i;this.persistOverrides=o;let a=n.getEnvironmentsPath();this.environmentsPath=a,this.sharedConfigPath=et.join(a,"_global.json"),this.localConfigPath=et.join(a,"_global.local.json"),this.historiesPath=n.getHistoryPath(),this.selectedEnvironment=t?.get(Us.SELECTED_ENVIRONMENT,"dev")??"dev",this.localGlobalValues={},this.localEnvironmentValues=new Map,this.persistOverrides&&this.loadPersistedEnvironmentOverrides(),this.loadSecretVariables(this.selectedEnvironment).catch(()=>{}),this.setupFileWatcher(),this.configService.onConfigReloaded=()=>this.invalidateResolvedConfigCache()}workspaceFolder;workspaceStore;configService;fileWatcherFactory;secretStore;persistOverrides;environmentsPath;sharedConfigPath;localConfigPath;historiesPath;sharedConfig=null;localConfig=null;selectedEnvironment="dev";fileWatcher;resolvedConfigCache=new Map;localGlobalValues={};localEnvironmentValues=new Map;secretValuesCache=new Map;onEnvironmentsChanged;setupFileWatcher(){if(!this.fileWatcherFactory||!Oe.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(!Oe.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(Us.SELECTED_ENVIRONMENT,e),!this.localEnvironmentValues.has(e)){let t=this.getEnvOverridesStateKey(e),n=this.workspaceStore?.get(t,{});n&&Object.keys(n).length>0&&this.localEnvironmentValues.set(e,{...n})}await this.loadSecretVariables(e),this.resolvedConfigCache.delete(e)}getEnvOverridesStateKey(e){return`${Us.ENV_OVERRIDES_PREFIX}${e||this.selectedEnvironment}`}loadPersistedEnvironmentOverrides(){let e=this.getEnvOverridesStateKey(),t=this.workspaceStore?.get(e,{});t&&Object.keys(t).length>0&&this.localEnvironmentValues.set(this.selectedEnvironment,{...t})}persistEnvironmentOverrides(e){if(!this.persistOverrides)return;let t=this.getEnvOverridesStateKey(e),n=this.localEnvironmentValues.get(e)||{};this.workspaceStore?.update(t,n)}setEnvironmentVariable(e,t,n){let s=n??this.selectedEnvironment;this.localEnvironmentValues.has(s)||this.localEnvironmentValues.set(s,{}),this.localEnvironmentValues.get(s)[e]=String(t),this.persistEnvironmentOverrides(s)}deleteEnvironmentVariable(e,t){let n=t??this.selectedEnvironment,s=this.localEnvironmentValues.get(n);s&&(delete s[e],this.persistEnvironmentOverrides(n))}clearEnvironmentVariables(e){let t=e??this.selectedEnvironment;this.localEnvironmentValues.set(t,{}),this.persistEnvironmentOverrides(t)}async resetEnvironmentOverrides(e){let t=e||this.selectedEnvironment;this.localEnvironmentValues.delete(t),await this.workspaceStore?.update(this.getEnvOverridesStateKey(t),void 0)}getEnvironmentVariableLocal(e){return this.localEnvironmentValues.get(this.selectedEnvironment)?.[e]}getEnvironmentVariableLocals(){return{...this.localEnvironmentValues.get(this.selectedEnvironment)||{}}}getAllEnvironmentVariableLocals(){let e={};for(let[t,n]of this.localEnvironmentValues)e[t]={...n};return e}setGlobalVariable(e,t){this.localGlobalValues[e]=String(t)}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 t=e||this.selectedEnvironment,n=this.getSharedConfig(),s=this.getLocalConfig();if(!n?.environments?.[t])return null;let i=n.environments[t],o=s?.credentials?.[t],a=s?.variables||{},c=o?.variables||{},l=o&&o.headers||{},u=Vi(n.defaultHeaders||{},l),d=this.localEnvironmentValues.get(t)||{},p=this.secretValuesCache.get(t)||{},m={...i.variables||{},...c,...d,...p};return{name:t,description:i.description,requiresConfirmation:i.requiresConfirmation,headers:u,variables:m}}async getSecretVariable(e,t){return this.secretStore?.get(`${e}:${t}`)}async setSecretVariable(e,t,n){await this.secretStore?.store(`${e}:${t}`,n),this.secretValuesCache.has(e)||this.secretValuesCache.set(e,{}),this.secretValuesCache.get(e)[t]=n}async deleteSecretVariable(e,t){await this.secretStore?.delete(`${e}:${t}`),this.secretValuesCache.get(e)&&delete this.secretValuesCache.get(e)[t]}async loadSecretVariables(e){if(!this.secretStore)return;let t=e||this.selectedEnvironment,n=this.getSharedConfig()?.environments?.[t]?.secretVariables??[];if(n.length===0)return;let s={};await Promise.all(n.map(async i=>{let o=await this.secretStore.get(`${t}:${i}`);o!==void 0&&(s[i]=o)})),this.secretValuesCache.set(t,s)}resolveVariables(e,t){return this.createResolver(t).resolveString(e,!0)}exportEnvironmentsToFolder(e,t=!0){let n=this.getEnvironmentNames(),s=this.getSharedConfig(),i=s?.globalVariables?{...s.globalVariables}:{};if(!t&&Object.keys(i).length){let o=et.join(e,"globals.env");Nr(o,i)}n.forEach(o=>{let a=s?.environments?.[o];if(!a)return;let c={...a.variables||{}};t&&(c={...i,...c});let l=et.join(e,`${xe(o)}.env`);Nr(l,c)})}resolveVariablesWithExtra(e,t,n){return this.createResolver(n,t).resolveString(e,!0)}resolveVariablesInObject(e,t){return this.createResolver(t).resolveObject(e,!0)}resolveVariablesInObjectWithExtra(e,t,n){return this.createResolver(n,t).resolveObject(e,!0)}getHistoriesPath(){return this.historiesPath}getSharedConfigPath(){return this.sharedConfigPath}getLocalConfigPath(){return this.localConfigPath}getEnvironmentConfigPath(e){return et.join(this.environmentsPath,`${e}.json`)}localConfigExists(){return Oe.existsSync(this.localConfigPath)}saveSharedConfig(e){this.saveFolderSharedConfig(e),this.sharedConfig=e}saveLocalConfig(e){let t={variables:e.variables||{}};this.saveJsonFile(this.localConfigPath,t);for(let[n,s]of Object.entries(e.credentials||{})){let i=this.getEnvLocalConfigPath(n),o={variables:s.variables||{}};this.saveJsonFile(i,o)}this.localConfig=e}importPostmanEnvironmentFile(e){try{let t=Oe.readFileSync(e,"utf-8"),n=Mc(t);if(!n)throw new Error("Failed to parse Postman environment file");this.sharedConfig||this.loadConfigs(),this.sharedConfig||(this.sharedConfig={environments:{},globalVariables:{},defaultHeaders:{}});let s=n.name||`imported-${Date.now()}`;return this.sharedConfig.environments=this.sharedConfig.environments||{},this.sharedConfig.environments[s]=this.sharedConfig.environments[s]||{},this.sharedConfig.environments[s].variables=n.variables,n.description&&(this.sharedConfig.environments[s].description=n.description),this.saveSharedConfig(this.sharedConfig),n}catch(t){throw console.error("[EnvironmentConfigService] importPostmanEnvironmentFile failed:",t),t}}saveEnvLocalConfig(e,t){let n=this.getEnvLocalConfigPath(e),s={variables:t};this.saveJsonFile(n,s),this.localConfig||(this.localConfig={credentials:{},variables:{}}),this.localConfig.credentials||(this.localConfig.credentials={}),this.localConfig.credentials[e]={variables:t}}getEnvLocalPath(e){return this.getEnvLocalConfigPath(e)}getEnvLocalConfigPath(e){return et.join(this.environmentsPath,`${e}.local.json`)}loadFolderConfigs(){let e=vs(this.environmentsPath);this.sharedConfig={environments:e.environments,globalVariables:e.globalVariables,defaultHeaders:e.defaultHeaders},this.localConfig={credentials:e.localCredentials,variables:e.localVariables}}createResolver(e,t){let s=this.getResolvedEnvironment(e)?.variables||{},i=this.getGlobalVariables(),o=this.getGlobalVariableLocals();return new Mn({globals:i,collectionVariables:{},environmentVariables:s,variables:{...o,...t||{}}})}saveFolderSharedConfig(e){Oe.existsSync(this.environmentsPath)||Oe.mkdirSync(this.environmentsPath,{recursive:!0});let t={$schema:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/global-environment.schema.json",variables:e.globalVariables||{},defaultHeaders:e.defaultHeaders||{}};this.saveJsonFile(this.sharedConfigPath,t);let n=Oe.readdirSync(this.environmentsPath).filter(i=>i.endsWith(".json")).filter(i=>!Yi(i)),s=new Set(Object.keys(e.environments||{}));for(let i of n){let o=et.basename(i,".json");if(!s.has(o))try{Oe.unlinkSync(et.join(this.environmentsPath,i))}catch{}}for(let[i,o]of Object.entries(e.environments||{})){let a={$schema:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/environment.schema.json",name:i,description:o.description,requiresConfirmation:o.requiresConfirmation,variables:o.variables||{}};this.saveJsonFile(et.join(this.environmentsPath,`${i}.json`),a)}}reload(){this.sharedConfig=null,this.localConfig=null,this.loadConfigs(),this.invalidateResolvedConfigCache()}invalidateResolvedConfigCache(){this.resolvedConfigCache.clear()}getFileOnlyVariables(e){this.loadConfigs();let t=this.sharedConfig,n=this.localConfig,s=t?.environments?.[e];return{...t?.globalVariables||{},...n?.variables||{},...s?.variables||{},...n?.credentials?.[e]?.variables||{}}}resolveConfigValues(e,t){if(e==null)return e;if(typeof e=="string"){let n=new Mn({globals:{},collectionVariables:{},environmentVariables:t,variables:{}});if(/^\s*\{\{.*\}\}\s*$/.test(e)){let s=n.resolveString(e);if(s==="true")return!0;if(s==="false")return!1;let i=Number(s);return s!==""&&!isNaN(i)?i:s}return n.resolveString(e)}if(Array.isArray(e))return e.map(n=>this.resolveConfigValues(n,t));if(typeof e=="object"){let n={};for(let[s,i]of Object.entries(e))n[s]=this.resolveConfigValues(i,t);return n}return e}getResolvedConfig(e){let t=e??this.selectedEnvironment;if(!this.resolvedConfigCache.has(t)){let n=this.configService.getConfig(),s=this.getFileOnlyVariables(t),i=this.resolveConfigValues(n,s);this.resolvedConfigCache.set(t,i)}return this.resolvedConfigCache.get(t)}getAllEnvironments(){return this.loadConfigs(),this.sharedConfig?Object.entries(this.sharedConfig.environments).map(([e,t])=>({id:e,name:e,active:e===this.selectedEnvironment,variables:t.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 t=Object.keys(this.sharedConfig.environments);this.selectedEnvironment=t.length>0?t[0]:"dev",await this.workspaceStore?.update(Us.SELECTED_ENVIRONMENT,this.selectedEnvironment)}this.saveSharedConfig(this.sharedConfig)}async duplicateEnvironment(e,t){this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentName(t),this.validateEnvironmentExists(e),this.validateEnvironmentNameNotTaken(t);let n=this.sharedConfig.environments[e];this.sharedConfig.environments[t]=JSON.parse(JSON.stringify(n)),this.sharedConfig.environments[t].description=`Copied from ${e}`,this.saveSharedConfig(this.sharedConfig)}async renameEnvironment(e,t){this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentName(t),this.validateEnvironmentExists(e),t!==e&&(this.validateEnvironmentNameNotTaken(t),this.sharedConfig.environments[t]=this.sharedConfig.environments[e],delete this.sharedConfig.environments[e],this.selectedEnvironment===e&&(this.selectedEnvironment=t,await this.workspaceStore?.update(Us.SELECTED_ENVIRONMENT,t)),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,t){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=t,this.saveSharedConfig(this.sharedConfig)}saveJsonFile(e,t){try{let n=et.dirname(e);Oe.existsSync(n)||Oe.mkdirSync(n,{recursive:!0}),Oe.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}catch(n){throw console.error(`Failed to save JSON to ${e}:`,n),n}}}});function vg(r){return r?[...new Set(Array.from(r).filter(e=>typeof e=="string"&&e.length>0))]:[]}function Hc(r,e){let t=vg(e);return t.length>0&&Ld.set(r,t),r}function Mr(r){return r?Ld.get(r)??[]:[]}function Bc(r,e){return Hc(e,Mr(r))}function Ud(r){return r.split("{{").join(Hd).split("}}").join(Bd)}function zs(r){return r.split(Hd).join("{{").split(Bd).join("}}")}function Dr(r){if(typeof r=="string")return zs(r);if(Array.isArray(r))return r.map(e=>Dr(e));if(r!==null&&typeof r=="object"){let e=Object.getPrototypeOf(r);if(e!==Object.prototype&&e!==null)return r;let t={};for(let[n,s]of Object.entries(r))t[n]=Dr(s);return t}return r}var Ld,Hd,Bd,jr=k(()=>{"use strict";Ld=new WeakMap,Hd="__HF_SECRET_OPEN__",Bd="__HF_SECRET_CLOSE__"});function Uc(){let r=new Error("WebSocket request cancelled");return r.name="AbortError",r}function Sg(r){return r===void 0||!Number.isFinite(r)?bg:Math.max(0,Math.floor(r))}function xg(r){if(!(!r||!Number.isFinite(r)||r<=0))return Math.floor(r*1024*1024)}function wg(r){let t=r.websocket?.settings?.handshakeTimeout,n=t&&t>0?t:r.settings?.timeout;if(!(!r.settings&&n===void 0))return{...r.settings??{},...n!==void 0?{timeout:n}:{}}}function Rg(r,e){return e==="hex"?Buffer.from(r,"hex"):Buffer.from(r,"base64")}function Cg(r,e){if(r.isBinary){let n=r.data;return{direction:e,type:"binary",data:Buffer.from(n).toString("base64"),encoding:"base64",size:n.byteLength,time:Date.now()}}let t=String(r.data);return{direction:e,type:"text",data:t,size:Buffer.byteLength(t,"utf8"),time:Date.now()}}async function kg(r,e,t){let n=t.type==="binary"?"binary":"text",s=n==="binary"?t.encoding==="hex"?"hex":"base64":void 0,i=t.data??"",o=n==="binary"?Rg(i,s):i;await r.send(o),e.frames.push({direction:"out",type:n,data:i,...s?{encoding:s}:{},size:n==="binary"?o.length:Buffer.byteLength(i,"utf8"),time:Date.now()})}function Eg(r,e,t){return new Promise(n=>{let s=!1,i,o,a=()=>{s||(s=!0,o&&clearTimeout(o),i?.dispose(),t?.removeEventListener("abort",a),n())};if(i=r.onClose(a),t?.addEventListener("abort",a,{once:!0}),r.state!=="open"){a();return}o=setTimeout(a,e)})}async function Js(r,e,t){if(r.state!=="closed")try{await r.close(e,t)}catch{}}async function Vd(r,e,t,n){if(e.websocket?.protocol==="socketio")throw new Error("Socket.IO requests must use runSocketIoRequest, not runWebSocketRequest");let s=Date.now(),i=e.websocket,o=Sg(i?.settings?.responseTimeout),a={protocol:"websocket",frames:[]},c=await r.connect({url:t.url,headers:t.headers,protocols:i?.subprotocols,settings:wg(e),maxPayloadBytes:xg(i?.settings?.maxMessageSizeMb),signal:n}),l=[],u;try{l.push(c.onFrame(d=>{a.frames.push(Cg(d,"in"))})),l.push(c.onClose(d=>{u=d})),l.push(c.onError(d=>{a.frames.push({direction:"system",type:"text",data:`Error: ${d.message}`,size:0,time:Date.now()})}));for(let d of i?.messages??[])if(d.enabled!==!1){if(n?.aborted)throw await Js(c,1001,"Run cancelled"),Uc();await kg(c,a,d)}if(n?.aborted)throw await Js(c,1001,"Run cancelled"),Uc();if(o>0&&c.state==="open"&&await Eg(c,o,n),n?.aborted)throw await Js(c,1001,"Run cancelled"),Uc();return await Js(c,1e3,"Run complete"),u&&(a.close={...u}),{status:101,statusText:"Switching Protocols",headers:c.handshakeHeaders??{},cookies:[],body:a,time:Date.now()-s,size:Buffer.byteLength(JSON.stringify(a),"utf8")}}finally{for(let d of l)d.dispose();c.state!=="closed"&&await Js(c,1e3,"Run complete")}}var bg,zd=k(()=>{"use strict";bg=1e3});function Jd(r,e){return e==="hex"?new Uint8Array(Buffer.from(r,"hex")):new Uint8Array(Buffer.from(r,"base64"))}function Ws(r){if(r==null)return"";if(typeof r=="string")return r;if(r instanceof Uint8Array||Buffer.isBuffer(r))return Buffer.from(r).toString("base64");try{return JSON.stringify(r)}catch{return String(r)}}function Ag(r,e,t,n){let s=r.data||"",i=e==="binary"?Jd(s,r.encoding).length:Buffer.byteLength(s,"utf8");return{direction:"out",type:e,data:s,encoding:e==="binary"?r.encoding||"base64":void 0,event:t,args:(r.args||[]).map(o=>String(o)),ack:r.ack===!0,size:i,time:Date.now()}}function Pg(r){let e=Array.isArray(r.args)?r.args:[],t=e[0],n=t instanceof Uint8Array||Buffer.isBuffer(t),s=e.slice(1).map(l=>Ws(l)),i="",o=0,a="text",c;return e.length===0?(i="",o=0):n?(a="binary",c="base64",i=Buffer.from(t).toString("base64"),o=t.byteLength):typeof t=="string"?(i=t,o=Buffer.byteLength(t,"utf8")):(i=Ws(t),o=Buffer.byteLength(i,"utf8")),o+=s.reduce((l,u)=>l+Buffer.byteLength(u,"utf8"),0),{direction:"in",type:a,data:i,encoding:c,event:r.event,args:s,size:o,time:Date.now()}}async function Wd(r,e,t,n){let s=Date.now(),i=(e.websocket?.messages??[]).filter(h=>h.enabled!==!1),o=e.websocket?.settings,a=o?.responseTimeout??qg,c=o?.handshakeTimeout&&o.handshakeTimeout>0?o.handshakeTimeout:(e.settings?.timeout??0)||3e4,l=[],u,d="Run complete",p,m,f;try{let h=e.websocket?.socketio,g={url:t.url,headers:t.headers,path:h?.handshakePath||"/socket.io",clientVersion:h?.clientVersion,namespace:h?.namespace,auth:h?.auth,transports:h?.transports,timeout:c,reconnectionAttempts:o?.reconnectionAttempts??0,reconnectionDelay:o?.reconnectionInterval??5e3};if(u=await r.connect(g),p=u.onEvent(y=>{l.push(Pg(y))}),m=u.onError(y=>{l.push({direction:"system",type:"text",data:y.message,size:0,time:Date.now()})}),f=u.onDisconnect(y=>{d=y||d}),n?.aborted)throw new Error("Request aborted");for(let y of i){if(n?.aborted)throw new Error("Request aborted");let S=y.event?.trim()||"message",b=y.type==="binary"?"binary":"text",C=b==="binary"?Jd(y.data,y.encoding):y.data,w=(y.args||[]).map(F=>F),E=[C,...w];if(l.push(Ag(y,b,S,E)),y.ack===!0){let F=await u.send(S,E,!0);F&&F.length>0&&l.push({direction:"in",type:"text",data:F.map(N=>Ws(N)).join(" "),event:"ack",args:F.map(N=>Ws(N)),ack:!0,size:F.reduce((N,j)=>N+Buffer.byteLength(Ws(j),"utf8"),0),time:Date.now()})}else await u.send(S,E,!1)}a>0&&!n?.aborted&&await new Promise(y=>{let S=setTimeout(y,a),b=()=>{clearTimeout(S),y()};n?.addEventListener("abort",b,{once:!0})}),u.close(),u.dispose(),p.dispose(),m.dispose(),f.dispose();let v={protocol:"socketio",frames:l,close:{code:1e3,reason:d,wasClean:!0}};return{status:101,statusText:"Switching Protocols",headers:{},body:v,cookies:[],time:Date.now()-s,size:Buffer.byteLength(JSON.stringify(v),"utf8")}}catch(h){try{p?.dispose(),m?.dispose(),f?.dispose(),u?.dispose()}catch{}throw h}}var qg,Gd=k(()=>{"use strict";qg=1e3});var Dt,Gs=k(()=>{"use strict";As();jr();zd();Gd();Dt=class r{constructor(e,t,n,s,i,o,a,c,l,u,d,p,m,f,h){this.httpService=e;this.scriptExecutor=t;this.envConfigService=n;this.requestPreparer=s;this.environment=i;this.cookieJar=o;this.collectionScripts=a;this.folderScriptsChain=c;this.onConsoleOutput=l;this.collectionName=u;this.collectionAuth=d;this.iteration=p;this.iterationCount=m;this.webSocketClient=f;this.socketIoClient=h}httpService;scriptExecutor;envConfigService;requestPreparer;environment;cookieJar;collectionScripts;folderScriptsChain;onConsoleOutput;collectionName;collectionAuth;iteration;iterationCount;webSocketClient;socketIoClient;async execute(e,t,n){if(e.requestType==="websocket"&&e.websocket?.protocol!=="socketio"&&!this.webSocketClient)throw new Error("WebSocket execution is not configured for this runner");if(e.requestType==="websocket"&&e.websocket?.protocol==="socketio"&&!this.socketIoClient)throw new Error("Socket.IO execution is not configured for this runner");let s=Date.now();return this.executeWithSession(e,t,n,s)}async executeWithSession(e,t,n,s){let i=this.collectPreRequestScripts(e),o=this.collectPostResponseScripts(e),a=this.envConfigService.getResolvedEnvironment(this.environment);if(!a)throw new Error(`Environment "${this.environment}" not found or not configured`);let c=this.envConfigService.getGlobalVariables(),l={request:e,variables:{...t},environmentVariables:a.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(p,m,f)=>{p==="set"&&m&&f!==void 0?this.envConfigService.setEnvironmentVariable(m,f,this.environment):p==="unset"&&m?this.envConfigService.deleteEnvironmentVariable(m,this.environment):p==="clear"&&this.envConfigService.clearEnvironmentVariables(this.environment)},onGlobalsChange:(p,m,f)=>{p==="set"&&m&&f!==void 0?this.envConfigService.setGlobalVariable(m,f):p==="unset"&&m?this.envConfigService.deleteGlobalVariable(m):p==="clear"&&this.envConfigService.clearGlobalVariables()}},u=this.scriptExecutor.createRequestSession(l),d=null;try{let p={...t},m={...e},f;if((!m.auth||m.auth.type==="inherit")&&(m.auth=this.collectionAuth&&this.collectionAuth.type!=="inherit"?this.collectionAuth:void 0),i.length>0){let O=await u.executePreRequest(i);if(O.consoleOutput&&O.consoleOutput.length>0&&this.onConsoleOutput?.(O.consoleOutput,{requestName:e.name||"",phase:"pre-request"}),O.nextRequest!==void 0&&(f=O.nextRequest),O.skipRequest){let D={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:{url:e.url||"",method:e.method||"GET",headers:{},body:D,params:{},query:{}},response:{status:0,statusText:"Skipped",headers:{},body:null,time:0,cookies:[]},duration:Date.now()-s,timestamp:Date.now(),passed:!0,assertions:[],modifiedVariables:p,nextRequest:f}}O.success&&(O.modifiedRequest&&(O.modifiedRequest.url&&(m.url=O.modifiedRequest.url),O.modifiedRequest.headers&&(m.headers=O.modifiedRequest.headers),O.modifiedRequest.params&&(m.params=O.modifiedRequest.params),O.modifiedRequest.query&&(m.query=O.modifiedRequest.query),O.modifiedRequest.body!==void 0&&(m.body=O.modifiedRequest.body)),(O.localVariables??O.modifiedVariables)&&(p=O.localVariables??O.modifiedVariables))}d=await this.requestPreparer.prepareRequest(m,this.environment,a,p);let{url:h,headers:g,body:v,method:y}=d,S={};for(let O in g)Object.prototype.hasOwnProperty.call(g,O)&&(S[O.toUpperCase()]=g[O]);if(!S.COOKIE&&m.settings?.includeCookies!==!1&&this.cookieJar){let D=this.cookieJar.getCookieHeader(h);D&&(S.COOKIE=D)}let b;if(m.requestType==="websocket")if(d={...d,headers:S,body:{type:"none",content:null}},m.websocket?.protocol==="socketio"){if(!this.socketIoClient)throw new Error("Socket.IO execution is not configured for this runner");b=await Wd(this.socketIoClient,m,d,n)}else{if(!this.webSocketClient)throw new Error("WebSocket execution is not configured for this runner");b=await Vd(this.webSocketClient,m,d,n)}else{let O={method:y,url:h,headers:S,body:v.content,signal:n,settings:m.settings?{...m.settings}:void 0};b=await this.httpService.execute(O)}this.cookieJar&&b.headers&&await this.cookieJar.setCookiesFromResponse(h,b.headers);let C=Date.now()-s,w=[],E={},F;if(o.length>0){let O=0;if(b.body)if(typeof b.body=="string")O=Buffer.byteLength(b.body,"utf8");else if(Buffer.isBuffer(b.body))O=b.body.length;else try{O=Buffer.byteLength(JSON.stringify(b.body),"utf8")}catch{O=0}let D=ao(b.headers,b.cookies,d.url),P={executedRequest:d,status:b.status,statusText:b.statusText,headers:Sc(b.headers||{}),body:b.body,cookies:D,responseTime:b.time,responseSize:O},M=await u.executePostResponse(o,P);w=M.testResults,E=M.modifiedEnvironmentVariables||{},F=M.visualizerData,(M.localVariables??M.modifiedVariables)&&(p=M.localVariables??M.modifiedVariables),M.nextRequest!==void 0&&(f=M.nextRequest),M.consoleOutput&&M.consoleOutput.length>0&&this.onConsoleOutput?.(M.consoleOutput,{requestName:e.name||"",phase:"post-response"})}let N=w.length===0||w.every(O=>O.passed),j=w.length>0?N:m.requestType==="websocket"?b.status===101:b.status>=200&&b.status<=302;return{requestId:e.id,name:e.name,executedRequest:Bc(d,{...d,headers:S}),response:{status:b.status,statusText:b.statusText,headers:b.headers||{},body:b.body,time:b.time||C,cookies:b.cookies||[]},duration:C,timestamp:Date.now(),passed:j,assertions:w,modifiedVariables:p,modifiedEnvironmentVariables:E,nextRequest:f,visualizerData:F}}catch(p){return this.handleError(e,d,p,s)}finally{u.dispose?.()}}collectPreRequestScripts(e){let t=[];if(this.collectionScripts?.preRequest&&t.push(this.collectionScripts.preRequest),this.folderScriptsChain)if(Array.isArray(this.folderScriptsChain))for(let n of this.folderScriptsChain)n?.preRequest&&t.push(n.preRequest);else this.folderScriptsChain.preRequest&&t.push(this.folderScriptsChain.preRequest);return e.scripts?.preRequest&&t.push(e.scripts.preRequest),t}collectPostResponseScripts(e){let t=[];if(e.scripts?.postResponse&&t.push(e.scripts.postResponse),this.folderScriptsChain)if(Array.isArray(this.folderScriptsChain)){let n=[...this.folderScriptsChain].reverse();for(let s of n)s?.postResponse&&t.push(s.postResponse)}else this.folderScriptsChain.postResponse&&t.push(this.folderScriptsChain.postResponse);return this.collectionScripts?.postResponse&&t.push(this.collectionScripts.postResponse),t}handleError(e,t,n,s){let i=Date.now()-s,o=t?.method||e.method,a=t?.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),l=n?.stack?String(n.stack):"",u=this.errorBodyFormat,d,p;u==="html"||u==="both"?(d=r.formatErrorAsHtml(c,l),p={"content-type":"text/html; charset=utf-8"}):(d=c,p={});let m={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:Bc(t,{url:a||"",method:o||"GET",headers:t?.headers||{},body:t?.body||m,params:t?.params||{},query:t?.query||{}}),response:{status:0,statusText:n.name==="AbortError"?"Aborted":n.code||n.message||"Request Error",headers:p,cookies:[],body:d,time:0},duration:i,timestamp:Date.now(),passed:!1,assertions:[],error:c}}get errorBodyFormat(){return"text"}static formatErrorAsHtml(e,t){let n=s=>s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");return`<!doctype html>
|
|
603
|
+
`)}function ug(r){let e=r.url;if(r.query&&r.query.length){let t=r.query.filter(n=>n.enabled!==!1).map(n=>`${encodeURIComponent(n.key)}=${encodeURIComponent(n.value)}`).join("&");t&&(e+=(e.includes("?")?"&":"?")+t)}return e}var go=k(()=>{"use strict";Ze()});import*as Le from"fs";import*as Ic from"path";var _r,Tc=k(()=>{"use strict";Ze();tn();_r=class{collectionsDir;cache=new Map;constructor(e){this.collectionsDir=e}ensureDirectory(){Le.existsSync(this.collectionsDir)||Le.mkdirSync(this.collectionsDir,{recursive:!0})}loadAll(){if(this.cache.clear(),!Le.existsSync(this.collectionsDir))return[];let e=Le.readdirSync(this.collectionsDir),t=[];for(let n of e)if(n.endsWith(".json"))try{let s=Ic.join(this.collectionsDir,n),i=Le.readFileSync(s,"utf-8"),o=JSON.parse(i);o.id&&o.name&&(this.cache.set(o.id,o),t.push(o))}catch(s){console.error(`[JsonCollectionLoader] Failed to load ${n}:`,s)}return t}load(e){if(this.cache.has(e))return this.cache.get(e);let t=this.getCollectionPath(e);if(Le.existsSync(t))try{let n=Le.readFileSync(t,"utf-8"),s=JSON.parse(n);return this.cache.set(e,s),s}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=le(e.name));let t=this.getCollectionPath(e.id),n=JSON.stringify(e,null,2);await Le.promises.writeFile(t,n,"utf-8"),this.cache.set(e.id,e)}async delete(e){let t=this.getCollectionPath(e);if(!Le.existsSync(t))return!1;try{return await Le.promises.unlink(t),this.cache.delete(e),!0}catch(n){return console.error(`[JsonCollectionLoader] Failed to delete collection ${e}:`,n),!1}}exists(e){return Le.existsSync(this.getCollectionPath(e))}getCollectionPath(e){return Ic.join(this.collectionsDir,`${e}.json`)}getItemPath(e,t){}async create(e,t){let n={id:t||le(e),name:e,items:[]};return await this.save(n),n}async saveScripts(e,t,n){let s=this.load(e);if(!s)throw new Error(`Collection ${e} not found`);let i=Ee(s.items,t);i&&(i.scripts=n,await this.save(s))}loadScripts(e,t){let n=this.load(e);return n?Ee(n.items,t)?.scripts:void 0}async updateCollectionMetadata(e,t){let n=this.load(e);if(!n)throw new Error(`Collection ${e} not found`);t.name!==void 0&&(n.name=t.name),t.description!==void 0&&(n.description=t.description),t.version!==void 0&&(n.version=t.version),t.variables!==void 0&&(n.variables=t.variables),t.auth!==void 0&&(n.auth=t.auth),await this.save(n)}async saveItem(e,t,n){let s=this.load(e);if(!s)throw new Error(`Collection ${e} not found`);let i=Ee(s.items,t.id);if(i)Object.assign(i,t);else if(n){let o=Ee(s.items,n);if(o&&o.type==="folder")o.items=o.items||[],o.items.push(t);else throw new Error(`Parent folder ${n} not found`)}else s.items.push(t);await this.save(s)}async deleteItem(e,t){let n=this.load(e);if(!n)return!1;let s=en(n.items,t);return s&&await this.save(n),s}async updateItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=Ee(s.items,t);if(!i)return!1;let{id:o,type:a,...c}=n;return Object.assign(i,c),await this.save(s),!0}async moveItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=Ee(s.items,t);if(!i)return!1;let o={...i};if(!en(s.items,t))return!1;if(n){let a=Ee(s.items,n);if(a&&a.type==="folder")a.items=a.items||[],a.items.push(o);else return s.items.push(o),!1}else s.items.push(o);return await this.save(s),!0}async reorderItems(e,t,n){let s=this.load(e);if(!s)return!1;try{let i;if(t){let c=Ee(s.items,t);if(!c||!c.items)return!1;i=c.items}else i=s.items;let o=new Map(i.map(c=>[c.id,c])),a=[];for(let c of n){let l=o.get(c);l&&(a.push(l),o.delete(c))}for(let c of o.values())a.push(c);if(t){let c=Ee(s.items,t);c&&(c.items=a)}else s.items=a;return await this.save(s),!0}catch(i){return console.error("[JsonCollectionLoader] Failed to reorder items:",i),!1}}}});var js,Oc=k(()=>{"use strict";Qi();Tc();js=class{static create(e){let t=e.getStorageConfig(),n=e.getCollectionsPath();return t.format==="folder"?new nn(n):new _r(n)}static createForFormat(e,t){return e==="folder"?new nn(t):new _r(t)}}});import*as he from"fs";import*as bt from"path";function dg(r){return r==null?!0:typeof r!="object"?!1:r.type==="raw"?r.content==null||r.content==="":r.type==="graphql"?r.content==null&&!r.query:!1}function Md(r){if(typeof r!="string")return"text";let e=r.trim();try{let t=JSON.parse(e);if(typeof t=="object"&&t!==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 pg(r){return{info:{name:r.name,_postman_id:r.id,schema:"https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},item:r.items.map(e=>jd(e)),event:$c(r.scripts),variable:r.variables?Object.entries(r.variables).map(([e,t])=>({key:e,value:t})):[]}}function jd(r){if(r.type==="folder")return{name:r.name,item:r.items?r.items.map(jd):[],event:$c(r.scripts)};if(r.type==="request"){let e=r;return{name:e.name,request:{method:e.method,header:(e.headers||[]).map(fg),url:mg(e),body:hg(e),auth:gg(e.auth),description:e.description},event:$c(e.scripts),protocolProfileBehavior:yg(e.settings)}}}function fg(r){return{key:r.key,value:r.value,disabled:r.enabled===!1,...r.description!==void 0?{description:r.description}:{},...r.type!==void 0?{type:r.type}:{},...r.required!==void 0?{required:r.required}:{},...r.format!==void 0?{format:r.format}:{},...r.enum!==void 0?{enum:r.enum}:{},...r.deprecated!==void 0?{deprecated:r.deprecated}:{},...r.pattern!==void 0?{pattern:r.pattern}:{},...r.minLength!==void 0?{minLength:r.minLength}:{},...r.maxLength!==void 0?{maxLength:r.maxLength}:{},...r.minimum!==void 0?{minimum:r.minimum}:{},...r.maximum!==void 0?{maximum:r.maximum}:{},...r.exclusiveMinimum!==void 0?{exclusiveMinimum:r.exclusiveMinimum}:{},...r.exclusiveMaximum!==void 0?{exclusiveMaximum:r.exclusiveMaximum}:{},...r.multipleOf!==void 0?{multipleOf:r.multipleOf}:{},...r.minItems!==void 0?{minItems:r.minItems}:{},...r.maxItems!==void 0?{maxItems:r.maxItems}:{},...r.uniqueItems!==void 0?{uniqueItems:r.uniqueItems}:{},...r.nullable!==void 0?{nullable:r.nullable}:{},...r.oneOf!==void 0?{oneOf:r.oneOf}:{}}}function mg(r){let e=r.url,t=r.url.replace(/^[a-zA-Z]+:\/\//,""),n=[],s=t.match(/^([^\/\?]+)/);if(s){let l=s[1];/^{{.*}}$/.test(l)?n=[l]:n=l.split(".")}let i=[],o=t.match(/^[^\/\?]+(\/[^\?]*)?/);if(o&&o[1]!==void 0){let l=o[1].replace(/^\//,"");l.endsWith("/")?(i=l.slice(0,-1).split("/"),i.push("")):i=l.length>0?l.split("/"):[]}let a;if(Array.isArray(r.query)&&r.query.length>0)a=r.query.map(l=>{let u={key:l.key,value:l.value};return l.enabled===!1&&(u.disabled=!0),l.description!==void 0&&(u.description=l.description),l.type!==void 0&&(u.type=l.type),l.required!==void 0&&(u.required=l.required),l.format!==void 0&&(u.format=l.format),l.enum!==void 0&&(u.enum=l.enum),l.deprecated!==void 0&&(u.deprecated=l.deprecated),l.pattern!==void 0&&(u.pattern=l.pattern),l.minLength!==void 0&&(u.minLength=l.minLength),l.maxLength!==void 0&&(u.maxLength=l.maxLength),l.minimum!==void 0&&(u.minimum=l.minimum),l.maximum!==void 0&&(u.maximum=l.maximum),l.exclusiveMinimum!==void 0&&(u.exclusiveMinimum=l.exclusiveMinimum),l.exclusiveMaximum!==void 0&&(u.exclusiveMaximum=l.exclusiveMaximum),l.multipleOf!==void 0&&(u.multipleOf=l.multipleOf),l.minItems!==void 0&&(u.minItems=l.minItems),l.maxItems!==void 0&&(u.maxItems=l.maxItems),l.uniqueItems!==void 0&&(u.uniqueItems=l.uniqueItems),l.nullable!==void 0&&(u.nullable=l.nullable),l.oneOf!==void 0&&(u.oneOf=l.oneOf),u});else{let l=t.indexOf("?");l!==-1&&(a=t.substring(l+1).split("&").map(d=>{let[p,...m]=d.split("=");return{key:p,value:m.join("=")}}))}let c;return r.params&&typeof r.params=="object"&&(c=Object.entries(r.params).map(([l,u])=>({key:l,value:String(u)}))),{raw:e,host:n.length>0?n:void 0,path:i.length>0?i:void 0,query:a&&a.length>0?a:void 0,variable:c&&c.length>0?c:void 0}}function hg(r){if(!r.body)return;let e=r.body;if(typeof e=="string"){let i=Md(e);return{mode:"raw",raw:e,options:{raw:{language:i}}}}if(e.type==="raw"){let i=e.format||Md(e.content);return{mode:"raw",raw:e.content,options:{raw:{language:i}}}}let t=e.type==="form-data"&&Array.isArray(e.content)?e.content:e.type==="formdata"&&Array.isArray(e.fields)?e.fields:null;if(t)return{mode:"formdata",formdata:t.map(i=>({key:i.key,value:i.value,type:i.type||"text",disabled:i.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(i=>({key:i.key,value:i.value,disabled:i.enabled===!1}))};if(e.type==="file"&&e.fileName)return{mode:"file",file:{src:e.fileName}};if(e.type==="binary")return{mode:"binary",file:{}};let s=e.type==="graphql"?e.content??(e.query?e:null):null;if(s){let i=s.query??"",o=s.variables;return{mode:"graphql",graphql:{query:i,variables:o?typeof o=="string"?o:JSON.stringify(o):void 0}}}if(e.content)return{mode:"raw",raw:e.content}}function gg(r){if(!(!r||!r.type||r.type==="none")){if(r.type==="bearer")return{type:"bearer",bearer:[{key:"token",value:r.bearerToken,type:"string"}]};if(r.type==="basic"&&r.basicAuth)return{type:"basic",basic:[{key:"username",value:r.basicAuth.username,type:"string"},{key:"password",value:r.basicAuth.password,type:"string"}]}}}function yg(r){if(!r)return;let e={};return r.followRedirects===!1&&(e.followRedirects=!1),r.followOriginalMethod===!0&&(e.followOriginalHttpMethod=!0),r.followAuthHeader===!1&&(e.followAuthorizationHeader=!1),r.maxRedirects!==void 0&&(e.maxRedirects=r.maxRedirects),r.strictSSL===!1&&(e.disableUrlEncoding=!1),r.timeout!==void 0&&(e.requestTimeout=r.timeout),Object.keys(e).length>0?e:void 0}function $c(r){if(!r)return[];let e=[];return r.preRequest&&e.push({listen:"prerequest",script:{type:"text/javascript",exec:[r.preRequest]}}),r.postResponse&&e.push({listen:"test",script:{type:"text/javascript",exec:[r.postResponse]}}),e}var Ls,Fc=k(()=>{"use strict";Ze();go();Oc();rc();tn();Ls=class{constructor(e,t){this.configService=e;this.fileWatcherFactory=t;this.collectionsDir=e.getCollectionsPath(),this.loader=js.create(e),this.loadCollections(),this.setupFileWatcher()}configService;fileWatcherFactory;collectionsDir;collections=new Map;fileWatcher;loader;debounceTimer=null;selfWritePending=!1;localCollectionValues=new Map;onCollectionsChanged;ensureCollectionsDir(){he.existsSync(this.collectionsDir)||he.mkdirSync(this.collectionsDir,{recursive:!0})}loadCollections(){this.collections.clear();let e=this.loader.loadAllLight?.()??this.loader.loadAll();for(let t of e)this.collections.set(t.id,t)}getRequestDetail(e,t){let n=this.loader.loadRequestDetail?.(e,t);return n||this.findRequest(e,t)}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 t=this.selfWritePending;this.selfWritePending=!1,t||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 t of this.collections.values())if(t.id===e)return t}getCollectionByName(e){let t=e.toLowerCase();for(let n of this.collections.values())if(n.name.toLowerCase()===t)return n}async saveCollection(e){if(this.ensureCollectionsDir(),!e.name)throw new Error("Collection name is required");e.id||(e.id=le(e.name)),this.selfWritePending=!0,await this.loader.save(e),this.collections.set(e.id,e)}getCollectionVariables(e){let t=this.collections.get(e);return t?.variables?{...t.variables}:{}}getCollectionVariableLocals(e){return{...this.localCollectionValues.get(e)||{}}}setCollectionVariable(e,t,n){this.localCollectionValues.has(e)||this.localCollectionValues.set(e,{}),this.localCollectionValues.get(e)[t]=String(n)}deleteCollectionVariable(e,t){let n=this.localCollectionValues.get(e);n&&delete n[t]}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,t){let n=this.collections.get(e);if(!n)return;let s=this.findItemRecursive(n.items,t);if(!s)return;if(Tn(s)||dg(s.body)){let o=this.loader.loadRequestDetail?.(e,t);if(zi(o??s),o)return o}return s}findRequestByPath(e,t){let n=this.collections.get(e);if(!n)return;let s=t.split("/").filter(i=>i.trim());return this.findItemByPath(n.items,s)}async updateRequest(e,t,n){let s=this.collections.get(e);if(!s)return!1;this.selfWritePending=!0;let i=await this.loader.updateItem(e,t,n);if(i){let o=this.findItemRecursive(s.items,t);if(o){let{id:a,type:c,...l}=n;Object.assign(o,l)}}return i}async addRequest(e,t,n){if(!this.collections.get(e))return!1;t.id||(t.id=le(t.name)),this.selfWritePending=!0;try{return await this.loader.saveItem(e,t,n),!0}catch(i){return console.error("[CollectionService] Failed to add request:",i),!1}}async deleteRequest(e,t){let n=this.collections.get(e);if(!n)return!1;this.selfWritePending=!0;let s=await this.loader.deleteItem(e,t);return s&&this.deleteItemRecursive(n.items,t),s}getAllRequests(e){let t=this.collections.get(e);if(!t)return[];let n=[];return this.collectRequestsRecursive(t.items,n),n}findItemRecursive(e,t){for(let n of e){if(n.id===t)return n;if(n.type==="folder"&&n.items){let s=this.findItemRecursive(n.items,t);if(s)return s}}}findItemByPath(e,t){if(t.length===0)return;let[n,...s]=t,i=e.find(o=>o.name===n);if(i){if(s.length===0)return i;if(i.type==="folder"&&i.items)return this.findItemByPath(i.items,s)}}deleteItemRecursive(e,t){for(let n=0;n<e.length;n++){let s=e[n];if(s.id===t)return e.splice(n,1),!0;if(s.type==="folder"&&s.items&&this.deleteItemRecursive(s.items,t))return!0}return!1}collectRequestsRecursive(e,t){for(let n of e)n.type==="request"?t.push(n):n.type==="folder"&&n.items&&this.collectRequestsRecursive(n.items,t)}async createCollection(e){let t={id:le(e),name:e,items:[]};return await this.saveCollection(t),t}async renameCollection(e,t){let n=this.collections.get(e);return n?(n.name=t,await this.saveCollection(n),!0):!1}async duplicateCollection(e,t){if(!this.collections.get(e))throw new Error(`Collection not found: ${e}`);this.selfWritePending=!0;let s=le(t),i=this.loader.getCollectionPath(e),o=bt.join(this.collectionsDir,s);if(!he.existsSync(i))throw new Error(`Collection directory not found: ${i}`);this.copyDirRecursive(i,o);let a=bt.join(o,"collection.json");if(he.existsSync(a)){let l=JSON.parse(he.readFileSync(a,"utf-8"));l.id=s,l.name=t,he.writeFileSync(a,JSON.stringify(l,null,2))}else he.writeFileSync(a,JSON.stringify({id:s,name:t},null,2));this.loadCollections();let c=this.collections.get(s);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:le(e.name),type:"folder",name:e.name,items:[]};await this.loader.saveItem(e.collectionId,n,e.parentId);let s=this.loader.load(e.collectionId);return s&&this.collections.set(e.collectionId,s),n}async deleteFolder(e,t){let n=this.collections.get(e);if(!n)return!1;this.selfWritePending=!0;let s=await this.loader.deleteItem(e,t);return s&&en(n.items,t),s}async renameFolder(e,t,n){let s=this.collections.get(e);if(!s)return!1;this.selfWritePending=!0;let i=await this.loader.updateItem(e,t,{name:n});if(i){let o=Ee(s.items,t);o&&(o.name=n)}return i}async duplicateFolder(e,t,n){if(!this.collections.get(e))throw new Error("Collection not found");let i=this.loader.getItemPath(e,t);if(!i||!he.existsSync(i))throw new Error(`Folder not found on disk: ${t}`);let o=bt.dirname(i),a=le(n),c=bt.join(o,a);this.selfWritePending=!0,this.copyDirRecursive(i,c);let l=bt.join(c,"folder.json");if(he.existsSync(l)){let p=JSON.parse(he.readFileSync(l,"utf-8"));p.id=a,p.name=n,he.writeFileSync(l,JSON.stringify(p,null,2))}else he.writeFileSync(l,JSON.stringify({id:a,name:n,type:"folder"},null,2));this.loadCollections();let u=this.collections.get(e),d=u?Ee(u.items,a):void 0;return d||{id:a,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||le(e.name),type:"request",name:e.name,requestType:e.requestType,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,websocket:e.websocket,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 s=this.loader.load(e.collectionId);return s&&this.collections.set(e.collectionId,s),n}async renameRequest(e,t,n){let s=this.collections.get(e);if(!s)return!1;this.selfWritePending=!0;let i=await this.loader.updateItem(e,t,{name:n});if(i){let o=Ee(s.items,t);o&&(o.name=n)}return i}async moveItem(e,t,n){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let i=await this.loader.moveItem(e,t,n);return i&&this.loadCollections(),i}async reorderItems(e,t,n){if(!this.collections.get(e))return!1;this.selfWritePending=!0;let i=await this.loader.reorderItems(e,t,n);return i&&this.loadCollections(),i}getRequestScript(e,t,n){let s=this.findRequest(e,t);if(s)return n==="pre-request"?s.scripts?.preRequest:s.scripts?.postResponse}async setRequestScript(e,t,n,s){let i=this.collections.get(e);if(!i)return!1;let o=Ee(i.items,t);if(!o||o.type!=="request")return!1;let a=o,l={...a.scripts??{},...n==="pre-request"?{preRequest:s}:{postResponse:s}};a.scripts=l,this.selfWritePending=!0;try{return await this.loader.saveScripts(e,t,l),!0}catch{return!1}}copyDirRecursive(e,t){he.existsSync(t)||he.mkdirSync(t,{recursive:!0});for(let n of he.readdirSync(e,{withFileTypes:!0})){let s=bt.join(e,n.name),i=bt.join(t,n.name);n.isDirectory()?this.copyDirRecursive(s,i):he.copyFileSync(s,i)}}async importCollection(e){let t=he.readFileSync(e,"utf-8"),n;try{n=JSON.parse(t)}catch{throw new Error("Invalid JSON file")}if(n.info&&n.info._postman_id)return this.importPostmanCollection(n);let s={id:n.id||le(n.name||"Imported Collection"),name:n.name||"Imported Collection",description:n.description,items:n.items||[]};return await this.saveCollection(s),s}async importPostmanCollection(e){let t=p=>{if(!p)return;switch(p.type?.toLowerCase()){case"bearer":return{type:"bearer",bearerToken:p.bearer?.find(b=>b.key==="token")?.value||""};case"basic":let h=p.basic?.find(b=>b.key==="username"),g=p.basic?.find(b=>b.key==="password");return{type:"basic",basicAuth:{username:h?.value||"",password:g?.value||""}};case"apikey":let v=p.apikey?.find(b=>b.key==="key"),y=p.apikey?.find(b=>b.key==="value"),S=p.apikey?.find(b=>b.key==="in");return{type:"apikey",apikey:{key:v?.value||"",value:y?.value||"",in:S?.value||"header"}};case"noauth":return{type:"none"};default:return}},n=p=>{if(!Array.isArray(p)||p.length===0)return;let m={};for(let f of p){let h=f.script?.exec;if(!h)continue;let g=Array.isArray(h)?h.join(`
|
|
604
|
+
`):h;f.listen==="prerequest"?m.preRequest=g:f.listen==="test"&&(m.postResponse=g)}return m.preRequest||m.postResponse?m:void 0},s=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},i=p=>{if(!p||typeof p=="string")return;let m=p.query;if(!(!Array.isArray(m)||m.length===0))return m.map(f=>({key:f.key||"",value:f.value||"",enabled:f.disabled!==!0,...f.description!==void 0?{description:f.description}:{},...f.type!==void 0?{type:f.type}:{},...f.required!==void 0?{required:f.required}:{},...f.format!==void 0?{format:f.format}:{},...f.enum!==void 0?{enum:f.enum}:{},...f.deprecated!==void 0?{deprecated:f.deprecated}:{},...f.pattern!==void 0?{pattern:f.pattern}:{},...f.minLength!==void 0?{minLength:f.minLength}:{},...f.maxLength!==void 0?{maxLength:f.maxLength}:{},...f.minimum!==void 0?{minimum:f.minimum}:{},...f.maximum!==void 0?{maximum:f.maximum}:{},...f.exclusiveMinimum!==void 0?{exclusiveMinimum:f.exclusiveMinimum}:{},...f.exclusiveMaximum!==void 0?{exclusiveMaximum:f.exclusiveMaximum}:{},...f.multipleOf!==void 0?{multipleOf:f.multipleOf}:{},...f.minItems!==void 0?{minItems:f.minItems}:{},...f.maxItems!==void 0?{maxItems:f.maxItems}:{},...f.uniqueItems!==void 0?{uniqueItems:f.uniqueItems}:{},...f.nullable!==void 0?{nullable:f.nullable}:{},...f.oneOf!==void 0?{oneOf:f.oneOf}:{}}))},o=p=>{if(typeof p=="string")return p;if(!p)return"";let m=new Set;if(Array.isArray(p.variable))for(let h of p.variable)h.key&&m.add(h.key);if(m.size===0&&p.raw)return p.raw;let f="";if(p.protocol&&(f+=p.protocol+"://"),p.host&&(f+=Array.isArray(p.host)?p.host.join("."):p.host),p.port&&(f+=":"+p.port),p.path){let g=(Array.isArray(p.path)?p.path:[p.path]).map(v=>{let y=v.startsWith(":")?v.substring(1):v;return m.has(y)?":"+y:(v.startsWith(":"),v)});f+="/"+g.join("/")}return!f&&p.raw?p.raw:f},a=p=>{if(!Array.isArray(p)||p.length===0)return;let m={responses:{}};for(let f of p){let h=String(f.code||200),g,v={};if(Array.isArray(f.header))for(let w of f.header)!w.key||w.disabled||(w.key.toLowerCase()==="content-type"?g=w.value?.split(";")[0]?.trim():v[w.key]={description:String(w.value??""),schema:{type:"string"}});let y=f.body;if(typeof f.body=="string"&&f.body)try{y=JSON.parse(f.body)}catch{}let S=f.originalRequest,b;if(S){let w=typeof S.url=="string"?S.url:S.url?.raw??"";b=`${S.method||""} ${w}`.trim()||void 0}let C=f.name?f.name.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toLowerCase()||`example_${h}`:`example_${h}`;if(m.responses[h]){let w=m.responses[h];w.examples=w.examples??{},w.examples[C]={summary:b,value:y}}else m.responses[h]={description:f.name,contentType:g,examples:{[C]:{summary:b,value:y}},...Object.keys(v).length>0?{headers:v}:{}}}return Object.keys(m.responses).length>0?m:void 0},c=p=>!(!p||typeof p!="object"||p.item===void 0&&p.request===void 0&&(p.listen!==void 0||p.script!==void 0)),l=p=>p.filter(c).map(m=>{if(m.item)return{id:le(m.name),type:"folder",name:m.name||"Folder",description:m.description,auth:t(m.auth),scripts:n(m.event),items:l(m.item)};{let f=m.request||{};return{id:le(m.name),type:"request",name:m.name||f.method||"Request",description:m.description||f.description,method:typeof f.method=="string"?f.method:"GET",url:o(f.url),query:i(f.url),headers:Array.isArray(f.header)?f.header.map(h=>({key:h.key||h.name||"",value:h.value||h.value||"",enabled:h.disabled!==!0,...h.description!==void 0?{description:h.description}:{},...h.type!==void 0?{type:h.type}:{},...h.required!==void 0?{required:h.required}:{},...h.format!==void 0?{format:h.format}:{},...h.enum!==void 0?{enum:h.enum}:{},...h.deprecated!==void 0?{deprecated:h.deprecated}:{},...h.pattern!==void 0?{pattern:h.pattern}:{},...h.minLength!==void 0?{minLength:h.minLength}:{},...h.maxLength!==void 0?{maxLength:h.maxLength}:{},...h.minimum!==void 0?{minimum:h.minimum}:{},...h.maximum!==void 0?{maximum:h.maximum}:{},...h.exclusiveMinimum!==void 0?{exclusiveMinimum:h.exclusiveMinimum}:{},...h.exclusiveMaximum!==void 0?{exclusiveMaximum:h.exclusiveMaximum}:{},...h.multipleOf!==void 0?{multipleOf:h.multipleOf}:{},...h.minItems!==void 0?{minItems:h.minItems}:{},...h.maxItems!==void 0?{maxItems:h.maxItems}:{},...h.uniqueItems!==void 0?{uniqueItems:h.uniqueItems}:{},...h.nullable!==void 0?{nullable:h.nullable}:{},...h.oneOf!==void 0?{oneOf:h.oneOf}:{}})):[],body:(()=>{let h=f.body;if(h){if(h.mode==="raw"&&h.raw){let g=h.options?.raw?.language;return{type:"raw",format:g==="xml"?"xml":g==="html"?"html":g==="javascript"?"javascript":g==="text"?"text":"json",content:h.raw}}if(h.mode==="urlencoded"&&Array.isArray(h.urlencoded))return{type:"x-www-form-urlencoded",content:h.urlencoded.map(g=>({key:g.key||"",value:g.value||"",enabled:g.disabled!==!0}))};if(h.mode==="formdata"&&Array.isArray(h.formdata))return{type:"form-data",content:h.formdata.map(g=>({key:g.key||"",value:g.value||"",type:g.type||"text",enabled:g.disabled!==!0}))};if(h.mode==="graphql"&&h.graphql){let g;if(h.graphql.variables)try{g=JSON.parse(h.graphql.variables)}catch{g=void 0}return{type:"graphql",content:{query:h.graphql.query||"",variables:g}}}if(h.mode==="binary")return{type:"binary",content:""}}})(),auth:t(f.auth),scripts:n(m.event),settings:s(m.protocolProfileBehavior),responseSchema:a(m.response)}}}),u=l(e.item||[]),d={id:le(e.info?.name||"Imported Postman Collection"),name:e.info?.name||"Imported Postman Collection",description:e.info?.description,auth:t(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:u};return await this.saveCollection(d),d}async exportCollection(e,t){let n=this.collections.get(e);if(!n)throw new Error("Collection not found");let s=pg(n),i=JSON.stringify(s,null,2);he.writeFileSync(t,i,"utf-8")}async exportCollectionAsRestClientFolder(e,t){let n=this.collections.get(e);if(!n)throw new Error("Collection not found");let s=bt.join(t,xe(n.name));he.mkdirSync(s,{recursive:!0});let i=n.variables||{};Nr(bt.join(s,`${xe(n.name)}.env`),i),Ms(s,xe(n.name),n.scripts),ho(n.items,s,n)}dispose(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.fileWatcher?.dispose()}}});var se,Wn,on,Nc=k(()=>{"use strict";se={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,report:{maxBodyChars:1e5,embedBodies:"failed"}},environments:{default:"dev"},restClientExport:{path:"collections-rest-client",mergeGlobals:!0},discovery:{customSeedLoaderModulePath:void 0,frameworks:["auto"],contextProperties:["locals"],skipComponentAnalysis:!1},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"}}}},Wn={preferred:".http-forge/http-forge.config.json",legacy:"http-forge.config.json"},on={collections:"collections",environments:"environments",flows:"flows",suites:"suites"}});import*as ee from"fs";import*as L from"path";var an,yo=k(()=>{"use strict";Nc();an=class{constructor(e,t,n){this.workspacePath=e;this.fileWatcherFactory=t;this.notifications=n;this.workspacePath=this.normalizeWorkspacePath(e),this.configPath=this.resolveConfigPath(),this.configDir=L.dirname(this.configPath),this.config=this.loadConfig(),this.setupFileWatcher()}workspacePath;fileWatcherFactory;notifications;config;configPath;configDir;fileWatchers=[];_standaloneProbeCache;_cachedWorkspaceNormalization;isStandaloneLayoutCached(){let e=Date.now();if(this._standaloneProbeCache&&e-this._standaloneProbeCache.ts<5e3)return this._standaloneProbeCache.value;let t=ee.existsSync(L.join(this.workspacePath,"assets")),n=ee.existsSync(L.join(this.workspacePath,".http-forge")),s=t&&!n;return this._standaloneProbeCache={key:this.workspacePath,value:s,ts:e},s}normalizeWorkspacePath(e){if(this._cachedWorkspaceNormalization&&this._cachedWorkspaceNormalization.input===e)return this._cachedWorkspaceNormalization.result;let t=L.resolve(e),n=L.basename(t),s=a=>ee.existsSync(L.join(a,"assets","collections"))||ee.existsSync(L.join(a,"collections"))||ee.existsSync(L.join(a,"environments"))||ee.existsSync(L.join(a,"http-forge.config.json"))?!0:ee.existsSync(L.join(a,".http-forge","http-forge.config.json"))?!1:ee.existsSync(L.join(a,"assets")),i=a=>!!(ee.existsSync(L.join(a,"collections"))||ee.existsSync(L.join(a,"environments"))||ee.existsSync(L.join(a,"suites"))),o;if(n===".http-forge")o=s(t)?t:L.dirname(t);else if(n==="assets")if(!i(t))o=t;else{let a=L.dirname(t);L.basename(a)===".http-forge"?o=L.dirname(a):o=a}else o=t;return this._cachedWorkspaceNormalization={input:e,result:o},o}resolveConfigPath(){let e=L.join(this.workspacePath,Wn.legacy),t=L.join(this.workspacePath,Wn.preferred);return ee.existsSync(e)?e:ee.existsSync(t)||ee.existsSync(L.join(this.workspacePath,".http-forge"))?t:this.hasFolderCollectionsAtRoot(L.join(this.workspacePath,"assets"))||ee.existsSync(L.join(this.workspacePath,"assets"))||this.hasFolderCollectionsAtRoot(this.workspacePath)?e:t}loadConfig(){if(this.configPath=this.resolveConfigPath(),this.configDir=L.dirname(this.configPath),!ee.existsSync(this.configPath))return{...se};try{let e=ee.readFileSync(this.configPath,"utf-8"),t=JSON.parse(e);return this.mergeWithDefaults(t)}catch(e){return console.error("[ConfigService] Failed to load config:",e),this.notifications?.showWarning(`Failed to parse ${L.relative(this.workspacePath,this.configPath)}. Using default configuration.`),{...se}}}mergeWithDefaults(e){return{version:e.version??se.version,storage:{...se.storage,...e.storage},request:{...se.request,...e.request},scripts:{...se.scripts,...e.scripts},runner:{...se.runner,...e.runner,report:{...se.runner.report,...e.runner?.report}},environments:{...se.environments,...e.environments},restClientExport:{...se.restClientExport,...e.restClientExport},proxy:e.proxy!==void 0?e.proxy:se.proxy,discovery:{...se.discovery,...e.discovery},mcp:{...se.mcp,...e.mcp,cors:{...se.mcp.cors,...e.mcp?.cors}},secrets:{...se.secrets,...e.secrets,providers:{...se.secrets?.providers,...e.secrets?.providers}}}}setupFileWatcher(){if(!this.fileWatcherFactory)return;let e=()=>{this.reload()};for(let t of[Wn.preferred,Wn.legacy]){let n=this.fileWatcherFactory.createFileWatcher(this.workspacePath,t);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(){let e=this.config.runner,t=e.report??se.runner.report,n=["all","failed","none"];return{...e,report:{maxBodyChars:Math.max(1e3,Math.floor(t.maxBodyChars??se.runner.report.maxBodyChars)),embedBodies:n.includes(t.embedBodies)?t.embedBodies:se.runner.report.embedBodies}}}getEnvironmentsConfig(){return this.config.environments}getRestClientExportPath(){let e=this.config.restClientExport?.path||"collections-rest-client";return L.isAbsolute(e)?e:this.resolvePath(e)}getRestClientMergeGlobals(){return this.config.restClientExport?.mergeGlobals??!0}getProxyConfig(){return this.config.proxy??null}getDiscoveryConfig(){let e=this.config.discovery??se.discovery;return{customSeedLoaderModulePath:e.customSeedLoaderModulePath,frameworks:e.frameworks??se.discovery.frameworks,contextProperties:e.contextProperties??se.discovery.contextProperties,skipComponentAnalysis:e.skipComponentAnalysis??se.discovery.skipComponentAnalysis}}getMcpConfig(){let e=this.config.mcp??se.mcp,t=["flat","drilldown","auto","execution-only"];return{...e,port:Math.min(65535,Math.max(1,Math.floor(e.port??3100))),toolMode:t.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){if(L.isAbsolute(e))return e;let t=e.startsWith("./")?e.slice(2):e,n=this.configExists()?this.configDir:this.workspacePath,s=t;return L.basename(n)===".http-forge"?(s===".http-forge"||s.startsWith(".http-forge/"))&&(s=s.slice(12)):n===this.workspacePath&&s.startsWith(".http-forge/")&&this.isStandaloneLayoutCached()&&(s=s.slice(12)),s?L.join(n,...s.split("/").filter(i=>i!==""&&i!==".")):n}hasFolderCollectionsAtRoot(e){let t=L.join(e,on.collections);if(!ee.existsSync(t))return!1;let n;try{n=ee.readdirSync(t,{withFileTypes:!0})}catch{return!1}return n.some(s=>{if(!s.isDirectory())return!1;let i=L.join(t,s.name,"collection.json");return ee.existsSync(i)})}hasAnyEntries(e){if(!ee.existsSync(e))return!1;try{return ee.readdirSync(e).length>0}catch{return!1}}resolveStorageRootPath(){let e=this.resolvePath(this.config.storage.root);if(this.configExists()||this.hasFolderCollectionsAtRoot(e))return e;let n=[L.join(this.workspacePath,".http-forge","assets"),L.join(this.workspacePath,"assets"),L.join(this.workspacePath,"http-forge-assets"),this.workspacePath].find(i=>this.hasFolderCollectionsAtRoot(i));if(n)return n;let s=L.join(this.workspacePath,"assets");return this.hasFolderCollectionsAtRoot(s)?s:e}getRootPath(){return this.resolveStorageRootPath()}getCollectionsPath(){return L.join(this.getRootPath(),on.collections)}getEnvironmentsPath(){return L.join(this.getRootPath(),on.environments)}getFlowsPath(){return L.join(this.getRootPath(),on.flows)}getHistoryPath(){let e=this.resolvePath(this.config.storage.history);return this.configExists()||this.hasAnyEntries(e)?e:[L.join(this.workspacePath,".http-forge",".cache","histories"),L.join(this.workspacePath,".cache","histories"),L.join(this.workspacePath,".http-forge-cache","histories"),L.join(this.getRootPath(),".cache","histories")].find(s=>this.hasAnyEntries(s))||e}getResultsPath(){let e=this.resolvePath(this.config.storage.results);return this.configExists()||this.hasAnyEntries(e)?e:[L.join(this.workspacePath,".http-forge",".cache","results"),L.join(this.workspacePath,".cache","results"),L.join(this.workspacePath,".http-forge-cache","results"),L.join(this.getRootPath(),".cache","results")].find(s=>this.hasAnyEntries(s))||e}getSuitesPath(){return L.join(this.getRootPath(),on.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}onConfigReloaded;reload(){this.configPath=this.resolveConfigPath(),this.configDir=L.dirname(this.configPath),this.config=this.loadConfig(),this.onConfigReloaded?.()}configExists(){return ee.existsSync(this.configPath)||ee.existsSync(this.resolveConfigPath())}getDefaultConfigForCurrentLocation(){if(L.basename(this.configDir)===".http-forge")return{...se,storage:{...se.storage,root:"./assets",history:"./.cache/histories",results:"./.cache/results"},scripts:{...se.scripts,modulePaths:["./assets/src","./assets/lib"]}};let e=ee.existsSync(L.join(this.workspacePath,"assets")),t=ee.existsSync(L.join(this.workspacePath,".http-forge"));return e&&!t?{...se,storage:{...se.storage,root:"./assets",history:"./.cache/histories",results:"./.cache/results"},scripts:{...se.scripts,modulePaths:["./assets/src","./assets/lib"]}}:{...se}}async createDefaultConfig(){this.configPath=this.resolveConfigPath(),this.configDir=L.dirname(this.configPath),await ee.promises.mkdir(L.dirname(this.configPath),{recursive:!0});let e=this.getDefaultConfigForCurrentLocation(),t=JSON.stringify(e,null,2);await ee.promises.writeFile(this.configPath,t,"utf-8");let n=[this.getCollectionsPath(),this.getEnvironmentsPath(),this.getFlowsPath(),this.getSuitesPath()];for(let i of n)ee.existsSync(i)||await ee.promises.mkdir(i,{recursive:!0});let s=[this.getHistoryPath(),this.getResultsPath()];for(let i of s)ee.existsSync(i)||await ee.promises.mkdir(i,{recursive:!0});await this.createSampleEnvironments()}async createSampleEnvironments(){let e=this.getEnvironmentsPath(),t={id:"globals",name:"Global Variables",variables:{appName:"HTTP Forge"}};await ee.promises.writeFile(L.join(e,"globals.json"),JSON.stringify(t,null,2),"utf-8");let n={id:"env_dev",name:"Development",variables:{baseUrl:"http://localhost:3000",apiVersion:"v1"}};await ee.promises.writeFile(L.join(e,"dev.json"),JSON.stringify(n,null,2),"utf-8");let s={id:"default_headers",name:"Default Headers",headers:{"Content-Type":"application/json",Accept:"application/json"}};await ee.promises.writeFile(L.join(e,"default-headers.json"),JSON.stringify(s,null,2),"utf-8")}dispose(){for(let e of this.fileWatchers)e.dispose();this.fileWatchers=[]}}});var vg,Hs,_c=k(()=>{"use strict";$n();vg="httpForge.cookies",Hs=class{constructor(e,t=vg){this.store=e;this.storeKey=t;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((t,n)=>{e[n]=t}),await this.store.update(this.storeKey,e)}catch(e){console.error("[CookieService] Failed to save cookies:",e)}}getCookieKey(e,t,n){return oe.cookieKey(e,t,n)}get(e,t){if(t){let i=this.getCookieKey(e,t),o=this.cookies.get(i);if(o&&!this.isExpired(o))return o}let n=this.getCookieKey(e,"*"),s=this.cookies.get(n);if(s&&!this.isExpired(s))return s;for(let i of this.cookies.values())if(i.name===e&&!this.isExpired(i))if(t&&i.domain){if(this.domainMatches(t,i.domain))return i}else return i}async set(e){let t=this.getCookieKey(e.name,e.domain,e.path);this.cookies.set(t,e),await this.saveCookies()}async setFromResponse(e){for(let t of e){let n=this.getCookieKey(t.name,t.domain,t.path);this.cookies.set(n,t)}await this.saveCookies()}has(e,t){return this.get(e,t)!==void 0}async delete(e,t,n){let s=this.getCookieKey(e,t,n),i=this.cookies.delete(s);return i&&await this.saveCookies(),i}getAll(e){let t=[];for(let n of this.cookies.values())this.isExpired(n)||(e?(!n.domain||this.domainMatches(e,n.domain))&&t.push(n):t.push(n));return t}getCookieHeader(e){let t=this.getAll(e);return oe.formatCookieHeader(t)}async clear(){this.cookies.clear(),await this.saveCookies()}async clearDomain(e){let t=[];for(let[n,s]of this.cookies.entries())s.domain&&this.domainMatches(e,s.domain)&&t.push(n);for(let n of t)this.cookies.delete(n);await this.saveCookies()}parseCookieHeaders(e,t){return oe.parseCookieHeaders(e,t)}isExpired(e){return oe.isExpired(e)}cleanExpiredCookies(){let e=[];for(let[t,n]of this.cookies.entries())this.isExpired(n)&&e.push(t);for(let t of e)this.cookies.delete(t);e.length>0&&this.saveCookies()}domainMatches(e,t){return oe.domainMatches(e,t)}get count(){return this.cookies.size}}});var Bs,Dc=k(()=>{"use strict";$n();Bs=class{constructor(e){this.cookieService=e;this.localCache=[...e.getAll()]}cookieService;localCache=[];pendingOperations=[];get(e,t){return t?this.localCache.find(n=>n.name===e&&(!n.domain||n.domain===t||t.endsWith(n.domain))):this.localCache.find(n=>n.name===e)}has(e,t){return this.get(e,t)!==void 0}set(e){let t=this.localCache.findIndex(n=>n.name===e.name&&(!e.domain||n.domain===e.domain));t>=0?this.localCache[t]=e:this.localCache.push(e),this.pendingOperations.push({type:"set",cookie:e})}delete(e,t,n){let s=this.localCache.findIndex(i=>i.name===e&&(!t||i.domain===t||i.domain&&t.endsWith(i.domain)));return s>=0&&this.localCache.splice(s,1),this.pendingOperations.push({type:"delete",name:e,domain:t,path:n}),!0}getAll(e){return e?this.localCache.filter(t=>{let n=t.domain||"";return n===e||e.endsWith(n)}):[...this.localCache]}getCookiesForDomain(e){return this.localCache.filter(t=>{let n=t.domain||"";return n===e||e.endsWith(n)})}async setCookiesFromResponse(e,t){let n=new URL(e).hostname,s=this.cookieService.parseCookieHeaders(t,n);s.length>0&&(s.forEach(i=>{let o=this.localCache.findIndex(a=>a.name===i.name&&a.domain===(i.domain||n));o>=0?this.localCache[o]=i:this.localCache.push(i)}),await this.cookieService.setFromResponse(s))}getCookieHeader(e){let t=new URL(e).hostname,n=new URL(e).pathname,s=this.localCache.filter(i=>!(oe.isExpired(i)||i.domain&&!oe.domainMatches(t,i.domain)||!i.domain||i.path&&!n.startsWith(i.path)));if(s.length!==0)return oe.formatCookieHeader(s)}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 Mc(r){try{let e=JSON.parse(typeof r=="string"?r:r.toString("utf-8"));if(!e)return null;let t=e.environment||e,n=t.name||e.name||"imported-environment",s=t.values||t.variables||e.values||e.variables||[],i={};if(Array.isArray(s))for(let a of s){if(!a)continue;let c=a.key??a.name,l=typeof a.enabled=="boolean"?a.enabled:!0;c&&l!==!1&&(i[c]=a.value??a.initial??"")}else if(typeof s=="object"&&s!==null)for(let[a,c]of Object.entries(s))i[a]=String(c??"");let o=t._postman_exported_at?"Imported from Postman export":t.description||"";return{name:n,variables:i,description:o}}catch{return null}}var jc=k(()=>{"use strict"});import*as Oe from"fs";import*as et from"path";var Us,Vs,Lc=k(()=>{"use strict";Ze();jc();go();Xi();Ar();Us={SELECTED_ENVIRONMENT:"httpForge.selectedEnvironment",ENV_OVERRIDES_PREFIX:"httpForge.envOverrides."},Vs=class{constructor(e,t,n,s,i,o=!0){this.workspaceFolder=e;this.workspaceStore=t;this.configService=n;this.fileWatcherFactory=s;this.secretStore=i;this.persistOverrides=o;let a=n.getEnvironmentsPath();this.environmentsPath=a,this.sharedConfigPath=et.join(a,"_global.json"),this.localConfigPath=et.join(a,"_global.local.json"),this.historiesPath=n.getHistoryPath();let c=t?.get(Us.SELECTED_ENVIRONMENT),l=this.configService.getEnvironmentsConfig,u=typeof l=="function"?l.call(this.configService)?.default:void 0;this.selectedEnvironment=c??(u||"dev"),this.localGlobalValues={},this.localEnvironmentValues=new Map,this.persistOverrides&&this.loadPersistedEnvironmentOverrides(),this.loadSecretVariables(this.selectedEnvironment).catch(()=>{}),this.setupFileWatcher(),this.configService.onConfigReloaded=()=>this.invalidateResolvedConfigCache()}workspaceFolder;workspaceStore;configService;fileWatcherFactory;secretStore;persistOverrides;environmentsPath;sharedConfigPath;localConfigPath;historiesPath;sharedConfig=null;localConfig=null;selectedEnvironment="dev";fileWatcher;resolvedConfigCache=new Map;localGlobalValues={};localEnvironmentValues=new Map;secretValuesCache=new Map;onEnvironmentsChanged;setupFileWatcher(){if(!this.fileWatcherFactory||!Oe.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(!Oe.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(Us.SELECTED_ENVIRONMENT,e),!this.localEnvironmentValues.has(e)){let t=this.getEnvOverridesStateKey(e),n=this.workspaceStore?.get(t,{});n&&Object.keys(n).length>0&&this.localEnvironmentValues.set(e,{...n})}await this.loadSecretVariables(e),this.resolvedConfigCache.delete(e)}getEnvOverridesStateKey(e){return`${Us.ENV_OVERRIDES_PREFIX}${e||this.selectedEnvironment}`}loadPersistedEnvironmentOverrides(){let e=this.getEnvOverridesStateKey(),t=this.workspaceStore?.get(e,{});t&&Object.keys(t).length>0&&this.localEnvironmentValues.set(this.selectedEnvironment,{...t})}persistEnvironmentOverrides(e){if(!this.persistOverrides)return;let t=this.getEnvOverridesStateKey(e),n=this.localEnvironmentValues.get(e)||{};this.workspaceStore?.update(t,n)}setEnvironmentVariable(e,t,n){let s=n??this.selectedEnvironment;this.localEnvironmentValues.has(s)||this.localEnvironmentValues.set(s,{}),this.localEnvironmentValues.get(s)[e]=String(t),this.persistEnvironmentOverrides(s)}deleteEnvironmentVariable(e,t){let n=t??this.selectedEnvironment,s=this.localEnvironmentValues.get(n);s&&(delete s[e],this.persistEnvironmentOverrides(n))}clearEnvironmentVariables(e){let t=e??this.selectedEnvironment;this.localEnvironmentValues.set(t,{}),this.persistEnvironmentOverrides(t)}async resetEnvironmentOverrides(e){let t=e||this.selectedEnvironment;this.localEnvironmentValues.delete(t),await this.workspaceStore?.update(this.getEnvOverridesStateKey(t),void 0)}getEnvironmentVariableLocal(e){return this.localEnvironmentValues.get(this.selectedEnvironment)?.[e]}getEnvironmentVariableLocals(){return{...this.localEnvironmentValues.get(this.selectedEnvironment)||{}}}getAllEnvironmentVariableLocals(){let e={};for(let[t,n]of this.localEnvironmentValues)e[t]={...n};return e}setGlobalVariable(e,t){this.localGlobalValues[e]=String(t)}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 t=e||this.selectedEnvironment,n=this.getSharedConfig(),s=this.getLocalConfig();if(!n?.environments?.[t])return null;let i=n.environments[t],o=s?.credentials?.[t],a=s?.variables||{},c=o?.variables||{},l=o&&o.headers||{},u=Vi(n.defaultHeaders||{},l),d=this.localEnvironmentValues.get(t)||{},p=this.secretValuesCache.get(t)||{},m={...i.variables||{},...c,...d,...p};return{name:t,description:i.description,requiresConfirmation:i.requiresConfirmation,headers:u,variables:m}}async getSecretVariable(e,t){return this.secretStore?.get(`${e}:${t}`)}async setSecretVariable(e,t,n){await this.secretStore?.store(`${e}:${t}`,n),this.secretValuesCache.has(e)||this.secretValuesCache.set(e,{}),this.secretValuesCache.get(e)[t]=n}async deleteSecretVariable(e,t){await this.secretStore?.delete(`${e}:${t}`),this.secretValuesCache.get(e)&&delete this.secretValuesCache.get(e)[t]}async loadSecretVariables(e){if(!this.secretStore)return;let t=e||this.selectedEnvironment,n=this.getSharedConfig()?.environments?.[t]?.secretVariables??[];if(n.length===0)return;let s={};await Promise.all(n.map(async i=>{let o=await this.secretStore.get(`${t}:${i}`);o!==void 0&&(s[i]=o)})),this.secretValuesCache.set(t,s)}resolveVariables(e,t){return this.createResolver(t).resolveString(e,!0)}exportEnvironmentsToFolder(e,t=!0){let n=this.getEnvironmentNames(),s=this.getSharedConfig(),i=s?.globalVariables?{...s.globalVariables}:{};if(!t&&Object.keys(i).length){let o=et.join(e,"globals.env");Nr(o,i)}n.forEach(o=>{let a=s?.environments?.[o];if(!a)return;let c={...a.variables||{}};t&&(c={...i,...c});let l=et.join(e,`${xe(o)}.env`);Nr(l,c)})}resolveVariablesWithExtra(e,t,n){return this.createResolver(n,t).resolveString(e,!0)}resolveVariablesInObject(e,t){return this.createResolver(t).resolveObject(e,!0)}resolveVariablesInObjectWithExtra(e,t,n){return this.createResolver(n,t).resolveObject(e,!0)}getHistoriesPath(){return this.historiesPath}getSharedConfigPath(){return this.sharedConfigPath}getLocalConfigPath(){return this.localConfigPath}getEnvironmentConfigPath(e){return et.join(this.environmentsPath,`${e}.json`)}localConfigExists(){return Oe.existsSync(this.localConfigPath)}saveSharedConfig(e){this.saveFolderSharedConfig(e),this.sharedConfig=e}saveLocalConfig(e){let t={variables:e.variables||{}};this.saveJsonFile(this.localConfigPath,t);for(let[n,s]of Object.entries(e.credentials||{})){let i=this.getEnvLocalConfigPath(n),o={variables:s.variables||{}};this.saveJsonFile(i,o)}this.localConfig=e}importPostmanEnvironmentFile(e){try{let t=Oe.readFileSync(e,"utf-8"),n=Mc(t);if(!n)throw new Error("Failed to parse Postman environment file");this.sharedConfig||this.loadConfigs(),this.sharedConfig||(this.sharedConfig={environments:{},globalVariables:{},defaultHeaders:{}});let s=n.name||`imported-${Date.now()}`;return this.sharedConfig.environments=this.sharedConfig.environments||{},this.sharedConfig.environments[s]=this.sharedConfig.environments[s]||{},this.sharedConfig.environments[s].variables=n.variables,n.description&&(this.sharedConfig.environments[s].description=n.description),this.saveSharedConfig(this.sharedConfig),n}catch(t){throw console.error("[EnvironmentConfigService] importPostmanEnvironmentFile failed:",t),t}}saveEnvLocalConfig(e,t){let n=this.getEnvLocalConfigPath(e),s={variables:t};this.saveJsonFile(n,s),this.localConfig||(this.localConfig={credentials:{},variables:{}}),this.localConfig.credentials||(this.localConfig.credentials={}),this.localConfig.credentials[e]={variables:t}}getEnvLocalPath(e){return this.getEnvLocalConfigPath(e)}getEnvLocalConfigPath(e){return et.join(this.environmentsPath,`${e}.local.json`)}loadFolderConfigs(){let e=vs(this.environmentsPath);this.sharedConfig={environments:e.environments,globalVariables:e.globalVariables,defaultHeaders:e.defaultHeaders},this.localConfig={credentials:e.localCredentials,variables:e.localVariables}}createResolver(e,t){let s=this.getResolvedEnvironment(e)?.variables||{},i=this.getGlobalVariables(),o=this.getGlobalVariableLocals();return new Mn({globals:i,collectionVariables:{},environmentVariables:s,variables:{...o,...t||{}}})}saveFolderSharedConfig(e){Oe.existsSync(this.environmentsPath)||Oe.mkdirSync(this.environmentsPath,{recursive:!0});let t={$schema:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/global-environment.schema.json",variables:e.globalVariables||{},defaultHeaders:e.defaultHeaders||{}};this.saveJsonFile(this.sharedConfigPath,t);let n=Oe.readdirSync(this.environmentsPath).filter(i=>i.endsWith(".json")).filter(i=>!Yi(i)),s=new Set(Object.keys(e.environments||{}));for(let i of n){let o=et.basename(i,".json");if(!s.has(o))try{Oe.unlinkSync(et.join(this.environmentsPath,i))}catch{}}for(let[i,o]of Object.entries(e.environments||{})){let a={$schema:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/environment.schema.json",name:i,description:o.description,requiresConfirmation:o.requiresConfirmation,variables:o.variables||{}};this.saveJsonFile(et.join(this.environmentsPath,`${i}.json`),a)}}reload(){this.sharedConfig=null,this.localConfig=null,this.loadConfigs(),this.invalidateResolvedConfigCache()}invalidateResolvedConfigCache(){this.resolvedConfigCache.clear()}getFileOnlyVariables(e){this.loadConfigs();let t=this.sharedConfig,n=this.localConfig,s=t?.environments?.[e];return{...t?.globalVariables||{},...n?.variables||{},...s?.variables||{},...n?.credentials?.[e]?.variables||{}}}resolveConfigValues(e,t){if(e==null)return e;if(typeof e=="string"){let n=new Mn({globals:{},collectionVariables:{},environmentVariables:t,variables:{}});if(/^\s*\{\{.*\}\}\s*$/.test(e)){let s=n.resolveString(e);if(s==="true")return!0;if(s==="false")return!1;let i=Number(s);return s!==""&&!isNaN(i)?i:s}return n.resolveString(e)}if(Array.isArray(e))return e.map(n=>this.resolveConfigValues(n,t));if(typeof e=="object"){let n={};for(let[s,i]of Object.entries(e))n[s]=this.resolveConfigValues(i,t);return n}return e}getResolvedConfig(e){let t=e??this.selectedEnvironment;if(!this.resolvedConfigCache.has(t)){let n=this.configService.getConfig(),s=this.getFileOnlyVariables(t),i=this.resolveConfigValues(n,s);this.resolvedConfigCache.set(t,i)}return this.resolvedConfigCache.get(t)}getAllEnvironments(){return this.loadConfigs(),this.sharedConfig?Object.entries(this.sharedConfig.environments).map(([e,t])=>({id:e,name:e,active:e===this.selectedEnvironment,variables:t.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 t=Object.keys(this.sharedConfig.environments);this.selectedEnvironment=t.length>0?t[0]:"dev",await this.workspaceStore?.update(Us.SELECTED_ENVIRONMENT,this.selectedEnvironment)}this.saveSharedConfig(this.sharedConfig)}async duplicateEnvironment(e,t){this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentName(t),this.validateEnvironmentExists(e),this.validateEnvironmentNameNotTaken(t);let n=this.sharedConfig.environments[e];this.sharedConfig.environments[t]=JSON.parse(JSON.stringify(n)),this.sharedConfig.environments[t].description=`Copied from ${e}`,this.saveSharedConfig(this.sharedConfig)}async renameEnvironment(e,t){this.loadConfigs(),this.validateConfigLoaded(),this.validateEnvironmentName(t),this.validateEnvironmentExists(e),t!==e&&(this.validateEnvironmentNameNotTaken(t),this.sharedConfig.environments[t]=this.sharedConfig.environments[e],delete this.sharedConfig.environments[e],this.selectedEnvironment===e&&(this.selectedEnvironment=t,await this.workspaceStore?.update(Us.SELECTED_ENVIRONMENT,t)),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,t){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=t,this.saveSharedConfig(this.sharedConfig)}saveJsonFile(e,t){try{let n=et.dirname(e);Oe.existsSync(n)||Oe.mkdirSync(n,{recursive:!0}),Oe.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}catch(n){throw console.error(`Failed to save JSON to ${e}:`,n),n}}}});function bg(r){return r?[...new Set(Array.from(r).filter(e=>typeof e=="string"&&e.length>0))]:[]}function Hc(r,e){let t=bg(e);return t.length>0&&Ld.set(r,t),r}function Mr(r){return r?Ld.get(r)??[]:[]}function Bc(r,e){return Hc(e,Mr(r))}function Ud(r){return r.split("{{").join(Hd).split("}}").join(Bd)}function zs(r){return r.split(Hd).join("{{").split(Bd).join("}}")}function Dr(r){if(typeof r=="string")return zs(r);if(Array.isArray(r))return r.map(e=>Dr(e));if(r!==null&&typeof r=="object"){let e=Object.getPrototypeOf(r);if(e!==Object.prototype&&e!==null)return r;let t={};for(let[n,s]of Object.entries(r))t[n]=Dr(s);return t}return r}var Ld,Hd,Bd,jr=k(()=>{"use strict";Ld=new WeakMap,Hd="__HF_SECRET_OPEN__",Bd="__HF_SECRET_CLOSE__"});function Uc(){let r=new Error("WebSocket request cancelled");return r.name="AbortError",r}function xg(r){return r===void 0||!Number.isFinite(r)?Sg:Math.max(0,Math.floor(r))}function wg(r){if(!(!r||!Number.isFinite(r)||r<=0))return Math.floor(r*1024*1024)}function Rg(r){let t=r.websocket?.settings?.handshakeTimeout,n=t&&t>0?t:r.settings?.timeout;if(!(!r.settings&&n===void 0))return{...r.settings??{},...n!==void 0?{timeout:n}:{}}}function Cg(r,e){return e==="hex"?Buffer.from(r,"hex"):Buffer.from(r,"base64")}function kg(r,e){if(r.isBinary){let n=r.data;return{direction:e,type:"binary",data:Buffer.from(n).toString("base64"),encoding:"base64",size:n.byteLength,time:Date.now()}}let t=String(r.data);return{direction:e,type:"text",data:t,size:Buffer.byteLength(t,"utf8"),time:Date.now()}}async function Eg(r,e,t){let n=t.type==="binary"?"binary":"text",s=n==="binary"?t.encoding==="hex"?"hex":"base64":void 0,i=t.data??"",o=n==="binary"?Cg(i,s):i;await r.send(o),e.frames.push({direction:"out",type:n,data:i,...s?{encoding:s}:{},size:n==="binary"?o.length:Buffer.byteLength(i,"utf8"),time:Date.now()})}function qg(r,e,t){return new Promise(n=>{let s=!1,i,o,a=()=>{s||(s=!0,o&&clearTimeout(o),i?.dispose(),t?.removeEventListener("abort",a),n())};if(i=r.onClose(a),t?.addEventListener("abort",a,{once:!0}),r.state!=="open"){a();return}o=setTimeout(a,e)})}async function Js(r,e,t){if(r.state!=="closed")try{await r.close(e,t)}catch{}}async function Vd(r,e,t,n){if(e.websocket?.protocol==="socketio")throw new Error("Socket.IO requests must use runSocketIoRequest, not runWebSocketRequest");let s=Date.now(),i=e.websocket,o=xg(i?.settings?.responseTimeout),a={protocol:"websocket",frames:[]},c=await r.connect({url:t.url,headers:t.headers,protocols:i?.subprotocols,settings:Rg(e),maxPayloadBytes:wg(i?.settings?.maxMessageSizeMb),signal:n}),l=[],u;try{l.push(c.onFrame(d=>{a.frames.push(kg(d,"in"))})),l.push(c.onClose(d=>{u=d})),l.push(c.onError(d=>{a.frames.push({direction:"system",type:"text",data:`Error: ${d.message}`,size:0,time:Date.now()})}));for(let d of i?.messages??[])if(d.enabled!==!1){if(n?.aborted)throw await Js(c,1001,"Run cancelled"),Uc();await Eg(c,a,d)}if(n?.aborted)throw await Js(c,1001,"Run cancelled"),Uc();if(o>0&&c.state==="open"&&await qg(c,o,n),n?.aborted)throw await Js(c,1001,"Run cancelled"),Uc();return await Js(c,1e3,"Run complete"),u&&(a.close={...u}),{status:101,statusText:"Switching Protocols",headers:c.handshakeHeaders??{},cookies:[],body:a,time:Date.now()-s,size:Buffer.byteLength(JSON.stringify(a),"utf8")}}finally{for(let d of l)d.dispose();c.state!=="closed"&&await Js(c,1e3,"Run complete")}}var Sg,zd=k(()=>{"use strict";Sg=1e3});function Jd(r,e){return e==="hex"?new Uint8Array(Buffer.from(r,"hex")):new Uint8Array(Buffer.from(r,"base64"))}function Ws(r){if(r==null)return"";if(typeof r=="string")return r;if(r instanceof Uint8Array||Buffer.isBuffer(r))return Buffer.from(r).toString("base64");try{return JSON.stringify(r)}catch{return String(r)}}function Pg(r,e,t,n){let s=r.data||"",i=e==="binary"?Jd(s,r.encoding).length:Buffer.byteLength(s,"utf8");return{direction:"out",type:e,data:s,encoding:e==="binary"?r.encoding||"base64":void 0,event:t,args:(r.args||[]).map(o=>String(o)),ack:r.ack===!0,size:i,time:Date.now()}}function Ig(r){let e=Array.isArray(r.args)?r.args:[],t=e[0],n=t instanceof Uint8Array||Buffer.isBuffer(t),s=e.slice(1).map(l=>Ws(l)),i="",o=0,a="text",c;return e.length===0?(i="",o=0):n?(a="binary",c="base64",i=Buffer.from(t).toString("base64"),o=t.byteLength):typeof t=="string"?(i=t,o=Buffer.byteLength(t,"utf8")):(i=Ws(t),o=Buffer.byteLength(i,"utf8")),o+=s.reduce((l,u)=>l+Buffer.byteLength(u,"utf8"),0),{direction:"in",type:a,data:i,encoding:c,event:r.event,args:s,size:o,time:Date.now()}}async function Wd(r,e,t,n){let s=Date.now(),i=(e.websocket?.messages??[]).filter(h=>h.enabled!==!1),o=e.websocket?.settings,a=o?.responseTimeout??Ag,c=o?.handshakeTimeout&&o.handshakeTimeout>0?o.handshakeTimeout:(e.settings?.timeout??0)||3e4,l=[],u,d="Run complete",p,m,f;try{let h=e.websocket?.socketio,g={url:t.url,headers:t.headers,path:h?.handshakePath||"/socket.io",clientVersion:h?.clientVersion,namespace:h?.namespace,auth:h?.auth,transports:h?.transports,timeout:c,reconnectionAttempts:o?.reconnectionAttempts??0,reconnectionDelay:o?.reconnectionInterval??5e3};if(u=await r.connect(g),p=u.onEvent(y=>{l.push(Ig(y))}),m=u.onError(y=>{l.push({direction:"system",type:"text",data:y.message,size:0,time:Date.now()})}),f=u.onDisconnect(y=>{d=y||d}),n?.aborted)throw new Error("Request aborted");for(let y of i){if(n?.aborted)throw new Error("Request aborted");let S=y.event?.trim()||"message",b=y.type==="binary"?"binary":"text",C=b==="binary"?Jd(y.data,y.encoding):y.data,w=(y.args||[]).map(F=>F),E=[C,...w];if(l.push(Pg(y,b,S,E)),y.ack===!0){let F=await u.send(S,E,!0);F&&F.length>0&&l.push({direction:"in",type:"text",data:F.map(N=>Ws(N)).join(" "),event:"ack",args:F.map(N=>Ws(N)),ack:!0,size:F.reduce((N,j)=>N+Buffer.byteLength(Ws(j),"utf8"),0),time:Date.now()})}else await u.send(S,E,!1)}a>0&&!n?.aborted&&await new Promise(y=>{let S=setTimeout(y,a),b=()=>{clearTimeout(S),y()};n?.addEventListener("abort",b,{once:!0})}),u.close(),u.dispose(),p.dispose(),m.dispose(),f.dispose();let v={protocol:"socketio",frames:l,close:{code:1e3,reason:d,wasClean:!0}};return{status:101,statusText:"Switching Protocols",headers:{},body:v,cookies:[],time:Date.now()-s,size:Buffer.byteLength(JSON.stringify(v),"utf8")}}catch(h){try{p?.dispose(),m?.dispose(),f?.dispose(),u?.dispose()}catch{}throw h}}var Ag,Gd=k(()=>{"use strict";Ag=1e3});var Dt,Gs=k(()=>{"use strict";As();jr();zd();Gd();Dt=class r{constructor(e,t,n,s,i,o,a,c,l,u,d,p,m,f,h){this.httpService=e;this.scriptExecutor=t;this.envConfigService=n;this.requestPreparer=s;this.environment=i;this.cookieJar=o;this.collectionScripts=a;this.folderScriptsChain=c;this.onConsoleOutput=l;this.collectionName=u;this.collectionAuth=d;this.iteration=p;this.iterationCount=m;this.webSocketClient=f;this.socketIoClient=h}httpService;scriptExecutor;envConfigService;requestPreparer;environment;cookieJar;collectionScripts;folderScriptsChain;onConsoleOutput;collectionName;collectionAuth;iteration;iterationCount;webSocketClient;socketIoClient;async execute(e,t,n){if(e.requestType==="websocket"&&e.websocket?.protocol!=="socketio"&&!this.webSocketClient)throw new Error("WebSocket execution is not configured for this runner");if(e.requestType==="websocket"&&e.websocket?.protocol==="socketio"&&!this.socketIoClient)throw new Error("Socket.IO execution is not configured for this runner");let s=Date.now();return this.executeWithSession(e,t,n,s)}async executeWithSession(e,t,n,s){let i=this.collectPreRequestScripts(e),o=this.collectPostResponseScripts(e),a=this.envConfigService.getResolvedEnvironment(this.environment);if(!a)throw new Error(`Environment "${this.environment}" not found or not configured`);let c=this.envConfigService.getGlobalVariables(),l={request:e,variables:{...t},environmentVariables:a.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(p,m,f)=>{p==="set"&&m&&f!==void 0?this.envConfigService.setEnvironmentVariable(m,f,this.environment):p==="unset"&&m?this.envConfigService.deleteEnvironmentVariable(m,this.environment):p==="clear"&&this.envConfigService.clearEnvironmentVariables(this.environment)},onGlobalsChange:(p,m,f)=>{p==="set"&&m&&f!==void 0?this.envConfigService.setGlobalVariable(m,f):p==="unset"&&m?this.envConfigService.deleteGlobalVariable(m):p==="clear"&&this.envConfigService.clearGlobalVariables()}},u=this.scriptExecutor.createRequestSession(l),d=null;try{let p={...t},m={...e},f;if((!m.auth||m.auth.type==="inherit")&&(m.auth=this.collectionAuth&&this.collectionAuth.type!=="inherit"?this.collectionAuth:void 0),i.length>0){let O=await u.executePreRequest(i);if(O.consoleOutput&&O.consoleOutput.length>0&&this.onConsoleOutput?.(O.consoleOutput,{requestName:e.name||"",phase:"pre-request"}),O.nextRequest!==void 0&&(f=O.nextRequest),O.skipRequest){let D={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:{url:e.url||"",method:e.method||"GET",headers:{},body:D,params:{},query:{}},response:{status:0,statusText:"Skipped",headers:{},body:null,time:0,cookies:[]},duration:Date.now()-s,timestamp:Date.now(),passed:!0,assertions:[],modifiedVariables:p,nextRequest:f}}O.success&&(O.modifiedRequest&&(O.modifiedRequest.url&&(m.url=O.modifiedRequest.url),O.modifiedRequest.headers&&(m.headers=O.modifiedRequest.headers),O.modifiedRequest.params&&(m.params=O.modifiedRequest.params),O.modifiedRequest.query&&(m.query=O.modifiedRequest.query),O.modifiedRequest.body!==void 0&&(m.body=O.modifiedRequest.body)),(O.localVariables??O.modifiedVariables)&&(p=O.localVariables??O.modifiedVariables))}d=await this.requestPreparer.prepareRequest(m,this.environment,a,p);let{url:h,headers:g,body:v,method:y}=d,S={};for(let O in g)Object.prototype.hasOwnProperty.call(g,O)&&(S[O.toUpperCase()]=g[O]);if(!S.COOKIE&&m.settings?.includeCookies!==!1&&this.cookieJar){let D=this.cookieJar.getCookieHeader(h);D&&(S.COOKIE=D)}let b;if(m.requestType==="websocket")if(d={...d,headers:S,body:{type:"none",content:null}},m.websocket?.protocol==="socketio"){if(!this.socketIoClient)throw new Error("Socket.IO execution is not configured for this runner");b=await Wd(this.socketIoClient,m,d,n)}else{if(!this.webSocketClient)throw new Error("WebSocket execution is not configured for this runner");b=await Vd(this.webSocketClient,m,d,n)}else{let O={method:y,url:h,headers:S,body:v.content,signal:n,settings:m.settings?{...m.settings}:void 0};b=await this.httpService.execute(O)}this.cookieJar&&b.headers&&await this.cookieJar.setCookiesFromResponse(h,b.headers);let C=Date.now()-s,w=[],E={},F;if(o.length>0){let O=0;if(b.body)if(typeof b.body=="string")O=Buffer.byteLength(b.body,"utf8");else if(Buffer.isBuffer(b.body))O=b.body.length;else try{O=Buffer.byteLength(JSON.stringify(b.body),"utf8")}catch{O=0}let D=ao(b.headers,b.cookies,d.url),P={executedRequest:d,status:b.status,statusText:b.statusText,headers:Sc(b.headers||{}),body:b.body,cookies:D,responseTime:b.time,responseSize:O},M=await u.executePostResponse(o,P);w=M.testResults,E=M.modifiedEnvironmentVariables||{},F=M.visualizerData,(M.localVariables??M.modifiedVariables)&&(p=M.localVariables??M.modifiedVariables),M.nextRequest!==void 0&&(f=M.nextRequest),M.consoleOutput&&M.consoleOutput.length>0&&this.onConsoleOutput?.(M.consoleOutput,{requestName:e.name||"",phase:"post-response"})}let N=w.length===0||w.every(O=>O.passed),j=w.length>0?N:m.requestType==="websocket"?b.status===101:b.status>=200&&b.status<=302;return{requestId:e.id,name:e.name,executedRequest:Bc(d,{...d,headers:S}),response:{status:b.status,statusText:b.statusText,headers:b.headers||{},body:b.body,time:b.time||C,cookies:b.cookies||[]},duration:C,timestamp:Date.now(),passed:j,assertions:w,modifiedVariables:p,modifiedEnvironmentVariables:E,nextRequest:f,visualizerData:F}}catch(p){return this.handleError(e,d,p,s)}finally{u.dispose?.()}}collectPreRequestScripts(e){let t=[];if(this.collectionScripts?.preRequest&&t.push(this.collectionScripts.preRequest),this.folderScriptsChain)if(Array.isArray(this.folderScriptsChain))for(let n of this.folderScriptsChain)n?.preRequest&&t.push(n.preRequest);else this.folderScriptsChain.preRequest&&t.push(this.folderScriptsChain.preRequest);return e.scripts?.preRequest&&t.push(e.scripts.preRequest),t}collectPostResponseScripts(e){let t=[];if(e.scripts?.postResponse&&t.push(e.scripts.postResponse),this.folderScriptsChain)if(Array.isArray(this.folderScriptsChain)){let n=[...this.folderScriptsChain].reverse();for(let s of n)s?.postResponse&&t.push(s.postResponse)}else this.folderScriptsChain.postResponse&&t.push(this.folderScriptsChain.postResponse);return this.collectionScripts?.postResponse&&t.push(this.collectionScripts.postResponse),t}handleError(e,t,n,s){let i=Date.now()-s,o=t?.method||e.method,a=t?.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),l=n?.stack?String(n.stack):"",u=this.errorBodyFormat,d,p;u==="html"||u==="both"?(d=r.formatErrorAsHtml(c,l),p={"content-type":"text/html; charset=utf-8"}):(d=c,p={});let m={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:Bc(t,{url:a||"",method:o||"GET",headers:t?.headers||{},body:t?.body||m,params:t?.params||{},query:t?.query||{}}),response:{status:0,statusText:n.name==="AbortError"?"Aborted":n.code||n.message||"Request Error",headers:p,cookies:[],body:d,time:0},duration:i,timestamp:Date.now(),passed:!1,assertions:[],error:c}}get errorBodyFormat(){return"text"}static formatErrorAsHtml(e,t){let n=s=>s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");return`<!doctype html>
|
|
605
605
|
<html>
|
|
606
606
|
<body style="font-family:system-ui,Segoe UI,Roboto,-apple-system,Helvetica,Arial,sans-serif;padding:12px;color:#c7254e;">
|
|
607
607
|
<h2 style="margin-top:0;color:#a94442">Request Error</h2>
|
|
@@ -610,7 +610,7 @@ ${s}
|
|
|
610
610
|
${n(t)}
|
|
611
611
|
</pre>`:""}
|
|
612
612
|
</body>
|
|
613
|
-
</html>`}}});var Ks,Vc=k(()=>{"use strict";Ze();jr();Ks=class{constructor(e,t,n,s,i,o){this.envConfigService=e;this.httpService=t;this.preprocessor=n;this.tokenManager=s;this.appInfo=i;this.secretRegistry=o}envConfigService;httpService;preprocessor;tokenManager;appInfo;secretRegistry;async prepareRequest(e,t,n,s){let i=[];if(this.secretRegistry?.hasProviders){let C=await this.secretRegistry.resolveSecretTokens([e,n,s]);if(Object.keys(C).length>0){i=Object.values(C);let w={};for(let[E,F]of Object.entries(C))w[E]=Ud(F);s={...w,...s??{}}}}let o=s&&Object.keys(s).length>0,a=i.length>0,c=o?this.envConfigService.resolveVariablesInObjectWithExtra(e.params||{},s,t):this.envConfigService.resolveVariablesInObject(e.params||{},t),l=o?this.envConfigService.resolveVariablesInObjectWithExtra(e.query||{},s,t):this.envConfigService.resolveVariablesInObject(e.query||{},t),u=Vi(n?.headers||{},e.headers||{}),d=o?this.envConfigService.resolveVariablesInObjectWithExtra(u,s,t):this.envConfigService.resolveVariablesInObject(u,t);if(d=this.preprocessor.sanitizeHeaders(d),!Object.keys(d).some(C=>C.toLowerCase()==="user-agent")){let C=this.appInfo?.version||"0.0.0",w=this.appInfo?.name||"HttpForge";d["User-Agent"]=`${w}/${C}`}if(e.auth?.type==="bearer"&&e.auth.bearerToken){let C=o?this.envConfigService.resolveVariablesWithExtra(e.auth.bearerToken,s,t):this.envConfigService.resolveVariables(e.auth.bearerToken,t),w=a?zs(C):C;d.Authorization=`Bearer ${w}`}if(e.auth?.type==="basic"&&e.auth.basicAuth){let C=o?this.envConfigService.resolveVariablesWithExtra(e.auth.basicAuth.username||"",s,t):this.envConfigService.resolveVariables(e.auth.basicAuth.username||"",t),w=o?this.envConfigService.resolveVariablesWithExtra(e.auth.basicAuth.password||"",s,t):this.envConfigService.resolveVariables(e.auth.basicAuth.password||"",t),E=a?zs(C):C,F=a?zs(w):w,N=Buffer.from(`${E}:${F}`).toString("base64");d.Authorization=`Basic ${N}`}e.auth?.type==="apikey"&&e.auth.apikey&&this.applyApiKey(e.auth.apikey,d,l,t,s),e.auth?.type==="oauth2"&&e.auth.oauth2&&await this.applyOAuth2(e.auth.oauth2,d,t,s);let m=null;if(e.body&&e.body.type!=="none"){let C=s&&Object.keys(s).length>0?this.envConfigService.resolveVariablesInObjectWithExtra(e.body.content,s,t):this.envConfigService.resolveVariablesInObject(e.body.content,t),w=a?Dr(C):C;if((e.body.format==="json"||e.body.type==="graphql")&&typeof w=="string")try{w=JSON.parse(w)}catch{e.body.format==="json"&&console.warn("[RequestPreparer] Failed to parse JSON body after variable resolution, keeping as string")}let E={type:e.body.type,format:e.body.format,content:w};e.body.type==="form-data"?m=this.buildMultipartFormData(E.content):m=this.preprocessor.encodeBody(E)}e.body?.type!=="form-data"&&this.preprocessor.setContentTypeHeader(d,e.body,e.bodyContentType);let f=e.method||"GET",h=e.url||"",g=s&&Object.keys(s).length>0?this.envConfigService.resolveVariablesWithExtra(h,s,t):this.envConfigService.resolveVariables(h,t),v=this.httpService.buildUrl(g,c,l),y=this.extractQueryFromUrl(v),S={type:e.body?.type||"none",format:e.body?.format,content:m},b={url:v,method:f,headers:d,body:S,params:c,query:y};return Hc(a?Dr(b):b,i)}extractQueryFromUrl(e){let t=e.indexOf("?");if(t===-1)return{};let n=e.indexOf("#",t),s=n===-1?e.slice(t+1):e.slice(t+1,n);if(!s)return{};let i={};return new URLSearchParams(s).forEach((a,c)=>{i[c]=a}),i}async applyOAuth2(e,t,n,s){let i=s&&Object.keys(s).length>0,o=s?Object.keys(s).some(u=>u.startsWith("secret:")):!1,a=i?this.envConfigService.resolveVariablesInObjectWithExtra(e,s,n):e,c=o?Dr(a):a;if(c.accessToken){let u=i?c.accessToken:this.envConfigService.resolveVariables(c.accessToken,n),d=c.tokenPrefix||"Bearer";t.Authorization=`${d} ${u}`;return}if(!this.tokenManager)throw new Error("OAuth2 authentication requires IOAuth2TokenManager. Ensure the service is properly registered.");let l=await this.tokenManager.getToken(c,n);t.Authorization=`${l.tokenType} ${l.accessToken}`}applyApiKey(e,t,n,s,i){if(!e||!e.key)return;let o=i&&Object.keys(i).length>0,a=o?this.envConfigService.resolveVariablesWithExtra(e.key||"",i,s):this.envConfigService.resolveVariables(e.key||"",s),c=o?this.envConfigService.resolveVariablesWithExtra(e.value||"",i,s):this.envConfigService.resolveVariables(e.value||"",s);(e.in||"header").toLowerCase()==="query"?n[a]=c:t[a]=c}buildMultipartFormData(e){if(!Array.isArray(e))return;let t=new FormData;for(let n of e)!n?.key||n.enabled===!1||t.append(n.key,n.value==null?"":String(n.value));return t}}});var
|
|
613
|
+
</html>`}}});var Ks,Vc=k(()=>{"use strict";Ze();jr();Ks=class{constructor(e,t,n,s,i,o){this.envConfigService=e;this.httpService=t;this.preprocessor=n;this.tokenManager=s;this.appInfo=i;this.secretRegistry=o}envConfigService;httpService;preprocessor;tokenManager;appInfo;secretRegistry;async prepareRequest(e,t,n,s){let i=[];if(this.secretRegistry?.hasProviders){let C=await this.secretRegistry.resolveSecretTokens([e,n,s]);if(Object.keys(C).length>0){i=Object.values(C);let w={};for(let[E,F]of Object.entries(C))w[E]=Ud(F);s={...w,...s??{}}}}let o=s&&Object.keys(s).length>0,a=i.length>0,c=o?this.envConfigService.resolveVariablesInObjectWithExtra(e.params||{},s,t):this.envConfigService.resolveVariablesInObject(e.params||{},t),l=o?this.envConfigService.resolveVariablesInObjectWithExtra(e.query||{},s,t):this.envConfigService.resolveVariablesInObject(e.query||{},t),u=Vi(n?.headers||{},e.headers||{}),d=o?this.envConfigService.resolveVariablesInObjectWithExtra(u,s,t):this.envConfigService.resolveVariablesInObject(u,t);if(d=this.preprocessor.sanitizeHeaders(d),!Object.keys(d).some(C=>C.toLowerCase()==="user-agent")){let C=this.appInfo?.version||"0.0.0",w=this.appInfo?.name||"HttpForge";d["User-Agent"]=`${w}/${C}`}if(e.auth?.type==="bearer"&&e.auth.bearerToken){let C=o?this.envConfigService.resolveVariablesWithExtra(e.auth.bearerToken,s,t):this.envConfigService.resolveVariables(e.auth.bearerToken,t),w=a?zs(C):C;d.Authorization=`Bearer ${w}`}if(e.auth?.type==="basic"&&e.auth.basicAuth){let C=o?this.envConfigService.resolveVariablesWithExtra(e.auth.basicAuth.username||"",s,t):this.envConfigService.resolveVariables(e.auth.basicAuth.username||"",t),w=o?this.envConfigService.resolveVariablesWithExtra(e.auth.basicAuth.password||"",s,t):this.envConfigService.resolveVariables(e.auth.basicAuth.password||"",t),E=a?zs(C):C,F=a?zs(w):w,N=Buffer.from(`${E}:${F}`).toString("base64");d.Authorization=`Basic ${N}`}e.auth?.type==="apikey"&&e.auth.apikey&&this.applyApiKey(e.auth.apikey,d,l,t,s),e.auth?.type==="oauth2"&&e.auth.oauth2&&await this.applyOAuth2(e.auth.oauth2,d,t,s);let m=null;if(e.body&&e.body.type!=="none"){let C=s&&Object.keys(s).length>0?this.envConfigService.resolveVariablesInObjectWithExtra(e.body.content,s,t):this.envConfigService.resolveVariablesInObject(e.body.content,t),w=a?Dr(C):C;if((e.body.format==="json"||e.body.type==="graphql")&&typeof w=="string")try{w=JSON.parse(w)}catch{e.body.format==="json"&&console.warn("[RequestPreparer] Failed to parse JSON body after variable resolution, keeping as string")}let E={type:e.body.type,format:e.body.format,content:w};e.body.type==="form-data"?m=this.buildMultipartFormData(E.content):m=this.preprocessor.encodeBody(E)}e.body?.type!=="form-data"&&this.preprocessor.setContentTypeHeader(d,e.body,e.bodyContentType);let f=e.method||"GET",h=e.url||"",g=s&&Object.keys(s).length>0?this.envConfigService.resolveVariablesWithExtra(h,s,t):this.envConfigService.resolveVariables(h,t),v=this.httpService.buildUrl(g,c,l),y=this.extractQueryFromUrl(v),S={type:e.body?.type||"none",format:e.body?.format,content:m},b={url:v,method:f,headers:d,body:S,params:c,query:y};return Hc(a?Dr(b):b,i)}extractQueryFromUrl(e){let t=e.indexOf("?");if(t===-1)return{};let n=e.indexOf("#",t),s=n===-1?e.slice(t+1):e.slice(t+1,n);if(!s)return{};let i={};return new URLSearchParams(s).forEach((a,c)=>{i[c]=a}),i}async applyOAuth2(e,t,n,s){let i=s&&Object.keys(s).length>0,o=s?Object.keys(s).some(u=>u.startsWith("secret:")):!1,a=i?this.envConfigService.resolveVariablesInObjectWithExtra(e,s,n):e,c=o?Dr(a):a;if(c.accessToken){let u=i?c.accessToken:this.envConfigService.resolveVariables(c.accessToken,n),d=c.tokenPrefix||"Bearer";t.Authorization=`${d} ${u}`;return}if(!this.tokenManager)throw new Error("OAuth2 authentication requires IOAuth2TokenManager. Ensure the service is properly registered.");let l=await this.tokenManager.getToken(c,n);t.Authorization=`${l.tokenType} ${l.accessToken}`}applyApiKey(e,t,n,s,i){if(!e||!e.key)return;let o=i&&Object.keys(i).length>0,a=o?this.envConfigService.resolveVariablesWithExtra(e.key||"",i,s):this.envConfigService.resolveVariables(e.key||"",s),c=o?this.envConfigService.resolveVariablesWithExtra(e.value||"",i,s):this.envConfigService.resolveVariables(e.value||"",s);(e.in||"header").toLowerCase()==="query"?n[a]=c:t[a]=c}buildMultipartFormData(e){if(!Array.isArray(e))return;let t=new FormData;for(let n of e)!n?.key||n.enabled===!1||t.append(n.key,n.value==null?"":String(n.value));return t}}});var Tg,Qs,zc=k(()=>{"use strict";Tg=`
|
|
614
614
|
query IntrospectionQuery {
|
|
615
615
|
__schema {
|
|
616
616
|
queryType { name }
|
|
@@ -638,26 +638,26 @@ fragment TypeRef on __Type {
|
|
|
638
638
|
kind name
|
|
639
639
|
ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } } }
|
|
640
640
|
}
|
|
641
|
-
`.trim(),Qs=class{constructor(e){this.httpClient=e}httpClient;schemaCache=new Map;async fetchSchema(e,t){let n={method:"POST",url:e,headers:{...t||{},"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({query:
|
|
642
|
-
`),s=/^\s*(query|mutation|subscription)\s+(\w+)/;for(let i=0;i<n.length;i++){let o=n[i].match(s);o&&t.push({type:o[1],name:o[2],line:i+1})}return t.length===0&&e.trim().startsWith("{")&&t.push({type:"query",name:"(anonymous)",line:1}),t}clearCache(e){e?this.schemaCache.delete(e):this.schemaCache.clear()}schemaToSerializable(e){let t={};for(let[n,s]of e.types)t[n]=s;return{queryType:e.queryType,mutationType:e.mutationType,subscriptionType:e.subscriptionType,types:t,directives:e.directives,fetchedAt:e.fetchedAt,endpointUrl:e.endpointUrl}}parseSchema(e,t){let n=new Map;for(let i of e.types||[]){if(i.name.startsWith("__"))continue;let o={name:i.name,kind:i.kind,description:i.description||void 0,fields:(i.fields||[]).map(a=>this.parseField(a)),inputFields:(i.inputFields||[]).map(a=>this.parseArg(a)),enumValues:(i.enumValues||[]).map(a=>({name:a.name,description:a.description||void 0,isDeprecated:a.isDeprecated||!1,deprecationReason:a.deprecationReason||void 0})),interfaces:(i.interfaces||[]).map(a=>this.renderTypeRef(a)),possibleTypes:(i.possibleTypes||[]).map(a=>this.renderTypeRef(a))};n.set(o.name,o)}let s=(e.directives||[]).map(i=>({name:i.name,description:i.description||void 0,locations:i.locations||[],args:(i.args||[]).map(o=>this.parseArg(o))}));return{queryType:e.queryType?.name||"Query",mutationType:e.mutationType?.name||void 0,subscriptionType:e.subscriptionType?.name||void 0,types:n,directives:s,fetchedAt:Date.now(),endpointUrl:t}}parseField(e){return{name:e.name,type:this.renderTypeRef(e.type),args:(e.args||[]).map(t=>this.parseArg(t)),description:e.description||void 0,isDeprecated:e.isDeprecated||!1,deprecationReason:e.deprecationReason||void 0}}parseArg(e){return{name:e.name,type:this.renderTypeRef(e.type),defaultValue:e.defaultValue??void 0,description:e.description||void 0}}renderTypeRef(e){return e?e.kind==="NON_NULL"?`${this.renderTypeRef(e.ofType)}!`:e.kind==="LIST"?`[${this.renderTypeRef(e.ofType)}]`:e.name||"Unknown":"Unknown"}}});function St(r){let e={};for(let[t,n]of Object.entries(r))Zd.test(t)?e[t]=Array.isArray(n)?n.map(()=>Mt):Mt:e[t]=n;return e}function Wc(r=[]){return r.map(e=>e&&typeof e=="object"&&e.name&&jt.test(e.name)?{...e,value:Mt}:e)}function Jc(r){try{let e=new URL(r),t=!1;for(let[n]of e.searchParams)jt.test(n)&&(e.searchParams.set(n,Mt),t=!0);return t?e.toString():r}catch{return r}}function Zs(r){if(r==null)return r;if(Array.isArray(r))return r.map(t=>Zs(t));if(typeof r!="object")return r;let e={};for(let[t,n]of Object.entries(r)){let s=jt.test(t);n===null||typeof n!="object"?e[t]=s?Mt:n:s&&Array.isArray(n)?e[t]=n.map(i=>i===null||typeof i!="object"?Mt:Zs(i)):e[t]=Zs(n)}return e}function
|
|
643
|
-
`))return
|
|
644
|
-
`)){try{let i=new URLSearchParams(s);for(let[o,a]of i)if(jt.test(o)&&a&&!cn(a)){let c=Gn(o),l=2;for(;t.has(c);)c=`${Gn(o)}_${l++}`;t.add(c),e.push({location:"body",field:o,path:n?`${n}.${o}`:o,value:a,variableName:c})}}catch{}return}return}if(Array.isArray(r)){r.forEach((s,i)=>vo(s,e,t,`${n}[${i}]`));return}if(typeof r=="object")for(let[s,i]of Object.entries(r)){let o=n?`${n}.${s}`:s;if(jt.test(s)&&i&&typeof i=="string"&&!cn(i)){let a=Gn(s),c=2;for(;t.has(a);)a=`${Gn(s)}_${c++}`;t.add(a),e.push({location:"body",field:s,path:o,value:i,variableName:a})}else typeof i=="object"&&i!==null&&vo(i,e,t,o)}}}function
|
|
645
|
-
`)){let c=new URLSearchParams(a);if(c.get(e)===n){c.set(e,s);let l=c.toString();i?i.content=l:r.body=l}return}return}typeof o=="object"&&o!==null&&Qd(o,e,t||e,n,s)}}function Qd(r,e,t,n,s){let i=t.split("."),o=r;for(let c=0;c<i.length-1;c++){let l=i[c],u=l.match(/^(.+)\[(\d+)\]$/);if(u?o=o?.[u[1]]?.[parseInt(u[2])]:o=o?.[l],o==null)return}let a=i[i.length-1];o&&o[a]===n&&(o[a]=s)}function Dg(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Mt,Kd,Zd,jt,$g,Lr=k(()=>{"use strict";jr();Mt="***",Kd=4,Zd=/^(authorization|proxy-authorization|www-authenticate)$|(token|cookie|secret|credential|api[_\-]?key|bearer|session[_\-]?id)/i,jt=/(password|passwd|pwd|token|cookie|secret|credential|api[_\-]?key|apikey|access[_\-]?token|refresh[_\-]?token|client[_\-]?secret|private[_\-]?key|auth[_\-]?code|bearer|session[_\-]?id|jwt)/i;$g=/\{\{[^}]+\}\}/});import*as Y from"fs";import*as Je from"path";var Ys,Zc=k(()=>{"use strict";Ze();Lr();Ys=class{historyPath;sharedHistoryPath;constructor(e,t){this.historyPath=e,this.sharedHistoryPath=t}getEnvironmentHistoryPath(e){return Je.join(this.historyPath,xe(e))}getCollectionHistoryPath(e,t){return Je.join(this.getEnvironmentHistoryPath(e),t)}getRequestPath(e,t,n){return Je.join(this.getCollectionHistoryPath(e,t),xe(n))}getSharedEnvironmentHistoryPath(e){return Je.join(this.sharedHistoryPath,xe(e))}getSharedCollectionHistoryPath(e,t){return Je.join(this.getSharedEnvironmentHistoryPath(e),t)}getSharedRequestPath(e,t,n){return Je.join(this.getSharedCollectionHistoryPath(e,t),xe(n))}getHistoryFilePath(e,t,n){return Je.join(this.getRequestPath(e,t,n),"transactions.json")}getSharedHistoryFilePath(e,t,n){return Je.join(this.getSharedRequestPath(e,t,n),"transactions.json")}getResponseFilePath(e,t,n,s){return Je.join(this.getRequestPath(e,t,n),`${s}.json`)}getSharedResponseFilePath(e,t,n,s){return Je.join(this.getSharedRequestPath(e,t,n),`${s}.json`)}loadHistory(e,t,n){let s=this.getHistoryFilePath(e,t,n);try{if(!Y.existsSync(s))return null;let i=Y.readFileSync(s,"utf-8"),o=JSON.parse(i);return{environment:e||o.environment,requestPath:t||o.requestPath,requestId:n||o.requestId,method:o.method,requests:o.requests}}catch(i){return console.error(`Failed to load history for ${n}:`,i),null}}loadSharedHistory(e,t,n){let s=this.getSharedHistoryFilePath(e,t,n);try{if(!Y.existsSync(s))return null;let i=Y.readFileSync(s,"utf-8"),o=JSON.parse(i);return{environment:e||o.environment,requestPath:t||o.requestPath,requestId:n||o.requestId,method:o.method,requests:o.requests}}catch(i){return console.error(`Failed to load shared history for ${n}:`,i),null}}getEntriesForEnvironment(e,t,n){let s=this.loadHistory(e,t,n);return s?s.requests:[]}getEntriesGroupedByTicket(e,t,n){let s=this.getEntriesForEnvironment(e,t,n),i=new Map;for(let o of s){let a=o.ticket||o.branch||"";i.has(a)||i.set(a,[]),i.get(a).push(o)}return i}getSharedEntriesGroupedByTicket(e,t,n){let s=this.loadSharedHistory(e,t,n)?.requests??[],i=new Map;for(let o of s){let a=o.ticket||o.branch||"";i.has(a)||i.set(a,[]),i.get(a).push(o)}return i}saveHistory(e){let t=this.getRequestPath(e.environment,e.requestPath,e.requestId),n=this.getHistoryFilePath(e.environment,e.requestPath,e.requestId);try{Y.existsSync(t)||Y.mkdirSync(t,{recursive:!0}),Y.writeFileSync(n,JSON.stringify(e,null,2),"utf-8")}catch(s){throw console.error(`Failed to save history for ${e.requestId}:`,s),s}}saveSharedHistory(e){let t=this.getSharedRequestPath(e.environment,e.requestPath,e.requestId),n=this.getSharedHistoryFilePath(e.environment,e.requestPath,e.requestId);try{Y.existsSync(t)||Y.mkdirSync(t,{recursive:!0}),Y.writeFileSync(n,JSON.stringify(e,null,2),"utf-8")}catch(s){throw console.error(`Failed to save shared history for ${e.requestId}:`,s),s}}addEntry(e,t,n,s,i){let o=this.loadHistory(e,t,n);o||(o={environment:e,requestPath:t,requestId:n,method:s,requests:[]});let a=Gc({...i,method:s,id:ld(),timestamp:Date.now()});return o.requests.unshift(a),o.requests.length>100&&(o.requests=o.requests.slice(0,100)),this.saveHistory(o),a}deleteEntry(e,t,n,s){let i=this.loadHistory(e,t,n);if(!i)return!1;let o=i.requests.length;if(i.requests=i.requests.filter(a=>a.id!==s),i.requests.length!==o){this.saveHistory(i);let a=this.getResponseFilePath(e,t,n,s);return Y.existsSync(a)&&Y.unlinkSync(a),!0}return!1}deleteSharedEntry(e,t,n,s){let i=this.loadSharedHistory(e,t,n);if(!i)return!1;let o=i.requests.length;if(i.requests=i.requests.filter(a=>a.id!==s),i.requests.length!==o){this.saveSharedHistory(i);let a=this.getSharedResponseFilePath(e,t,n,s);return Y.existsSync(a)&&Y.unlinkSync(a),!0}return!1}shareEntry(e,t,n,s,i){let o=(i||"").trim();if(!o)return!1;let a=this.loadHistory(e,t,n);if(!a)return!1;let c=a.requests.findIndex(m=>m.id===s);if(c===-1)return!1;let[l]=a.requests.splice(c,1);this.saveHistory(a);let u=this.loadSharedHistory(e,t,n)||{environment:e,requestPath:t,requestId:n,method:a.method,requests:[]};if(!u.requests.some(m=>m.id===s)){let m={...l,ticket:null,branch:o};u.requests.unshift(m),u.requests.length>100&&(u.requests=u.requests.slice(0,100)),this.saveSharedHistory(u)}let d=this.getResponseFilePath(e,t,n,s),p=this.getSharedResponseFilePath(e,t,n,s);if(Y.existsSync(d)){let m=Je.dirname(p);Y.existsSync(m)||Y.mkdirSync(m,{recursive:!0});try{Y.renameSync(d,p)}catch{try{Y.copyFileSync(d,p)}catch(h){return console.error(`Failed to copy full response from ${d} to ${p}:`,h),!0}try{Y.unlinkSync(d)}catch(h){console.warn(`Failed to remove original full response after copy: ${d}`,h)}}}return!0}moveSharedEntry(e,t,n,s,i){let o=(i||"").trim();if(!o)return!1;let a=this.loadSharedHistory(e,t,n);if(!a)return!1;let c=!1;return a.requests=a.requests.map(l=>l.id===s?(c=!0,{...l,ticket:null,branch:o}):l),c?(this.saveSharedHistory(a),!0):!1}renameSharedGroup(e,t,n,s,i){let o=(s||"").trim(),a=(i||"").trim();if(!o||!a||o===a)return!1;let c=this.loadSharedHistory(e,t,n);if(!c)return!1;let l=!1;return c.requests=c.requests.map(u=>!u.ticket&&u.branch===o?(l=!0,{...u,branch:a}):u),l?(this.saveSharedHistory(c),!0):!1}clearHistory(e,t,n){let s=this.getRequestPath(e,t,n);if(Y.existsSync(s)){let i=Y.readdirSync(s);for(let o of i)Y.unlinkSync(Je.join(s,o));Y.rmdirSync(s)}}saveFullResponse(e,t,n,s,i,o){let a=this.getRequestPath(e,t,n),c=this.getResponseFilePath(e,t,n,s);try{Y.existsSync(a)||Y.mkdirSync(a,{recursive:!0});let l=Kc(i,o);Y.writeFileSync(c,JSON.stringify(l,null,2),"utf-8")}catch(l){throw console.error(`Failed to save full response for ${s}:`,l),l}}loadFullResponse(e,t,n,s){let i=this.getResponseFilePath(e,t,n,s);try{if(!Y.existsSync(i))return null;let o=Y.readFileSync(i,"utf-8");return JSON.parse(o)}catch(o){return console.error(`Failed to load full response for ${s}:`,o),null}}loadSharedFullResponse(e,t,n,s){let i=this.getSharedResponseFilePath(e,t,n,s);try{if(!Y.existsSync(i))return null;let o=Y.readFileSync(i,"utf-8");return JSON.parse(o)}catch(o){return console.error(`Failed to load shared full response for ${s}:`,o),null}}}});var Hr,Yc=k(()=>{"use strict";Hr=class{constructor(e,t){this.historyService=e;this.inferrer=t}historyService;inferrer;async analyze(e,t,n){let s=n?.environment||"default",i=n?.maxSamples||50,o=this.historyService.loadHistory(s,e,t),a=this.historyService.loadSharedHistory(s,e,t),c=[...o?.requests||[],...a?.requests||[]];if(c.length===0)return{responses:{}};let l=c.slice(0,i),u=new Map;for(let p of l){let m=this.historyService.loadFullResponse(s,e,t,p.id);if(m||(m=this.historyService.loadSharedFullResponse(s,e,t,p.id)),m){let f=m.status;u.has(f)||u.set(f,[]),u.get(f).push(m)}}let d={};for(let[p,m]of u){let f=this.buildResponseDefinition(m);d[String(p)]=f}return{responses:d}}buildResponseDefinition(e){let t={};if(e.length===0)return t;let n=e[0];t.description=n.statusText||`Status ${n.status}`;let s=this.extractContentType(n.headers);if(s&&(t.contentType=s),s&&this.isJsonContentType(s)){let o=this.inferBodySchema(n);for(let a=1;a<e.length;a++){let c=this.inferBodySchema(e[a]);c&&o?o=this.inferrer.mergeSchemas(o,c):c&&(o=c)}if(o&&(t.schema=o),n.body!==void 0&&n.body!==null){let a=typeof n.body=="string"?this.tryParseJson(n.body):n.body;a!==void 0&&(t.examples={default:{summary:"Captured from history",value:a}})}}let i=this.findConsistentHeaders(e);return Object.keys(i).length>0&&(t.headers=i),t}inferBodySchema(e){if(e.body===void 0||e.body===null)return;let t=e.body;if(!(typeof t=="string"&&(t=this.tryParseJson(t),t===void 0)))return this.inferrer.inferFromValue(t)}extractContentType(e){for(let[t,n]of Object.entries(e))if(t.toLowerCase()==="content-type")return(Array.isArray(n)?n[0]:n).split(";")[0].trim()}isJsonContentType(e){return e.includes("json")||e.includes("+json")||e==="application/json"}findConsistentHeaders(e){if(e.length===0)return{};let t=new Set(["content-type","content-length","content-encoding","transfer-encoding","connection","date","server","set-cookie","vary","cache-control","expires","pragma","etag","last-modified","age"]),n=new Map,s=new Map;for(let a of e)for(let[c,l]of Object.entries(a.headers)){let u=c.toLowerCase();t.has(u)||(n.set(u,(n.get(u)||0)+1),s.has(u)||s.set(u,Array.isArray(l)?l.join(", "):l))}let i=Math.ceil(e.length/2),o={};for(let[a,c]of n)if(c>=i){let l=s.get(a);o[a]={schema:this.inferHeaderSchema(l)}}return o}inferHeaderSchema(e){return e?/^\d+$/.test(e)?{type:"integer"}:{type:"string"}:{type:"string"}}tryParseJson(e){try{return JSON.parse(e)}catch{return}}}});function tp(r){let e=r,t=null,n=e.match(/^\{\{(\w+)\}\}/);return n&&(t=n[1],e=e.slice(n[0].length)),e=e.replace(/:([a-zA-Z_]\w*)/g,"{$1}"),e=e.replace(/\{\{(\w+)\}\}/g,"{$1}"),e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e=e.replace(/\/\//g,"/"),{path:e,hostVar:t}}function Xd(r){return/^-?\d+$/.test(r)?"integer":/^-?\d+\.\d+$/.test(r)?"number":r==="true"||r==="false"?"boolean":"string"}function bo(r,e){if(r==="integer"&&e==="number"||r==="number"&&e==="integer")return"number"}function np(r){return r.replace(/\{\{(\w+)\}\}/g,"<$1>")}function Xc(r,e){let t=np(r);switch(e){case"integer":return parseInt(t,10)||t;case"number":return parseFloat(t)||t;case"boolean":return t==="true";default:return t}}function el(r){if(typeof r=="string")return np(r);if(Array.isArray(r))return r.map(e=>el(e));if(r!==null&&typeof r=="object"){let e={};for(let[t,n]of Object.entries(r))e[t]=el(n);return e}return r}function Xs(r){if(!r||!r.content)return;let e;if(typeof r.content=="string")try{e=JSON.parse(r.content)}catch{e=r.content}else e=r.content;return el(e)}function tl(r){if(!r)return"application/json";switch(r.type){case"raw":switch(r.format){case"json":return"application/json";case"xml":return"application/xml";case"html":return"text/html";case"text":return"text/plain";default:return"text/plain"}case"form-data":return"multipart/form-data";case"x-www-form-urlencoded":return"application/x-www-form-urlencoded";case"binary":return"application/octet-stream";case"graphql":return"application/json";default:return"application/json"}}function nl(r){let e={type:"object",properties:{}},t=r.formData||r.urlencoded||[];for(let n of t)n.enabled!==!1&&(n.type==="file"?e.properties[n.key]={type:"string",format:"binary"}:e.properties[n.key]={type:"string"});return e}function ep(r,e){let t={name:r.key,in:e,schema:{}};return r.oneOf?(t.schema.oneOf=r.oneOf,r.type&&(t.schema.type=r.type)):(t.schema.type=r.type||"string",r.format&&(t.schema.format=r.format),r.enum&&(t.schema.enum=r.enum),r.pattern&&(t.schema.pattern=r.pattern),r.minimum!==void 0&&(t.schema.minimum=r.minimum),r.maximum!==void 0&&(t.schema.maximum=r.maximum),r.exclusiveMinimum!==void 0&&(t.schema.exclusiveMinimum=r.exclusiveMinimum),r.exclusiveMaximum!==void 0&&(t.schema.exclusiveMaximum=r.exclusiveMaximum),r.multipleOf!==void 0&&(t.schema.multipleOf=r.multipleOf),r.minLength!==void 0&&(t.schema.minLength=r.minLength),r.maxLength!==void 0&&(t.schema.maxLength=r.maxLength),r.minItems!==void 0&&(t.schema.minItems=r.minItems),r.maxItems!==void 0&&(t.schema.maxItems=r.maxItems),r.uniqueItems&&(t.schema.uniqueItems=!0),r.nullable&&(t.schema.nullable=!0)),r.required&&(t.required=!0),r.description&&(t.description=r.description),r.deprecated&&(t.deprecated=!0),r.value&&(t.example=Xc(r.value,t.schema.type||"string")),t}function jg(r){let e=[],t=r.split(";").map(n=>n.trim()).filter(Boolean);for(let n of t){let s=n.indexOf("=");if(s>0){let i=n.substring(0,s).trim(),o=n.substring(s+1).trim();e.push({name:i,in:"cookie",schema:{type:"string"},example:o})}}return e}function rp(r){let e=[];if(r.params)for(let[t,n]of Object.entries(r.params)){let s={name:t,in:"path",required:!0};if(typeof n=="string")s.schema={type:Xd(n)},s.example=Xc(n,s.schema.type);else{let i=n;i.oneOf?(s.schema={oneOf:i.oneOf},i.type&&(s.schema.type=i.type)):(s.schema={type:i.type||Xd(i.value)},i.format&&(s.schema.format=i.format),i.enum&&(s.schema.enum=i.enum),i.pattern&&(s.schema.pattern=i.pattern),i.minimum!==void 0&&(s.schema.minimum=i.minimum),i.maximum!==void 0&&(s.schema.maximum=i.maximum),i.exclusiveMinimum!==void 0&&(s.schema.exclusiveMinimum=i.exclusiveMinimum),i.exclusiveMaximum!==void 0&&(s.schema.exclusiveMaximum=i.exclusiveMaximum),i.multipleOf!==void 0&&(s.schema.multipleOf=i.multipleOf),i.minLength!==void 0&&(s.schema.minLength=i.minLength),i.maxLength!==void 0&&(s.schema.maxLength=i.maxLength),i.minItems!==void 0&&(s.schema.minItems=i.minItems),i.maxItems!==void 0&&(s.schema.maxItems=i.maxItems),i.uniqueItems&&(s.schema.uniqueItems=!0),i.nullable&&(s.schema.nullable=!0)),i.description&&(s.description=i.description),i.deprecated&&(s.deprecated=!0),s.example=Xc(i.value,s.schema.type||"string")}e.push(s)}if(r.query)for(let t of r.query){if(!t.key)continue;let n=ep(t,"query");e.push(n)}if(r.headers){let t=r.headers.find(n=>n.key.toLowerCase()==="cookie");if(t){let n=jg(t.value);e.push(...n)}for(let n of r.headers){if(!n.key||Mg.has(n.key.toLowerCase()))continue;let s=ep(n,"header");e.push(s)}}return e}function sp(r){return r.replace(/[^a-zA-Z0-9]+(.)/g,(e,t)=>t.toUpperCase()).replace(/^[A-Z]/,e=>e.toLowerCase()).replace(/[^a-zA-Z0-9]/g,"")}function ip(r){return r.replace(/^\[DEPRECATED\]\s*/i,"")}function rl(r){return/^\[DEPRECATED\]/i.test(r)}function ei(r){let e={};for(let t of r.split(/\s+/))t&&(e[t]="");return e}var Mg,ti=k(()=>{"use strict";Mg=new Set(["content-type","authorization","accept","cookie","host","content-length"])});var Lg,Hg,Bg,Ug,Vg,zg,Jg,ln,So=k(()=>{"use strict";ti();Lg=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,Hg=/^\d{4}-\d{2}-\d{2}$/,Bg=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,Ug=/^https?:\/\/[^\s]+$/,Vg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,zg=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Jg=/^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/,ln=class{inferFromValue(e){if(e==null)return{nullable:!0};if(Array.isArray(e))return this.inferArraySchema(e);switch(typeof e){case"string":return this.inferStringSchema(e);case"number":return Number.isInteger(e)?{type:"integer"}:{type:"number"};case"boolean":return{type:"boolean"};case"object":return this.inferObjectSchema(e);default:return{}}}mergeSchemas(e,t){if(!e||Object.keys(e).length===0)return{...t};if(!t||Object.keys(t).length===0)return{...e};let n=e.nullable||t.nullable;if(!e.type&&e.nullable)return{...t,nullable:!0};if(!t.type&&t.nullable)return{...e,nullable:!0};if(e.type!==t.type){let i=bo(e.type,t.type);return i?{type:i,...n&&{nullable:!0}}:{...n&&{nullable:!0}}}let s={type:e.type};return n&&(s.nullable=!0),e.type==="object"&&t.type==="object"?this.mergeObjectSchemas(e,t,n):e.type==="array"&&t.type==="array"?this.mergeArraySchemas(e,t,n):(e.format&&e.format===t.format&&(s.format=e.format),s)}inferStringFormat(e){if(Lg.test(e))return"date-time";if(Hg.test(e))return"date";if(Bg.test(e))return"email";if(Vg.test(e))return"uuid";if(Ug.test(e))return"uri";if(zg.test(e))return"ipv4";if(Jg.test(e))return"ipv6"}inferStringSchema(e){let t={type:"string"},n=this.inferStringFormat(e);return n&&(t.format=n),t}inferArraySchema(e){let t={type:"array"};if(e.length===0)return t;let n=this.inferFromValue(e[0]);for(let s=1;s<e.length;s++)n=this.mergeSchemas(n,this.inferFromValue(e[s]));return t.items=n,t}inferObjectSchema(e){let t={type:"object",properties:{}},n=Object.keys(e);for(let s of n)t.properties[s]=this.inferFromValue(e[s]);return t}mergeObjectSchemas(e,t,n){let s={type:"object",properties:{},...n&&{nullable:!0}},i=e.properties||{},o=t.properties||{},a=new Set([...Object.keys(i),...Object.keys(o)]);for(let d of a)i[d]&&o[d]?s.properties[d]=this.mergeSchemas(i[d],o[d]):i[d]?s.properties[d]={...i[d]}:s.properties[d]={...o[d]};let c=new Set(e.required||Object.keys(i)),l=new Set(t.required||Object.keys(o)),u=[...a].filter(d=>c.has(d)&&l.has(d));return u.length>0&&(s.required=u),s}mergeArraySchemas(e,t,n){let s={type:"array",...n&&{nullable:!0}};return e.items&&t.items?s.items=this.mergeSchemas(e.items,t.items):e.items?s.items={...e.items}:t.items&&(s.items={...t.items}),s}}});var xo,op=k(()=>{"use strict";ti();xo=class{constructor(e){this.inferrer=e}inferrer;async buildOperation(e,t,n,s,i,o,a,c,l){let u={};u.operationId=e.operationId||this.generateOperationId(e,t,n,s),u.summary=e.summary||ip(e.name),e.description&&(u.description=e.description),(e.deprecated||rl(e.name))&&(u.deprecated=!0,rl(e.name)&&(u.summary=e.name.replace(/^\[DEPRECATED\]\s*/i,"")));let d=e.tags;if(d&&d.length>0){u.tags=d;for(let g of d)o.add(g)}else a&&(u.tags=[a]);let p=rp(e);p.length>0&&(u.parameters=p);let m=await this.buildRequestBody(e,l);m&&(u.requestBody=m);let f=e.responses;f&&Object.keys(f).length>0?u.responses=this.mapResponseDefinitions(f):u.responses=await this.buildResponses(e,c.id,l);let h=e.security;if(h&&h.length>0)u.security=h;else{let g=this.buildOperationSecurity(e,c,i);g!==void 0&&(u.security=g)}return u}generateOperationId(e,t,n,s){let i=sp(e.name),o=this.collectOperationIds(s);if(o.has(i)&&(i=`${i}${t.charAt(0).toUpperCase()}${t.slice(1)}`),!i||o.has(i)){let a=n.split("/").filter(c=>c&&!c.startsWith("{"));i=t+a.map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("")}return i}collectOperationIds(e){let t=new Set;if(e.paths)for(let n of Object.values(e.paths))for(let s of Object.values(n))s.operationId&&t.add(s.operationId);return t}async buildRequestBody(e,t){if(!e.body||e.body.type==="none")return null;let n=e.body,s={required:!0,content:{}},i,o,a,c;if(e.bodySchema){if(e.bodySchema.content){for(let[d,p]of Object.entries(e.bodySchema.content)){let m={};p.schema&&(m.schema=p.schema),p.examples&&(m.examples=p.examples),p.encoding&&(m.encoding=p.encoding),s.content[d]=m}let u=e.bodySchema.contentType||Object.keys(e.bodySchema.content)[0];if(u&&n.content){let d=Xs(n);d!==void 0&&s.content[u]&&(s.content[u].example=d)}return s}i=e.bodySchema.contentType||tl(n),o=e.bodySchema.schema,a=Xs(n),e.bodySchema.encoding&&(c=e.bodySchema.encoding)}else switch(i=tl(n),n.type){case"raw":{if(n.format==="json"&&n.content){let u=Xs(n);u!==void 0?(o=this.inferrer.inferFromValue(u),a=u):o={type:"string"}}else o={type:"string"},a=typeof n.content=="string"?n.content:void 0;break}case"form-data":{o=nl(n);break}case"x-www-form-urlencoded":{o=nl(n);break}case"binary":{o={type:"string",format:"binary"};break}case"graphql":{o={type:"object",properties:{query:{type:"string"},variables:{type:"object"}}},a=Xs(n);break}default:return null}let l={};return o&&(l.schema=o),a!==void 0&&(l.example=a),c&&(l.encoding=c),s.content[i]=l,s}async buildResponses(e,t,n){let s={};if(e.responseSchema)for(let[i,o]of Object.entries(e.responseSchema.responses)){let a={description:o.description||`Status ${i}`};if(o.content){a.content={};for(let[c,l]of Object.entries(o.content)){let u={};l.schema&&(u.schema=l.schema),l.examples&&(u.examples=l.examples),a.content[c]=u}}else if(o.schema){let c=o.contentType||"application/json",l={schema:o.schema};o.examples&&(l.examples=o.examples),a.content={[c]:l}}if(o.headers){a.headers={};for(let[c,l]of Object.entries(o.headers))a.headers[c]={...l.description&&{description:l.description},schema:l.schema}}s[i]=a}return Object.keys(s).length===0&&(s[200]={description:"Successful response"}),s}mapResponseDefinitions(e){let t={};for(let[n,s]of Object.entries(e)){let i={description:s.description||`Status ${n}`};if(s.schema||s.examples){let o=s.contentType||"application/json",a={};s.schema&&(a.schema=s.schema),s.examples&&Object.keys(s.examples).length>0&&(a.examples=s.examples),i.content={[o]:a}}if(s.headers&&Object.keys(s.headers).length>0){i.headers={};for(let[o,a]of Object.entries(s.headers)){let c=a;i.headers[o]={...c.description&&{description:c.description},...c.schema&&{schema:c.schema}}}}t[n]=i}return Object.keys(t).length===0&&(t[200]={description:"Successful response"}),t}buildOperationSecurity(e,t,n){if(!e.auth||e.auth.type==="inherit")return;if(e.auth.type==="none")return[];let s=this.mapAuthToSecurityScheme(e.auth);if(!s)return;let{schemeName:i,scheme:o,requirement:a}=s;return n.set(i,o),[a]}mapAuthToSecurityScheme(e){switch(e.type){case"bearer":return{schemeName:"BearerAuth",scheme:{type:"http",scheme:"bearer"},requirement:{BearerAuth:[]}};case"basic":return{schemeName:"BasicAuth",scheme:{type:"http",scheme:"basic"},requirement:{BasicAuth:[]}};case"apikey":{let t=e.apikey||{key:"X-Api-Key",value:"",in:"header"},n=`ApiKey_${t.key||"key"}`;return{schemeName:n,scheme:{type:"apiKey",in:t.in||"header",name:t.key||"X-Api-Key"},requirement:{[n]:[]}}}case"oauth2":{let t=e.oauth2;if(!t)return;let n={};switch(t.grantType){case"client_credentials":n.clientCredentials={tokenUrl:t.tokenUrl||"",scopes:t.scope?ei(t.scope):{}};break;case"authorization_code":n.authorizationCode={authorizationUrl:t.authUrl||"",tokenUrl:t.tokenUrl||"",scopes:t.scope?ei(t.scope):{}};break;case"password":n.password={tokenUrl:t.tokenUrl||"",scopes:t.scope?ei(t.scope):{}};break;case"implicit":n.implicit={authorizationUrl:t.authUrl||"",scopes:t.scope?ei(t.scope):{}};break;default:n.clientCredentials={tokenUrl:t.tokenUrl||"",scopes:{}}}return{schemeName:"OAuth2",scheme:{type:"oauth2",flows:n},requirement:{OAuth2:[]}}}default:return{schemeName:"BearerAuth",scheme:{type:"http",scheme:"bearer"},requirement:{BearerAuth:[]}}}}}});var wo,ap=k(()=>{"use strict";ti();wo=class{mergeOperation(e,t,n){if(t.summary&&t.summary!==e.summary&&(e.description=(e.description||e.summary||"")+`
|
|
641
|
+
`.trim(),Qs=class{constructor(e){this.httpClient=e}httpClient;schemaCache=new Map;async fetchSchema(e,t){let n={method:"POST",url:e,headers:{...t||{},"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({query:Tg,operationName:"IntrospectionQuery"})},s=await this.httpClient.send(n);if(s.status<200||s.status>=300)throw new Error(`Introspection query failed with status ${s.status}: ${s.statusText}`);let i=typeof s.body=="string"?JSON.parse(s.body):s.body;if(i.errors&&i.errors.length>0){let a=i.errors.map(c=>c.message).join("; ");throw new Error(`Introspection query returned errors: ${a}`)}if(!i.data?.__schema)throw new Error("Invalid introspection response: missing __schema");let o=this.parseSchema(i.data.__schema,e);return this.schemaCache.set(e,o),o}getCachedSchema(e){return this.schemaCache.get(e)}extractOperations(e){let t=[],n=e.split(`
|
|
642
|
+
`),s=/^\s*(query|mutation|subscription)\s+(\w+)/;for(let i=0;i<n.length;i++){let o=n[i].match(s);o&&t.push({type:o[1],name:o[2],line:i+1})}return t.length===0&&e.trim().startsWith("{")&&t.push({type:"query",name:"(anonymous)",line:1}),t}clearCache(e){e?this.schemaCache.delete(e):this.schemaCache.clear()}schemaToSerializable(e){let t={};for(let[n,s]of e.types)t[n]=s;return{queryType:e.queryType,mutationType:e.mutationType,subscriptionType:e.subscriptionType,types:t,directives:e.directives,fetchedAt:e.fetchedAt,endpointUrl:e.endpointUrl}}parseSchema(e,t){let n=new Map;for(let i of e.types||[]){if(i.name.startsWith("__"))continue;let o={name:i.name,kind:i.kind,description:i.description||void 0,fields:(i.fields||[]).map(a=>this.parseField(a)),inputFields:(i.inputFields||[]).map(a=>this.parseArg(a)),enumValues:(i.enumValues||[]).map(a=>({name:a.name,description:a.description||void 0,isDeprecated:a.isDeprecated||!1,deprecationReason:a.deprecationReason||void 0})),interfaces:(i.interfaces||[]).map(a=>this.renderTypeRef(a)),possibleTypes:(i.possibleTypes||[]).map(a=>this.renderTypeRef(a))};n.set(o.name,o)}let s=(e.directives||[]).map(i=>({name:i.name,description:i.description||void 0,locations:i.locations||[],args:(i.args||[]).map(o=>this.parseArg(o))}));return{queryType:e.queryType?.name||"Query",mutationType:e.mutationType?.name||void 0,subscriptionType:e.subscriptionType?.name||void 0,types:n,directives:s,fetchedAt:Date.now(),endpointUrl:t}}parseField(e){return{name:e.name,type:this.renderTypeRef(e.type),args:(e.args||[]).map(t=>this.parseArg(t)),description:e.description||void 0,isDeprecated:e.isDeprecated||!1,deprecationReason:e.deprecationReason||void 0}}parseArg(e){return{name:e.name,type:this.renderTypeRef(e.type),defaultValue:e.defaultValue??void 0,description:e.description||void 0}}renderTypeRef(e){return e?e.kind==="NON_NULL"?`${this.renderTypeRef(e.ofType)}!`:e.kind==="LIST"?`[${this.renderTypeRef(e.ofType)}]`:e.name||"Unknown":"Unknown"}}});function St(r){let e={};for(let[t,n]of Object.entries(r))Zd.test(t)?e[t]=Array.isArray(n)?n.map(()=>Mt):Mt:e[t]=n;return e}function Wc(r=[]){return r.map(e=>e&&typeof e=="object"&&e.name&&jt.test(e.name)?{...e,value:Mt}:e)}function Jc(r){try{let e=new URL(r),t=!1;for(let[n]of e.searchParams)jt.test(n)&&(e.searchParams.set(n,Mt),t=!0);return t?e.toString():r}catch{return r}}function Zs(r){if(r==null)return r;if(Array.isArray(r))return r.map(t=>Zs(t));if(typeof r!="object")return r;let e={};for(let[t,n]of Object.entries(r)){let s=jt.test(t);n===null||typeof n!="object"?e[t]=s?Mt:n:s&&Array.isArray(n)?e[t]=n.map(i=>i===null||typeof i!="object"?Mt:Zs(i)):e[t]=Zs(n)}return e}function Og(r){try{let e=new URLSearchParams(r),t=!1;for(let[n]of e)jt.test(n)&&(e.set(n,Mt),t=!0);return t?e.toString():r}catch{return r}}function Yd(r){if(r==null)return r;if(typeof r=="object"&&!Buffer.isBuffer(r))return Zs(r);if(typeof r=="string"){let e=r.trim();if(e.startsWith("{")||e.startsWith("["))try{let t=JSON.parse(e),n=Zs(t);return JSON.stringify(n)}catch{}if(e.includes("=")&&!e.includes(`
|
|
643
|
+
`))return Og(e)}return r}function $g(r,e){let t=r;for(let n of e){if(n.length<Kd)continue;let s=new Set([n]);for(let i of[encodeURI,encodeURIComponent])try{s.add(i(n))}catch{}for(let i of s)i.length<Kd||!t.includes(i)||(t=t.split(i).join(Mt))}return t}function Kn(r,e){if(e.length===0)return r;if(typeof r=="string")return $g(r,e);if(Array.isArray(r))return r.map(t=>Kn(t,e));if(r!==null&&typeof r=="object"){let t=Object.getPrototypeOf(r);if(t!==Object.prototype&&t!==null)return r;let n={};for(let[s,i]of Object.entries(r))n[s]=Kn(i,e);return n}return r}function Gc(r,e){let t=e??Mr(r.sentRequest),n={...r,sentRequest:{...r.sentRequest,url:Jc(r.sentRequest.url),headers:St(r.sentRequest.headers),body:r.sentRequest.body!=null?Yd(r.sentRequest.body):r.sentRequest.body}};return Kn(n,t)}function Kc(r,e=[]){let t={...r,headers:St(r.headers),cookies:r.cookies.map(n=>n&&typeof n=="object"&&n.name&&jt.test(n.name)?{...n,value:Mt}:n)};return Kn(t,e)}function Qc(r,e=[]){let t={...r,url:Jc(r.url),request:{...r.request,url:Jc(r.request.url),headers:St(r.request.headers),query:St(r.request.query),params:St(r.request.params),body:r.request.body!=null?Yd(r.request.body):r.request.body},response:{headers:St(r.response.headers),body:r.response.body,time:r.response.time,size:r.response.size,cookies:r.response.cookies?Wc(r.response.cookies):r.response.cookies}};return Kn(t,e)}function cn(r){return typeof r=="string"&&Fg.test(r)}function Gn(r){return r.replace(/\./g,"_").replace(/[^a-zA-Z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toLowerCase()}function Ng(r){let e=[],t=new Set;function n(s){let i=s,o=2;for(;t.has(i);)i=`${s}_${o++}`;return t.add(i),i}if(r.url)try{let s=new URL(r.url.includes("://")?r.url:`http://placeholder${r.url.startsWith("/")?"":"/"}${r.url}`);for(let[i,o]of s.searchParams)jt.test(i)&&o&&!cn(o)&&e.push({location:"url",field:i,value:o,variableName:n(Gn(i))})}catch{}if(r.headers){let s=Array.isArray(r.headers)?r.headers.filter(i=>i.enabled!==!1).map(i=>[i.key,i.value]):Object.entries(r.headers);for(let[i,o]of s)Zd.test(i)&&o&&!cn(o)&&e.push({location:"header",field:i,value:o,variableName:n(Gn(i))})}if(r.query){let s=Array.isArray(r.query)?r.query.filter(i=>i.enabled!==!1).map(i=>[i.key,i.value]):Object.entries(r.query);for(let[i,o]of s)jt.test(i)&&o&&!cn(o)&&e.push({location:"query",field:i,value:o,variableName:n(Gn(i))})}if(r.auth){let s=r.auth;if(s.bearerToken&&!cn(s.bearerToken)&&e.push({location:"auth",field:"bearerToken",value:s.bearerToken,variableName:n("bearer_token")}),s.basicAuth&&s.basicAuth.password&&!cn(s.basicAuth.password)&&e.push({location:"auth",field:"basicAuth.password",value:s.basicAuth.password,variableName:n("basic_auth_password")}),s.apikey||s.apiKey){let i=s.apikey||s.apiKey;i.value&&!cn(i.value)&&e.push({location:"auth",field:"apiKey.value",value:i.value,variableName:n("api_key")})}}if(r.body){let s=typeof r.body=="object"&&"content"in r.body?r.body.content:r.body;s&&vo(s,e,t,"")}return e}function vo(r,e,t,n){if(r!=null){if(typeof r=="string"){let s=r.trim();if(s.startsWith("{")||s.startsWith("[")){try{vo(JSON.parse(s),e,t,n)}catch{}return}if(s.includes("=")&&!s.includes(`
|
|
644
|
+
`)){try{let i=new URLSearchParams(s);for(let[o,a]of i)if(jt.test(o)&&a&&!cn(a)){let c=Gn(o),l=2;for(;t.has(c);)c=`${Gn(o)}_${l++}`;t.add(c),e.push({location:"body",field:o,path:n?`${n}.${o}`:o,value:a,variableName:c})}}catch{}return}return}if(Array.isArray(r)){r.forEach((s,i)=>vo(s,e,t,`${n}[${i}]`));return}if(typeof r=="object")for(let[s,i]of Object.entries(r)){let o=n?`${n}.${s}`:s;if(jt.test(s)&&i&&typeof i=="string"&&!cn(i)){let a=Gn(s),c=2;for(;t.has(a);)a=`${Gn(s)}_${c++}`;t.add(a),e.push({location:"body",field:s,path:o,value:i,variableName:a})}else typeof i=="object"&&i!==null&&vo(i,e,t,o)}}}function _g(r,e){let t=JSON.parse(JSON.stringify(r));for(let n of e){let s=`{{${n.variableName}}}`;switch(n.location){case"url":t.url&&(t.url=t.url.replace(new RegExp(`([?&])${Mg(n.field)}=[^&]*`),`$1${n.field}=${s}`));break;case"header":if(Array.isArray(t.headers)){let i=t.headers.find(o=>o.key===n.field&&o.value===n.value);i&&(i.value=s)}else t.headers&&t.headers[n.field]===n.value&&(t.headers[n.field]=s);break;case"query":if(Array.isArray(t.query)){let i=t.query.find(o=>o.key===n.field&&o.value===n.value);i&&(i.value=s)}else t.query&&t.query[n.field]===n.value&&(t.query[n.field]=s);break;case"auth":if(t.auth){if(n.field==="bearerToken")t.auth.bearerToken=s;else if(n.field==="basicAuth.password"&&t.auth.basicAuth)t.auth.basicAuth.password=s;else if(n.field==="apiKey.value"){let i=t.auth.apikey||t.auth.apiKey;i&&(i.value=s)}}break;case"body":Dg(t,n.field,n.path,n.value,s);break}}return t}function Dg(r,e,t,n,s){let i=typeof r.body=="object"&&r.body!==null&&"content"in r.body?r.body:null,o=i?i.content:r.body;if(o){if(typeof o=="string"){let a=o.trim();if(a.startsWith("{")||a.startsWith("[")){try{let c=JSON.parse(a);Qd(c,e,t||e,n,s);let l=JSON.stringify(c,null,2);i?i.content=l:r.body=l}catch{}return}if(a.includes("=")&&!a.includes(`
|
|
645
|
+
`)){let c=new URLSearchParams(a);if(c.get(e)===n){c.set(e,s);let l=c.toString();i?i.content=l:r.body=l}return}return}typeof o=="object"&&o!==null&&Qd(o,e,t||e,n,s)}}function Qd(r,e,t,n,s){let i=t.split("."),o=r;for(let c=0;c<i.length-1;c++){let l=i[c],u=l.match(/^(.+)\[(\d+)\]$/);if(u?o=o?.[u[1]]?.[parseInt(u[2])]:o=o?.[l],o==null)return}let a=i[i.length-1];o&&o[a]===n&&(o[a]=s)}function Mg(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Mt,Kd,Zd,jt,Fg,Lr=k(()=>{"use strict";jr();Mt="***",Kd=4,Zd=/^(authorization|proxy-authorization|www-authenticate)$|(token|cookie|secret|credential|api[_\-]?key|bearer|session[_\-]?id)/i,jt=/(password|passwd|pwd|token|cookie|secret|credential|api[_\-]?key|apikey|access[_\-]?token|refresh[_\-]?token|client[_\-]?secret|private[_\-]?key|auth[_\-]?code|bearer|session[_\-]?id|jwt)/i;Fg=/\{\{[^}]+\}\}/});import*as Y from"fs";import*as Je from"path";var Ys,Zc=k(()=>{"use strict";Ze();Lr();Ys=class{historyPath;sharedHistoryPath;constructor(e,t){this.historyPath=e,this.sharedHistoryPath=t}getEnvironmentHistoryPath(e){return Je.join(this.historyPath,xe(e))}getCollectionHistoryPath(e,t){return Je.join(this.getEnvironmentHistoryPath(e),t)}getRequestPath(e,t,n){return Je.join(this.getCollectionHistoryPath(e,t),xe(n))}getSharedEnvironmentHistoryPath(e){return Je.join(this.sharedHistoryPath,xe(e))}getSharedCollectionHistoryPath(e,t){return Je.join(this.getSharedEnvironmentHistoryPath(e),t)}getSharedRequestPath(e,t,n){return Je.join(this.getSharedCollectionHistoryPath(e,t),xe(n))}getHistoryFilePath(e,t,n){return Je.join(this.getRequestPath(e,t,n),"transactions.json")}getSharedHistoryFilePath(e,t,n){return Je.join(this.getSharedRequestPath(e,t,n),"transactions.json")}getResponseFilePath(e,t,n,s){return Je.join(this.getRequestPath(e,t,n),`${s}.json`)}getSharedResponseFilePath(e,t,n,s){return Je.join(this.getSharedRequestPath(e,t,n),`${s}.json`)}loadHistory(e,t,n){let s=this.getHistoryFilePath(e,t,n);try{if(!Y.existsSync(s))return null;let i=Y.readFileSync(s,"utf-8"),o=JSON.parse(i);return{environment:e||o.environment,requestPath:t||o.requestPath,requestId:n||o.requestId,method:o.method,requests:o.requests}}catch(i){return console.error(`Failed to load history for ${n}:`,i),null}}loadSharedHistory(e,t,n){let s=this.getSharedHistoryFilePath(e,t,n);try{if(!Y.existsSync(s))return null;let i=Y.readFileSync(s,"utf-8"),o=JSON.parse(i);return{environment:e||o.environment,requestPath:t||o.requestPath,requestId:n||o.requestId,method:o.method,requests:o.requests}}catch(i){return console.error(`Failed to load shared history for ${n}:`,i),null}}getEntriesForEnvironment(e,t,n){let s=this.loadHistory(e,t,n);return s?s.requests:[]}getEntriesGroupedByTicket(e,t,n){let s=this.getEntriesForEnvironment(e,t,n),i=new Map;for(let o of s){let a=o.ticket||o.branch||"";i.has(a)||i.set(a,[]),i.get(a).push(o)}return i}getSharedEntriesGroupedByTicket(e,t,n){let s=this.loadSharedHistory(e,t,n)?.requests??[],i=new Map;for(let o of s){let a=o.ticket||o.branch||"";i.has(a)||i.set(a,[]),i.get(a).push(o)}return i}saveHistory(e){let t=this.getRequestPath(e.environment,e.requestPath,e.requestId),n=this.getHistoryFilePath(e.environment,e.requestPath,e.requestId);try{Y.existsSync(t)||Y.mkdirSync(t,{recursive:!0}),Y.writeFileSync(n,JSON.stringify(e,null,2),"utf-8")}catch(s){throw console.error(`Failed to save history for ${e.requestId}:`,s),s}}saveSharedHistory(e){let t=this.getSharedRequestPath(e.environment,e.requestPath,e.requestId),n=this.getSharedHistoryFilePath(e.environment,e.requestPath,e.requestId);try{Y.existsSync(t)||Y.mkdirSync(t,{recursive:!0}),Y.writeFileSync(n,JSON.stringify(e,null,2),"utf-8")}catch(s){throw console.error(`Failed to save shared history for ${e.requestId}:`,s),s}}addEntry(e,t,n,s,i){let o=this.loadHistory(e,t,n);o||(o={environment:e,requestPath:t,requestId:n,method:s,requests:[]});let a=Gc({...i,method:s,id:ld(),timestamp:Date.now()});return o.requests.unshift(a),o.requests.length>100&&(o.requests=o.requests.slice(0,100)),this.saveHistory(o),a}deleteEntry(e,t,n,s){let i=this.loadHistory(e,t,n);if(!i)return!1;let o=i.requests.length;if(i.requests=i.requests.filter(a=>a.id!==s),i.requests.length!==o){this.saveHistory(i);let a=this.getResponseFilePath(e,t,n,s);return Y.existsSync(a)&&Y.unlinkSync(a),!0}return!1}deleteSharedEntry(e,t,n,s){let i=this.loadSharedHistory(e,t,n);if(!i)return!1;let o=i.requests.length;if(i.requests=i.requests.filter(a=>a.id!==s),i.requests.length!==o){this.saveSharedHistory(i);let a=this.getSharedResponseFilePath(e,t,n,s);return Y.existsSync(a)&&Y.unlinkSync(a),!0}return!1}shareEntry(e,t,n,s,i){let o=(i||"").trim();if(!o)return!1;let a=this.loadHistory(e,t,n);if(!a)return!1;let c=a.requests.findIndex(m=>m.id===s);if(c===-1)return!1;let[l]=a.requests.splice(c,1);this.saveHistory(a);let u=this.loadSharedHistory(e,t,n)||{environment:e,requestPath:t,requestId:n,method:a.method,requests:[]};if(!u.requests.some(m=>m.id===s)){let m={...l,ticket:null,branch:o};u.requests.unshift(m),u.requests.length>100&&(u.requests=u.requests.slice(0,100)),this.saveSharedHistory(u)}let d=this.getResponseFilePath(e,t,n,s),p=this.getSharedResponseFilePath(e,t,n,s);if(Y.existsSync(d)){let m=Je.dirname(p);Y.existsSync(m)||Y.mkdirSync(m,{recursive:!0});try{Y.renameSync(d,p)}catch{try{Y.copyFileSync(d,p)}catch(h){return console.error(`Failed to copy full response from ${d} to ${p}:`,h),!0}try{Y.unlinkSync(d)}catch(h){console.warn(`Failed to remove original full response after copy: ${d}`,h)}}}return!0}moveSharedEntry(e,t,n,s,i){let o=(i||"").trim();if(!o)return!1;let a=this.loadSharedHistory(e,t,n);if(!a)return!1;let c=!1;return a.requests=a.requests.map(l=>l.id===s?(c=!0,{...l,ticket:null,branch:o}):l),c?(this.saveSharedHistory(a),!0):!1}renameSharedGroup(e,t,n,s,i){let o=(s||"").trim(),a=(i||"").trim();if(!o||!a||o===a)return!1;let c=this.loadSharedHistory(e,t,n);if(!c)return!1;let l=!1;return c.requests=c.requests.map(u=>!u.ticket&&u.branch===o?(l=!0,{...u,branch:a}):u),l?(this.saveSharedHistory(c),!0):!1}clearHistory(e,t,n){let s=this.getRequestPath(e,t,n);if(Y.existsSync(s)){let i=Y.readdirSync(s);for(let o of i)Y.unlinkSync(Je.join(s,o));Y.rmdirSync(s)}}saveFullResponse(e,t,n,s,i,o){let a=this.getRequestPath(e,t,n),c=this.getResponseFilePath(e,t,n,s);try{Y.existsSync(a)||Y.mkdirSync(a,{recursive:!0});let l=Kc(i,o);Y.writeFileSync(c,JSON.stringify(l,null,2),"utf-8")}catch(l){throw console.error(`Failed to save full response for ${s}:`,l),l}}loadFullResponse(e,t,n,s){let i=this.getResponseFilePath(e,t,n,s);try{if(!Y.existsSync(i))return null;let o=Y.readFileSync(i,"utf-8");return JSON.parse(o)}catch(o){return console.error(`Failed to load full response for ${s}:`,o),null}}loadSharedFullResponse(e,t,n,s){let i=this.getSharedResponseFilePath(e,t,n,s);try{if(!Y.existsSync(i))return null;let o=Y.readFileSync(i,"utf-8");return JSON.parse(o)}catch(o){return console.error(`Failed to load shared full response for ${s}:`,o),null}}}});var Hr,Yc=k(()=>{"use strict";Hr=class{constructor(e,t){this.historyService=e;this.inferrer=t}historyService;inferrer;async analyze(e,t,n){let s=n?.environment||"default",i=n?.maxSamples||50,o=this.historyService.loadHistory(s,e,t),a=this.historyService.loadSharedHistory(s,e,t),c=[...o?.requests||[],...a?.requests||[]];if(c.length===0)return{responses:{}};let l=c.slice(0,i),u=new Map;for(let p of l){let m=this.historyService.loadFullResponse(s,e,t,p.id);if(m||(m=this.historyService.loadSharedFullResponse(s,e,t,p.id)),m){let f=m.status;u.has(f)||u.set(f,[]),u.get(f).push(m)}}let d={};for(let[p,m]of u){let f=this.buildResponseDefinition(m);d[String(p)]=f}return{responses:d}}buildResponseDefinition(e){let t={};if(e.length===0)return t;let n=e[0];t.description=n.statusText||`Status ${n.status}`;let s=this.extractContentType(n.headers);if(s&&(t.contentType=s),s&&this.isJsonContentType(s)){let o=this.inferBodySchema(n);for(let a=1;a<e.length;a++){let c=this.inferBodySchema(e[a]);c&&o?o=this.inferrer.mergeSchemas(o,c):c&&(o=c)}if(o&&(t.schema=o),n.body!==void 0&&n.body!==null){let a=typeof n.body=="string"?this.tryParseJson(n.body):n.body;a!==void 0&&(t.examples={default:{summary:"Captured from history",value:a}})}}let i=this.findConsistentHeaders(e);return Object.keys(i).length>0&&(t.headers=i),t}inferBodySchema(e){if(e.body===void 0||e.body===null)return;let t=e.body;if(!(typeof t=="string"&&(t=this.tryParseJson(t),t===void 0)))return this.inferrer.inferFromValue(t)}extractContentType(e){for(let[t,n]of Object.entries(e))if(t.toLowerCase()==="content-type")return(Array.isArray(n)?n[0]:n).split(";")[0].trim()}isJsonContentType(e){return e.includes("json")||e.includes("+json")||e==="application/json"}findConsistentHeaders(e){if(e.length===0)return{};let t=new Set(["content-type","content-length","content-encoding","transfer-encoding","connection","date","server","set-cookie","vary","cache-control","expires","pragma","etag","last-modified","age"]),n=new Map,s=new Map;for(let a of e)for(let[c,l]of Object.entries(a.headers)){let u=c.toLowerCase();t.has(u)||(n.set(u,(n.get(u)||0)+1),s.has(u)||s.set(u,Array.isArray(l)?l.join(", "):l))}let i=Math.ceil(e.length/2),o={};for(let[a,c]of n)if(c>=i){let l=s.get(a);o[a]={schema:this.inferHeaderSchema(l)}}return o}inferHeaderSchema(e){return e?/^\d+$/.test(e)?{type:"integer"}:{type:"string"}:{type:"string"}}tryParseJson(e){try{return JSON.parse(e)}catch{return}}}});function tp(r){let e=r,t=null,n=e.match(/^\{\{(\w+)\}\}/);return n&&(t=n[1],e=e.slice(n[0].length)),e=e.replace(/:([a-zA-Z_]\w*)/g,"{$1}"),e=e.replace(/\{\{(\w+)\}\}/g,"{$1}"),e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e=e.replace(/\/\//g,"/"),{path:e,hostVar:t}}function Xd(r){return/^-?\d+$/.test(r)?"integer":/^-?\d+\.\d+$/.test(r)?"number":r==="true"||r==="false"?"boolean":"string"}function bo(r,e){if(r==="integer"&&e==="number"||r==="number"&&e==="integer")return"number"}function np(r){return r.replace(/\{\{(\w+)\}\}/g,"<$1>")}function Xc(r,e){let t=np(r);switch(e){case"integer":return parseInt(t,10)||t;case"number":return parseFloat(t)||t;case"boolean":return t==="true";default:return t}}function el(r){if(typeof r=="string")return np(r);if(Array.isArray(r))return r.map(e=>el(e));if(r!==null&&typeof r=="object"){let e={};for(let[t,n]of Object.entries(r))e[t]=el(n);return e}return r}function Xs(r){if(!r||!r.content)return;let e;if(typeof r.content=="string")try{e=JSON.parse(r.content)}catch{e=r.content}else e=r.content;return el(e)}function tl(r){if(!r)return"application/json";switch(r.type){case"raw":switch(r.format){case"json":return"application/json";case"xml":return"application/xml";case"html":return"text/html";case"text":return"text/plain";default:return"text/plain"}case"form-data":return"multipart/form-data";case"x-www-form-urlencoded":return"application/x-www-form-urlencoded";case"binary":return"application/octet-stream";case"graphql":return"application/json";default:return"application/json"}}function nl(r){let e={type:"object",properties:{}},t=r.formData||r.urlencoded||[];for(let n of t)n.enabled!==!1&&(n.type==="file"?e.properties[n.key]={type:"string",format:"binary"}:e.properties[n.key]={type:"string"});return e}function ep(r,e){let t={name:r.key,in:e,schema:{}};return r.oneOf?(t.schema.oneOf=r.oneOf,r.type&&(t.schema.type=r.type)):(t.schema.type=r.type||"string",r.format&&(t.schema.format=r.format),r.enum&&(t.schema.enum=r.enum),r.pattern&&(t.schema.pattern=r.pattern),r.minimum!==void 0&&(t.schema.minimum=r.minimum),r.maximum!==void 0&&(t.schema.maximum=r.maximum),r.exclusiveMinimum!==void 0&&(t.schema.exclusiveMinimum=r.exclusiveMinimum),r.exclusiveMaximum!==void 0&&(t.schema.exclusiveMaximum=r.exclusiveMaximum),r.multipleOf!==void 0&&(t.schema.multipleOf=r.multipleOf),r.minLength!==void 0&&(t.schema.minLength=r.minLength),r.maxLength!==void 0&&(t.schema.maxLength=r.maxLength),r.minItems!==void 0&&(t.schema.minItems=r.minItems),r.maxItems!==void 0&&(t.schema.maxItems=r.maxItems),r.uniqueItems&&(t.schema.uniqueItems=!0),r.nullable&&(t.schema.nullable=!0)),r.required&&(t.required=!0),r.description&&(t.description=r.description),r.deprecated&&(t.deprecated=!0),r.value&&(t.example=Xc(r.value,t.schema.type||"string")),t}function Lg(r){let e=[],t=r.split(";").map(n=>n.trim()).filter(Boolean);for(let n of t){let s=n.indexOf("=");if(s>0){let i=n.substring(0,s).trim(),o=n.substring(s+1).trim();e.push({name:i,in:"cookie",schema:{type:"string"},example:o})}}return e}function rp(r){let e=[];if(r.params)for(let[t,n]of Object.entries(r.params)){let s={name:t,in:"path",required:!0};if(typeof n=="string")s.schema={type:Xd(n)},s.example=Xc(n,s.schema.type);else{let i=n;i.oneOf?(s.schema={oneOf:i.oneOf},i.type&&(s.schema.type=i.type)):(s.schema={type:i.type||Xd(i.value)},i.format&&(s.schema.format=i.format),i.enum&&(s.schema.enum=i.enum),i.pattern&&(s.schema.pattern=i.pattern),i.minimum!==void 0&&(s.schema.minimum=i.minimum),i.maximum!==void 0&&(s.schema.maximum=i.maximum),i.exclusiveMinimum!==void 0&&(s.schema.exclusiveMinimum=i.exclusiveMinimum),i.exclusiveMaximum!==void 0&&(s.schema.exclusiveMaximum=i.exclusiveMaximum),i.multipleOf!==void 0&&(s.schema.multipleOf=i.multipleOf),i.minLength!==void 0&&(s.schema.minLength=i.minLength),i.maxLength!==void 0&&(s.schema.maxLength=i.maxLength),i.minItems!==void 0&&(s.schema.minItems=i.minItems),i.maxItems!==void 0&&(s.schema.maxItems=i.maxItems),i.uniqueItems&&(s.schema.uniqueItems=!0),i.nullable&&(s.schema.nullable=!0)),i.description&&(s.description=i.description),i.deprecated&&(s.deprecated=!0),s.example=Xc(i.value,s.schema.type||"string")}e.push(s)}if(r.query)for(let t of r.query){if(!t.key)continue;let n=ep(t,"query");e.push(n)}if(r.headers){let t=r.headers.find(n=>n.key.toLowerCase()==="cookie");if(t){let n=Lg(t.value);e.push(...n)}for(let n of r.headers){if(!n.key||jg.has(n.key.toLowerCase()))continue;let s=ep(n,"header");e.push(s)}}return e}function sp(r){return r.replace(/[^a-zA-Z0-9]+(.)/g,(e,t)=>t.toUpperCase()).replace(/^[A-Z]/,e=>e.toLowerCase()).replace(/[^a-zA-Z0-9]/g,"")}function ip(r){return r.replace(/^\[DEPRECATED\]\s*/i,"")}function rl(r){return/^\[DEPRECATED\]/i.test(r)}function ei(r){let e={};for(let t of r.split(/\s+/))t&&(e[t]="");return e}var jg,ti=k(()=>{"use strict";jg=new Set(["content-type","authorization","accept","cookie","host","content-length"])});var Hg,Bg,Ug,Vg,zg,Jg,Wg,ln,So=k(()=>{"use strict";ti();Hg=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,Bg=/^\d{4}-\d{2}-\d{2}$/,Ug=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,Vg=/^https?:\/\/[^\s]+$/,zg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Jg=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Wg=/^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/,ln=class{inferFromValue(e){if(e==null)return{nullable:!0};if(Array.isArray(e))return this.inferArraySchema(e);switch(typeof e){case"string":return this.inferStringSchema(e);case"number":return Number.isInteger(e)?{type:"integer"}:{type:"number"};case"boolean":return{type:"boolean"};case"object":return this.inferObjectSchema(e);default:return{}}}mergeSchemas(e,t){if(!e||Object.keys(e).length===0)return{...t};if(!t||Object.keys(t).length===0)return{...e};let n=e.nullable||t.nullable;if(!e.type&&e.nullable)return{...t,nullable:!0};if(!t.type&&t.nullable)return{...e,nullable:!0};if(e.type!==t.type){let i=bo(e.type,t.type);return i?{type:i,...n&&{nullable:!0}}:{...n&&{nullable:!0}}}let s={type:e.type};return n&&(s.nullable=!0),e.type==="object"&&t.type==="object"?this.mergeObjectSchemas(e,t,n):e.type==="array"&&t.type==="array"?this.mergeArraySchemas(e,t,n):(e.format&&e.format===t.format&&(s.format=e.format),s)}inferStringFormat(e){if(Hg.test(e))return"date-time";if(Bg.test(e))return"date";if(Ug.test(e))return"email";if(zg.test(e))return"uuid";if(Vg.test(e))return"uri";if(Jg.test(e))return"ipv4";if(Wg.test(e))return"ipv6"}inferStringSchema(e){let t={type:"string"},n=this.inferStringFormat(e);return n&&(t.format=n),t}inferArraySchema(e){let t={type:"array"};if(e.length===0)return t;let n=this.inferFromValue(e[0]);for(let s=1;s<e.length;s++)n=this.mergeSchemas(n,this.inferFromValue(e[s]));return t.items=n,t}inferObjectSchema(e){let t={type:"object",properties:{}},n=Object.keys(e);for(let s of n)t.properties[s]=this.inferFromValue(e[s]);return t}mergeObjectSchemas(e,t,n){let s={type:"object",properties:{},...n&&{nullable:!0}},i=e.properties||{},o=t.properties||{},a=new Set([...Object.keys(i),...Object.keys(o)]);for(let d of a)i[d]&&o[d]?s.properties[d]=this.mergeSchemas(i[d],o[d]):i[d]?s.properties[d]={...i[d]}:s.properties[d]={...o[d]};let c=new Set(e.required||Object.keys(i)),l=new Set(t.required||Object.keys(o)),u=[...a].filter(d=>c.has(d)&&l.has(d));return u.length>0&&(s.required=u),s}mergeArraySchemas(e,t,n){let s={type:"array",...n&&{nullable:!0}};return e.items&&t.items?s.items=this.mergeSchemas(e.items,t.items):e.items?s.items={...e.items}:t.items&&(s.items={...t.items}),s}}});var xo,op=k(()=>{"use strict";ti();xo=class{constructor(e){this.inferrer=e}inferrer;async buildOperation(e,t,n,s,i,o,a,c,l){let u={};u.operationId=e.operationId||this.generateOperationId(e,t,n,s),u.summary=e.summary||ip(e.name),e.description&&(u.description=e.description),(e.deprecated||rl(e.name))&&(u.deprecated=!0,rl(e.name)&&(u.summary=e.name.replace(/^\[DEPRECATED\]\s*/i,"")));let d=e.tags;if(d&&d.length>0){u.tags=d;for(let g of d)o.add(g)}else a&&(u.tags=[a]);let p=rp(e);p.length>0&&(u.parameters=p);let m=await this.buildRequestBody(e,l);m&&(u.requestBody=m);let f=e.responses;f&&Object.keys(f).length>0?u.responses=this.mapResponseDefinitions(f):u.responses=await this.buildResponses(e,c.id,l);let h=e.security;if(h&&h.length>0)u.security=h;else{let g=this.buildOperationSecurity(e,c,i);g!==void 0&&(u.security=g)}return u}generateOperationId(e,t,n,s){let i=sp(e.name),o=this.collectOperationIds(s);if(o.has(i)&&(i=`${i}${t.charAt(0).toUpperCase()}${t.slice(1)}`),!i||o.has(i)){let a=n.split("/").filter(c=>c&&!c.startsWith("{"));i=t+a.map(c=>c.charAt(0).toUpperCase()+c.slice(1)).join("")}return i}collectOperationIds(e){let t=new Set;if(e.paths)for(let n of Object.values(e.paths))for(let s of Object.values(n))s.operationId&&t.add(s.operationId);return t}async buildRequestBody(e,t){if(!e.body||e.body.type==="none")return null;let n=e.body,s={required:!0,content:{}},i,o,a,c;if(e.bodySchema){if(e.bodySchema.content){for(let[d,p]of Object.entries(e.bodySchema.content)){let m={};p.schema&&(m.schema=p.schema),p.examples&&(m.examples=p.examples),p.encoding&&(m.encoding=p.encoding),s.content[d]=m}let u=e.bodySchema.contentType||Object.keys(e.bodySchema.content)[0];if(u&&n.content){let d=Xs(n);d!==void 0&&s.content[u]&&(s.content[u].example=d)}return s}i=e.bodySchema.contentType||tl(n),o=e.bodySchema.schema,a=Xs(n),e.bodySchema.encoding&&(c=e.bodySchema.encoding)}else switch(i=tl(n),n.type){case"raw":{if(n.format==="json"&&n.content){let u=Xs(n);u!==void 0?(o=this.inferrer.inferFromValue(u),a=u):o={type:"string"}}else o={type:"string"},a=typeof n.content=="string"?n.content:void 0;break}case"form-data":{o=nl(n);break}case"x-www-form-urlencoded":{o=nl(n);break}case"binary":{o={type:"string",format:"binary"};break}case"graphql":{o={type:"object",properties:{query:{type:"string"},variables:{type:"object"}}},a=Xs(n);break}default:return null}let l={};return o&&(l.schema=o),a!==void 0&&(l.example=a),c&&(l.encoding=c),s.content[i]=l,s}async buildResponses(e,t,n){let s={};if(e.responseSchema)for(let[i,o]of Object.entries(e.responseSchema.responses)){let a={description:o.description||`Status ${i}`};if(o.content){a.content={};for(let[c,l]of Object.entries(o.content)){let u={};l.schema&&(u.schema=l.schema),l.examples&&(u.examples=l.examples),a.content[c]=u}}else if(o.schema){let c=o.contentType||"application/json",l={schema:o.schema};o.examples&&(l.examples=o.examples),a.content={[c]:l}}if(o.headers){a.headers={};for(let[c,l]of Object.entries(o.headers))a.headers[c]={...l.description&&{description:l.description},schema:l.schema}}s[i]=a}return Object.keys(s).length===0&&(s[200]={description:"Successful response"}),s}mapResponseDefinitions(e){let t={};for(let[n,s]of Object.entries(e)){let i={description:s.description||`Status ${n}`};if(s.schema||s.examples){let o=s.contentType||"application/json",a={};s.schema&&(a.schema=s.schema),s.examples&&Object.keys(s.examples).length>0&&(a.examples=s.examples),i.content={[o]:a}}if(s.headers&&Object.keys(s.headers).length>0){i.headers={};for(let[o,a]of Object.entries(s.headers)){let c=a;i.headers[o]={...c.description&&{description:c.description},...c.schema&&{schema:c.schema}}}}t[n]=i}return Object.keys(t).length===0&&(t[200]={description:"Successful response"}),t}buildOperationSecurity(e,t,n){if(!e.auth||e.auth.type==="inherit")return;if(e.auth.type==="none")return[];let s=this.mapAuthToSecurityScheme(e.auth);if(!s)return;let{schemeName:i,scheme:o,requirement:a}=s;return n.set(i,o),[a]}mapAuthToSecurityScheme(e){switch(e.type){case"bearer":return{schemeName:"BearerAuth",scheme:{type:"http",scheme:"bearer"},requirement:{BearerAuth:[]}};case"basic":return{schemeName:"BasicAuth",scheme:{type:"http",scheme:"basic"},requirement:{BasicAuth:[]}};case"apikey":{let t=e.apikey||{key:"X-Api-Key",value:"",in:"header"},n=`ApiKey_${t.key||"key"}`;return{schemeName:n,scheme:{type:"apiKey",in:t.in||"header",name:t.key||"X-Api-Key"},requirement:{[n]:[]}}}case"oauth2":{let t=e.oauth2;if(!t)return;let n={};switch(t.grantType){case"client_credentials":n.clientCredentials={tokenUrl:t.tokenUrl||"",scopes:t.scope?ei(t.scope):{}};break;case"authorization_code":n.authorizationCode={authorizationUrl:t.authUrl||"",tokenUrl:t.tokenUrl||"",scopes:t.scope?ei(t.scope):{}};break;case"password":n.password={tokenUrl:t.tokenUrl||"",scopes:t.scope?ei(t.scope):{}};break;case"implicit":n.implicit={authorizationUrl:t.authUrl||"",scopes:t.scope?ei(t.scope):{}};break;default:n.clientCredentials={tokenUrl:t.tokenUrl||"",scopes:{}}}return{schemeName:"OAuth2",scheme:{type:"oauth2",flows:n},requirement:{OAuth2:[]}}}default:return{schemeName:"BearerAuth",scheme:{type:"http",scheme:"bearer"},requirement:{BearerAuth:[]}}}}}});var wo,ap=k(()=>{"use strict";ti();wo=class{mergeOperation(e,t,n){if(t.summary&&t.summary!==e.summary&&(e.description=(e.description||e.summary||"")+`
|
|
646
646
|
|
|
647
|
-
Variant: **${n}**`+(t.description?` \u2014 ${t.description}`:"")),t.tags){let s=new Set(e.tags||[]);for(let i of t.tags)s.add(i);e.tags=[...s]}if(t.parameters){e.parameters||(e.parameters=[]);for(let s of t.parameters){let i=e.parameters.find(o=>o.name===s.name&&o.in===s.in);i?this.mergeParameterSchema(i,s,n):e.parameters.push(s)}}if(t.responses){e.responses||(e.responses={});for(let[s,i]of Object.entries(t.responses))e.responses[s]||(e.responses[s]=i)}if(t.requestBody?.content&&e.requestBody?.content)for(let[s,i]of Object.entries(t.requestBody.content))e.requestBody.content[s]||(e.requestBody.content[s]=i);else t.requestBody&&!e.requestBody&&(e.requestBody=t.requestBody)}mergeParameterSchema(e,t,n){e.schema||(e.schema={});let s=e.schema,i=t.schema||{},o=this.getConstraintKind(s),a=this.getConstraintKind(i);if(o==="none"&&a==="none")this.widenType(s,i);else if(o==="none")Object.assign(s,this.extractConstraints(i)),this.widenType(s,i);else if(a==="none")this.widenType(s,i);else if(o===a)this.mergeSameKindConstraints(s,i,o),this.widenType(s,i);else{if(s.oneOf){let c=this.buildVariantSchema(i);s.oneOf.some(l=>JSON.stringify(l)===JSON.stringify(c))||s.oneOf.push(c)}else if(i.oneOf){let c=this.buildVariantSchema(s);s.oneOf=[c,...i.oneOf]}else{let c=this.buildVariantSchema(s),l=this.buildVariantSchema(i);s.oneOf=[c,l]}this.stripConstraints(s)}if(t.description&&t.description!==e.description&&(e.description=(e.description||"")+(e.description?"; ":"")+t.description),t.example!==void 0&&t.example!==e.example){e.examples||(e.examples={},e.example!==void 0&&(e.examples.variant1={value:e.example}));let c=`variant_${n.replace(/[^a-zA-Z0-9_]/g,"_")}`;e.examples[c]={value:t.example},delete e.example}}getConstraintKind(e){return e.oneOf?"oneOf":e.enum&&e.enum.length>0?"enum":e.pattern?"pattern":e.minimum!==void 0||e.maximum!==void 0||e.exclusiveMinimum!==void 0||e.exclusiveMaximum!==void 0||e.multipleOf!==void 0?"range":e.minLength!==void 0||e.maxLength!==void 0?"length":e.minItems!==void 0||e.maxItems!==void 0||e.uniqueItems?"array":e.format?"format":"none"}mergeSameKindConstraints(e,t,n){switch(n){case"enum":{let s=new Set(e.enum||[]);for(let i of t.enum||[])s.add(i);e.enum=[...s];break}case"pattern":{t.pattern&&t.pattern!==e.pattern&&(e.pattern=`(?:${e.pattern})|(?:${t.pattern})`);break}case"range":{t.minimum!==void 0&&(e.minimum=e.minimum!==void 0?Math.min(e.minimum,t.minimum):t.minimum),t.maximum!==void 0&&(e.maximum=e.maximum!==void 0?Math.max(e.maximum,t.maximum):t.maximum),t.exclusiveMinimum&&(e.exclusiveMinimum=!0),t.exclusiveMaximum&&(e.exclusiveMaximum=!0),t.multipleOf!==void 0&&(e.multipleOf=e.multipleOf!==void 0?Math.min(e.multipleOf,t.multipleOf):t.multipleOf);break}case"length":{t.minLength!==void 0&&(e.minLength=e.minLength!==void 0?Math.min(e.minLength,t.minLength):t.minLength),t.maxLength!==void 0&&(e.maxLength=e.maxLength!==void 0?Math.max(e.maxLength,t.maxLength):t.maxLength);break}case"array":{t.minItems!==void 0&&(e.minItems=e.minItems!==void 0?Math.min(e.minItems,t.minItems):t.minItems),t.maxItems!==void 0&&(e.maxItems=e.maxItems!==void 0?Math.max(e.maxItems,t.maxItems):t.maxItems),t.uniqueItems&&(e.uniqueItems=!0);break}case"format":{if(t.format&&t.format!==e.format){let s={type:e.type||"string",format:e.format},i={type:t.type||"string",format:t.format};delete e.format,e.oneOf=[s,i]}break}case"oneOf":{if(t.oneOf)for(let s of t.oneOf)e.oneOf.some(i=>JSON.stringify(i)===JSON.stringify(s))||e.oneOf.push(s);break}}}buildVariantSchema(e){let t={};return e.type&&(t.type=e.type),e.enum&&(t.enum=[...e.enum]),e.pattern&&(t.pattern=e.pattern),e.format&&(t.format=e.format),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.exclusiveMinimum!==void 0&&(t.exclusiveMinimum=e.exclusiveMinimum),e.exclusiveMaximum!==void 0&&(t.exclusiveMaximum=e.exclusiveMaximum),e.multipleOf!==void 0&&(t.multipleOf=e.multipleOf),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.minItems!==void 0&&(t.minItems=e.minItems),e.maxItems!==void 0&&(t.maxItems=e.maxItems),e.uniqueItems&&(t.uniqueItems=!0),e.nullable&&(t.nullable=!0),t}stripConstraints(e){delete e.enum,delete e.pattern,delete e.format,delete e.minimum,delete e.maximum,delete e.exclusiveMinimum,delete e.exclusiveMaximum,delete e.multipleOf,delete e.minLength,delete e.maxLength,delete e.minItems,delete e.maxItems,delete e.uniqueItems,delete e.nullable}extractConstraints(e){let t={};return e.enum&&(t.enum=[...e.enum]),e.pattern&&(t.pattern=e.pattern),e.format&&(t.format=e.format),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.exclusiveMinimum!==void 0&&(t.exclusiveMinimum=e.exclusiveMinimum),e.exclusiveMaximum!==void 0&&(t.exclusiveMaximum=e.exclusiveMaximum),e.multipleOf!==void 0&&(t.multipleOf=e.multipleOf),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.minItems!==void 0&&(t.minItems=e.minItems),e.maxItems!==void 0&&(t.maxItems=e.maxItems),e.uniqueItems&&(t.uniqueItems=!0),e.nullable&&(t.nullable=!0),t}widenType(e,t){if(!(!t.type||t.type===e.type))if(!e.type)e.type=t.type;else{let n=bo(e.type,t.type);n&&(e.type=n)}}}});import*as cp from"yaml";var Ro,lp=k(()=>{"use strict";Ro=class{finalize(e,t,n,s){if(t.size>0)for(let[i,o]of t)e.components.securitySchemes[i]=o;else delete e.components.securitySchemes;return e.tags=[...n].map(i=>({name:i})),e.tags.length===0&&delete e.tags,this.deduplicateComponents(e),Object.keys(e.components.schemas).length===0&&delete e.components.schemas,Object.keys(e.components).length===0&&delete e.components,s.format==="yaml"?cp.stringify(e,{indent:2}):JSON.stringify(e,null,2)}deduplicateComponents(e){let t=new Map,n=new Map;if(e.paths)for(let[s,i]of Object.entries(e.paths))for(let[o,a]of Object.entries(i)){let c=a;if(c.responses){for(let[l,u]of Object.entries(c.responses))if(u.content)for(let d of Object.values(u.content))d.schema&&this.trackSchema(d.schema,`${o}${s}Response${l}`,t,n)}if(c.requestBody?.content)for(let l of Object.values(c.requestBody.content))l.schema&&this.trackSchema(l.schema,`${o}${s}Request`,t,n)}for(let[s,i]of t)if((n.get(s)||0)>=2){let a=this.sanitizeComponentName(i.name);e.components.schemas[a]=i.schema,this.replaceInlineSchema(e,i.schema,`#/components/schemas/${a}`)}}trackSchema(e,t,n,s){if(!e||e.type!=="object"||!e.properties)return;let i=JSON.stringify(e);n.has(i)||n.set(i,{name:t,schema:e}),s.set(i,(s.get(i)||0)+1)}replaceInlineSchema(e,t,n){let s=JSON.stringify(t);if(e.paths)for(let i of Object.values(e.paths))for(let o of Object.values(i)){if(o.responses){for(let a of Object.values(o.responses))if(a.content)for(let c of Object.values(a.content))c.schema&&JSON.stringify(c.schema)===s&&(c.schema={$ref:n})}if(o.requestBody?.content)for(let a of Object.values(o.requestBody.content))a.schema&&JSON.stringify(a.schema)===s&&(a.schema={$ref:n})}}sanitizeComponentName(e){return e.replace(/[^a-zA-Z0-9._-]/g,"").replace(/^[^a-zA-Z]/,"Schema")}}});var un,Co=k(()=>{"use strict";So();op();ap();lp();ti();un=class{constructor(e,t,n){this.collectionService=e;this.envConfigService=t;this.inferenceService=n;let s=new ln;this.merger=new wo,this.operationBuilder=new xo(s),this.specWriter=new Ro}collectionService;envConfigService;inferenceService;merger;operationBuilder;specWriter;async export(e,t){let n=this.collectionService.getCollection(e);if(!n)throw new Error(`Collection ${e} not found`);let s={openapi:"3.0.3",info:this.buildInfo(n,t),servers:this.buildServers(t),paths:{},components:{schemas:{},securitySchemes:{}},tags:[]},i=new Map;if(n.auth&&n.auth.type!=="none"&&n.auth.type!=="inherit"){let c=this.operationBuilder.mapAuthToSecurityScheme(n.auth);if(c){let{schemeName:l,scheme:u,requirement:d}=c;i.set(l,u),s.security=[d]}}let o=new Set,a=new Set;return await this.processItems(n.items,s,i,o,a,void 0,n,t),this.augmentServersFromHostVars(a,s.servers,t),this.specWriter.finalize(s,i,o,t)}buildInfo(e,t){return{title:t.info?.title||e.name,description:t.info?.description||e.description||"",version:t.info?.version||e.version||"1.0.0"}}buildServers(e){let t=[],n=e.environments||[];if(n.length===0){let s=this.envConfigService.getSelectedEnvironment();if(s){let i=this.envConfigService.resolveVariables("{{baseUrl}}",s);i&&i!=="{{baseUrl}}"&&t.push({url:i,description:s})}}else{let s=new Set;for(let i of n){let o=this.envConfigService.resolveVariables("{{baseUrl}}",i);o&&o!=="{{baseUrl}}"&&!s.has(o)&&(s.add(o),t.push({url:o,description:i}))}}return t.length===0&&t.push({url:"http://localhost",description:"Default server"}),t}async processItems(e,t,n,s,i,o,a,c){for(let l of e)if(l.type==="folder"){let u=l,d=o||u.name;s.add(d),u.items&&await this.processItems(u.items,t,n,s,i,d,a,c)}else{let u=l;await this.processRequest(u,t,n,s,i,o,a,c)}}async processRequest(e,t,n,s,i,o,a,c){let{path:l,hostVar:u}=tp(e.url);u&&i.add(u);let d=(e.method||"GET").toLowerCase();t.paths[l]||(t.paths[l]={});let p=await this.operationBuilder.buildOperation(e,d,l,t,n,s,o,a,c),m=t.paths[l][d];m?this.merger.mergeOperation(m,p,e.name):t.paths[l][d]=p}augmentServersFromHostVars(e,t,n){if(e.size===0)return;let s=new Set(t.map(o=>o.url)),i=n.environments?.length?n.environments:[this.envConfigService.getSelectedEnvironment()].filter(o=>!!o);for(let o of e){let a=`{{${o}}}`,c=!1;for(let l of i){let u=this.envConfigService.resolveVariables(a,l);u&&u!==a&&!s.has(u)&&(t.push({url:u,description:l}),s.add(u),c=!0)}if(!c){let l=`{${o}}`;s.has(l)||(t.push({url:l,variables:{[o]:{default:""}}}),s.add(l))}}}}});var Br,sl=k(()=>{"use strict";Br=class{generate(e,t){if(!e)return;let n=t||{};if(e.$ref){let s=this.resolveLocalRef(e.$ref,n.components);return s?this.generate(s,n):{}}if(e.nullable&&!e.type)return null;if(e.enum&&e.enum.length>0)return e.enum[0];if(e.default!==void 0)return e.default;if(e.example!==void 0)return e.example;if(e.allOf)return this.generateFromAllOf(e.allOf,e.discriminator,n);if(e.oneOf)return this.generateFromOneOfAnyOf(e.oneOf,e.discriminator,n);if(e.anyOf)return this.generateFromOneOfAnyOf(e.anyOf,e.discriminator,n);switch(e.type){case"string":return this.generateString(e);case"integer":return this.generateInteger(e);case"number":return this.generateNumber(e);case"boolean":return!1;case"array":return this.generateArray(e,n);case"object":return this.generateObject(e,n);default:return e.properties?this.generateObject(e,n):{}}}generateString(e){switch(e.format){case"email":return"user@example.com";case"date-time":return"2026-01-01T00:00:00Z";case"date":return"2026-01-01";case"time":return"00:00:00";case"uri":case"url":return"https://example.com";case"uuid":return"00000000-0000-0000-0000-000000000000";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"hostname":return"example.com";case"binary":return"";case"byte":return"c3RyaW5n";case"password":return"********";default:return"string"}}generateInteger(e){return e.minimum!==void 0?e.minimum:e.exclusiveMinimum!==void 0?e.exclusiveMinimum+1:0}generateNumber(e){return e.minimum!==void 0?e.minimum:e.exclusiveMinimum!==void 0?e.exclusiveMinimum+.1:0}generateArray(e,t){return e.items?[this.generate(e.items,t)]:[]}generateObject(e,t){let n={},s=e.properties||{};for(let[i,o]of Object.entries(s))t.omitReadOnly&&o.readOnly||(n[i]=this.generate(o,t));return n}generateFromAllOf(e,t,n){let s={type:"object",properties:{},required:[]};for(let o of e){let a=o.$ref?this.resolveLocalRef(o.$ref,n.components)||{}:o;a.properties&&Object.assign(s.properties,a.properties),a.required&&(s.required=[...s.required||[],...a.required])}let i=this.generateObject(s,n);return t?.propertyName&&(i[t.propertyName]=this.guessDiscriminatorValue(e,n)),i}generateFromOneOfAnyOf(e,t,n){if(e.length===0)return{};let s=e[0].$ref&&this.resolveLocalRef(e[0].$ref,n.components)||e[0],i=this.generate(s,n);return t?.propertyName&&typeof i=="object"&&i!==null&&(i[t.propertyName]=this.guessDiscriminatorValue(e,n)),i}guessDiscriminatorValue(e,t){if(e.length===0)return"unknown";let n=e[0];if(n.$ref){let s=n.$ref.split("/");return s[s.length-1]}return"variant1"}resolveLocalRef(e,t){if(!e||!t)return;let n=e.match(/^#\/components\/(?:schemas\/)?(.+)$/);if(n)return t[n[1]];let s=e.match(/^#\/components\/(.+)$/);if(s)return t[s[1]]}}});import il from"@apidevtools/json-schema-ref-parser";var Ur,ol=k(()=>{"use strict";Ur=class{async resolve(e){try{return await il.dereference(e,{dereference:{circular:"ignore"}})}catch(t){return console.error("[RefResolver] Failed to fully resolve $ref pointers:",t),e}}async bundle(e){try{return await il.bundle(e)}catch(t){return console.error("[RefResolver] Failed to bundle $ref pointers:",t),e}}async resolveFile(e){try{return await il.dereference(e,{dereference:{circular:"ignore"}})}catch(t){throw console.error(`[RefResolver] Failed to resolve file ${e}:`,t),t}}}});import*as up from"fs";import*as dp from"yaml";var Wg,Lt,ko=k(()=>{"use strict";Ze();sl();ol();Wg=["application/json","text/plain","text/html","multipart/form-data","application/x-www-form-urlencoded"],Lt=class{constructor(e,t){this.collectionService=e;this.envConfigService=t;this.exampleGenerator=new Br,this.refResolver=new Ur}collectionService;envConfigService;exampleGenerator;refResolver;async import(e,t){let n=await up.promises.readFile(e,"utf-8"),s=this.parseSpec(n,e);return this.importFromSpec(s,t)}async importFromUrl(e,t){let n=await fetch(e,{headers:{Accept:"application/json, application/yaml, text/yaml"}});if(!n.ok)throw new Error(`Failed to fetch OpenAPI spec from ${e}: HTTP ${n.status} ${n.statusText}`);let s=await n.text(),i=this.parseSpec(s,e);return this.importFromSpec(i,t)}async importFromString(e,t){let n=this.parseSpec(e,"spec");return this.importFromSpec(n,t)}parseSpec(e,t){let n=e.trim();if(!n)throw new Error(`OpenAPI spec is empty (${t})`);return n.startsWith("{")||n.startsWith("[")?JSON.parse(e):dp.parse(e)}async importFromSpec(e,t){let n=e;n=await this.refResolver.resolve(n);let s=n.components?.schemas||{},i=t?.collectionName||n.info?.title||"Imported API",a={id:le(i),name:i,description:n.info?.description||"",version:n.info?.version||"1.0.0",variables:{},items:[]};if(n.servers&&n.servers.length>0&&(a.variables.baseUrl=n.servers[0].url),n.security&&n.security.length>0&&n.components?.securitySchemes){let u=this.mapSecurityToAuth(n.security[0],n.components.securitySchemes);u&&(a.auth=u)}let c=new Map;if(n.tags)for(let u of n.tags){let d={type:"folder",id:le(u.name),name:u.name,description:u.description,items:[]};c.set(u.name,d),a.items.push(d)}if(n.paths)for(let[u,d]of Object.entries(n.paths))for(let p of["get","post","put","patch","delete","head","options","trace"]){let m=d[p];if(!m)continue;let f=this.processOperation(p,u,m,d,n,s),h=m.tags?.[0];if(h&&c.has(h))c.get(h).items.push(f);else if(h){let g={type:"folder",id:le(h),name:h,items:[f]};c.set(h,g),a.items.push(g)}else a.items.push(f)}await this.collectionService.saveCollection(a);let l;return t?.environmentName&&n.servers&&(l=await this.createEnvironmentFromServers(n.servers,t.environmentName)),{collection:a,environmentCreated:l}}processOperation(e,t,n,s,i,o){let a=le(n.operationId||`${e}-${t}`),c=`{{baseUrl}}${this.convertPathParams(t)}`,l=n.summary||n.operationId||`${e.toUpperCase()} ${t}`,u=n.deprecated===!0;u&&(l=`[DEPRECATED] ${l}`);let d={type:"request",id:a,name:l,method:e.toUpperCase(),url:c,description:n.description||"",deprecated:u};n.operationId&&(d.operationId=n.operationId),n.summary&&(d.summary=n.summary),n.tags?.length&&(d.tags=[...n.tags]);let p=[...s.parameters||[],...n.parameters||[]];if(this.processParameters(d,p,o),n.requestBody&&this.processRequestBody(d,n.requestBody,o),n.responses&&(d.responseSchema=this.processResponses(n.responses,o)),n.security!==void 0&&i.components?.securitySchemes){if(Array.isArray(n.security)&&n.security.length===0)d.auth={type:"none"};else if(n.security&&n.security.length>0){let m=this.mapSecurityToAuth(n.security[0],i.components.securitySchemes);m&&(d.auth=m)}}return d}convertPathParams(e){return e.replace(/\{(\w+)\}/g,":$1")}processParameters(e,t,n){let s=[],i=[],o={},a=[];for(let c of t){let l=c.name,u=c.in,d=c.schema||{},p=c.example!==void 0?String(c.example):this.generateExampleForParam(d,n),m=c.deprecated===!0;switch(u){case"path":{if(c.description||d.type||d.format||d.enum||m||d.pattern||d.minimum!==void 0||d.maximum!==void 0||d.minLength!==void 0||d.maxLength!==void 0||d.multipleOf!==void 0||d.minItems!==void 0||d.maxItems!==void 0||d.uniqueItems||d.nullable||d.oneOf){let h={value:p};d.oneOf?(h.oneOf=d.oneOf,this.applyOneOfHints(h,d.oneOf)):(d.type&&(h.type=d.type),d.format&&(h.format=d.format),d.enum&&(h.enum=d.enum.map(String)),d.pattern&&(h.pattern=d.pattern),d.minimum!==void 0&&(h.minimum=d.minimum),d.maximum!==void 0&&(h.maximum=d.maximum),d.exclusiveMinimum!==void 0&&(h.exclusiveMinimum=d.exclusiveMinimum),d.exclusiveMaximum!==void 0&&(h.exclusiveMaximum=d.exclusiveMaximum),d.multipleOf!==void 0&&(h.multipleOf=d.multipleOf),d.minLength!==void 0&&(h.minLength=d.minLength),d.maxLength!==void 0&&(h.maxLength=d.maxLength),d.minItems!==void 0&&(h.minItems=d.minItems),d.maxItems!==void 0&&(h.maxItems=d.maxItems),d.uniqueItems&&(h.uniqueItems=!0),d.nullable&&(h.nullable=!0)),c.description&&(h.description=c.description),m&&(h.deprecated=!0),o[l]=h}else o[l]=p;break}case"query":{let f={key:l,value:p};this.applySchemaConstraints(f,d,c,m),i.push(f);break}case"header":{let f={key:l,value:p};this.applySchemaConstraints(f,d,c,m),s.push(f);break}case"cookie":{a.push(`${l}={{${l}}}`);break}}}a.length>0&&s.push({key:"Cookie",value:a.join("; ")}),Object.keys(o).length>0&&(e.params=o),i.length>0&&(e.query=i),s.length>0&&(e.headers=s)}applySchemaConstraints(e,t,n,s){t.oneOf?(e.oneOf=t.oneOf,this.applyOneOfHints(e,t.oneOf)):(t.type&&(e.type=t.type),t.format&&(e.format=t.format),t.enum&&(e.enum=t.enum.map(String)),t.pattern&&(e.pattern=t.pattern),t.minimum!==void 0&&(e.minimum=t.minimum),t.maximum!==void 0&&(e.maximum=t.maximum),t.exclusiveMinimum!==void 0&&(e.exclusiveMinimum=t.exclusiveMinimum),t.exclusiveMaximum!==void 0&&(e.exclusiveMaximum=t.exclusiveMaximum),t.multipleOf!==void 0&&(e.multipleOf=t.multipleOf),t.minLength!==void 0&&(e.minLength=t.minLength),t.maxLength!==void 0&&(e.maxLength=t.maxLength),t.minItems!==void 0&&(e.minItems=t.minItems),t.maxItems!==void 0&&(e.maxItems=t.maxItems),t.uniqueItems&&(e.uniqueItems=!0),t.nullable&&(e.nullable=!0)),n.required&&(e.required=!0),n.description&&(e.description=n.description),s&&(e.deprecated=!0)}applyOneOfHints(e,t){let n=[],s=new Set;for(let i of t)i.type&&s.add(i.type),i.enum&&n.push(...i.enum.map(String));s.size===1&&(e.type=[...s][0]),n.length>0&&(e.enum=[...new Set(n)])}generateExampleForParam(e,t){if(!e)return"";let n=this.exampleGenerator.generate(e,{components:t});return n==null?"":String(n)}processRequestBody(e,t,n){if(!t.content)return;let s=Object.keys(t.content);if(s.length===0)return;let i=this.selectPrimaryContentType(s),o=t.content[i],{bodyType:a,bodyFormat:c}=this.mapContentTypeToBodyType(i);if(e.body={type:a,...c&&{format:c},content:""},o){let u=this.generateBodyContent(o,i,n);u!==void 0&&(e.body.content=typeof u=="string"?u:JSON.stringify(u,null,2)),a==="form-data"&&o.schema?.properties&&(e.body.content=this.buildFormDataEntries(o.schema,n)),a==="x-www-form-urlencoded"&&o.schema?.properties&&(e.body.content=this.buildFormDataEntries(o.schema,n))}let l=this.buildBodySchema(t,i,n);l&&(e.bodySchema=l)}selectPrimaryContentType(e){for(let s of Wg)if(e.includes(s))return s;let t=e.find(s=>s.includes("json"));if(t)return t;let n=e.find(s=>s.startsWith("text/"));return n||e[0]}mapContentTypeToBodyType(e){return e.includes("json")?{bodyType:"raw",bodyFormat:"json"}:e==="application/xml"||e==="text/xml"?{bodyType:"raw",bodyFormat:"xml"}:e==="text/html"?{bodyType:"raw",bodyFormat:"html"}:e.startsWith("text/")?{bodyType:"raw",bodyFormat:"text"}:e==="multipart/form-data"?{bodyType:"form-data"}:e==="application/x-www-form-urlencoded"?{bodyType:"x-www-form-urlencoded"}:e==="application/octet-stream"?{bodyType:"binary"}:{bodyType:"raw",bodyFormat:"text"}}generateBodyContent(e,t,n){if(e.example!==void 0)return e.example;if(e.examples){let s=Object.values(e.examples)[0];if(s?.value!==void 0)return s.value}if(e.schema)return this.exampleGenerator.generate(e.schema,{omitReadOnly:!0,components:n})}buildFormDataEntries(e,t){let n=[],s=e.properties||{},i=new Set(e.required||[]);for(let[o,a]of Object.entries(s)){let c=a,l=c.type==="string"&&c.format==="binary",u={key:o,value:l?"":String(this.exampleGenerator.generate(c,{components:t})||""),type:l?"file":"text",enabled:!0};n.push(u)}return n}buildBodySchema(e,t,n){let s=Object.keys(e.content),i=e.content[t];if(!i?.schema)return;let o={contentType:t,schema:i.schema};if(s.length>1){o.content={};for(let c of s){let l=e.content[c],u={};l.schema&&(u.schema=l.schema),l.examples&&(u.examples=l.examples),l.encoding&&(u.encoding=l.encoding),o.content[c]=u}}i.encoding&&(o.encoding=i.encoding);let a=this.extractUsedComponents(i.schema,n);return Object.keys(a).length>0&&(o.components=a),o}processResponses(e,t){let n={responses:{}},s={};for(let[i,o]of Object.entries(e)){let a=o,c={description:a.description||`Status ${i}`};if(a.content){let l=Object.keys(a.content);if(l.length===1){let u=l[0],d=a.content[u];c.contentType=u,d.schema&&(c.schema=d.schema),d.examples&&(c.examples=d.examples),d.schema&&Object.assign(s,this.extractUsedComponents(d.schema,t))}else{c.content={};for(let u of l){let d=a.content[u],p={};d.schema&&(p.schema=d.schema),d.examples&&(p.examples=d.examples),c.content[u]=p,d.schema&&Object.assign(s,this.extractUsedComponents(d.schema,t))}}}if(a.headers){c.headers={};for(let[l,u]of Object.entries(a.headers)){let d=u;c.headers[l]={...d.description&&{description:d.description},schema:d.schema||{type:"string"}}}}n.responses[i]=c}return Object.keys(s).length>0&&(n.components=s),n}mapSecurityToAuth(e,t){let n=Object.keys(e)[0];if(!n)return;let s=t[n];if(s)switch(s.type){case"http":if(s.scheme==="bearer")return{type:"bearer",bearerToken:""};if(s.scheme==="basic")return{type:"basic",basicAuth:{username:"",password:""}};break;case"apiKey":return{type:"apikey",apikey:{key:s.name||"X-Api-Key",value:"",in:s.in||"header"}};case"oauth2":{let i=s.flows||{},o=i.authorizationCode||i.clientCredentials||i.password||i.implicit||{},a="client_credentials";return i.authorizationCode?a="authorization_code":i.password?a="password":i.implicit&&(a="implicit"),{type:"oauth2",oauth2:{grantType:a,tokenUrl:o.tokenUrl||"",authUrl:o.authorizationUrl||"",clientId:"",clientSecret:"",scope:Object.keys(o.scopes||{}).join(" ")}}}}}async createEnvironmentFromServers(e,t){if(e.length>0){let n=e[0].url;this.envConfigService.setEnvironmentVariable("baseUrl",n)}return t}extractUsedComponents(e,t,n){let s=n||{};if(!e)return s;if(e.$ref){let i=this.extractRefName(e.$ref);i&&t[i]&&!s[i]&&(s[i]=t[i],this.extractUsedComponents(t[i],t,s))}if(e.properties)for(let i of Object.values(e.properties))this.extractUsedComponents(i,t,s);e.items&&this.extractUsedComponents(e.items,t,s);for(let i of["allOf","oneOf","anyOf"])if(e[i])for(let o of e[i])this.extractUsedComponents(o,t,s);return e.additionalProperties&&typeof e.additionalProperties=="object"&&this.extractUsedComponents(e.additionalProperties,t,s),s}extractRefName(e){return e.match(/^#\/components\/schemas\/(.+)$/)?.[1]}}});var dn,Eo=k(()=>{"use strict";dn=class{constructor(e,t,n){this.historyAnalyzer=e;this.scriptAnalyzer=t;this.inferrer=n}historyAnalyzer;scriptAnalyzer;inferrer;async infer(e,t,n,s){let i=await this.historyAnalyzer.analyze(e,t,{environment:s?.environment}),o;return s?.postResponseScript&&(o=this.scriptAnalyzer.analyze(s.postResponseScript)),this.mergeResponseSchemas(n,i,o)}async inferBodySchema(e,t,n,s,i){let o,a;if(t==="raw"&&n==="json"&&e){let c=e;if(typeof e=="string")try{c=JSON.parse(e)}catch{return}o=this.inferrer.inferFromValue(c),a="application/json"}else t==="form-data"&&s?(o=this.buildFormDataSchema(s),a="multipart/form-data"):t==="x-www-form-urlencoded"&&s?(o=this.buildFormDataSchema(s),a="application/x-www-form-urlencoded"):t==="raw"&&n==="xml"?(o={type:"string"},a="application/xml"):t==="raw"&&(n==="text"||n==="html")?(o={type:"string"},a=n==="html"?"text/html":"text/plain"):t==="binary"?(o={type:"string",format:"binary"},a="application/octet-stream"):t==="graphql"&&(o={type:"object",properties:{query:{type:"string"},variables:{type:"object"}}},a="application/json");if(o)return i?this.mergeBodySchemaWithExisting(o,i):{contentType:a,schema:o}}buildFormDataSchema(e){let t={type:"object",properties:{}},n=[];for(let s of e){if(!s.enabled&&s.enabled!==void 0)continue;let i={};s.type?i.type=s.type:i.type="string",s.description&&(i.description=s.description),s.format&&(i.format=s.format),s.enum&&(i.enum=s.enum),s.type==="file"&&(i.type="string",i.format="binary"),t.properties[s.key]=i,s.required&&n.push(s.key)}return n.length>0&&(t.required=n),t}mergeResponseSchemas(e,t,n){let s={responses:{}};for(let[i,o]of Object.entries(t.responses))s.responses[i]={...o};if(n&&this.applyScriptHints(s,n),e){for(let[i,o]of Object.entries(e.responses))s.responses[i]?s.responses[i]=this.mergeResponseDefinitions(s.responses[i],o):s.responses[i]={...o};e.components&&(s.components={...e.components})}return s}applyScriptHints(e,t){for(let n of t.expectedStatuses){let s=String(n);e.responses[s]||(e.responses[s]={description:`Status ${n}`})}for(let[,n]of Object.entries(e.responses))n.schema&&this.augmentSchemaWithHints(n.schema,t)}augmentSchemaWithHints(e,t){if(!(e.type!=="object"||!e.properties))for(let n of t.fieldPaths){let s=n.split(".");this.ensureFieldPath(e,s,t)}}ensureFieldPath(e,t,n,s=""){if(t.length===0||e.type!=="object")return;e.properties||(e.properties={});let i=t[0],o=i.endsWith("[]"),a=o?i.slice(0,-2):i,c=s?`${s}.${i}`:i,l=t.slice(1);if(!e.properties[a])if(o)e.properties[a]={type:"array",items:{type:"object"}};else if(l.length>0)e.properties[a]={type:"object",properties:{}};else{let u=n.typeHints[c];e.properties[a]={type:u||"string"};return}if(l.length>0){let u=o?e.properties[a].items:e.properties[a];u&&this.ensureFieldPath(u,l,n,c)}}mergeResponseDefinitions(e,t){let n={...e};return t.description&&(n.description=t.description),t.contentType&&(n.contentType=t.contentType),t.schema&&e.schema?n.schema=this.inferrer.mergeSchemas(e.schema,t.schema):t.schema&&(n.schema=t.schema),t.examples&&(n.examples={...e.examples||{},...t.examples}),t.content&&(n.content={...e.content||{},...t.content}),t.headers&&(n.headers={...e.headers||{},...t.headers}),n}mergeBodySchemaWithExisting(e,t){let n={...t};return t.schema?n.schema=this.inferrer.mergeSchemas(e,t.schema):n.schema=e,n}}});var pp,qo,fp,mp,hp,gp,yp,Vr,al=k(()=>{"use strict";pp=/(?:jsonData|responseJson|data|json|body|response\.json\(\))\.([a-zA-Z_][\w.\[\]]*)/g,qo="(?:pm|hf|ctx)",fp=new RegExp(`${qo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.be\\.(?:a|an)\\(['"](\\w+)['"]\\)`,"g"),mp=new RegExp(`${qo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.(?:equal|eql)\\((.+?)\\)`,"g"),hp=/(?:to\.have\.status|response\.code.*?equal)\((\d+)\)/g,gp=new RegExp(`${qo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.be\\.(true|false)`,"g"),yp=new RegExp(`${qo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.have\\.(?:lengthOf|length\\.above|length\\.below)`,"g"),Vr=class{analyze(e){let t={fieldPaths:[],typeHints:{},valueHints:{},expectedStatuses:[]};if(!e||e.trim().length===0)return t;let n=this.stripComments(e);return this.extractFieldPaths(n,t),this.extractTypeAssertions(n,t),this.extractEqualityAssertions(n,t),this.extractBooleanAssertions(n,t),this.extractLengthAssertions(n,t),this.extractStatusAssertions(n,t),t.fieldPaths=[...new Set(t.fieldPaths)],t.expectedStatuses=[...new Set(t.expectedStatuses)],t}stripComments(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,"");return t=t.replace(/\/\/.*$/gm,""),t}extractFieldPaths(e,t){let n,s=new RegExp(pp.source,pp.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]);i&&!this.isCommonMethodCall(i)&&t.fieldPaths.push(i)}}extractTypeAssertions(e,t){let n,s=new RegExp(fp.source,fp.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]),o=n[2].toLowerCase();i&&(t.typeHints[i]=this.mapAssertionType(o),t.fieldPaths.includes(i)||t.fieldPaths.push(i))}}extractEqualityAssertions(e,t){let n,s=new RegExp(mp.source,mp.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]),o=n[2].trim();if(i){let a=this.parseAssertionValue(o);a!==void 0&&(t.valueHints[i]=a,typeof a=="string"?t.typeHints[i]=t.typeHints[i]||"string":typeof a=="number"?t.typeHints[i]=t.typeHints[i]||(Number.isInteger(a)?"integer":"number"):typeof a=="boolean"&&(t.typeHints[i]=t.typeHints[i]||"boolean")),t.fieldPaths.includes(i)||t.fieldPaths.push(i)}}}extractBooleanAssertions(e,t){let n,s=new RegExp(gp.source,gp.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]);i&&(t.typeHints[i]="boolean",t.valueHints[i]=n[2]==="true",t.fieldPaths.includes(i)||t.fieldPaths.push(i))}}extractLengthAssertions(e,t){let n,s=new RegExp(yp.source,yp.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]);i&&(t.typeHints[i]=t.typeHints[i]||"array",t.fieldPaths.includes(i)||t.fieldPaths.push(i))}}extractStatusAssertions(e,t){let n,s=new RegExp(hp.source,hp.flags);for(;(n=s.exec(e))!==null;){let i=parseInt(n[1],10);!isNaN(i)&&i>=100&&i<600&&t.expectedStatuses.push(i)}}normalizeFieldPath(e){let t=e.replace(/^\./,"");return t=t.replace(/\[\d+\]/g,"[]"),t}isCommonMethodCall(e){return new Set(["to","be","have","not","deep","any","all","that","is","has","include","includes","equal","eql","above","below","least","most","within","length","lengthOf","match","string","keys","key","property","ownProperty","status","header","json","text"]).has(e.split(".")[0])}mapAssertionType(e){return{string:"string",number:"number",object:"object",array:"array",boolean:"boolean",null:"null",undefined:"null",int:"integer",integer:"integer",float:"number",double:"number"}[e]||"string"}parseAssertionValue(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);let t=Number(e);return!isNaN(t)&&e.trim().length>0?t:e==="true"?!0:e==="false"?!1:e==="null"?null:e}}});var ni,cl=k(()=>{"use strict";ni=class{providerName="aws";region;profile;moduleRequire;sdk;constructor(e,t){this.region=e.region??process.env.AWS_DEFAULT_REGION??process.env.AWS_REGION,this.profile=e.profile||void 0,this.moduleRequire=t??(n=>pe(n))}async resolve(e){let t=e.lastIndexOf("#"),n=t>=0?e.slice(0,t):e,s=t>=0?e.slice(t+1):void 0;try{if(!this.sdk){let{SecretsManagerClient:a,GetSecretValueCommand:c}=this.moduleRequire("@aws-sdk/client-secrets-manager");this.sdk={client:new a({region:this.region,profile:this.profile}),GetSecretValueCommand:c}}let i=await this.sdk.client.send(new this.sdk.GetSecretValueCommand({SecretId:n})),o=i.SecretString??(i.SecretBinary?Buffer.from(i.SecretBinary).toString("utf-8"):void 0);if(o===void 0)return;if(s)try{let a=JSON.parse(o);return a[s]!==void 0?String(a[s]):void 0}catch{return}return o}catch(i){throw i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND"?new Error("[HTTP Forge] AWS secret resolver requires @aws-sdk/client-secrets-manager. Install it in your project: npm install @aws-sdk/client-secrets-manager"):i}}}});var ri,ll=k(()=>{"use strict";ri=class{providerName="azure";vaultUrl;moduleRequire;client;constructor(e,t){let n=(e.vaultUrl||process.env.AZURE_KEYVAULT_URL)??"";this.vaultUrl=n.replace(/\/$/,""),this.moduleRequire=t??(s=>pe(s))}async resolve(e){if(!this.vaultUrl)throw new Error("[HTTP Forge] Azure Key Vault resolver: no vault URL configured. Set secrets.providers.<alias>.vaultUrl or the AZURE_KEYVAULT_URL env var.");let t=e.split("/"),n=t[0],s=t[1];try{if(!this.client){let{SecretClient:o}=this.moduleRequire("@azure/keyvault-secrets"),{DefaultAzureCredential:a}=this.moduleRequire("@azure/identity");this.client=new o(this.vaultUrl,new a)}return(await this.client.getSecret(n,s?{version:s}:{})).value}catch(i){throw i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND"?new Error("[HTTP Forge] Azure Key Vault resolver requires @azure/keyvault-secrets and @azure/identity. Install them: npm install @azure/keyvault-secrets @azure/identity"):i}}}});import*as bp from"https";var vp,si,ul=k(()=>{"use strict";vp=1e4,si=class{providerName="doppler";token;requestFn;constructor(e,t=bp.request){this.token=e.serviceToken||process.env.DOPPLER_TOKEN,this.requestFn=t}async resolve(e){let t=e.trim().toUpperCase(),n=this.token;if(!n)throw new Error("[HTTP Forge] Doppler secret resolver: no service token found. Set DOPPLER_TOKEN env var or add serviceToken to config.");let s=`https://api.doppler.com/v3/configs/config/secret?name=${encodeURIComponent(t)}`;return new Promise((i,o)=>{let a=this.requestFn(s,{method:"GET",timeout:vp,headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}},c=>{let l=[];c.on("data",u=>l.push(u)),c.on("error",o),c.on("end",()=>{let u=Buffer.concat(l).toString("utf-8");if(c.statusCode===404){i(void 0);return}if(c.statusCode!==200){o(new Error(`[HTTP Forge] Doppler API returned ${c.statusCode} for secret "${t}": ${u}`));return}try{let p=JSON.parse(u)?.value?.computed;i(p!=null?String(p):void 0)}catch{o(new Error(`[HTTP Forge] Doppler API returned non-JSON response for secret "${t}"`))}})});a.on("error",o),a.on("timeout",()=>{a.destroy(new Error(`[HTTP Forge] Doppler request timed out after ${vp}ms`))}),a.end()})}}});var ii,dl=k(()=>{"use strict";ii=class{providerName="gcp";projectId;moduleRequire;client;constructor(e,t){this.projectId=e.projectId||process.env.GOOGLE_CLOUD_PROJECT||process.env.GCLOUD_PROJECT||process.env.GCP_PROJECT,this.moduleRequire=t??(n=>pe(n))}async resolve(e){let t=e.split("/"),n=t[0],s=t.length===1?"latest":t.length===3&&t[1]==="versions"&&t[2]?t[2]:void 0;if(!n||s===void 0)throw new Error(`[HTTP Forge] GCP secret path "${e}" must be "<secretName>" or "<secretName>/versions/<version>".`);if(!this.projectId)throw new Error("[HTTP Forge] GCP secret resolver: no projectId configured and GOOGLE_CLOUD_PROJECT env var is not set.");try{if(!this.client){let{SecretManagerServiceClient:c}=this.moduleRequire("@google-cloud/secret-manager");this.client=new c}let i=`projects/${this.projectId}/secrets/${n}/versions/${s}`,[o]=await this.client.accessSecretVersion({name:i}),a=o.payload?.data;return a?Buffer.isBuffer(a)?a.toString("utf-8"):Buffer.from(a).toString("utf-8"):void 0}catch(i){throw i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND"?new Error("[HTTP Forge] GCP secret resolver requires @google-cloud/secret-manager. Install it: npm install @google-cloud/secret-manager"):i}}}});function Sp(r){return r.split("/").map(e=>encodeURIComponent(e)).join("/")}var oi,pl=k(()=>{"use strict";oi=class{providerName="vault";address;mountPath;namespace;constructor(e){this.address=(e.address||process.env.VAULT_ADDR||"http://127.0.0.1:8200").replace(/\/$/,""),this.mountPath=e.mountPath||"secret",this.namespace=e.namespace||process.env.VAULT_NAMESPACE}async resolve(e){let t=e.lastIndexOf("#"),n=t>=0?e.slice(0,t):e,s=t>=0?e.slice(t+1):void 0,i=process.env.VAULT_TOKEN;if(!i)throw new Error("[HTTP Forge] HashiCorp Vault resolver requires VAULT_TOKEN environment variable to be set.");let o=`${this.address}/v1/${Sp(this.mountPath)}/data/${Sp(n)}`,a={"X-Vault-Token":i};this.namespace&&(a["X-Vault-Namespace"]=this.namespace);let c;try{c=await fetch(o,{headers:a,signal:AbortSignal.timeout(1e4)})}catch(p){let m=p?.name==="TimeoutError"?"request timed out after 10000ms":p?.message??p;throw new Error(`[HTTP Forge] Vault request failed: ${m}`)}if(c.status===404)return;if(!c.ok)throw new Error(`[HTTP Forge] Vault returned HTTP ${c.status} for path: ${n}`);let u=(await c.json())?.data?.data;if(!u)return;if(s)return u[s]!==void 0?String(u[s]):void 0;if("value"in u)return String(u.value);let d=Object.keys(u);return d.length===1?String(u[d[0]]):void 0}}});import{execFile as Gg}from"child_process";import{promisify as Kg}from"util";var Qg,Zg,Yg,ai,fl=k(()=>{"use strict";Qg=Kg(Gg),Zg=/not found|isn't an item|is not an item|no item matched|could not find/i,Yg=/not signed in|sign in|authentication|authorization|unauthorized/i,ai=class{providerName="1password";defaultVault;account;moduleRequire;execFileFn;sdkClientPromise;sdkAuthKey;constructor(e,t,n=Qg){this.defaultVault=e.vault,this.account=e.account,this.moduleRequire=t??(s=>pe(s)),this.execFileFn=n}async resolve(e){let t=e.split("/"),n,s,i;if(this.defaultVault){if(t.length<2)throw new Error(`[HTTP Forge] 1Password path "${e}" must be "<item>/<field>" when vault is set in config.`);n=this.defaultVault,s=t.slice(0,t.length-1).join("/"),i=t[t.length-1]}else{if(t.length<3)throw new Error(`[HTTP Forge] 1Password path "${e}" must be "<vault>/<item>/<field>".`);n=t[0],s=t.slice(1,t.length-1).join("/"),i=t[t.length-1]}let o=await this.tryResolveSdk(n,s,i);return o!==null?o:this.resolveViaCli(n,s,i)}async tryResolveSdk(e,t,n){let s=process.env.OP_SERVICE_ACCOUNT_TOKEN||void 0,i=s?void 0:this.account;if(!s&&!i)return null;try{let o=await this.getSdkClient(s,i),a=`op://${e}/${t}/${n}`;return await o.secrets.resolve(a)}catch(o){if(o?.name==="MODULE_NOT_FOUND"||o?.code==="MODULE_NOT_FOUND")return null;throw new Error(`[HTTP Forge] 1Password SDK error for "${e}/${t}/${n}": ${o?.message??o}`)}}getSdkClient(e,t){let n=e?`t:${e}`:`a:${t}`;return(!this.sdkClientPromise||this.sdkAuthKey!==n)&&(this.sdkAuthKey=n,this.sdkClientPromise=(async()=>{let s=this.moduleRequire("@1password/sdk");if(!e&&typeof s.DesktopAuth!="function")throw new Error("[HTTP Forge] DesktopAuth requires @1password/sdk 0.5.0+.");let i=e??new s.DesktopAuth(t);return s.createClient({auth:i,integrationName:"HTTP Forge",integrationVersion:"1.0.0"})})().catch(s=>{throw this.sdkClientPromise=void 0,this.sdkAuthKey=void 0,s})),this.sdkClientPromise}async resolveViaCli(e,t,n){let s={...process.env};s.OP_SERVICE_ACCOUNT_TOKEN?delete s.OP_ACCOUNT:this.account&&(s.OP_ACCOUNT=this.account);try{let{stdout:i}=await this.execFileFn("op",["read",`op://${e}/${t}/${n}`],{env:s,timeout:1e4});return i.replace(/\r?\n$/,"")}catch(i){if(i?.code==="ENOENT")throw new Error('[HTTP Forge] 1Password needs @1password/sdk or the `op` CLI.\n Service Account: set OP_SERVICE_ACCOUNT_TOKEN\n Desktop account: set "account" (SDK 0.5.0+)\n CLI: install 1Password CLI and run `op signin`');let o=String(i?.stderr??"");if(Zg.test(o))return;throw Yg.test(o)?new Error("[HTTP Forge] 1Password CLI is not authenticated. Run `op signin` or set OP_SERVICE_ACCOUNT_TOKEN and install @1password/sdk."):new Error(`[HTTP Forge] 1Password CLI error: ${i?.stderr||i?.message||i}`)}}}});import*as Ao from"fs";import{createRequire as Xg}from"module";import*as Po from"path";var ci,ml=k(()=>{"use strict";ws();cl();ll();ul();dl();pl();fl();ci=class{constructor(e){this.configService=e;this.moduleRequire=t=>pe(t),this.refreshProviders()}configService;resolvers=new Map;moduleRequire;configKey;async resolveSecretTokens(e,t){this.refreshProviders();let n=t??new Map,s=new Set;if(this.collectTokens(e,s),s.size===0)return{};await Promise.all(Array.from(s).map(async o=>{if(n.has(o))return;let a=o.slice(7),c=a.indexOf("/");if(c<0){console.warn(`[HTTP Forge] {{${o}}} is malformed; expected {{secret:<alias>/<path>}}.`);return}let l=a.slice(0,c),u=a.slice(c+1),d=this.resolvers.get(l);if(!d){console.warn(`[HTTP Forge] {{${o}}} could not be resolved: no secret provider is configured for alias "${l}".`);return}try{let p=await d.resolve(u);p!==void 0?n.set(o,p):console.warn(`[HTTP Forge] {{${o}}} could not be resolved: secret not found.`)}catch(p){let m=p?.message??String(p);console.warn(`[HTTP Forge] {{${o}}} could not be resolved: ${m}`)}}));let i={};for(let[o,a]of n.entries())i[o]=a;return i}get hasProviders(){return this.refreshProviders(),this.resolvers.size>0}refreshProviders(){if(!this.configService)return;let e,t=[];try{e=this.configService.getConfig().secrets,t=this.configService.getModulePaths()??[]}catch{return}let n=JSON.stringify({secrets:e||null,modulePaths:t});if(n!==this.configKey&&(this.configKey=n,this.moduleRequire=this.buildModuleRequire(t),this.resolvers.clear(),!(!e?.providers||typeof e.providers!="object")))for(let[s,i]of Object.entries(e.providers))try{let o=this.createResolver(s,i);o?this.resolvers.set(s,o):console.warn(`[HTTP Forge] Secret "${s}" skipped: unsupported type "${i?.provider}".`)}catch(o){let a=i?.provider??"unknown";console.warn(`[HTTP Forge] Secret "${s}" (${a}) skipped: ${o?.message??String(o)}`)}}collectTokens(e,t){if(typeof e=="string"){let n=/\{\{(secret:[^}]+)\}\}/g,s;for(;(s=n.exec(e))!==null;){let i=this.baseToken(s[1]);i&&t.add(i)}}else Array.isArray(e)?e.forEach(n=>this.collectTokens(n,t)):e!==null&&typeof e=="object"&&Object.values(e).forEach(n=>this.collectTokens(n,t))}baseToken(e){let t=e.trim(),s=(Dn(t)?.input??t).trim();return s.startsWith("secret:")?s:void 0}createResolver(e,t){switch(t.provider){case"aws":return new ni(t,this.moduleRequire);case"azure":return new ri(t,this.moduleRequire);case"vault":return new oi(t);case"1password":return new ai(t,this.moduleRequire);case"gcp":return new ii(t,this.moduleRequire);case"doppler":return new si(t);case"custom":return this.createCustomResolver(e,t);default:return}}createCustomResolver(e,t){if(!t.module||typeof t.module!="string")throw new Error(`Custom secret provider "${e}" requires a "module" path or package name.`);let n;try{n=this.moduleRequire(t.module)}catch(a){throw new Error(`Custom secret provider "${e}" could not load module "${t.module}". Ensure scripts.modulePaths contains a package.json and the module is installed or the relative path is correct. Cause: ${a?.message??String(a)}`)}let s=n?.default??n,i=typeof s=="function"?s:typeof s?.createResolver=="function"?s.createResolver.bind(s):void 0,o;if(i)o=i({alias:e,options:t.options??{}});else if(s&&typeof s.resolve=="function")o=s;else throw new Error(`Custom secret provider "${e}" module "${t.module}" must export a resolver factory function, a createResolver function, or an object with resolve(path).`);if(o&&typeof o.then=="function")throw new Error(`Custom secret provider "${e}" module "${t.module}" returned a Promise. Resolver factories must be synchronous; use an async resolve(path) method instead.`);if(!o||typeof o.resolve!="function")throw new Error(`Custom secret provider "${e}" module "${t.module}" did not return a resolver with resolve(path).`);return{providerName:typeof o.providerName=="string"&&o.providerName.trim()?o.providerName:e,resolve:async a=>o.resolve(a)}}buildModuleRequire(e){let t=n=>pe(n);for(let n of e)try{let s=Po.resolve(n,"package.json");if(Ao.existsSync(s)){let i=Ao.realpathSync(s),o=Xg(i);return a=>{try{return o(a)}catch(c){let l=!a.startsWith(".")&&!Po.isAbsolute(a),u=c?.code==="MODULE_NOT_FOUND"&&String(c?.message??"").includes(`'${a}'`);if(l&&u)return t(a);throw c}}}}catch{}return t}}});function $e(r){return r.replace(/\//g,"%2F")}function ey(r){return r.replace(/%2F/gi,"/")}function Tt(r){return r?r.split("/").map(ey).join(" / "):""}function zr(r){return r.includes(" / ")?r.split(" / ").map(e=>$e(e.trim())).join("/"):$e(r)}function X(r,e=r.items,t=""){let n=[];for(let s of e)if(s.type==="request")n.push({request:s,folderPath:t});else{let i=s,o=$e(i.name),a=t?`${t}/${o}`:o;n.push(...X(r,i.items??[],a))}return n}function qe(r,e=r.items,t=""){let n=[];for(let s of e)if(s.type==="folder"){let i=s,o=$e(i.name),a=t?`${t}/${o}`:o;n.push({folderId:i.id,folderPath:a,requestCount:hl(i.items??[])}),n.push(...qe(r,i.items??[],a))}return n}function hl(r){let e=0;for(let t of r)t.type==="request"?e++:e+=hl(t.items??[]);return e}var tt=k(()=>{"use strict"});var Ht,gl=k(()=>{"use strict";Ht={iterations:1,delayBetweenRequests:0,stopOnError:!1,readFromSharedSession:!1,writeToSharedSession:!1}});import*as ue from"fs";import*as xt from"path";var li,yl=k(()=>{"use strict";tt();Ze();gl();li=class{constructor(e,t,n){this.collectionService=e;this.configService=t;this.suitesDir=t.getSuitesPath(),this.onSuitesChanged=n?.onSuitesChanged,this.loadSuites(),n?.watch!==!1&&this.setupFileWatcher()}collectionService;configService;suitesDir;suites=new Map;fileWatcher=null;debounceTimer=null;onSuitesChanged;ensureSuitesDir(){ue.existsSync(this.suitesDir)||ue.mkdirSync(this.suitesDir,{recursive:!0})}setupFileWatcher(){try{this.fileWatcher=ue.watch(this.suitesDir,(e,t)=>{t&&!t.endsWith(".suite.json")||(this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.loadSuites(),this.onSuitesChanged?.()},200))}),this.fileWatcher.on("error",()=>{})}catch{}}dispose(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.fileWatcher?.close(),this.fileWatcher=null}loadSuites(){if(this.suites.clear(),!ue.existsSync(this.suitesDir))return;let e=ue.readdirSync(this.suitesDir);for(let t of e)if(t.endsWith(".suite.json"))try{let n=xt.join(this.suitesDir,t),s=ue.readFileSync(n,"utf-8"),i=JSON.parse(s),o=Array.isArray(i.nodes)&&i.nodes.length>0?i.nodes:(Array.isArray(i.requests)?i.requests:[]).map(c=>({type:"request",name:c.description||c.name,request:c,enabled:c.enabled!==!1})),a={id:i.id,name:i.name,description:i.description,scripts:i.scripts,nodes:o,config:i.config??{...Ht},isTemporary:i.isTemporary,ai_generated:i.ai_generated===!0,derived_from:Array.isArray(i.derived_from)?i.derived_from:void 0,createdAt:i.createdAt??Date.now(),updatedAt:i.updatedAt??Date.now()};a.id&&a.name&&this.suites.set(a.id,a)}catch(n){console.error(`[TestSuiteService] Failed to load ${t}:`,n)}}async getAllSuites(){return Array.from(this.suites.values())}async getSuite(e){return this.suites.get(e)}async createSuite(e){let t=Date.now(),n={id:le(e),name:e,nodes:[],config:{...Ht},createdAt:t,updatedAt:t};return await this.saveSuiteToDisk(n),this.suites.set(n.id,n),n}async updateSuite(e){e.updatedAt=Date.now(),await this.saveSuiteToDisk(e),this.suites.set(e.id,e)}async duplicateSuite(e,t){let n=this.suites.get(e);if(!n)throw new Error(`Suite not found: ${e}`);let s=n.nodes||[],i=await this.createSuite(t);i.nodes=s.map(c=>({...c})),i.config={...n.config},i.description=n.description;let o=xt.join(this.suitesDir,e),a=xt.join(this.suitesDir,i.id);return ue.existsSync(o)&&this.copyDirRecursive(o,a),await this.saveSuiteToDisk(i),this.suites.set(i.id,i),i}copyDirRecursive(e,t){ue.existsSync(t)||ue.mkdirSync(t,{recursive:!0});for(let n of ue.readdirSync(e,{withFileTypes:!0})){let s=xt.join(e,n.name),i=xt.join(t,n.name);n.isDirectory()?this.copyDirRecursive(s,i):ue.copyFileSync(s,i)}}async deleteSuite(e){let t=this.suites.get(e);if(!t)return!1;let n=`${t.id}.suite.json`,s=xt.join(this.suitesDir,n),i=xt.join(this.suitesDir,t.id);try{return ue.existsSync(s)&&ue.unlinkSync(s),ue.existsSync(i)&&ue.rmSync(i,{recursive:!0,force:!0}),this.suites.delete(e),!0}catch(o){return console.error("[TestSuiteService] Failed to delete suite:",o),!1}}async createTempSuiteFromCollection(e){let t=this.collectionService.getCollection(e);if(!t){console.error(`[TestSuiteService] Collection not found: ${e}`);return}let n=[];this.extractRequestsFromCollection(t,e,t.name,"",n);let s=n.map(a=>({type:"request",name:a.description||a.name,request:a,enabled:a.enabled!==!1})),i=Date.now();return{id:`temp-${e}`,name:t.name,nodes:s,config:{...Ht},isTemporary:!0,createdAt:i,updatedAt:i}}async createTempSuiteFromFolder(e,t,n=!0){let s=this.collectionService.getCollection(e);if(!s){console.error(`[TestSuiteService] Collection not found: ${e}`);return}let i=[];this.extractRequestsFromCollection(s,e,s.name,"",i);let o=t.replace(/\/+$/,""),a=i.filter(d=>n?d.folderPath===o||d.folderPath.startsWith(`${o}/`):d.folderPath===o);if(a.length===0){console.error(`[TestSuiteService] No requests under folder "${t}" in collection: ${e}`);return}let c=a.map(d=>({type:"request",name:d.description||d.name,request:d,enabled:d.enabled!==!1})),l=Date.now();return{id:`temp-${e}-${this.slugifyFolderPath(o)}`,name:`${s.name} / ${Tt(o)}`,nodes:c,config:{...Ht},isTemporary:!0,createdAt:l,updatedAt:l}}async createTempSuiteFromRequest(e,t){let n=this.collectionService.getCollection(e);if(!n){console.error(`[TestSuiteService] Collection not found: ${e}`);return}let s=[];this.extractRequestsFromCollection(n,e,n.name,"",s);let i=s.find(u=>u.requestId===t);if(!i){console.error(`[TestSuiteService] Request not found: ${t} in collection: ${e}`);return}let a={type:"for",name:"Performance Loop (100 iterations)",init:'hf.variables.set("__i", 0)',loopCondition:'hf.variables.get("__i") < 100',update:'hf.variables.set("__i", hf.variables.get("__i") + 1)',maxIterations:100,nodes:[{type:"request",name:i.description||i.name,request:i,enabled:!0}],enabled:!0},c=Date.now();return{id:`temp-perf-${e}-${t}`,name:`${i.name} \u2014 Performance Test`,nodes:[a],config:{...Ht},isTemporary:!0,createdAt:c,updatedAt:c}}slugifyFolderPath(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}async saveTempSuite(e,t){let n=Date.now(),s=xt.join(this.suitesDir,e.id),i={...e,id:le(t),name:t,isTemporary:!1,createdAt:n,updatedAt:n},o=xt.join(this.suitesDir,i.id);return ue.existsSync(s)&&(ue.existsSync(o)&&ue.rmSync(o,{recursive:!0,force:!0}),ue.renameSync(s,o)),await this.saveSuiteToDisk(i),this.suites.set(i.id,i),i}getAllAvailableRequests(){let e=[],t=this.collectionService.getAllCollections();for(let n of t)this.extractRequestsFromCollection(n,n.id,n.name,"",e);return e}extractRequestsFromCollection(e,t,n,s,i){if(e.requests)for(let o of e.requests)i.push({collectionId:t,collectionName:n,requestId:o.id,name:o.name||"Unnamed Request",method:o.method||"GET",folderPath:s});if(e.items)for(let o of e.items)if(o.items||o.folders||o.requests){let a=s?`${s}/${$e(o.name)}`:$e(o.name);this.extractRequestsFromCollection(o,t,n,a,i)}else i.push({collectionId:t,collectionName:n,requestId:o.id,name:o.name||"Unnamed Request",method:o.method||"GET",folderPath:s});if(e.folders)for(let o of e.folders){let a=s?`${s}/${$e(o.name)}`:$e(o.name);this.extractRequestsFromCollection(o,t,n,a,i)}}async saveSuiteToDisk(e){this.ensureSuitesDir();let t=`${e.id}.suite.json`,n=xt.join(this.suitesDir,t),s=`${n}.tmp-${process.pid}-${Date.now()}`,i={$schema:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/suite.schema.json",id:e.id,name:e.name,description:e.description,scripts:e.scripts,nodes:Array.isArray(e.nodes)?e.nodes:[],config:e.config??{...Ht},isTemporary:e.isTemporary,ai_generated:e.ai_generated,derived_from:e.derived_from,createdAt:e.createdAt??Date.now(),updatedAt:e.updatedAt??Date.now()},o=JSON.stringify(i,null,2);ue.writeFileSync(s,o,"utf-8"),ue.renameSync(s,n)}}});function xp(r){return{timeout:r?.timeout??ze.timeout,followRedirects:r?.followRedirects??ze.followRedirects,followOriginalMethod:r?.followOriginalMethod??ze.followOriginalMethod,followAuthHeader:r?.followAuthHeader??ze.followAuthHeader,maxRedirects:r?.maxRedirects??ze.maxRedirects,strictSSL:r?.strictSSL??ze.strictSSL,decompress:r?.decompress??ze.decompress,includeCookies:r?.includeCookies??ze.includeCookies,tls:r?.tls??ze.tls,certificates:r?.certificates??ze.certificates}}var wp=k(()=>{"use strict";Ns()});import ty from"fs";import Rp from"path";function ny(r){return Buffer.isBuffer(r)?r:Array.isArray(r)?Buffer.concat(r):new Uint8Array(r)}function Io(r,e,t){if(!r)return;let n=Rp.isAbsolute(r)?r:Rp.resolve(e||process.cwd(),r);try{return ty.readFileSync(n)}catch(s){throw new Error(`[NodeWebSocketClient] Failed to read ${t} file at ${n}: ${s?.message||"Unknown error"}`)}}async function ry(){return(await import("ws")).WebSocket}function Cp(){let r=new Error("WebSocket connection cancelled");return r.name="AbortError",r}var vl,pn,ui,bl=k(()=>{"use strict";wp();vl=class{constructor(e){this.socket=e;e.on("upgrade",t=>{if(t&&t.headers&&typeof t.headers=="object"){let n={};for(let[s,i]of Object.entries(t.headers))typeof i=="string"?n[s]=i:Array.isArray(i)&&(n[s]=i.join(", "));this._handshakeHeaders=n}}),e.on("message",(t,n)=>{let s={data:n?ny(t):t.toString(),isBinary:n};for(let i of this.frameListeners)try{i(s)}catch{}}),e.on("close",(t,n)=>{let s={code:t,reason:n.toString(),wasClean:t!==1006&&t!==1015};for(let i of this.closeListeners)try{i(s)}catch{}}),e.on("error",t=>{for(let n of this.errorListeners)try{n(t)}catch{}})}socket;frameListeners=new Set;closeListeners=new Set;errorListeners=new Set;_handshakeHeaders;get state(){switch(this.socket.readyState){case pn.CONNECTING:return"connecting";case pn.OPEN:return"open";case pn.CLOSING:return"closing";default:return"closed"}}get negotiatedProtocol(){return this.socket.protocol}get handshakeHeaders(){return this._handshakeHeaders}send(e){return this.socket.readyState!==pn.OPEN?Promise.reject(new Error("WebSocket is not open")):new Promise((t,n)=>{this.socket.send(e,{binary:typeof e!="string"},s=>{s?n(s):t()})})}close(e=1e3,t=""){return this.socket.readyState===pn.CLOSED?Promise.resolve():this.socket.readyState===pn.CONNECTING?(this.socket.terminate(),Promise.resolve()):new Promise(n=>{let s,i=()=>{s&&clearTimeout(s),n()};this.socket.once("close",i),s=setTimeout(()=>{this.socket.terminate(),i()},5e3),this.socket.readyState!==pn.CLOSING&&this.socket.close(e,t)})}onFrame(e){return this.frameListeners.add(e),{dispose:()=>this.frameListeners.delete(e)}}onClose(e){return this.closeListeners.add(e),{dispose:()=>this.closeListeners.delete(e)}}onError(e){return this.errorListeners.add(e),{dispose:()=>this.errorListeners.delete(e)}}dispose(){this.socket.readyState!==pn.CLOSED&&this.close(1e3,"Disposed").catch(()=>{this.socket.terminate()})}},pn={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},ui=class{constructor(e={}){this.options=e}options;async connect(e){if(e.signal?.aborted)throw Cp();let t=xp(e.settings),n=await ry(),s=this.buildTransportOptions(e,t);return new Promise((i,o)=>{let a=!1,c,l=()=>{e.signal?.removeEventListener("abort",d)},u=p=>{a||(a=!0,l(),o(p))},d=()=>{c&&c.terminate(),u(Cp())};try{c=new n(e.url,e.protocols&&e.protocols.length>0?e.protocols:void 0,s)}catch(p){u(p instanceof Error?p:new Error(String(p)));return}e.signal?.addEventListener("abort",d,{once:!0}),c.once("open",()=>{a||(a=!0,l(),i(new vl(c)))}),c.once("error",p=>{u(p)}),c.once("unexpected-response",(p,m)=>{c.terminate(),u(new Error(`WebSocket handshake failed: HTTP ${m.statusCode} ${m.statusMessage||""}`.trim()))})})}buildTransportOptions(e,t){let n=t.tls,s={headers:e.headers,handshakeTimeout:t.timeout>0?t.timeout:void 0,maxPayload:e.maxPayloadBytes&&e.maxPayloadBytes>0?e.maxPayloadBytes:void 0,rejectUnauthorized:t.strictSSL},i=Io(n?.caPath,this.options.basePath,"CA certificate");i&&(s.ca=i);let o=Io(n?.certPath,this.options.basePath,"client certificate");o&&(s.cert=o);let a=Io(n?.keyPath,this.options.basePath,"client private key");a&&(s.key=a);let c=Io(n?.pfxPath,this.options.basePath,"client pfx");return c&&(s.pfx=c),n?.passphrase&&(s.passphrase=n.passphrase),n?.servername&&(s.servername=n.servername),s}}});import*as To from"socket.io-client";function sy(r){if(typeof r!="string")return r;let e=r.trim();if(e!=="")try{return JSON.parse(e)}catch{return e}}async function oy(){return{io:To.io??To.default?.io}}var iy,Jr,Sl,xl,wl=k(()=>{"use strict";iy=new Set(["connect","connect_error","disconnect","disconnecting","newListener","removeListener"]),Jr=class{async connect(e){let t=await oy(),n=e.namespace?.trim(),s=e.url.endsWith("/")?e.url.slice(0,-1):e.url,i=n?n.startsWith("/")?n.slice(1):n:"",o=n&&n!=="/"?`${s}/${i}`:e.url,a=e.transports&&e.transports.length>0?e.transports:e.clientVersion==="2"||e.clientVersion==="3"?["polling","websocket"]:["websocket"];return new Promise((c,l)=>{let u=t.io(o,{transports:a,extraHeaders:e.headers,path:e.path,timeout:e.timeout,reconnection:(e.reconnectionAttempts??0)>0,reconnectionAttempts:e.reconnectionAttempts,reconnectionDelay:e.reconnectionDelay,auth:sy(e.auth)}),d=!1,p=m=>{d||(d=!0,u.disconnect(),l(m))};u.once("connect",()=>{d||(d=!0,c(new xl(u,e.listeners)))}),u.once("connect_error",m=>{p(m instanceof Error?m:new Error(String(m)))})})}},Sl=class extends Jr{},xl=class{constructor(e,t){this.socket=e;let n=(c,...l)=>{if(!iy.has(c))for(let u of[...this.eventListeners])u({event:c,args:l})},s=()=>{for(let c of[...this.connectListeners])c()},i=c=>{for(let l of[...this.disconnectListeners])l(c)},o=()=>{for(let c of[...this.reconnectFailedListeners])c()},a=c=>{for(let l of[...this.errorListeners])l(c)};this.socket.on("connect",s),this.socket.on("disconnect",i),this.socket.on("connect_error",a),this.socket.io.on("reconnect_failed",o),this.socket.onAny(n),this.disposal.push({dispose:()=>{this.socket.off("connect",s),this.socket.off("disconnect",i),this.socket.off("connect_error",a),this.socket.io.off("reconnect_failed",o),this.socket.offAny(n)}})}socket;eventListeners=new Set;connectListeners=new Set;disconnectListeners=new Set;reconnectFailedListeners=new Set;errorListeners=new Set;disposal=[];disposed=!1;get connected(){return this.socket.connected}get id(){return this.socket.id}async send(e,t,n=!1){let s=e?.trim()||"message";return n?new Promise(i=>{this.socket.emit(s,...t,(...o)=>{i(o)})}):(this.socket.emit(s,...t),Promise.resolve(void 0))}close(){this.socket.disconnect()}onEvent(e){return this.eventListeners.add(e),{dispose:()=>this.eventListeners.delete(e)}}onConnect(e){return this.connectListeners.add(e),{dispose:()=>this.connectListeners.delete(e)}}onDisconnect(e){return this.disconnectListeners.add(e),{dispose:()=>this.disconnectListeners.delete(e)}}onReconnectFailed(e){return this.reconnectFailedListeners.add(e),{dispose:()=>this.reconnectFailedListeners.delete(e)}}onError(e){return this.errorListeners.add(e),{dispose:()=>this.errorListeners.delete(e)}}dispose(){if(!this.disposed){this.disposed=!0,this.socket.disconnect();for(let e of this.disposal)e.dispose();this.disposal.length=0,this.eventListeners.clear(),this.connectListeners.clear(),this.disconnectListeners.clear(),this.reconnectFailedListeners.clear(),this.errorListeners.clear()}}}});var $,Oo=k(()=>{"use strict";$={Config:Symbol.for("IConfigService"),Console:Symbol.for("IConsoleService"),EnvironmentConfig:Symbol.for("IEnvironmentConfigService"),Collection:Symbol.for("ICollectionService"),HttpRequest:Symbol.for("IHttpRequestService"),HttpClient:Symbol.for("IHttpClient"),WebSocketClient:Symbol.for("IWebSocketClient"),SocketIoClient:Symbol.for("ISocketIoClient"),Cookie:Symbol.for("ICookieService"),RequestHistory:Symbol.for("IRequestHistoryService"),TestSuite:Symbol.for("ITestSuiteService"),UrlBuilder:Symbol.for("IUrlBuilder"),RequestPreprocessor:Symbol.for("IRequestPreprocessor"),RequestPreparer:Symbol.for("IRequestPreparer"),InterceptorChain:Symbol.for("IInterceptorChain"),ScriptExecutor:Symbol.for("IScriptExecutor"),DataFileParser:Symbol.for("IDataFileParser"),CollectionRequestExecutor:Symbol.for("ICollectionRequestExecutor"),WorkspaceFolder:Symbol.for("WorkspaceFolder"),PersistentCookieJar:Symbol.for("PersistentCookieJar"),OAuth2TokenManager:Symbol.for("IOAuth2TokenManager"),GraphQLSchemaService:Symbol.for("IGraphQLSchemaService"),SchemaInferrer:Symbol.for("SchemaInferrer"),HistoryAnalyzer:Symbol.for("HistoryAnalyzer"),ScriptAnalyzer:Symbol.for("ScriptAnalyzer"),SchemaInferenceService:Symbol.for("SchemaInferenceService"),OpenApiExporter:Symbol.for("OpenApiExporter"),OpenApiImporter:Symbol.for("OpenApiImporter"),SecretResolverRegistry:Symbol.for("SecretResolverRegistry")}});import*as kp from"path";function $o(r,e){let{workspaceFolder:t,fileWatcherFactory:n,notificationService:s,workspaceStore:i,globalStore:o,secretStore:a,browserService:c,applicationInfo:l,consoleService:u}=e;r.registerValue($.WorkspaceFolder,t),r.registerSingleton($.Config,()=>new an(t,n,s)),r.registerSingleton($.Console,()=>u??ay),r.registerSingleton($.EnvironmentConfig,p=>new Vs(t,i,p.resolve($.Config),n,a,e.persistOverrides??!0)),r.registerSingleton($.Cookie,()=>new Hs(o)),r.registerSingleton($.Collection,p=>new Ls(p.resolve($.Config),n)),r.registerSingleton($.TestSuite,p=>new li(p.resolve($.Collection),p.resolve($.Config))),r.registerSingleton($.HttpClient,p=>{let m=p.resolve($.Config),f=p.resolve($.EnvironmentConfig);return new Bn(()=>f.getResolvedConfig().request,t,()=>f.getResolvedConfig()?.proxy??null)}),r.registerSingleton($.WebSocketClient,()=>new ui({basePath:t})),r.registerSingleton($.SocketIoClient,()=>new Jr),r.registerSingleton($.UrlBuilder,()=>new yt),r.registerSingleton($.InterceptorChain,()=>new Nt),r.registerSingleton($.HttpRequest,p=>new Ft(p.resolve($.UrlBuilder),p.resolve($.InterceptorChain),p.resolve($.HttpClient))),r.registerSingleton($.RequestPreprocessor,()=>new Un),r.registerSingleton($.RequestHistory,p=>{let m=p.resolve($.EnvironmentConfig);return new Ys(m.getHistoriesPath(),kp.join(m.getRootPath(),"shared-histories"))}),a&&c&&r.registerSingleton($.OAuth2TokenManager,p=>new Ds(a,c,p.resolve($.EnvironmentConfig),p.resolve($.HttpRequest))),r.registerSingleton($.GraphQLSchemaService,p=>new Qs(p.resolve($.HttpClient))),r.registerSingleton($.SecretResolverRegistry,p=>new ci(p.resolve($.Config)));let d=l??{name:"HttpForge",version:"0.0.0"};r.registerSingleton($.RequestPreparer,p=>new Ks(p.resolve($.EnvironmentConfig),p.resolve($.HttpRequest),p.resolve($.RequestPreprocessor),p.has($.OAuth2TokenManager)?p.resolve($.OAuth2TokenManager):void 0,d,p.resolve($.SecretResolverRegistry))),r.registerSingleton($.ScriptExecutor,p=>{let m=p.resolve($.Config);return new _t(p.resolve($.HttpRequest),m.getModulePaths(),p.resolve($.SecretResolverRegistry),m.getScriptScope(),m.getScriptTimeout())}),r.registerSingleton($.DataFileParser,()=>new zn),r.registerSingleton($.CollectionRequestExecutor,p=>new Dt(p.resolve($.HttpRequest),p.resolve($.ScriptExecutor),p.resolve($.EnvironmentConfig),p.resolve($.RequestPreparer),"",void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,p.resolve($.WebSocketClient),p.resolve($.SocketIoClient))),r.registerSingleton($.PersistentCookieJar,p=>new Bs(p.resolve($.Cookie))),r.registerSingleton($.SchemaInferrer,()=>new ln),r.registerSingleton($.HistoryAnalyzer,p=>new Hr(p.resolve($.RequestHistory),p.resolve($.SchemaInferrer))),r.registerSingleton($.ScriptAnalyzer,()=>new Vr),r.registerSingleton($.SchemaInferenceService,p=>new dn(p.resolve($.HistoryAnalyzer),p.resolve($.ScriptAnalyzer),p.resolve($.SchemaInferrer))),r.registerSingleton($.OpenApiExporter,p=>new un(p.resolve($.Collection),p.resolve($.EnvironmentConfig),p.resolve($.SchemaInferenceService))),r.registerSingleton($.OpenApiImporter,p=>new Lt(p.resolve($.Collection),p.resolve($.EnvironmentConfig)))}var ay,Rl=k(()=>{"use strict";Pc();Fc();yo();_c();Dc();Lc();Gs();Vc();zc();Zc();Cs();ks();Ns();fo();Er();Yc();Co();ko();Eo();So();al();mo();Is();ml();yl();bl();wl();Oo();ay={log:()=>{},trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},logBatch:()=>{},logRawLines:()=>{},show:()=>{},clear:()=>{},dispose:()=>{}}});function Ep(){return Qn.instance}var Qn,Cl=k(()=>{"use strict";Oo();Qn=class r{static _instance;services=new Map;primitives=new Map;constructor(){}static get instance(){return r._instance||(r._instance=new r),r._instance}static createFresh(){return new r}static reset(){r._instance&&r._instance.clear(),r._instance=void 0}registerValue(e,t){return this.primitives.set(e,t),this}registerSingleton(e,t){return this.services.set(e,{factory:t,singleton:!0}),this}registerTransient(e,t){return this.services.set(e,{factory:t,singleton:!1}),this}registerInstance(e,t){return this.services.set(e,{factory:()=>t,singleton:!0,instance:t}),this}resolve(e){if(this.primitives.has(e))return this.primitives.get(e);let t=this.services.get(e);if(!t)throw new Error(`Service not registered: ${e.toString()}`);return t.singleton?(t.instance||(t.instance=t.factory(this)),t.instance):t.factory(this)}has(e){return this.services.has(e)||this.primitives.has(e)}dispose(){for(let e of this.services.values())if(e.singleton&&e.instance){let t=e.instance;if(typeof t.dispose=="function")try{t.dispose()}catch{}}this.clear()}clear(){this.services.clear(),this.primitives.clear()}get config(){return this.resolve($.Config)}get console(){return this.resolve($.Console)}get environmentConfig(){return this.resolve($.EnvironmentConfig)}get collection(){return this.resolve($.Collection)}get httpRequest(){return this.resolve($.HttpRequest)}get httpClient(){return this.resolve($.HttpClient)}get webSocketClient(){return this.resolve($.WebSocketClient)}get socketIoClient(){return this.resolve($.SocketIoClient)}get cookie(){return this.resolve($.Cookie)}get requestHistory(){return this.resolve($.RequestHistory)}get dataFileParser(){return this.resolve($.DataFileParser)}get scriptExecutor(){return this.resolve($.ScriptExecutor)}get requestPreparer(){return this.resolve($.RequestPreparer)}get persistentCookieJar(){return this.resolve($.PersistentCookieJar)}get oauth2TokenManager(){return this.has($.OAuth2TokenManager)?this.resolve($.OAuth2TokenManager):void 0}get graphqlSchemaService(){return this.resolve($.GraphQLSchemaService)}get testSuite(){return this.resolve($.TestSuite)}}});import*as Yn from"fs";import*as Wr from"path";function Bt(r){return{kind:"collection",snapshot:()=>({kind:"collection",heading:"Collection",body:Ap(r),generatedAt:Date.now()}),freshness:()=>r.items.length>0?"fresh":"stale"}}function st(r,e){return{kind:"collection",snapshot:()=>({kind:"collection",heading:"Request",body:kl(r,e),generatedAt:Date.now()}),freshness:()=>kl(r,e)?"fresh":"stale"}}function it(r){return{kind:"workspace-knowledge",snapshot:()=>({kind:"workspace-knowledge",heading:"Business Knowledge",body:di(r),generatedAt:Date.now()}),freshness:()=>di(r)?"fresh":"stale"}}function No(r,e){return{kind:"run-results",snapshot:()=>({kind:"run-results",heading:"Test Results",body:Pp(r,e),generatedAt:Date.now()}),freshness:()=>{if(!e||!r)return"stale";let t=r.get(e);return t?t.status==="running"?"stale":"fresh":"stale"}}}function dy(r){_o.push(r)}function py(){_o.length=0}function fy(){return _o.slice()}function kl(r,e){let t=[],n=e&&e!=="(root)"?`${e} / ${r.name}`:r.name;return r.description?.trim()&&t.push(`Description: ${Zn(r.description,400)}`),r.doc?.trim()&&t.push(`Docs (doc.md): ${Zn(r.doc,cy)}`),r.operationId&&t.push(`OpenAPI operationId: ${r.operationId}`),r.summary?.trim()&&t.push(`OpenAPI summary: ${Zn(r.summary,200)}`),r.tags?.length&&t.push(`OpenAPI tags: ${r.tags.join(", ")}`),r.deprecated&&t.push("Deprecated: true"),r.responseSchema&&t.push(`Response schema: ${Zn(JSON.stringify(r.responseSchema),400)}`),r.bodySchema&&t.push(`Request body schema: ${Zn(JSON.stringify(r.bodySchema),300)}`),r.settings?.timeout!==void 0&&t.push(`Timeout: ${r.settings.timeout}ms`),t.length===0?"":`[${r.method??"GET"} ${r.url??""}] ${n}
|
|
647
|
+
Variant: **${n}**`+(t.description?` \u2014 ${t.description}`:"")),t.tags){let s=new Set(e.tags||[]);for(let i of t.tags)s.add(i);e.tags=[...s]}if(t.parameters){e.parameters||(e.parameters=[]);for(let s of t.parameters){let i=e.parameters.find(o=>o.name===s.name&&o.in===s.in);i?this.mergeParameterSchema(i,s,n):e.parameters.push(s)}}if(t.responses){e.responses||(e.responses={});for(let[s,i]of Object.entries(t.responses))e.responses[s]||(e.responses[s]=i)}if(t.requestBody?.content&&e.requestBody?.content)for(let[s,i]of Object.entries(t.requestBody.content))e.requestBody.content[s]||(e.requestBody.content[s]=i);else t.requestBody&&!e.requestBody&&(e.requestBody=t.requestBody)}mergeParameterSchema(e,t,n){e.schema||(e.schema={});let s=e.schema,i=t.schema||{},o=this.getConstraintKind(s),a=this.getConstraintKind(i);if(o==="none"&&a==="none")this.widenType(s,i);else if(o==="none")Object.assign(s,this.extractConstraints(i)),this.widenType(s,i);else if(a==="none")this.widenType(s,i);else if(o===a)this.mergeSameKindConstraints(s,i,o),this.widenType(s,i);else{if(s.oneOf){let c=this.buildVariantSchema(i);s.oneOf.some(l=>JSON.stringify(l)===JSON.stringify(c))||s.oneOf.push(c)}else if(i.oneOf){let c=this.buildVariantSchema(s);s.oneOf=[c,...i.oneOf]}else{let c=this.buildVariantSchema(s),l=this.buildVariantSchema(i);s.oneOf=[c,l]}this.stripConstraints(s)}if(t.description&&t.description!==e.description&&(e.description=(e.description||"")+(e.description?"; ":"")+t.description),t.example!==void 0&&t.example!==e.example){e.examples||(e.examples={},e.example!==void 0&&(e.examples.variant1={value:e.example}));let c=`variant_${n.replace(/[^a-zA-Z0-9_]/g,"_")}`;e.examples[c]={value:t.example},delete e.example}}getConstraintKind(e){return e.oneOf?"oneOf":e.enum&&e.enum.length>0?"enum":e.pattern?"pattern":e.minimum!==void 0||e.maximum!==void 0||e.exclusiveMinimum!==void 0||e.exclusiveMaximum!==void 0||e.multipleOf!==void 0?"range":e.minLength!==void 0||e.maxLength!==void 0?"length":e.minItems!==void 0||e.maxItems!==void 0||e.uniqueItems?"array":e.format?"format":"none"}mergeSameKindConstraints(e,t,n){switch(n){case"enum":{let s=new Set(e.enum||[]);for(let i of t.enum||[])s.add(i);e.enum=[...s];break}case"pattern":{t.pattern&&t.pattern!==e.pattern&&(e.pattern=`(?:${e.pattern})|(?:${t.pattern})`);break}case"range":{t.minimum!==void 0&&(e.minimum=e.minimum!==void 0?Math.min(e.minimum,t.minimum):t.minimum),t.maximum!==void 0&&(e.maximum=e.maximum!==void 0?Math.max(e.maximum,t.maximum):t.maximum),t.exclusiveMinimum&&(e.exclusiveMinimum=!0),t.exclusiveMaximum&&(e.exclusiveMaximum=!0),t.multipleOf!==void 0&&(e.multipleOf=e.multipleOf!==void 0?Math.min(e.multipleOf,t.multipleOf):t.multipleOf);break}case"length":{t.minLength!==void 0&&(e.minLength=e.minLength!==void 0?Math.min(e.minLength,t.minLength):t.minLength),t.maxLength!==void 0&&(e.maxLength=e.maxLength!==void 0?Math.max(e.maxLength,t.maxLength):t.maxLength);break}case"array":{t.minItems!==void 0&&(e.minItems=e.minItems!==void 0?Math.min(e.minItems,t.minItems):t.minItems),t.maxItems!==void 0&&(e.maxItems=e.maxItems!==void 0?Math.max(e.maxItems,t.maxItems):t.maxItems),t.uniqueItems&&(e.uniqueItems=!0);break}case"format":{if(t.format&&t.format!==e.format){let s={type:e.type||"string",format:e.format},i={type:t.type||"string",format:t.format};delete e.format,e.oneOf=[s,i]}break}case"oneOf":{if(t.oneOf)for(let s of t.oneOf)e.oneOf.some(i=>JSON.stringify(i)===JSON.stringify(s))||e.oneOf.push(s);break}}}buildVariantSchema(e){let t={};return e.type&&(t.type=e.type),e.enum&&(t.enum=[...e.enum]),e.pattern&&(t.pattern=e.pattern),e.format&&(t.format=e.format),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.exclusiveMinimum!==void 0&&(t.exclusiveMinimum=e.exclusiveMinimum),e.exclusiveMaximum!==void 0&&(t.exclusiveMaximum=e.exclusiveMaximum),e.multipleOf!==void 0&&(t.multipleOf=e.multipleOf),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.minItems!==void 0&&(t.minItems=e.minItems),e.maxItems!==void 0&&(t.maxItems=e.maxItems),e.uniqueItems&&(t.uniqueItems=!0),e.nullable&&(t.nullable=!0),t}stripConstraints(e){delete e.enum,delete e.pattern,delete e.format,delete e.minimum,delete e.maximum,delete e.exclusiveMinimum,delete e.exclusiveMaximum,delete e.multipleOf,delete e.minLength,delete e.maxLength,delete e.minItems,delete e.maxItems,delete e.uniqueItems,delete e.nullable}extractConstraints(e){let t={};return e.enum&&(t.enum=[...e.enum]),e.pattern&&(t.pattern=e.pattern),e.format&&(t.format=e.format),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.exclusiveMinimum!==void 0&&(t.exclusiveMinimum=e.exclusiveMinimum),e.exclusiveMaximum!==void 0&&(t.exclusiveMaximum=e.exclusiveMaximum),e.multipleOf!==void 0&&(t.multipleOf=e.multipleOf),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.minItems!==void 0&&(t.minItems=e.minItems),e.maxItems!==void 0&&(t.maxItems=e.maxItems),e.uniqueItems&&(t.uniqueItems=!0),e.nullable&&(t.nullable=!0),t}widenType(e,t){if(!(!t.type||t.type===e.type))if(!e.type)e.type=t.type;else{let n=bo(e.type,t.type);n&&(e.type=n)}}}});import*as cp from"yaml";var Ro,lp=k(()=>{"use strict";Ro=class{finalize(e,t,n,s){if(t.size>0)for(let[i,o]of t)e.components.securitySchemes[i]=o;else delete e.components.securitySchemes;return e.tags=[...n].map(i=>({name:i})),e.tags.length===0&&delete e.tags,this.deduplicateComponents(e),Object.keys(e.components.schemas).length===0&&delete e.components.schemas,Object.keys(e.components).length===0&&delete e.components,s.format==="yaml"?cp.stringify(e,{indent:2}):JSON.stringify(e,null,2)}deduplicateComponents(e){let t=new Map,n=new Map;if(e.paths)for(let[s,i]of Object.entries(e.paths))for(let[o,a]of Object.entries(i)){let c=a;if(c.responses){for(let[l,u]of Object.entries(c.responses))if(u.content)for(let d of Object.values(u.content))d.schema&&this.trackSchema(d.schema,`${o}${s}Response${l}`,t,n)}if(c.requestBody?.content)for(let l of Object.values(c.requestBody.content))l.schema&&this.trackSchema(l.schema,`${o}${s}Request`,t,n)}for(let[s,i]of t)if((n.get(s)||0)>=2){let a=this.sanitizeComponentName(i.name);e.components.schemas[a]=i.schema,this.replaceInlineSchema(e,i.schema,`#/components/schemas/${a}`)}}trackSchema(e,t,n,s){if(!e||e.type!=="object"||!e.properties)return;let i=JSON.stringify(e);n.has(i)||n.set(i,{name:t,schema:e}),s.set(i,(s.get(i)||0)+1)}replaceInlineSchema(e,t,n){let s=JSON.stringify(t);if(e.paths)for(let i of Object.values(e.paths))for(let o of Object.values(i)){if(o.responses){for(let a of Object.values(o.responses))if(a.content)for(let c of Object.values(a.content))c.schema&&JSON.stringify(c.schema)===s&&(c.schema={$ref:n})}if(o.requestBody?.content)for(let a of Object.values(o.requestBody.content))a.schema&&JSON.stringify(a.schema)===s&&(a.schema={$ref:n})}}sanitizeComponentName(e){return e.replace(/[^a-zA-Z0-9._-]/g,"").replace(/^[^a-zA-Z]/,"Schema")}}});var un,Co=k(()=>{"use strict";So();op();ap();lp();ti();un=class{constructor(e,t,n){this.collectionService=e;this.envConfigService=t;this.inferenceService=n;let s=new ln;this.merger=new wo,this.operationBuilder=new xo(s),this.specWriter=new Ro}collectionService;envConfigService;inferenceService;merger;operationBuilder;specWriter;async export(e,t){let n=this.collectionService.getCollection(e);if(!n)throw new Error(`Collection ${e} not found`);let s={openapi:"3.0.3",info:this.buildInfo(n,t),servers:this.buildServers(t),paths:{},components:{schemas:{},securitySchemes:{}},tags:[]},i=new Map;if(n.auth&&n.auth.type!=="none"&&n.auth.type!=="inherit"){let c=this.operationBuilder.mapAuthToSecurityScheme(n.auth);if(c){let{schemeName:l,scheme:u,requirement:d}=c;i.set(l,u),s.security=[d]}}let o=new Set,a=new Set;return await this.processItems(n.items,s,i,o,a,void 0,n,t),this.augmentServersFromHostVars(a,s.servers,t),this.specWriter.finalize(s,i,o,t)}buildInfo(e,t){return{title:t.info?.title||e.name,description:t.info?.description||e.description||"",version:t.info?.version||e.version||"1.0.0"}}buildServers(e){let t=[],n=e.environments||[];if(n.length===0){let s=this.envConfigService.getSelectedEnvironment();if(s){let i=this.envConfigService.resolveVariables("{{baseUrl}}",s);i&&i!=="{{baseUrl}}"&&t.push({url:i,description:s})}}else{let s=new Set;for(let i of n){let o=this.envConfigService.resolveVariables("{{baseUrl}}",i);o&&o!=="{{baseUrl}}"&&!s.has(o)&&(s.add(o),t.push({url:o,description:i}))}}return t.length===0&&t.push({url:"http://localhost",description:"Default server"}),t}async processItems(e,t,n,s,i,o,a,c){for(let l of e)if(l.type==="folder"){let u=l,d=o||u.name;s.add(d),u.items&&await this.processItems(u.items,t,n,s,i,d,a,c)}else{let u=l;await this.processRequest(u,t,n,s,i,o,a,c)}}async processRequest(e,t,n,s,i,o,a,c){let{path:l,hostVar:u}=tp(e.url);u&&i.add(u);let d=(e.method||"GET").toLowerCase();t.paths[l]||(t.paths[l]={});let p=await this.operationBuilder.buildOperation(e,d,l,t,n,s,o,a,c),m=t.paths[l][d];m?this.merger.mergeOperation(m,p,e.name):t.paths[l][d]=p}augmentServersFromHostVars(e,t,n){if(e.size===0)return;let s=new Set(t.map(o=>o.url)),i=n.environments?.length?n.environments:[this.envConfigService.getSelectedEnvironment()].filter(o=>!!o);for(let o of e){let a=`{{${o}}}`,c=!1;for(let l of i){let u=this.envConfigService.resolveVariables(a,l);u&&u!==a&&!s.has(u)&&(t.push({url:u,description:l}),s.add(u),c=!0)}if(!c){let l=`{${o}}`;s.has(l)||(t.push({url:l,variables:{[o]:{default:""}}}),s.add(l))}}}}});var Br,sl=k(()=>{"use strict";Br=class{generate(e,t){if(!e)return;let n=t||{};if(e.$ref){let s=this.resolveLocalRef(e.$ref,n.components);return s?this.generate(s,n):{}}if(e.nullable&&!e.type)return null;if(e.enum&&e.enum.length>0)return e.enum[0];if(e.default!==void 0)return e.default;if(e.example!==void 0)return e.example;if(e.allOf)return this.generateFromAllOf(e.allOf,e.discriminator,n);if(e.oneOf)return this.generateFromOneOfAnyOf(e.oneOf,e.discriminator,n);if(e.anyOf)return this.generateFromOneOfAnyOf(e.anyOf,e.discriminator,n);switch(e.type){case"string":return this.generateString(e);case"integer":return this.generateInteger(e);case"number":return this.generateNumber(e);case"boolean":return!1;case"array":return this.generateArray(e,n);case"object":return this.generateObject(e,n);default:return e.properties?this.generateObject(e,n):{}}}generateString(e){switch(e.format){case"email":return"user@example.com";case"date-time":return"2026-01-01T00:00:00Z";case"date":return"2026-01-01";case"time":return"00:00:00";case"uri":case"url":return"https://example.com";case"uuid":return"00000000-0000-0000-0000-000000000000";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"hostname":return"example.com";case"binary":return"";case"byte":return"c3RyaW5n";case"password":return"********";default:return"string"}}generateInteger(e){return e.minimum!==void 0?e.minimum:e.exclusiveMinimum!==void 0?e.exclusiveMinimum+1:0}generateNumber(e){return e.minimum!==void 0?e.minimum:e.exclusiveMinimum!==void 0?e.exclusiveMinimum+.1:0}generateArray(e,t){return e.items?[this.generate(e.items,t)]:[]}generateObject(e,t){let n={},s=e.properties||{};for(let[i,o]of Object.entries(s))t.omitReadOnly&&o.readOnly||(n[i]=this.generate(o,t));return n}generateFromAllOf(e,t,n){let s={type:"object",properties:{},required:[]};for(let o of e){let a=o.$ref?this.resolveLocalRef(o.$ref,n.components)||{}:o;a.properties&&Object.assign(s.properties,a.properties),a.required&&(s.required=[...s.required||[],...a.required])}let i=this.generateObject(s,n);return t?.propertyName&&(i[t.propertyName]=this.guessDiscriminatorValue(e,n)),i}generateFromOneOfAnyOf(e,t,n){if(e.length===0)return{};let s=e[0].$ref&&this.resolveLocalRef(e[0].$ref,n.components)||e[0],i=this.generate(s,n);return t?.propertyName&&typeof i=="object"&&i!==null&&(i[t.propertyName]=this.guessDiscriminatorValue(e,n)),i}guessDiscriminatorValue(e,t){if(e.length===0)return"unknown";let n=e[0];if(n.$ref){let s=n.$ref.split("/");return s[s.length-1]}return"variant1"}resolveLocalRef(e,t){if(!e||!t)return;let n=e.match(/^#\/components\/(?:schemas\/)?(.+)$/);if(n)return t[n[1]];let s=e.match(/^#\/components\/(.+)$/);if(s)return t[s[1]]}}});import il from"@apidevtools/json-schema-ref-parser";var Ur,ol=k(()=>{"use strict";Ur=class{async resolve(e){try{return await il.dereference(e,{dereference:{circular:"ignore"}})}catch(t){return console.error("[RefResolver] Failed to fully resolve $ref pointers:",t),e}}async bundle(e){try{return await il.bundle(e)}catch(t){return console.error("[RefResolver] Failed to bundle $ref pointers:",t),e}}async resolveFile(e){try{return await il.dereference(e,{dereference:{circular:"ignore"}})}catch(t){throw console.error(`[RefResolver] Failed to resolve file ${e}:`,t),t}}}});import*as up from"fs";import*as dp from"yaml";var Gg,Lt,ko=k(()=>{"use strict";Ze();sl();ol();Gg=["application/json","text/plain","text/html","multipart/form-data","application/x-www-form-urlencoded"],Lt=class{constructor(e,t){this.collectionService=e;this.envConfigService=t;this.exampleGenerator=new Br,this.refResolver=new Ur}collectionService;envConfigService;exampleGenerator;refResolver;async import(e,t){let n=await up.promises.readFile(e,"utf-8"),s=this.parseSpec(n,e);return this.importFromSpec(s,t)}async importFromUrl(e,t){let n=await fetch(e,{headers:{Accept:"application/json, application/yaml, text/yaml"}});if(!n.ok)throw new Error(`Failed to fetch OpenAPI spec from ${e}: HTTP ${n.status} ${n.statusText}`);let s=await n.text(),i=this.parseSpec(s,e);return this.importFromSpec(i,t)}async importFromString(e,t){let n=this.parseSpec(e,"spec");return this.importFromSpec(n,t)}parseSpec(e,t){let n=e.trim();if(!n)throw new Error(`OpenAPI spec is empty (${t})`);return n.startsWith("{")||n.startsWith("[")?JSON.parse(e):dp.parse(e)}async importFromSpec(e,t){let n=e;n=await this.refResolver.resolve(n);let s=n.components?.schemas||{},i=t?.collectionName||n.info?.title||"Imported API",a={id:le(i),name:i,description:n.info?.description||"",version:n.info?.version||"1.0.0",variables:{},items:[]};if(n.servers&&n.servers.length>0&&(a.variables.baseUrl=n.servers[0].url),n.security&&n.security.length>0&&n.components?.securitySchemes){let u=this.mapSecurityToAuth(n.security[0],n.components.securitySchemes);u&&(a.auth=u)}let c=new Map;if(n.tags)for(let u of n.tags){let d={type:"folder",id:le(u.name),name:u.name,description:u.description,items:[]};c.set(u.name,d),a.items.push(d)}if(n.paths)for(let[u,d]of Object.entries(n.paths))for(let p of["get","post","put","patch","delete","head","options","trace"]){let m=d[p];if(!m)continue;let f=this.processOperation(p,u,m,d,n,s),h=m.tags?.[0];if(h&&c.has(h))c.get(h).items.push(f);else if(h){let g={type:"folder",id:le(h),name:h,items:[f]};c.set(h,g),a.items.push(g)}else a.items.push(f)}await this.collectionService.saveCollection(a);let l;return t?.environmentName&&n.servers&&(l=await this.createEnvironmentFromServers(n.servers,t.environmentName)),{collection:a,environmentCreated:l}}processOperation(e,t,n,s,i,o){let a=le(n.operationId||`${e}-${t}`),c=`{{baseUrl}}${this.convertPathParams(t)}`,l=n.summary||n.operationId||`${e.toUpperCase()} ${t}`,u=n.deprecated===!0;u&&(l=`[DEPRECATED] ${l}`);let d={type:"request",id:a,name:l,method:e.toUpperCase(),url:c,description:n.description||"",deprecated:u};n.operationId&&(d.operationId=n.operationId),n.summary&&(d.summary=n.summary),n.tags?.length&&(d.tags=[...n.tags]);let p=[...s.parameters||[],...n.parameters||[]];if(this.processParameters(d,p,o),n.requestBody&&this.processRequestBody(d,n.requestBody,o),n.responses&&(d.responseSchema=this.processResponses(n.responses,o)),n.security!==void 0&&i.components?.securitySchemes){if(Array.isArray(n.security)&&n.security.length===0)d.auth={type:"none"};else if(n.security&&n.security.length>0){let m=this.mapSecurityToAuth(n.security[0],i.components.securitySchemes);m&&(d.auth=m)}}return d}convertPathParams(e){return e.replace(/\{(\w+)\}/g,":$1")}processParameters(e,t,n){let s=[],i=[],o={},a=[];for(let c of t){let l=c.name,u=c.in,d=c.schema||{},p=c.example!==void 0?String(c.example):this.generateExampleForParam(d,n),m=c.deprecated===!0;switch(u){case"path":{if(c.description||d.type||d.format||d.enum||m||d.pattern||d.minimum!==void 0||d.maximum!==void 0||d.minLength!==void 0||d.maxLength!==void 0||d.multipleOf!==void 0||d.minItems!==void 0||d.maxItems!==void 0||d.uniqueItems||d.nullable||d.oneOf){let h={value:p};d.oneOf?(h.oneOf=d.oneOf,this.applyOneOfHints(h,d.oneOf)):(d.type&&(h.type=d.type),d.format&&(h.format=d.format),d.enum&&(h.enum=d.enum.map(String)),d.pattern&&(h.pattern=d.pattern),d.minimum!==void 0&&(h.minimum=d.minimum),d.maximum!==void 0&&(h.maximum=d.maximum),d.exclusiveMinimum!==void 0&&(h.exclusiveMinimum=d.exclusiveMinimum),d.exclusiveMaximum!==void 0&&(h.exclusiveMaximum=d.exclusiveMaximum),d.multipleOf!==void 0&&(h.multipleOf=d.multipleOf),d.minLength!==void 0&&(h.minLength=d.minLength),d.maxLength!==void 0&&(h.maxLength=d.maxLength),d.minItems!==void 0&&(h.minItems=d.minItems),d.maxItems!==void 0&&(h.maxItems=d.maxItems),d.uniqueItems&&(h.uniqueItems=!0),d.nullable&&(h.nullable=!0)),c.description&&(h.description=c.description),m&&(h.deprecated=!0),o[l]=h}else o[l]=p;break}case"query":{let f={key:l,value:p};this.applySchemaConstraints(f,d,c,m),i.push(f);break}case"header":{let f={key:l,value:p};this.applySchemaConstraints(f,d,c,m),s.push(f);break}case"cookie":{a.push(`${l}={{${l}}}`);break}}}a.length>0&&s.push({key:"Cookie",value:a.join("; ")}),Object.keys(o).length>0&&(e.params=o),i.length>0&&(e.query=i),s.length>0&&(e.headers=s)}applySchemaConstraints(e,t,n,s){t.oneOf?(e.oneOf=t.oneOf,this.applyOneOfHints(e,t.oneOf)):(t.type&&(e.type=t.type),t.format&&(e.format=t.format),t.enum&&(e.enum=t.enum.map(String)),t.pattern&&(e.pattern=t.pattern),t.minimum!==void 0&&(e.minimum=t.minimum),t.maximum!==void 0&&(e.maximum=t.maximum),t.exclusiveMinimum!==void 0&&(e.exclusiveMinimum=t.exclusiveMinimum),t.exclusiveMaximum!==void 0&&(e.exclusiveMaximum=t.exclusiveMaximum),t.multipleOf!==void 0&&(e.multipleOf=t.multipleOf),t.minLength!==void 0&&(e.minLength=t.minLength),t.maxLength!==void 0&&(e.maxLength=t.maxLength),t.minItems!==void 0&&(e.minItems=t.minItems),t.maxItems!==void 0&&(e.maxItems=t.maxItems),t.uniqueItems&&(e.uniqueItems=!0),t.nullable&&(e.nullable=!0)),n.required&&(e.required=!0),n.description&&(e.description=n.description),s&&(e.deprecated=!0)}applyOneOfHints(e,t){let n=[],s=new Set;for(let i of t)i.type&&s.add(i.type),i.enum&&n.push(...i.enum.map(String));s.size===1&&(e.type=[...s][0]),n.length>0&&(e.enum=[...new Set(n)])}generateExampleForParam(e,t){if(!e)return"";let n=this.exampleGenerator.generate(e,{components:t});return n==null?"":String(n)}processRequestBody(e,t,n){if(!t.content)return;let s=Object.keys(t.content);if(s.length===0)return;let i=this.selectPrimaryContentType(s),o=t.content[i],{bodyType:a,bodyFormat:c}=this.mapContentTypeToBodyType(i);if(e.body={type:a,...c&&{format:c},content:""},o){let u=this.generateBodyContent(o,i,n);u!==void 0&&(e.body.content=typeof u=="string"?u:JSON.stringify(u,null,2)),a==="form-data"&&o.schema?.properties&&(e.body.content=this.buildFormDataEntries(o.schema,n)),a==="x-www-form-urlencoded"&&o.schema?.properties&&(e.body.content=this.buildFormDataEntries(o.schema,n))}let l=this.buildBodySchema(t,i,n);l&&(e.bodySchema=l)}selectPrimaryContentType(e){for(let s of Gg)if(e.includes(s))return s;let t=e.find(s=>s.includes("json"));if(t)return t;let n=e.find(s=>s.startsWith("text/"));return n||e[0]}mapContentTypeToBodyType(e){return e.includes("json")?{bodyType:"raw",bodyFormat:"json"}:e==="application/xml"||e==="text/xml"?{bodyType:"raw",bodyFormat:"xml"}:e==="text/html"?{bodyType:"raw",bodyFormat:"html"}:e.startsWith("text/")?{bodyType:"raw",bodyFormat:"text"}:e==="multipart/form-data"?{bodyType:"form-data"}:e==="application/x-www-form-urlencoded"?{bodyType:"x-www-form-urlencoded"}:e==="application/octet-stream"?{bodyType:"binary"}:{bodyType:"raw",bodyFormat:"text"}}generateBodyContent(e,t,n){if(e.example!==void 0)return e.example;if(e.examples){let s=Object.values(e.examples)[0];if(s?.value!==void 0)return s.value}if(e.schema)return this.exampleGenerator.generate(e.schema,{omitReadOnly:!0,components:n})}buildFormDataEntries(e,t){let n=[],s=e.properties||{},i=new Set(e.required||[]);for(let[o,a]of Object.entries(s)){let c=a,l=c.type==="string"&&c.format==="binary",u={key:o,value:l?"":String(this.exampleGenerator.generate(c,{components:t})||""),type:l?"file":"text",enabled:!0};n.push(u)}return n}buildBodySchema(e,t,n){let s=Object.keys(e.content),i=e.content[t];if(!i?.schema)return;let o={contentType:t,schema:i.schema};if(s.length>1){o.content={};for(let c of s){let l=e.content[c],u={};l.schema&&(u.schema=l.schema),l.examples&&(u.examples=l.examples),l.encoding&&(u.encoding=l.encoding),o.content[c]=u}}i.encoding&&(o.encoding=i.encoding);let a=this.extractUsedComponents(i.schema,n);return Object.keys(a).length>0&&(o.components=a),o}processResponses(e,t){let n={responses:{}},s={};for(let[i,o]of Object.entries(e)){let a=o,c={description:a.description||`Status ${i}`};if(a.content){let l=Object.keys(a.content);if(l.length===1){let u=l[0],d=a.content[u];c.contentType=u,d.schema&&(c.schema=d.schema),d.examples&&(c.examples=d.examples),d.schema&&Object.assign(s,this.extractUsedComponents(d.schema,t))}else{c.content={};for(let u of l){let d=a.content[u],p={};d.schema&&(p.schema=d.schema),d.examples&&(p.examples=d.examples),c.content[u]=p,d.schema&&Object.assign(s,this.extractUsedComponents(d.schema,t))}}}if(a.headers){c.headers={};for(let[l,u]of Object.entries(a.headers)){let d=u;c.headers[l]={...d.description&&{description:d.description},schema:d.schema||{type:"string"}}}}n.responses[i]=c}return Object.keys(s).length>0&&(n.components=s),n}mapSecurityToAuth(e,t){let n=Object.keys(e)[0];if(!n)return;let s=t[n];if(s)switch(s.type){case"http":if(s.scheme==="bearer")return{type:"bearer",bearerToken:""};if(s.scheme==="basic")return{type:"basic",basicAuth:{username:"",password:""}};break;case"apiKey":return{type:"apikey",apikey:{key:s.name||"X-Api-Key",value:"",in:s.in||"header"}};case"oauth2":{let i=s.flows||{},o=i.authorizationCode||i.clientCredentials||i.password||i.implicit||{},a="client_credentials";return i.authorizationCode?a="authorization_code":i.password?a="password":i.implicit&&(a="implicit"),{type:"oauth2",oauth2:{grantType:a,tokenUrl:o.tokenUrl||"",authUrl:o.authorizationUrl||"",clientId:"",clientSecret:"",scope:Object.keys(o.scopes||{}).join(" ")}}}}}async createEnvironmentFromServers(e,t){if(e.length>0){let n=e[0].url;this.envConfigService.setEnvironmentVariable("baseUrl",n)}return t}extractUsedComponents(e,t,n){let s=n||{};if(!e)return s;if(e.$ref){let i=this.extractRefName(e.$ref);i&&t[i]&&!s[i]&&(s[i]=t[i],this.extractUsedComponents(t[i],t,s))}if(e.properties)for(let i of Object.values(e.properties))this.extractUsedComponents(i,t,s);e.items&&this.extractUsedComponents(e.items,t,s);for(let i of["allOf","oneOf","anyOf"])if(e[i])for(let o of e[i])this.extractUsedComponents(o,t,s);return e.additionalProperties&&typeof e.additionalProperties=="object"&&this.extractUsedComponents(e.additionalProperties,t,s),s}extractRefName(e){return e.match(/^#\/components\/schemas\/(.+)$/)?.[1]}}});var dn,Eo=k(()=>{"use strict";dn=class{constructor(e,t,n){this.historyAnalyzer=e;this.scriptAnalyzer=t;this.inferrer=n}historyAnalyzer;scriptAnalyzer;inferrer;async infer(e,t,n,s){let i=await this.historyAnalyzer.analyze(e,t,{environment:s?.environment}),o;return s?.postResponseScript&&(o=this.scriptAnalyzer.analyze(s.postResponseScript)),this.mergeResponseSchemas(n,i,o)}async inferBodySchema(e,t,n,s,i){let o,a;if(t==="raw"&&n==="json"&&e){let c=e;if(typeof e=="string")try{c=JSON.parse(e)}catch{return}o=this.inferrer.inferFromValue(c),a="application/json"}else t==="form-data"&&s?(o=this.buildFormDataSchema(s),a="multipart/form-data"):t==="x-www-form-urlencoded"&&s?(o=this.buildFormDataSchema(s),a="application/x-www-form-urlencoded"):t==="raw"&&n==="xml"?(o={type:"string"},a="application/xml"):t==="raw"&&(n==="text"||n==="html")?(o={type:"string"},a=n==="html"?"text/html":"text/plain"):t==="binary"?(o={type:"string",format:"binary"},a="application/octet-stream"):t==="graphql"&&(o={type:"object",properties:{query:{type:"string"},variables:{type:"object"}}},a="application/json");if(o)return i?this.mergeBodySchemaWithExisting(o,i):{contentType:a,schema:o}}buildFormDataSchema(e){let t={type:"object",properties:{}},n=[];for(let s of e){if(!s.enabled&&s.enabled!==void 0)continue;let i={};s.type?i.type=s.type:i.type="string",s.description&&(i.description=s.description),s.format&&(i.format=s.format),s.enum&&(i.enum=s.enum),s.type==="file"&&(i.type="string",i.format="binary"),t.properties[s.key]=i,s.required&&n.push(s.key)}return n.length>0&&(t.required=n),t}mergeResponseSchemas(e,t,n){let s={responses:{}};for(let[i,o]of Object.entries(t.responses))s.responses[i]={...o};if(n&&this.applyScriptHints(s,n),e){for(let[i,o]of Object.entries(e.responses))s.responses[i]?s.responses[i]=this.mergeResponseDefinitions(s.responses[i],o):s.responses[i]={...o};e.components&&(s.components={...e.components})}return s}applyScriptHints(e,t){for(let n of t.expectedStatuses){let s=String(n);e.responses[s]||(e.responses[s]={description:`Status ${n}`})}for(let[,n]of Object.entries(e.responses))n.schema&&this.augmentSchemaWithHints(n.schema,t)}augmentSchemaWithHints(e,t){if(!(e.type!=="object"||!e.properties))for(let n of t.fieldPaths){let s=n.split(".");this.ensureFieldPath(e,s,t)}}ensureFieldPath(e,t,n,s=""){if(t.length===0||e.type!=="object")return;e.properties||(e.properties={});let i=t[0],o=i.endsWith("[]"),a=o?i.slice(0,-2):i,c=s?`${s}.${i}`:i,l=t.slice(1);if(!e.properties[a])if(o)e.properties[a]={type:"array",items:{type:"object"}};else if(l.length>0)e.properties[a]={type:"object",properties:{}};else{let u=n.typeHints[c];e.properties[a]={type:u||"string"};return}if(l.length>0){let u=o?e.properties[a].items:e.properties[a];u&&this.ensureFieldPath(u,l,n,c)}}mergeResponseDefinitions(e,t){let n={...e};return t.description&&(n.description=t.description),t.contentType&&(n.contentType=t.contentType),t.schema&&e.schema?n.schema=this.inferrer.mergeSchemas(e.schema,t.schema):t.schema&&(n.schema=t.schema),t.examples&&(n.examples={...e.examples||{},...t.examples}),t.content&&(n.content={...e.content||{},...t.content}),t.headers&&(n.headers={...e.headers||{},...t.headers}),n}mergeBodySchemaWithExisting(e,t){let n={...t};return t.schema?n.schema=this.inferrer.mergeSchemas(e,t.schema):n.schema=e,n}}});var pp,qo,fp,mp,hp,gp,yp,Vr,al=k(()=>{"use strict";pp=/(?:jsonData|responseJson|data|json|body|response\.json\(\))\.([a-zA-Z_][\w.\[\]]*)/g,qo="(?:pm|hf|ctx)",fp=new RegExp(`${qo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.be\\.(?:a|an)\\(['"](\\w+)['"]\\)`,"g"),mp=new RegExp(`${qo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.(?:equal|eql)\\((.+?)\\)`,"g"),hp=/(?:to\.have\.status|response\.code.*?equal)\((\d+)\)/g,gp=new RegExp(`${qo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.be\\.(true|false)`,"g"),yp=new RegExp(`${qo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.have\\.(?:lengthOf|length\\.above|length\\.below)`,"g"),Vr=class{analyze(e){let t={fieldPaths:[],typeHints:{},valueHints:{},expectedStatuses:[]};if(!e||e.trim().length===0)return t;let n=this.stripComments(e);return this.extractFieldPaths(n,t),this.extractTypeAssertions(n,t),this.extractEqualityAssertions(n,t),this.extractBooleanAssertions(n,t),this.extractLengthAssertions(n,t),this.extractStatusAssertions(n,t),t.fieldPaths=[...new Set(t.fieldPaths)],t.expectedStatuses=[...new Set(t.expectedStatuses)],t}stripComments(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,"");return t=t.replace(/\/\/.*$/gm,""),t}extractFieldPaths(e,t){let n,s=new RegExp(pp.source,pp.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]);i&&!this.isCommonMethodCall(i)&&t.fieldPaths.push(i)}}extractTypeAssertions(e,t){let n,s=new RegExp(fp.source,fp.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]),o=n[2].toLowerCase();i&&(t.typeHints[i]=this.mapAssertionType(o),t.fieldPaths.includes(i)||t.fieldPaths.push(i))}}extractEqualityAssertions(e,t){let n,s=new RegExp(mp.source,mp.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]),o=n[2].trim();if(i){let a=this.parseAssertionValue(o);a!==void 0&&(t.valueHints[i]=a,typeof a=="string"?t.typeHints[i]=t.typeHints[i]||"string":typeof a=="number"?t.typeHints[i]=t.typeHints[i]||(Number.isInteger(a)?"integer":"number"):typeof a=="boolean"&&(t.typeHints[i]=t.typeHints[i]||"boolean")),t.fieldPaths.includes(i)||t.fieldPaths.push(i)}}}extractBooleanAssertions(e,t){let n,s=new RegExp(gp.source,gp.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]);i&&(t.typeHints[i]="boolean",t.valueHints[i]=n[2]==="true",t.fieldPaths.includes(i)||t.fieldPaths.push(i))}}extractLengthAssertions(e,t){let n,s=new RegExp(yp.source,yp.flags);for(;(n=s.exec(e))!==null;){let i=this.normalizeFieldPath(n[1]);i&&(t.typeHints[i]=t.typeHints[i]||"array",t.fieldPaths.includes(i)||t.fieldPaths.push(i))}}extractStatusAssertions(e,t){let n,s=new RegExp(hp.source,hp.flags);for(;(n=s.exec(e))!==null;){let i=parseInt(n[1],10);!isNaN(i)&&i>=100&&i<600&&t.expectedStatuses.push(i)}}normalizeFieldPath(e){let t=e.replace(/^\./,"");return t=t.replace(/\[\d+\]/g,"[]"),t}isCommonMethodCall(e){return new Set(["to","be","have","not","deep","any","all","that","is","has","include","includes","equal","eql","above","below","least","most","within","length","lengthOf","match","string","keys","key","property","ownProperty","status","header","json","text"]).has(e.split(".")[0])}mapAssertionType(e){return{string:"string",number:"number",object:"object",array:"array",boolean:"boolean",null:"null",undefined:"null",int:"integer",integer:"integer",float:"number",double:"number"}[e]||"string"}parseAssertionValue(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);let t=Number(e);return!isNaN(t)&&e.trim().length>0?t:e==="true"?!0:e==="false"?!1:e==="null"?null:e}}});var ni,cl=k(()=>{"use strict";ni=class{providerName="aws";region;profile;moduleRequire;sdk;constructor(e,t){this.region=e.region??process.env.AWS_DEFAULT_REGION??process.env.AWS_REGION,this.profile=e.profile||void 0,this.moduleRequire=t??(n=>pe(n))}async resolve(e){let t=e.lastIndexOf("#"),n=t>=0?e.slice(0,t):e,s=t>=0?e.slice(t+1):void 0;try{if(!this.sdk){let{SecretsManagerClient:a,GetSecretValueCommand:c}=this.moduleRequire("@aws-sdk/client-secrets-manager");this.sdk={client:new a({region:this.region,profile:this.profile}),GetSecretValueCommand:c}}let i=await this.sdk.client.send(new this.sdk.GetSecretValueCommand({SecretId:n})),o=i.SecretString??(i.SecretBinary?Buffer.from(i.SecretBinary).toString("utf-8"):void 0);if(o===void 0)return;if(s)try{let a=JSON.parse(o);return a[s]!==void 0?String(a[s]):void 0}catch{return}return o}catch(i){throw i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND"?new Error("[HTTP Forge] AWS secret resolver requires @aws-sdk/client-secrets-manager. Install it in your project: npm install @aws-sdk/client-secrets-manager"):i}}}});var ri,ll=k(()=>{"use strict";ri=class{providerName="azure";vaultUrl;moduleRequire;client;constructor(e,t){let n=(e.vaultUrl||process.env.AZURE_KEYVAULT_URL)??"";this.vaultUrl=n.replace(/\/$/,""),this.moduleRequire=t??(s=>pe(s))}async resolve(e){if(!this.vaultUrl)throw new Error("[HTTP Forge] Azure Key Vault resolver: no vault URL configured. Set secrets.providers.<alias>.vaultUrl or the AZURE_KEYVAULT_URL env var.");let t=e.split("/"),n=t[0],s=t[1];try{if(!this.client){let{SecretClient:o}=this.moduleRequire("@azure/keyvault-secrets"),{DefaultAzureCredential:a}=this.moduleRequire("@azure/identity");this.client=new o(this.vaultUrl,new a)}return(await this.client.getSecret(n,s?{version:s}:{})).value}catch(i){throw i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND"?new Error("[HTTP Forge] Azure Key Vault resolver requires @azure/keyvault-secrets and @azure/identity. Install them: npm install @azure/keyvault-secrets @azure/identity"):i}}}});import*as bp from"https";var vp,si,ul=k(()=>{"use strict";vp=1e4,si=class{providerName="doppler";token;requestFn;constructor(e,t=bp.request){this.token=e.serviceToken||process.env.DOPPLER_TOKEN,this.requestFn=t}async resolve(e){let t=e.trim().toUpperCase(),n=this.token;if(!n)throw new Error("[HTTP Forge] Doppler secret resolver: no service token found. Set DOPPLER_TOKEN env var or add serviceToken to config.");let s=`https://api.doppler.com/v3/configs/config/secret?name=${encodeURIComponent(t)}`;return new Promise((i,o)=>{let a=this.requestFn(s,{method:"GET",timeout:vp,headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}},c=>{let l=[];c.on("data",u=>l.push(u)),c.on("error",o),c.on("end",()=>{let u=Buffer.concat(l).toString("utf-8");if(c.statusCode===404){i(void 0);return}if(c.statusCode!==200){o(new Error(`[HTTP Forge] Doppler API returned ${c.statusCode} for secret "${t}": ${u}`));return}try{let p=JSON.parse(u)?.value?.computed;i(p!=null?String(p):void 0)}catch{o(new Error(`[HTTP Forge] Doppler API returned non-JSON response for secret "${t}"`))}})});a.on("error",o),a.on("timeout",()=>{a.destroy(new Error(`[HTTP Forge] Doppler request timed out after ${vp}ms`))}),a.end()})}}});var ii,dl=k(()=>{"use strict";ii=class{providerName="gcp";projectId;moduleRequire;client;constructor(e,t){this.projectId=e.projectId||process.env.GOOGLE_CLOUD_PROJECT||process.env.GCLOUD_PROJECT||process.env.GCP_PROJECT,this.moduleRequire=t??(n=>pe(n))}async resolve(e){let t=e.split("/"),n=t[0],s=t.length===1?"latest":t.length===3&&t[1]==="versions"&&t[2]?t[2]:void 0;if(!n||s===void 0)throw new Error(`[HTTP Forge] GCP secret path "${e}" must be "<secretName>" or "<secretName>/versions/<version>".`);if(!this.projectId)throw new Error("[HTTP Forge] GCP secret resolver: no projectId configured and GOOGLE_CLOUD_PROJECT env var is not set.");try{if(!this.client){let{SecretManagerServiceClient:c}=this.moduleRequire("@google-cloud/secret-manager");this.client=new c}let i=`projects/${this.projectId}/secrets/${n}/versions/${s}`,[o]=await this.client.accessSecretVersion({name:i}),a=o.payload?.data;return a?Buffer.isBuffer(a)?a.toString("utf-8"):Buffer.from(a).toString("utf-8"):void 0}catch(i){throw i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND"?new Error("[HTTP Forge] GCP secret resolver requires @google-cloud/secret-manager. Install it: npm install @google-cloud/secret-manager"):i}}}});function Sp(r){return r.split("/").map(e=>encodeURIComponent(e)).join("/")}var oi,pl=k(()=>{"use strict";oi=class{providerName="vault";address;mountPath;namespace;constructor(e){this.address=(e.address||process.env.VAULT_ADDR||"http://127.0.0.1:8200").replace(/\/$/,""),this.mountPath=e.mountPath||"secret",this.namespace=e.namespace||process.env.VAULT_NAMESPACE}async resolve(e){let t=e.lastIndexOf("#"),n=t>=0?e.slice(0,t):e,s=t>=0?e.slice(t+1):void 0,i=process.env.VAULT_TOKEN;if(!i)throw new Error("[HTTP Forge] HashiCorp Vault resolver requires VAULT_TOKEN environment variable to be set.");let o=`${this.address}/v1/${Sp(this.mountPath)}/data/${Sp(n)}`,a={"X-Vault-Token":i};this.namespace&&(a["X-Vault-Namespace"]=this.namespace);let c;try{c=await fetch(o,{headers:a,signal:AbortSignal.timeout(1e4)})}catch(p){let m=p?.name==="TimeoutError"?"request timed out after 10000ms":p?.message??p;throw new Error(`[HTTP Forge] Vault request failed: ${m}`)}if(c.status===404)return;if(!c.ok)throw new Error(`[HTTP Forge] Vault returned HTTP ${c.status} for path: ${n}`);let u=(await c.json())?.data?.data;if(!u)return;if(s)return u[s]!==void 0?String(u[s]):void 0;if("value"in u)return String(u.value);let d=Object.keys(u);return d.length===1?String(u[d[0]]):void 0}}});import{execFile as Kg}from"child_process";import{promisify as Qg}from"util";var Zg,Yg,Xg,ai,fl=k(()=>{"use strict";Zg=Qg(Kg),Yg=/not found|isn't an item|is not an item|no item matched|could not find/i,Xg=/not signed in|sign in|authentication|authorization|unauthorized/i,ai=class{providerName="1password";defaultVault;account;moduleRequire;execFileFn;sdkClientPromise;sdkAuthKey;constructor(e,t,n=Zg){this.defaultVault=e.vault,this.account=e.account,this.moduleRequire=t??(s=>pe(s)),this.execFileFn=n}async resolve(e){let t=e.split("/"),n,s,i;if(this.defaultVault){if(t.length<2)throw new Error(`[HTTP Forge] 1Password path "${e}" must be "<item>/<field>" when vault is set in config.`);n=this.defaultVault,s=t.slice(0,t.length-1).join("/"),i=t[t.length-1]}else{if(t.length<3)throw new Error(`[HTTP Forge] 1Password path "${e}" must be "<vault>/<item>/<field>".`);n=t[0],s=t.slice(1,t.length-1).join("/"),i=t[t.length-1]}let o=await this.tryResolveSdk(n,s,i);return o!==null?o:this.resolveViaCli(n,s,i)}async tryResolveSdk(e,t,n){let s=process.env.OP_SERVICE_ACCOUNT_TOKEN||void 0,i=s?void 0:this.account;if(!s&&!i)return null;try{let o=await this.getSdkClient(s,i),a=`op://${e}/${t}/${n}`;return await o.secrets.resolve(a)}catch(o){if(o?.name==="MODULE_NOT_FOUND"||o?.code==="MODULE_NOT_FOUND")return null;throw new Error(`[HTTP Forge] 1Password SDK error for "${e}/${t}/${n}": ${o?.message??o}`)}}getSdkClient(e,t){let n=e?`t:${e}`:`a:${t}`;return(!this.sdkClientPromise||this.sdkAuthKey!==n)&&(this.sdkAuthKey=n,this.sdkClientPromise=(async()=>{let s=this.moduleRequire("@1password/sdk");if(!e&&typeof s.DesktopAuth!="function")throw new Error("[HTTP Forge] DesktopAuth requires @1password/sdk 0.5.0+.");let i=e??new s.DesktopAuth(t);return s.createClient({auth:i,integrationName:"HTTP Forge",integrationVersion:"1.0.0"})})().catch(s=>{throw this.sdkClientPromise=void 0,this.sdkAuthKey=void 0,s})),this.sdkClientPromise}async resolveViaCli(e,t,n){let s={...process.env};s.OP_SERVICE_ACCOUNT_TOKEN?delete s.OP_ACCOUNT:this.account&&(s.OP_ACCOUNT=this.account);try{let{stdout:i}=await this.execFileFn("op",["read",`op://${e}/${t}/${n}`],{env:s,timeout:1e4});return i.replace(/\r?\n$/,"")}catch(i){if(i?.code==="ENOENT")throw new Error('[HTTP Forge] 1Password needs @1password/sdk or the `op` CLI.\n Service Account: set OP_SERVICE_ACCOUNT_TOKEN\n Desktop account: set "account" (SDK 0.5.0+)\n CLI: install 1Password CLI and run `op signin`');let o=String(i?.stderr??"");if(Yg.test(o))return;throw Xg.test(o)?new Error("[HTTP Forge] 1Password CLI is not authenticated. Run `op signin` or set OP_SERVICE_ACCOUNT_TOKEN and install @1password/sdk."):new Error(`[HTTP Forge] 1Password CLI error: ${i?.stderr||i?.message||i}`)}}}});import*as Ao from"fs";import{createRequire as ey}from"module";import*as Po from"path";var ci,ml=k(()=>{"use strict";ws();cl();ll();ul();dl();pl();fl();ci=class{constructor(e){this.configService=e;this.moduleRequire=t=>pe(t),this.refreshProviders()}configService;resolvers=new Map;moduleRequire;configKey;async resolveSecretTokens(e,t){this.refreshProviders();let n=t??new Map,s=new Set;if(this.collectTokens(e,s),s.size===0)return{};await Promise.all(Array.from(s).map(async o=>{if(n.has(o))return;let a=o.slice(7),c=a.indexOf("/");if(c<0){console.warn(`[HTTP Forge] {{${o}}} is malformed; expected {{secret:<alias>/<path>}}.`);return}let l=a.slice(0,c),u=a.slice(c+1),d=this.resolvers.get(l);if(!d){console.warn(`[HTTP Forge] {{${o}}} could not be resolved: no secret provider is configured for alias "${l}".`);return}try{let p=await d.resolve(u);p!==void 0?n.set(o,p):console.warn(`[HTTP Forge] {{${o}}} could not be resolved: secret not found.`)}catch(p){let m=p?.message??String(p);console.warn(`[HTTP Forge] {{${o}}} could not be resolved: ${m}`)}}));let i={};for(let[o,a]of n.entries())i[o]=a;return i}get hasProviders(){return this.refreshProviders(),this.resolvers.size>0}refreshProviders(){if(!this.configService)return;let e,t=[];try{e=this.configService.getConfig().secrets,t=this.configService.getModulePaths()??[]}catch{return}let n=JSON.stringify({secrets:e||null,modulePaths:t});if(n!==this.configKey&&(this.configKey=n,this.moduleRequire=this.buildModuleRequire(t),this.resolvers.clear(),!(!e?.providers||typeof e.providers!="object")))for(let[s,i]of Object.entries(e.providers))try{let o=this.createResolver(s,i);o?this.resolvers.set(s,o):console.warn(`[HTTP Forge] Secret "${s}" skipped: unsupported type "${i?.provider}".`)}catch(o){let a=i?.provider??"unknown";console.warn(`[HTTP Forge] Secret "${s}" (${a}) skipped: ${o?.message??String(o)}`)}}collectTokens(e,t){if(typeof e=="string"){let n=/\{\{(secret:[^}]+)\}\}/g,s;for(;(s=n.exec(e))!==null;){let i=this.baseToken(s[1]);i&&t.add(i)}}else Array.isArray(e)?e.forEach(n=>this.collectTokens(n,t)):e!==null&&typeof e=="object"&&Object.values(e).forEach(n=>this.collectTokens(n,t))}baseToken(e){let t=e.trim(),s=(Dn(t)?.input??t).trim();return s.startsWith("secret:")?s:void 0}createResolver(e,t){switch(t.provider){case"aws":return new ni(t,this.moduleRequire);case"azure":return new ri(t,this.moduleRequire);case"vault":return new oi(t);case"1password":return new ai(t,this.moduleRequire);case"gcp":return new ii(t,this.moduleRequire);case"doppler":return new si(t);case"custom":return this.createCustomResolver(e,t);default:return}}createCustomResolver(e,t){if(!t.module||typeof t.module!="string")throw new Error(`Custom secret provider "${e}" requires a "module" path or package name.`);let n;try{n=this.moduleRequire(t.module)}catch(a){throw new Error(`Custom secret provider "${e}" could not load module "${t.module}". Ensure scripts.modulePaths contains a package.json and the module is installed or the relative path is correct. Cause: ${a?.message??String(a)}`)}let s=n?.default??n,i=typeof s=="function"?s:typeof s?.createResolver=="function"?s.createResolver.bind(s):void 0,o;if(i)o=i({alias:e,options:t.options??{}});else if(s&&typeof s.resolve=="function")o=s;else throw new Error(`Custom secret provider "${e}" module "${t.module}" must export a resolver factory function, a createResolver function, or an object with resolve(path).`);if(o&&typeof o.then=="function")throw new Error(`Custom secret provider "${e}" module "${t.module}" returned a Promise. Resolver factories must be synchronous; use an async resolve(path) method instead.`);if(!o||typeof o.resolve!="function")throw new Error(`Custom secret provider "${e}" module "${t.module}" did not return a resolver with resolve(path).`);return{providerName:typeof o.providerName=="string"&&o.providerName.trim()?o.providerName:e,resolve:async a=>o.resolve(a)}}buildModuleRequire(e){let t=n=>pe(n);for(let n of e)try{let s=Po.resolve(n,"package.json");if(Ao.existsSync(s)){let i=Ao.realpathSync(s),o=ey(i);return a=>{try{return o(a)}catch(c){let l=!a.startsWith(".")&&!Po.isAbsolute(a),u=c?.code==="MODULE_NOT_FOUND"&&String(c?.message??"").includes(`'${a}'`);if(l&&u)return t(a);throw c}}}}catch{}return t}}});function $e(r){return r.replace(/\//g,"%2F")}function ty(r){return r.replace(/%2F/gi,"/")}function Tt(r){return r?r.split("/").map(ty).join(" / "):""}function zr(r){return r.includes(" / ")?r.split(" / ").map(e=>$e(e.trim())).join("/"):$e(r)}function X(r,e=r.items,t=""){let n=[];for(let s of e)if(s.type==="request")n.push({request:s,folderPath:t});else{let i=s,o=$e(i.name),a=t?`${t}/${o}`:o;n.push(...X(r,i.items??[],a))}return n}function qe(r,e=r.items,t=""){let n=[];for(let s of e)if(s.type==="folder"){let i=s,o=$e(i.name),a=t?`${t}/${o}`:o;n.push({folderId:i.id,folderPath:a,requestCount:hl(i.items??[])}),n.push(...qe(r,i.items??[],a))}return n}function hl(r){let e=0;for(let t of r)t.type==="request"?e++:e+=hl(t.items??[]);return e}var tt=k(()=>{"use strict"});var Ht,gl=k(()=>{"use strict";Ht={iterations:1,delayBetweenRequests:0,stopOnError:!1,readFromSharedSession:!1,writeToSharedSession:!1}});import*as ue from"fs";import*as xt from"path";var li,yl=k(()=>{"use strict";tt();Ze();gl();li=class{constructor(e,t,n){this.collectionService=e;this.configService=t;this.suitesDir=t.getSuitesPath(),this.onSuitesChanged=n?.onSuitesChanged,this.loadSuites(),n?.watch!==!1&&this.setupFileWatcher()}collectionService;configService;suitesDir;suites=new Map;fileWatcher=null;debounceTimer=null;onSuitesChanged;ensureSuitesDir(){ue.existsSync(this.suitesDir)||ue.mkdirSync(this.suitesDir,{recursive:!0})}setupFileWatcher(){try{this.fileWatcher=ue.watch(this.suitesDir,(e,t)=>{t&&!t.endsWith(".suite.json")||(this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.loadSuites(),this.onSuitesChanged?.()},200))}),this.fileWatcher.on("error",()=>{})}catch{}}dispose(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.fileWatcher?.close(),this.fileWatcher=null}loadSuites(){if(this.suites.clear(),!ue.existsSync(this.suitesDir))return;let e=ue.readdirSync(this.suitesDir);for(let t of e)if(t.endsWith(".suite.json"))try{let n=xt.join(this.suitesDir,t),s=ue.readFileSync(n,"utf-8"),i=JSON.parse(s),o=Array.isArray(i.nodes)&&i.nodes.length>0?i.nodes:(Array.isArray(i.requests)?i.requests:[]).map(c=>({type:"request",name:c.description||c.name,request:c,enabled:c.enabled!==!1})),a={id:i.id,name:i.name,description:i.description,scripts:i.scripts,nodes:o,config:i.config??{...Ht},isTemporary:i.isTemporary,ai_generated:i.ai_generated===!0,derived_from:Array.isArray(i.derived_from)?i.derived_from:void 0,createdAt:i.createdAt??Date.now(),updatedAt:i.updatedAt??Date.now()};a.id&&a.name&&this.suites.set(a.id,a)}catch(n){console.error(`[TestSuiteService] Failed to load ${t}:`,n)}}async getAllSuites(){return Array.from(this.suites.values())}async getSuite(e){return this.suites.get(e)}async createSuite(e){let t=Date.now(),n={id:le(e),name:e,nodes:[],config:{...Ht},createdAt:t,updatedAt:t};return await this.saveSuiteToDisk(n),this.suites.set(n.id,n),n}async updateSuite(e){e.updatedAt=Date.now(),await this.saveSuiteToDisk(e),this.suites.set(e.id,e)}async duplicateSuite(e,t){let n=this.suites.get(e);if(!n)throw new Error(`Suite not found: ${e}`);let s=n.nodes||[],i=await this.createSuite(t);i.nodes=s.map(c=>({...c})),i.config={...n.config},i.description=n.description;let o=xt.join(this.suitesDir,e),a=xt.join(this.suitesDir,i.id);return ue.existsSync(o)&&this.copyDirRecursive(o,a),await this.saveSuiteToDisk(i),this.suites.set(i.id,i),i}copyDirRecursive(e,t){ue.existsSync(t)||ue.mkdirSync(t,{recursive:!0});for(let n of ue.readdirSync(e,{withFileTypes:!0})){let s=xt.join(e,n.name),i=xt.join(t,n.name);n.isDirectory()?this.copyDirRecursive(s,i):ue.copyFileSync(s,i)}}async deleteSuite(e){let t=this.suites.get(e);if(!t)return!1;let n=`${t.id}.suite.json`,s=xt.join(this.suitesDir,n),i=xt.join(this.suitesDir,t.id);try{return ue.existsSync(s)&&ue.unlinkSync(s),ue.existsSync(i)&&ue.rmSync(i,{recursive:!0,force:!0}),this.suites.delete(e),!0}catch(o){return console.error("[TestSuiteService] Failed to delete suite:",o),!1}}async createTempSuiteFromCollection(e){let t=this.collectionService.getCollection(e);if(!t){console.error(`[TestSuiteService] Collection not found: ${e}`);return}let n=[];this.extractRequestsFromCollection(t,e,t.name,"",n);let s=n.map(a=>({type:"request",name:a.description||a.name,request:a,enabled:a.enabled!==!1})),i=Date.now();return{id:`temp-${e}`,name:t.name,nodes:s,config:{...Ht},isTemporary:!0,createdAt:i,updatedAt:i}}async createTempSuiteFromFolder(e,t,n=!0){let s=this.collectionService.getCollection(e);if(!s){console.error(`[TestSuiteService] Collection not found: ${e}`);return}let i=[];this.extractRequestsFromCollection(s,e,s.name,"",i);let o=t.replace(/\/+$/,""),a=i.filter(d=>n?d.folderPath===o||d.folderPath.startsWith(`${o}/`):d.folderPath===o);if(a.length===0){console.error(`[TestSuiteService] No requests under folder "${t}" in collection: ${e}`);return}let c=a.map(d=>({type:"request",name:d.description||d.name,request:d,enabled:d.enabled!==!1})),l=Date.now();return{id:`temp-${e}-${this.slugifyFolderPath(o)}`,name:`${s.name} / ${Tt(o)}`,nodes:c,config:{...Ht},isTemporary:!0,createdAt:l,updatedAt:l}}async createTempSuiteFromRequest(e,t){let n=this.collectionService.getCollection(e);if(!n){console.error(`[TestSuiteService] Collection not found: ${e}`);return}let s=[];this.extractRequestsFromCollection(n,e,n.name,"",s);let i=s.find(u=>u.requestId===t);if(!i){console.error(`[TestSuiteService] Request not found: ${t} in collection: ${e}`);return}let a={type:"for",name:"Performance Loop (100 iterations)",init:'hf.variables.set("__i", 0)',loopCondition:'hf.variables.get("__i") < 100',update:'hf.variables.set("__i", hf.variables.get("__i") + 1)',maxIterations:100,nodes:[{type:"request",name:i.description||i.name,request:i,enabled:!0}],enabled:!0},c=Date.now();return{id:`temp-perf-${e}-${t}`,name:`${i.name} \u2014 Performance Test`,nodes:[a],config:{...Ht},isTemporary:!0,createdAt:c,updatedAt:c}}slugifyFolderPath(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}async saveTempSuite(e,t){let n=Date.now(),s=xt.join(this.suitesDir,e.id),i={...e,id:le(t),name:t,isTemporary:!1,createdAt:n,updatedAt:n},o=xt.join(this.suitesDir,i.id);return ue.existsSync(s)&&(ue.existsSync(o)&&ue.rmSync(o,{recursive:!0,force:!0}),ue.renameSync(s,o)),await this.saveSuiteToDisk(i),this.suites.set(i.id,i),i}getAllAvailableRequests(){let e=[],t=this.collectionService.getAllCollections();for(let n of t)this.extractRequestsFromCollection(n,n.id,n.name,"",e);return e}extractRequestsFromCollection(e,t,n,s,i){if(e.requests)for(let o of e.requests)i.push({collectionId:t,collectionName:n,requestId:o.id,name:o.name||"Unnamed Request",method:o.method||"GET",folderPath:s});if(e.items)for(let o of e.items)if(o.items||o.folders||o.requests){let a=s?`${s}/${$e(o.name)}`:$e(o.name);this.extractRequestsFromCollection(o,t,n,a,i)}else i.push({collectionId:t,collectionName:n,requestId:o.id,name:o.name||"Unnamed Request",method:o.method||"GET",folderPath:s});if(e.folders)for(let o of e.folders){let a=s?`${s}/${$e(o.name)}`:$e(o.name);this.extractRequestsFromCollection(o,t,n,a,i)}}async saveSuiteToDisk(e){this.ensureSuitesDir();let t=`${e.id}.suite.json`,n=xt.join(this.suitesDir,t),s=`${n}.tmp-${process.pid}-${Date.now()}`,i={$schema:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/suite.schema.json",id:e.id,name:e.name,description:e.description,scripts:e.scripts,nodes:Array.isArray(e.nodes)?e.nodes:[],config:e.config??{...Ht},isTemporary:e.isTemporary,ai_generated:e.ai_generated,derived_from:e.derived_from,createdAt:e.createdAt??Date.now(),updatedAt:e.updatedAt??Date.now()},o=JSON.stringify(i,null,2);ue.writeFileSync(s,o,"utf-8"),ue.renameSync(s,n)}}});function xp(r){return{timeout:r?.timeout??ze.timeout,followRedirects:r?.followRedirects??ze.followRedirects,followOriginalMethod:r?.followOriginalMethod??ze.followOriginalMethod,followAuthHeader:r?.followAuthHeader??ze.followAuthHeader,maxRedirects:r?.maxRedirects??ze.maxRedirects,strictSSL:r?.strictSSL??ze.strictSSL,decompress:r?.decompress??ze.decompress,includeCookies:r?.includeCookies??ze.includeCookies,tls:r?.tls??ze.tls,certificates:r?.certificates??ze.certificates}}var wp=k(()=>{"use strict";Ns()});import ny from"fs";import Rp from"path";function ry(r){return Buffer.isBuffer(r)?r:Array.isArray(r)?Buffer.concat(r):new Uint8Array(r)}function Io(r,e,t){if(!r)return;let n=Rp.isAbsolute(r)?r:Rp.resolve(e||process.cwd(),r);try{return ny.readFileSync(n)}catch(s){throw new Error(`[NodeWebSocketClient] Failed to read ${t} file at ${n}: ${s?.message||"Unknown error"}`)}}async function sy(){return(await import("ws")).WebSocket}function Cp(){let r=new Error("WebSocket connection cancelled");return r.name="AbortError",r}var vl,pn,ui,bl=k(()=>{"use strict";wp();vl=class{constructor(e){this.socket=e;e.on("upgrade",t=>{if(t&&t.headers&&typeof t.headers=="object"){let n={};for(let[s,i]of Object.entries(t.headers))typeof i=="string"?n[s]=i:Array.isArray(i)&&(n[s]=i.join(", "));this._handshakeHeaders=n}}),e.on("message",(t,n)=>{let s={data:n?ry(t):t.toString(),isBinary:n};for(let i of this.frameListeners)try{i(s)}catch{}}),e.on("close",(t,n)=>{let s={code:t,reason:n.toString(),wasClean:t!==1006&&t!==1015};for(let i of this.closeListeners)try{i(s)}catch{}}),e.on("error",t=>{for(let n of this.errorListeners)try{n(t)}catch{}})}socket;frameListeners=new Set;closeListeners=new Set;errorListeners=new Set;_handshakeHeaders;get state(){switch(this.socket.readyState){case pn.CONNECTING:return"connecting";case pn.OPEN:return"open";case pn.CLOSING:return"closing";default:return"closed"}}get negotiatedProtocol(){return this.socket.protocol}get handshakeHeaders(){return this._handshakeHeaders}send(e){return this.socket.readyState!==pn.OPEN?Promise.reject(new Error("WebSocket is not open")):new Promise((t,n)=>{this.socket.send(e,{binary:typeof e!="string"},s=>{s?n(s):t()})})}close(e=1e3,t=""){return this.socket.readyState===pn.CLOSED?Promise.resolve():this.socket.readyState===pn.CONNECTING?(this.socket.terminate(),Promise.resolve()):new Promise(n=>{let s,i=()=>{s&&clearTimeout(s),n()};this.socket.once("close",i),s=setTimeout(()=>{this.socket.terminate(),i()},5e3),this.socket.readyState!==pn.CLOSING&&this.socket.close(e,t)})}onFrame(e){return this.frameListeners.add(e),{dispose:()=>this.frameListeners.delete(e)}}onClose(e){return this.closeListeners.add(e),{dispose:()=>this.closeListeners.delete(e)}}onError(e){return this.errorListeners.add(e),{dispose:()=>this.errorListeners.delete(e)}}dispose(){this.socket.readyState!==pn.CLOSED&&this.close(1e3,"Disposed").catch(()=>{this.socket.terminate()})}},pn={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},ui=class{constructor(e={}){this.options=e}options;async connect(e){if(e.signal?.aborted)throw Cp();let t=xp(e.settings),n=await sy(),s=this.buildTransportOptions(e,t);return new Promise((i,o)=>{let a=!1,c,l=()=>{e.signal?.removeEventListener("abort",d)},u=p=>{a||(a=!0,l(),o(p))},d=()=>{c&&c.terminate(),u(Cp())};try{c=new n(e.url,e.protocols&&e.protocols.length>0?e.protocols:void 0,s)}catch(p){u(p instanceof Error?p:new Error(String(p)));return}e.signal?.addEventListener("abort",d,{once:!0}),c.once("open",()=>{a||(a=!0,l(),i(new vl(c)))}),c.once("error",p=>{u(p)}),c.once("unexpected-response",(p,m)=>{c.terminate(),u(new Error(`WebSocket handshake failed: HTTP ${m.statusCode} ${m.statusMessage||""}`.trim()))})})}buildTransportOptions(e,t){let n=t.tls,s={headers:e.headers,handshakeTimeout:t.timeout>0?t.timeout:void 0,maxPayload:e.maxPayloadBytes&&e.maxPayloadBytes>0?e.maxPayloadBytes:void 0,rejectUnauthorized:t.strictSSL},i=Io(n?.caPath,this.options.basePath,"CA certificate");i&&(s.ca=i);let o=Io(n?.certPath,this.options.basePath,"client certificate");o&&(s.cert=o);let a=Io(n?.keyPath,this.options.basePath,"client private key");a&&(s.key=a);let c=Io(n?.pfxPath,this.options.basePath,"client pfx");return c&&(s.pfx=c),n?.passphrase&&(s.passphrase=n.passphrase),n?.servername&&(s.servername=n.servername),s}}});import*as To from"socket.io-client";function iy(r){if(typeof r!="string")return r;let e=r.trim();if(e!=="")try{return JSON.parse(e)}catch{return e}}async function ay(){return{io:To.io??To.default?.io}}var oy,Jr,Sl,xl,wl=k(()=>{"use strict";oy=new Set(["connect","connect_error","disconnect","disconnecting","newListener","removeListener"]),Jr=class{async connect(e){let t=await ay(),n=e.namespace?.trim(),s=e.url.endsWith("/")?e.url.slice(0,-1):e.url,i=n?n.startsWith("/")?n.slice(1):n:"",o=n&&n!=="/"?`${s}/${i}`:e.url,a=e.transports&&e.transports.length>0?e.transports:e.clientVersion==="2"||e.clientVersion==="3"?["polling","websocket"]:["websocket"];return new Promise((c,l)=>{let u=t.io(o,{transports:a,extraHeaders:e.headers,path:e.path,timeout:e.timeout,reconnection:(e.reconnectionAttempts??0)>0,reconnectionAttempts:e.reconnectionAttempts,reconnectionDelay:e.reconnectionDelay,auth:iy(e.auth)}),d=!1,p=m=>{d||(d=!0,u.disconnect(),l(m))};u.once("connect",()=>{d||(d=!0,c(new xl(u,e.listeners)))}),u.once("connect_error",m=>{p(m instanceof Error?m:new Error(String(m)))})})}},Sl=class extends Jr{},xl=class{constructor(e,t){this.socket=e;let n=(c,...l)=>{if(!oy.has(c))for(let u of[...this.eventListeners])u({event:c,args:l})},s=()=>{for(let c of[...this.connectListeners])c()},i=c=>{for(let l of[...this.disconnectListeners])l(c)},o=()=>{for(let c of[...this.reconnectFailedListeners])c()},a=c=>{for(let l of[...this.errorListeners])l(c)};this.socket.on("connect",s),this.socket.on("disconnect",i),this.socket.on("connect_error",a),this.socket.io.on("reconnect_failed",o),this.socket.onAny(n),this.disposal.push({dispose:()=>{this.socket.off("connect",s),this.socket.off("disconnect",i),this.socket.off("connect_error",a),this.socket.io.off("reconnect_failed",o),this.socket.offAny(n)}})}socket;eventListeners=new Set;connectListeners=new Set;disconnectListeners=new Set;reconnectFailedListeners=new Set;errorListeners=new Set;disposal=[];disposed=!1;get connected(){return this.socket.connected}get id(){return this.socket.id}async send(e,t,n=!1){let s=e?.trim()||"message";return n?new Promise(i=>{this.socket.emit(s,...t,(...o)=>{i(o)})}):(this.socket.emit(s,...t),Promise.resolve(void 0))}close(){this.socket.disconnect()}onEvent(e){return this.eventListeners.add(e),{dispose:()=>this.eventListeners.delete(e)}}onConnect(e){return this.connectListeners.add(e),{dispose:()=>this.connectListeners.delete(e)}}onDisconnect(e){return this.disconnectListeners.add(e),{dispose:()=>this.disconnectListeners.delete(e)}}onReconnectFailed(e){return this.reconnectFailedListeners.add(e),{dispose:()=>this.reconnectFailedListeners.delete(e)}}onError(e){return this.errorListeners.add(e),{dispose:()=>this.errorListeners.delete(e)}}dispose(){if(!this.disposed){this.disposed=!0,this.socket.disconnect();for(let e of this.disposal)e.dispose();this.disposal.length=0,this.eventListeners.clear(),this.connectListeners.clear(),this.disconnectListeners.clear(),this.reconnectFailedListeners.clear(),this.errorListeners.clear()}}}});var $,Oo=k(()=>{"use strict";$={Config:Symbol.for("IConfigService"),Console:Symbol.for("IConsoleService"),EnvironmentConfig:Symbol.for("IEnvironmentConfigService"),Collection:Symbol.for("ICollectionService"),HttpRequest:Symbol.for("IHttpRequestService"),HttpClient:Symbol.for("IHttpClient"),WebSocketClient:Symbol.for("IWebSocketClient"),SocketIoClient:Symbol.for("ISocketIoClient"),Cookie:Symbol.for("ICookieService"),RequestHistory:Symbol.for("IRequestHistoryService"),TestSuite:Symbol.for("ITestSuiteService"),UrlBuilder:Symbol.for("IUrlBuilder"),RequestPreprocessor:Symbol.for("IRequestPreprocessor"),RequestPreparer:Symbol.for("IRequestPreparer"),InterceptorChain:Symbol.for("IInterceptorChain"),ScriptExecutor:Symbol.for("IScriptExecutor"),DataFileParser:Symbol.for("IDataFileParser"),CollectionRequestExecutor:Symbol.for("ICollectionRequestExecutor"),WorkspaceFolder:Symbol.for("WorkspaceFolder"),PersistentCookieJar:Symbol.for("PersistentCookieJar"),OAuth2TokenManager:Symbol.for("IOAuth2TokenManager"),GraphQLSchemaService:Symbol.for("IGraphQLSchemaService"),SchemaInferrer:Symbol.for("SchemaInferrer"),HistoryAnalyzer:Symbol.for("HistoryAnalyzer"),ScriptAnalyzer:Symbol.for("ScriptAnalyzer"),SchemaInferenceService:Symbol.for("SchemaInferenceService"),OpenApiExporter:Symbol.for("OpenApiExporter"),OpenApiImporter:Symbol.for("OpenApiImporter"),SecretResolverRegistry:Symbol.for("SecretResolverRegistry")}});import*as kp from"path";function $o(r,e){let{workspaceFolder:t,fileWatcherFactory:n,notificationService:s,workspaceStore:i,globalStore:o,secretStore:a,browserService:c,applicationInfo:l,consoleService:u}=e;r.registerValue($.WorkspaceFolder,t),r.registerSingleton($.Config,()=>new an(t,n,s)),r.registerSingleton($.Console,()=>u??cy),r.registerSingleton($.EnvironmentConfig,p=>new Vs(t,i,p.resolve($.Config),n,a,e.persistOverrides??!0)),r.registerSingleton($.Cookie,()=>new Hs(o)),r.registerSingleton($.Collection,p=>new Ls(p.resolve($.Config),n)),r.registerSingleton($.TestSuite,p=>new li(p.resolve($.Collection),p.resolve($.Config))),r.registerSingleton($.HttpClient,p=>{let m=p.resolve($.Config),f=p.resolve($.EnvironmentConfig);return new Bn(()=>f.getResolvedConfig().request,t,()=>f.getResolvedConfig()?.proxy??null)}),r.registerSingleton($.WebSocketClient,()=>new ui({basePath:t})),r.registerSingleton($.SocketIoClient,()=>new Jr),r.registerSingleton($.UrlBuilder,()=>new yt),r.registerSingleton($.InterceptorChain,()=>new Nt),r.registerSingleton($.HttpRequest,p=>new Ft(p.resolve($.UrlBuilder),p.resolve($.InterceptorChain),p.resolve($.HttpClient))),r.registerSingleton($.RequestPreprocessor,()=>new Un),r.registerSingleton($.RequestHistory,p=>{let m=p.resolve($.EnvironmentConfig);return new Ys(m.getHistoriesPath(),kp.join(m.getRootPath(),"shared-histories"))}),a&&c&&r.registerSingleton($.OAuth2TokenManager,p=>new Ds(a,c,p.resolve($.EnvironmentConfig),p.resolve($.HttpRequest))),r.registerSingleton($.GraphQLSchemaService,p=>new Qs(p.resolve($.HttpClient))),r.registerSingleton($.SecretResolverRegistry,p=>new ci(p.resolve($.Config)));let d=l??{name:"HttpForge",version:"0.0.0"};r.registerSingleton($.RequestPreparer,p=>new Ks(p.resolve($.EnvironmentConfig),p.resolve($.HttpRequest),p.resolve($.RequestPreprocessor),p.has($.OAuth2TokenManager)?p.resolve($.OAuth2TokenManager):void 0,d,p.resolve($.SecretResolverRegistry))),r.registerSingleton($.ScriptExecutor,p=>{let m=p.resolve($.Config);return new _t(p.resolve($.HttpRequest),m.getModulePaths(),p.resolve($.SecretResolverRegistry),m.getScriptScope(),m.getScriptTimeout())}),r.registerSingleton($.DataFileParser,()=>new zn),r.registerSingleton($.CollectionRequestExecutor,p=>new Dt(p.resolve($.HttpRequest),p.resolve($.ScriptExecutor),p.resolve($.EnvironmentConfig),p.resolve($.RequestPreparer),"",void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,p.resolve($.WebSocketClient),p.resolve($.SocketIoClient))),r.registerSingleton($.PersistentCookieJar,p=>new Bs(p.resolve($.Cookie))),r.registerSingleton($.SchemaInferrer,()=>new ln),r.registerSingleton($.HistoryAnalyzer,p=>new Hr(p.resolve($.RequestHistory),p.resolve($.SchemaInferrer))),r.registerSingleton($.ScriptAnalyzer,()=>new Vr),r.registerSingleton($.SchemaInferenceService,p=>new dn(p.resolve($.HistoryAnalyzer),p.resolve($.ScriptAnalyzer),p.resolve($.SchemaInferrer))),r.registerSingleton($.OpenApiExporter,p=>new un(p.resolve($.Collection),p.resolve($.EnvironmentConfig),p.resolve($.SchemaInferenceService))),r.registerSingleton($.OpenApiImporter,p=>new Lt(p.resolve($.Collection),p.resolve($.EnvironmentConfig)))}var cy,Rl=k(()=>{"use strict";Pc();Fc();yo();_c();Dc();Lc();Gs();Vc();zc();Zc();Cs();ks();Ns();fo();Er();Yc();Co();ko();Eo();So();al();mo();Is();ml();yl();bl();wl();Oo();cy={log:()=>{},trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},logBatch:()=>{},logRawLines:()=>{},show:()=>{},clear:()=>{},dispose:()=>{}}});function Ep(){return Qn.instance}var Qn,Cl=k(()=>{"use strict";Oo();Qn=class r{static _instance;services=new Map;primitives=new Map;constructor(){}static get instance(){return r._instance||(r._instance=new r),r._instance}static createFresh(){return new r}static reset(){r._instance&&r._instance.clear(),r._instance=void 0}registerValue(e,t){return this.primitives.set(e,t),this}registerSingleton(e,t){return this.services.set(e,{factory:t,singleton:!0}),this}registerTransient(e,t){return this.services.set(e,{factory:t,singleton:!1}),this}registerInstance(e,t){return this.services.set(e,{factory:()=>t,singleton:!0,instance:t}),this}resolve(e){if(this.primitives.has(e))return this.primitives.get(e);let t=this.services.get(e);if(!t)throw new Error(`Service not registered: ${e.toString()}`);return t.singleton?(t.instance||(t.instance=t.factory(this)),t.instance):t.factory(this)}has(e){return this.services.has(e)||this.primitives.has(e)}dispose(){for(let e of this.services.values())if(e.singleton&&e.instance){let t=e.instance;if(typeof t.dispose=="function")try{t.dispose()}catch{}}this.clear()}clear(){this.services.clear(),this.primitives.clear()}get config(){return this.resolve($.Config)}get console(){return this.resolve($.Console)}get environmentConfig(){return this.resolve($.EnvironmentConfig)}get collection(){return this.resolve($.Collection)}get httpRequest(){return this.resolve($.HttpRequest)}get httpClient(){return this.resolve($.HttpClient)}get webSocketClient(){return this.resolve($.WebSocketClient)}get socketIoClient(){return this.resolve($.SocketIoClient)}get cookie(){return this.resolve($.Cookie)}get requestHistory(){return this.resolve($.RequestHistory)}get dataFileParser(){return this.resolve($.DataFileParser)}get scriptExecutor(){return this.resolve($.ScriptExecutor)}get requestPreparer(){return this.resolve($.RequestPreparer)}get persistentCookieJar(){return this.resolve($.PersistentCookieJar)}get oauth2TokenManager(){return this.has($.OAuth2TokenManager)?this.resolve($.OAuth2TokenManager):void 0}get graphqlSchemaService(){return this.resolve($.GraphQLSchemaService)}get testSuite(){return this.resolve($.TestSuite)}}});import*as Yn from"fs";import*as Wr from"path";function Bt(r){return{kind:"collection",snapshot:()=>({kind:"collection",heading:"Collection",body:Ap(r),generatedAt:Date.now()}),freshness:()=>r.items.length>0?"fresh":"stale"}}function st(r,e){return{kind:"collection",snapshot:()=>({kind:"collection",heading:"Request",body:kl(r,e),generatedAt:Date.now()}),freshness:()=>kl(r,e)?"fresh":"stale"}}function it(r){return{kind:"workspace-knowledge",snapshot:()=>({kind:"workspace-knowledge",heading:"Business Knowledge",body:di(r),generatedAt:Date.now()}),freshness:()=>di(r)?"fresh":"stale"}}function No(r,e){return{kind:"run-results",snapshot:()=>({kind:"run-results",heading:"Test Results",body:Pp(r,e),generatedAt:Date.now()}),freshness:()=>{if(!e||!r)return"stale";let t=r.get(e);return t?t.status==="running"?"stale":"fresh":"stale"}}}function py(r){_o.push(r)}function fy(){_o.length=0}function my(){return _o.slice()}function kl(r,e){let t=[],n=e&&e!=="(root)"?`${e} / ${r.name}`:r.name;return r.description?.trim()&&t.push(`Description: ${Zn(r.description,400)}`),r.doc?.trim()&&t.push(`Docs (doc.md): ${Zn(r.doc,ly)}`),r.operationId&&t.push(`OpenAPI operationId: ${r.operationId}`),r.summary?.trim()&&t.push(`OpenAPI summary: ${Zn(r.summary,200)}`),r.tags?.length&&t.push(`OpenAPI tags: ${r.tags.join(", ")}`),r.deprecated&&t.push("Deprecated: true"),r.responseSchema&&t.push(`Response schema: ${Zn(JSON.stringify(r.responseSchema),400)}`),r.bodySchema&&t.push(`Request body schema: ${Zn(JSON.stringify(r.bodySchema),300)}`),r.settings?.timeout!==void 0&&t.push(`Timeout: ${r.settings.timeout}ms`),t.length===0?"":`[${r.method??"GET"} ${r.url??""}] ${n}
|
|
648
648
|
${t.join(`
|
|
649
649
|
`)}`}function Ap(r){let e=[];r.description?.trim()&&e.push(`Description: ${Zn(r.description,400)}`);let t=Object.keys(r.variables??{});t.length>0&&e.push(`Collection variables: ${t.join(", ")}`),r.auth?.type&&e.push(`Collection auth: ${r.auth.type}`);let n=[],s=(c,l)=>{for(let u of c)u.type==="request"?n.push({folderPath:l||"(root)",req:u}):u.type==="folder"&&u.items&&s(u.items,`${l}/${u.name}`.replace(/^\//,""))};if(s(r.items,""),n.length===0)return e.join(`
|
|
650
650
|
`);let i=new Set(n.map(c=>c.folderPath)),o=[...i].sort().map(c=>` ${c} (${n.filter(l=>l.folderPath===c).length} requests)`).join(`
|
|
651
651
|
`);e.push(`Requests: ${n.length} across ${i.size} folder(s)`),o&&e.push(`Folders:
|
|
652
652
|
${o}`);let a=n.reduce((c,l)=>(c[l.req.method??"GET"]=(c[l.req.method??"GET"]??0)+1,c),{});return e.push(`Methods: ${Object.entries(a).map(([c,l])=>`${c}(${l})`).join(", ")}`),e.join(`
|
|
653
|
-
`).slice(0,
|
|
653
|
+
`).slice(0,uy)}function di(r){if(!r||!Yn.existsSync(r))return"";let e=[],t=0,n=(i,o)=>{let a=Fo-t;if(a<=0)return;let c;try{c=Yn.readFileSync(o,"utf-8")}catch{return}c.trim()&&(e.push({title:i,body:Zn(c,Math.min(a,1500))}),t+=e[e.length-1].body.length)},s=Wr.join(r,".http-forge","knowledge");for(let i of hy(s)){if(t>=Fo)break;n(`Knowledge: ${Wr.relative(r,i)}`,i)}for(let i of["README.md","AGENTS.md"]){if(t>=Fo)break;n(`Workspace: ${i}`,Wr.join(r,i))}return e.length===0?"":e.map(i=>`### ${i.title}
|
|
654
654
|
${i.body}`).join(`
|
|
655
655
|
|
|
656
656
|
`).slice(0,Fo)}function Pp(r,e){if(!e||!r)return"";let t=r.get(e);if(!t)return"";if(t.status==="running")return`Run ${e} is still in progress.`;let n=[`Run: ${t.suiteName||e} \u2014 ${t.status}`,`Result: ${t.summary.passed} passed / ${t.summary.failed} failed / ${t.summary.total} total`];t.error&&n.push(`Run error: ${t.error}`);let i=(t.allResults??[]).filter(o=>o.passed===!1||Array.isArray(o.assertions)&&o.assertions.some(a=>!a.passed));for(let o of i.slice(0,5)){let a=o.assertions?.filter(l=>!l.passed)??[],c=o.responseStatus??o.status;n.push(`- ${o.name??"request"}: status ${c??"?"}`+(a.length>0?` \u2014 ${a.map(l=>`"${l.name}"${l.message?`: ${l.message}`:""}`).join("; ")}`:o.error?` \u2014 ${o.error}`:""))}return i.length>5&&n.push(`\u2026 and ${i.length-5} more failures`),n.join(`
|
|
657
|
-
`).slice(0,
|
|
657
|
+
`).slice(0,dy)}function Ip(r){let e=[];return e.push(Bt(r.collection)),r.request&&e.push(st(r.request,r.requestFolderPath)),r.workspaceFolder&&e.push(it(r.workspaceFolder)),r.runStore&&r.runId&&e.push(No(r.runStore,r.runId)),e}function qp(r){let e=[];for(let t of[...r,..._o]){let n=t.snapshot();n.body&&e.push({heading:n.heading,body:n.body})}return e.length===0?"":e.map(t=>`## ${t.heading}
|
|
658
658
|
${t.body}`).join(`
|
|
659
659
|
|
|
660
|
-
`)}function pi(r){return Array.isArray(r)?qp(r):qp(Ip(r))}function Zn(r,e){return!r||r.length<=e?r:r.slice(0,e)+`\u2026 (truncated, ${r.length-e} chars omitted)`}function
|
|
660
|
+
`)}function pi(r){return Array.isArray(r)?qp(r):qp(Ip(r))}function Zn(r,e){return!r||r.length<=e?r:r.slice(0,e)+`\u2026 (truncated, ${r.length-e} chars omitted)`}function hy(r){if(!Yn.existsSync(r))return[];let e=[],t=n=>{let s;try{s=Yn.readdirSync(n,{withFileTypes:!0})}catch{return}for(let i of s){let o=Wr.join(n,i.name);i.isDirectory()?t(o):i.isFile()&&(i.name.endsWith(".md")||i.name.endsWith(".markdown"))&&e.push(o)}};return t(r),e}var ly,uy,Fo,dy,_o,Xn=k(()=>{"use strict";ly=1200,uy=800,Fo=4e3,dy=2500;_o=[]});function Ot(r){if(typeof r!="string"||r.trim()==="")return null;let e=r.trim();for(let s of[e,...yy(e)])try{return JSON.parse(s)}catch{}let t=/[[{]/g,n;for(;(n=t.exec(e))!==null;){let s=vy(e,n.index);if(s!==-1)try{return JSON.parse(e.slice(n.index,s))}catch{}}return null}async function ot(r,e={}){let t=e.attempts??3,n=e.baseDelayMs??250,s=e.isRetryable??(()=>!0),i;for(let o=0;o<t;o++)try{return await r()}catch(a){if(i=a,o===t-1||!s(a))throw a;await gy(n*2**o)}throw i}function gy(r){return new Promise(e=>setTimeout(e,r))}function yy(r){let e=[],t=/```(?:json)?\s*([\s\S]*?)```/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1].trim());return e}function vy(r,e){let t=r[e],n=t==="["?"]":"}",s=0,i=!1,o=!1;for(let a=e;a<r.length;a++){let c=r[a];if(i){o?o=!1:c==="\\"?o=!0:c==='"'&&(i=!1);continue}if(c==='"'){i=!0;continue}if(c===t)s++;else if(c===n&&(s--,s===0))return a+1}return-1}var er=k(()=>{"use strict"});function fi(r){return/\{\{[^}]+\}\}/.test(r)}function wt(r,e=16){return!!r&&r.length>=e&&!fi(r)}function Ut(r){return r.toUpperCase().replace(/[^A-Z0-9]/g,"_")}var Do,Mo,jo=k(()=>{"use strict";Do=new Set(["x-api-key","x-auth-token","x-access-token","x-token","x-secret","api-key","apikey","x-client-secret","x-rapidapi-key"]),Mo=new Set(["api_key","apikey","api-key","access_token","token","auth_token","client_id","client_secret","key","secret"])});function mi(r,e,t,n,s,i=10){let o=r.get(e);o||(o={varName:t,reason:n,occurrences:[],priority:i},r.set(e,o));let a=`${s.requestId}::${s.field}`;o.occurrences.some(c=>`${c.requestId}::${c.field}`===a)||o.occurrences.push(s)}function Lo(r,e=1){let t=X(r),n=new Map;for(let{request:i}of t){let o=a=>({requestId:i.id,requestName:i.name,field:a});for(let a of i.headers??[]){if(a.enabled===!1)continue;let c=a.key.toLowerCase(),l=a.value;if(c==="authorization"){let u=l.match(/^(bearer|basic|token|digest)\s+(.+)$/i);u&&wt(u[2])?mi(n,u[2],`${u[1].toUpperCase()}_TOKEN`,`Authorization ${u[1]} token`,o(`header:${a.key}`),1):wt(l)&&mi(n,l,"AUTH_TOKEN","Authorization header value",o(`header:${a.key}`),1)}else Do.has(c)&&wt(l)?mi(n,l,Ut(a.key),`Sensitive header: ${a.key}`,o(`header:${a.key}`),2):wt(l,20)&&!l.includes(" ")&&/^[A-Za-z0-9+/=_.-]+$/.test(l)&&mi(n,l,Ut(a.key)||"HEADER_VALUE",`Long opaque value in header: ${a.key}`,o(`header:${a.key}`),5)}for(let a of i.query??[])a.enabled!==!1&&Mo.has(a.key.toLowerCase())&&wt(a.value)&&mi(n,a.value,Ut(a.key),`Sensitive query param: ${a.key}`,o(`query:${a.key}`),2)}let s=new Map;for(let{request:i}of t)if(!(!i.url||fi(i.url)))try{let o=new URL(i.url);if(!["localhost","127.0.0.1","0.0.0.0","::1"].includes(o.hostname)){let c=`${o.protocol}//${o.host}`,l=s.get(c)??[];l.push({requestId:i.id,requestName:i.name,field:"url"}),s.set(c,l)}}catch{}for(let[i,o]of s)o.length>=Math.max(e,2)&&!n.has(i)&&n.set(i,{varName:"BASE_URL",reason:`Shared base URL across ${o.length} requests`,occurrences:o,priority:3});return[...n.entries()].filter(([,i])=>i.occurrences.length>=e).sort((i,o)=>i[1].priority-o[1].priority||i[0].localeCompare(o[0])).map(([i,o])=>({varName:o.varName,value:i,reason:o.reason,occurrences:o.occurrences}))}function El(r,e){let t={};return Tp(r,e,t),t}function Tp(r,e,t){for(let n of r){if(n.type==="folder"){n.items&&Tp(n.items,e,t);continue}let s=n;for(let i of e){let o=`{{${i.varName}}}`;s.url?.includes(i.value)&&(s.url=s.url.split(i.value).join(o),t[i.varName]=(t[i.varName]??0)+1);for(let a of s.headers??[]){let c=a.value.match(/^(bearer|basic|token|digest)\s+(.+)$/i);c&&c[2]===i.value?(a.value=`${c[1]} ${o}`,t[i.varName]=(t[i.varName]??0)+1):a.value===i.value&&(a.value=o,t[i.varName]=(t[i.varName]??0)+1)}for(let a of s.query??[])a.value===i.value&&(a.value=o,t[i.varName]=(t[i.varName]??0)+1)}}}var ql=k(()=>{"use strict";tt();jo()});function by(r){return r.replace(/^\{\{\w+\}\}/,"").replace(/^\//,"/").replace(/:([a-zA-Z_]\w*)/g,"{$1}")}function Op(r){return!r||r.type==="none"||r.type==="inherit"||!r.type?void 0:{required:!0,type:r.type==="bearer"?"jwt":r.type==="apikey"?"apiKey":r.type}}function Sy(r){let e=[];for(let[t,n]of Object.entries(r.params??{}))e.push({name:t,location:"path",required:!0,type:typeof n=="string"?"string":n.type});for(let t of r.query??[])t.enabled!==!1&&e.push({name:t.key,location:"query",type:t.type,required:t.required,description:t.description});return e}function xy(r){let e=[];for(let[t,n]of Object.entries(r.responseSchema?.responses??{}))e.push({statusCode:Number(t),body:n.contentType&&n.schema?{type:n.contentType.split("/")[0],schema:n.schema}:n.schema?{schema:n.schema}:void 0});return e}function Al(r){let e=[],t=Op(r.auth),n=s=>{for(let i of s){if(i.type==="folder"){n(i.items??[]);continue}let o=i,a=by(o.url),c=Op(o.auth),l=o.auth?.type==="none"?void 0:c??t;e.push({id:o.id,framework:"unknown",method:o.method||"GET",pathExpression:a,resolvedPath:a,confidence:"high",source:{filePath:"design-from-intent",line:0,symbolName:o.name},description:o.description,tags:o.tags,requestBody:o.bodySchema?.schema?{type:"json",schema:o.bodySchema.schema}:void 0,params:Sy(o),responses:xy(o),auth:l})}};return n(r.items),e}var Pl=k(()=>{"use strict"});function Il(r,e={}){let t=e.baseUrl||"http://localhost:3000",n=e.collectionName||"Designed API",s=e.workspaceKnowledge?`
|
|
661
661
|
|
|
662
662
|
=== Workspace context ===
|
|
663
663
|
${e.workspaceKnowledge}
|
|
@@ -687,8 +687,8 @@ Requirements:
|
|
|
687
687
|
entry (e.g. bearerAuth, http/bearer) and apply a global "security" array.
|
|
688
688
|
- Do not invent unrelated endpoints; keep the surface focused on the intent.${s}
|
|
689
689
|
|
|
690
|
-
Now output the OpenAPI JSON document for the intent.`}var Tl=k(()=>{"use strict"});function tr(r){let e=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"suite",t=0;for(let n of r)t=t*31+n.charCodeAt(0)|0;return`${e}_${(t>>>0).toString(36).slice(0,8)}`}function fn(r,e){let t=e.name??"Generated from discovery",n=[],s=[],i=e.folderPath??"";for(let c of r){let l=c.source?.symbolName||`${c.method||"GET"} ${c.pathExpression}`,u=c.responses?.[0]?.statusCode??200,d=["const code = lastResult?.response?.status || 0;",`pm.test('status is ${u}', function () {`,` pm.expect(code).to.eq(${u});`,"});"];e.assertBodySchema&&c.responses?.[0]?.body?.schema&&c.responses[0].body.schema?.type==="array"&&d.push("pm.test('response body is a JSON array', function () {"," const body = (() => { try { return JSON.parse(lastResult?.response?.body || '[]'); } catch { return null; } })();"," pm.expect(Array.isArray(body)).to.eq(true);","});"),n.push({type:"request",name:l,request:{collectionId:e.collectionId,collectionName:e.collectionName,requestId:c.id||l,name:l,method:c.method||"GET",folderPath:i,enabled:!0,description:`Generated from ${c.framework} endpoint (confidence: ${c.confidence}).`},postResponseScript:d}),s.push({endpointId:c.id,requestName:l,method:c.method||"GET",path:c.pathExpression})}let o=Date.now();return{suite:{id:e.id??tr(t),name:t,description:"Auto-generated from source-code discovery (Phase 2a).",nodes:n,config:{...Ht},ai_generated:!0,derived_from:r.map(c=>c.id).filter(Boolean),createdAt:o,updatedAt:o},derived:s}}function Gr(r,e){let t=e.name??"discovered-api-flow",n=[];n.push("/**"),n.push(` * ${t} \u2014 auto-generated from source-code discovery (Phase 2a L4).`),n.push(" * ai_generated: true"),n.push(` * derived_from: ${r.map(s=>s.id).filter(Boolean).join(", ")||"(none)"}`),n.push(" */"),n.push("export default async function (f) {");for(let s of r){let i=e.requestPathOf?e.requestPathOf(s):
|
|
691
|
-
`)}function
|
|
690
|
+
Now output the OpenAPI JSON document for the intent.`}var Tl=k(()=>{"use strict"});function tr(r){let e=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"suite",t=0;for(let n of r)t=t*31+n.charCodeAt(0)|0;return`${e}_${(t>>>0).toString(36).slice(0,8)}`}function fn(r,e){let t=e.name??"Generated from discovery",n=[],s=[],i=e.folderPath??"";for(let c of r){let l=c.source?.symbolName||`${c.method||"GET"} ${c.pathExpression}`,u=c.responses?.[0]?.statusCode??200,d=["const code = lastResult?.response?.status || 0;",`pm.test('status is ${u}', function () {`,` pm.expect(code).to.eq(${u});`,"});"];e.assertBodySchema&&c.responses?.[0]?.body?.schema&&c.responses[0].body.schema?.type==="array"&&d.push("pm.test('response body is a JSON array', function () {"," const body = (() => { try { return JSON.parse(lastResult?.response?.body || '[]'); } catch { return null; } })();"," pm.expect(Array.isArray(body)).to.eq(true);","});"),n.push({type:"request",name:l,request:{collectionId:e.collectionId,collectionName:e.collectionName,requestId:c.id||l,name:l,method:c.method||"GET",folderPath:i,enabled:!0,description:`Generated from ${c.framework} endpoint (confidence: ${c.confidence}).`},postResponseScript:d}),s.push({endpointId:c.id,requestName:l,method:c.method||"GET",path:c.pathExpression})}let o=Date.now();return{suite:{id:e.id??tr(t),name:t,description:"Auto-generated from source-code discovery (Phase 2a).",nodes:n,config:{...Ht},ai_generated:!0,derived_from:r.map(c=>c.id).filter(Boolean),createdAt:o,updatedAt:o},derived:s}}function Gr(r,e){let t=e.name??"discovered-api-flow",n=[];n.push("/**"),n.push(` * ${t} \u2014 auto-generated from source-code discovery (Phase 2a L4).`),n.push(" * ai_generated: true"),n.push(` * derived_from: ${r.map(s=>s.id).filter(Boolean).join(", ")||"(none)"}`),n.push(" */"),n.push("export default async function (f) {");for(let s of r){let i=e.requestPathOf?e.requestPathOf(s):wy(s),o=s.responses?.[0]?.statusCode??200,c=`${s.method||"GET"} ${s.pathExpression}`;n.push(" {"),n.push(` // ${c}`),n.push(` const res = await f.send('${i.replace(/'/g,"\\'")}');`),n.push(` f.expect(res.status).toBe(${o});`),n.push(" }"),n.push("")}return n.push("}"),n.push(""),n.join(`
|
|
691
|
+
`)}function wy(r){return r.id&&/^[a-zA-Z0-9_-]+_[a-zA-Z0-9]{8,}$/.test(r.id)?`#${r.id}`:r.source?.symbolName??`${r.method||"GET"} ${r.pathExpression}`}var Ho=k(()=>{"use strict";gl()});function ky(r){return r.auth?.required?!0:(r.middleware??[]).some(e=>Cy.test(e.name))}function Ey(r){let e=r.split("/").filter(Boolean);if(e.length===0)return;let t=e[e.length-1];if(/^\{.*\}$/.test(t)&&(e.pop(),e.length===0))return;let n=e[e.length-1];if(!/^\{.*\}$/.test(n))return n}function $p(r,e,t){let n=0,s=`${r}:${e}:${t}`;for(let i of s)n=n*31+i.charCodeAt(0)|0;return`${r}_${(n>>>0).toString(36).slice(0,10)}`}function Fp(r){return{endpointId:r.id,requestName:r.source?.symbolName||`${r.method||"GET"} ${r.pathExpression}`,method:r.method||"GET",path:r.pathExpression}}function Np(r){return{endpointId:r.id,requestName:r.source?.symbolName||`${r.method||"GET"} ${r.pathExpression}`,method:r.method||"GET",path:r.pathExpression}}function Uo(r,e,t){return{type:"request",name:r.source?.symbolName||`${r.method||"GET"} ${r.pathExpression}`,request:{collectionId:e.collectionId,collectionName:e.collectionName,requestId:r.id,name:r.source?.symbolName||`${r.method||"GET"} ${r.pathExpression}`,method:r.method||"GET",folderPath:e.folderPath??"",enabled:!0},...t?{postResponseScript:t}:{}}}function nr(r,e){let t=[],n=r.filter(a=>Ry.some(c=>c.test(a.pathExpression))),s=r.filter(ky);for(let a of n){let c=s.filter(p=>p.id!==a.id);if(c.length===0)continue;let l=Uo(a,e,["const body = (() => {"," try { return JSON.parse(lastResult?.response?.body || '{}'); } catch { return {}; }","})();","const token = body.token || body.access_token || body.id_token || body.jwt;",`if (token) pm.variables.set('${Bo}', token);`]),u=c.map(p=>Uo(p,e)),d=[l,{type:"if",if:`!!pm.variables.get('${Bo}')`,then:u}];t.push({id:$p("auth",a.pathExpression,Bo),kind:"auth",name:`${a.method} ${a.pathExpression} \u2192 protected endpoints`,confidence:"high",producer:Fp(a),dependents:c.map(Np),variableName:Bo,nodes:d})}let i=new Map;for(let a of r){let c=Ey(a.pathExpression);if(!c)continue;let l=i.get(c)??[];l.push(a),i.set(c,l)}let o=[];for(let[a,c]of i.entries()){let l=c.find(h=>h.method==="POST"),u=c.filter(h=>h.method!=="POST"&&/\{id\}/.test(h.pathExpression));if(!l||u.length===0)continue;let d=`${a.replace(/[^a-zA-Z0-9]/g,"_")}Id`,p=Uo(l,e,["const body = (() => {"," try { return JSON.parse(lastResult?.response?.body || '{}'); } catch { return {}; }","})();",`const id = body.id ?? body.${a}?.id;`,`if (id !== undefined) pm.variables.set('${d}', id);`]),m=u.map(h=>Uo(h,e)),f=[p,{type:"if",if:`pm.variables.get('${d}') !== undefined`,then:m}];o.push({id:$p("crud",l.pathExpression,d),kind:"crud",name:`Create ${a} \u2192 id-scoped operations`,confidence:"high",producer:Fp(l),dependents:u.map(Np),variableName:d,nodes:f})}return o.sort((a,c)=>a.name<c.name?-1:1),t.push(...o),t}var Ry,Bo,Cy,Vo=k(()=>{"use strict";Ry=[/(^|\/)(login|signin|token|oauth|auth|sessions?)(\/|$)/i,/token|jwt|bearer/i],Bo="authToken",Cy=/(auth|require|protect|token|jwt|guard|secured)/i});function _p(r){if(typeof r!="object"||r===null||Array.isArray(r))return"AI response is not a JSON object";let e=r,t=e.openapi;if(typeof t!="string"||!/^3\.0/.test(t))return`openapi field must be 3.0.x, got "${String(t)}"`;let n=e.paths;return typeof n!="object"||n===null||Array.isArray(n)?"paths object is missing":Object.keys(n).length===0?"paths object is empty (no endpoints designed)":null}function Dp(r,e,t,n){let s=[];s.push(`# ${e}`),s.push(""),s.push(`> Auto-generated from the intent: *${r}*`),s.push(""),s.push("## Endpoints"),s.push(""),s.push("| Method | Path | Name | Auth |"),s.push("| --- | --- | --- | --- |");for(let i of t){let o=i.source?.symbolName||i.pathExpression,a=i.auth?.required?"yes":"";s.push(`| ${i.method.toUpperCase()} | \`${i.pathExpression}\` | ${o} | ${a} |`)}if(s.push(""),n.length>0){s.push(`## Workflows (${n.length})`),s.push("");for(let i of n){s.push(`- **[${i.kind}] ${i.name}** (${i.confidence})`),s.push(` - Producer: \`${i.producer.method} ${i.producer.path}\``);for(let o of i.dependents)s.push(` - Depends on: \`${o.method} ${o.path}\``)}s.push("")}return s.push("## Generated artifacts"),s.push(""),s.push(`- \`${e}.suite.json\` \u2014 one request node per endpoint`),s.push(`- \`${e}.flow.js\` \u2014 runnable flow`),s.push("- OpenAPI document \u2014 round-trip export of the collection"),s.push(""),s.push("*ai_generated: true*"),s.push(""),s.join(`
|
|
692
692
|
`)}var hi,Ol=k(()=>{"use strict";er();Xn();Pl();Tl();Ho();Vo();hi=class{constructor(e,t,n){this.importer=e;this.exporter=t;this.aiProvider=n}importer;exporter;aiProvider;async designFromIntent(e,t={}){let n=t.workspaceFolder?di(t.workspaceFolder):"",s=await this.designSpec(e,t,n),i=await this.importer.importFromString(JSON.stringify(s),{collectionName:t.collectionName,environmentName:t.environmentName}),o=Al(i.collection),a=fn(o,{collectionId:i.collection.id,collectionName:i.collection.name,folderPath:t.suiteFolderPath,assertBodySchema:t.assertBodySchema,name:`${i.collection.name} \u2014 designed from intent`}),l=nr(o,{collectionId:i.collection.id,collectionName:i.collection.name,folderPath:t.suiteFolderPath}),u=Gr(o,{name:`${i.collection.name}-designed`}),d=await this.exporter.export(i.collection.id,{format:t.openapiFormat??"json",info:t.openapiInfo,environments:t.environmentName?[t.environmentName]:void 0}),p=Dp(e,i.collection.name,o,l);return{intent:e,collectionId:i.collection.id,collectionName:i.collection.name,environmentCreated:i.environmentCreated,endpoints:o,suite:a.suite,flow:u,workflows:l,openapi:d,docs:p,ai_generated:!0,derivedFrom:o.map(m=>m.id).filter(Boolean)}}async designSpec(e,t,n){let s=Il(e,{collectionName:t.collectionName,baseUrl:t.baseUrl,workspaceKnowledge:n}),i=await ot(()=>this.aiProvider.complete(s)),o=Ot(i),a=_p(o);if(o===null||a!==null)throw new Error(`AI architect could not produce a valid OpenAPI spec. ${a??"No JSON object found in the response."}`);return o}}});function yi(){let r=process.env.HTTP_FORGE_AI_PROVIDER?.toLowerCase();if(r==="anthropic"||!r&&process.env.ANTHROPIC_API_KEY&&!process.env.OPENAI_API_KEY){let e=process.env.ANTHROPIC_API_KEY;return e?new gi(e,process.env.ANTHROPIC_MODEL):null}return process.env.OPENAI_API_KEY?new zo(process.env.OPENAI_API_KEY,process.env.OPENAI_MODEL):process.env.ANTHROPIC_API_KEY?new gi(process.env.ANTHROPIC_API_KEY,process.env.ANTHROPIC_MODEL):null}var zo,gi,Jo=k(()=>{"use strict";zo=class{constructor(e,t="gpt-4o-mini"){this.apiKey=e;this.model=t}apiKey;model;async complete(e){let t=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.model,messages:[{role:"user",content:e}],temperature:0})});if(!t.ok){let s=await t.text();throw new Error(`OpenAI API error ${t.status}: ${s}`)}return(await t.json()).choices[0].message.content}},gi=class{constructor(e,t="claude-3-5-haiku-20241022"){this.apiKey=e;this.model=t}apiKey;model;async complete(e){let t=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:this.model,max_tokens:4096,messages:[{role:"user",content:e}]})});if(!t.ok){let s=await t.text();throw new Error(`Anthropic API error ${t.status}: ${s}`)}return(await t.json()).content[0].text}}});function Ue(r,e){let t={type:"string",description:r};return e.length>0&&(t.enum=[...e]),t}function Zo(r,e,t){let n=s=>Ue("Name of the collection to act on."+(s?"":" Optional."),e);return[{name:`${r}${x.listCollections}`,description:"List all available HTTP Forge collections (name, description, and request count). Call this first to discover what collections exist, then use list_folders, list_requests or run_* tools.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:!0}},{name:`${r}${x.listFolders}`,description:"List all folders in a collection with their full paths and request counts. Use this before run_folder to discover the exact folder path string to pass.",inputSchema:{type:"object",properties:{collection:n(!0)},required:["collection"]},annotations:{readOnlyHint:!0}},{name:`${r}${x.listRequests}`,description:"List the saved requests in a collection (name, HTTP method, folder, and description). Use this to find the exact request name before calling run_request. For large collections use the folder filter and offset/limit to page through results.",inputSchema:{type:"object",properties:{collection:n(!0),folder:{type:"string",description:'Optional folder path to filter by (e.g. "Auth").'},offset:{type:"number",description:"Zero-based index to start from (default: 0)."},limit:{type:"number",description:"Maximum number of results to return (default: 50, max: 200)."}},required:["collection"]},annotations:{readOnlyHint:!0}},{name:`${r}${x.searchRequests}`,description:"Search for requests across a collection by name, URL, method, or folder path. Returns matching requests with their folder location. Useful for large collections.",inputSchema:{type:"object",properties:{collection:n(!0),query:{type:"string",description:"Text to search for in request names, URLs, methods, and folder paths (case-insensitive)."}},required:["collection","query"]},annotations:{readOnlyHint:!0}},{name:`${r}${x.getRequest}`,description:"Get the full details of a single saved request: URL, method, headers, body, auth, and scripts. Use this to inspect a request before editing it, or to read a script before rewriting it.",inputSchema:{type:"object",properties:{collection:n(!0),request:{type:"string",description:"Request name or id. Use list_requests to find names."}},required:["collection","request"]},annotations:{readOnlyHint:!0}},{name:`${r}${x.getEnvironment}`,description:"Show the current environment variable values (merged initial + runtime pm.environment.set overrides). Use this to inspect variable state before running a folder, or to debug {{variable}} resolution failures.",inputSchema:{type:"object",properties:{environment:{type:"string",description:"Environment name to inspect (defaults to the currently selected environment)."}}},annotations:{readOnlyHint:!0}},{name:`${r}${x.setVariable}`,description:'Override an environment variable for the current session. In the VS Code extension the change is saved to VS Code workspace storage (survives restarts, but is not in the env JSON file and not source-controlled). In the standalone CLI/core runtime the change is in-memory only and lost when the server restarts. Use set_environment_variable with scope:"permanent" to write to the env JSON file (source-controlled, works in both runtimes).',inputSchema:{type:"object",properties:{key:{type:"string",description:"Variable name (the part inside {{...}})."},value:{type:"string",description:"New value to set."},environment:{type:"string",description:"Environment to update (defaults to the currently selected environment)."}},required:["key","value"]},annotations:{idempotentHint:!0}},{name:`${r}${x.getRunStatus}`,description:"Check whether an async run is still running, completed, or failed. Poll this after calling run_folder/run_collection/run_suite with async:true.",inputSchema:{type:"object",properties:{runId:{type:"string",description:"Run ID returned by an async run_* call."}},required:["runId"]},annotations:{readOnlyHint:!0}},{name:`${r}${x.getRunSummary}`,description:'Get the pass/fail summary of a completed async run (total, passed, failed counts). Use after get_run_status shows "completed". When failures are present the response includes a failedRequests array with full details (method, url, requestBody, status, responseBody, failedTests) and a _nextStep directive. You MUST follow the _nextStep directive immediately \u2014 analyze the failures and provide diagnosis without waiting for the user to ask.',inputSchema:{type:"object",properties:{runId:{type:"string",description:"Run ID returned by an async run_* call."}},required:["runId"]},annotations:{readOnlyHint:!0}},{name:`${r}${x.getFailedRequests}`,description:"Get the list of failed requests from a completed async run \u2014 the failures-first view. Never returns passing requests. Use this instead of get_run_summary when you need to see what broke.",inputSchema:{type:"object",properties:{runId:{type:"string",description:"Run ID returned by an async run_* call."},offset:{type:"number",description:"Zero-based index to start from (default: 0)."},limit:{type:"number",description:"Maximum failures to return (default: 20, max: 100)."}},required:["runId"]},annotations:{readOnlyHint:!0}},{name:`${r}${x.getRequestResult}`,description:"Get the full result (status, body, assertions, console output) for one specific request from an async run. Use after get_failed_requests to drill into a single failure.",inputSchema:{type:"object",properties:{runId:{type:"string",description:"Run ID returned by an async run_* call."},request:{type:"string",description:"Name of the request to look up."},iteration:{type:"number",description:"Iteration number (default: 1)."}},required:["runId","request"]},annotations:{readOnlyHint:!0}},{name:`${r}${x.cancelRun}`,description:'Request cancellation of an in-progress async run. Cancellation is best-effort: the currently-executing HTTP request completes normally, but no further requests in the run are started. The run status changes to "cancelled". Has no effect on runs that are already completed, failed, or cancelled.',inputSchema:{type:"object",properties:{runId:{type:"string",description:"Run ID returned by run_collection, run_folder, or run_suite with async:true."}},required:["runId"]},annotations:{idempotentHint:!0}},{name:`${r}${x.runRequest}`,description:"Run a single saved request. Pick the collection, then the request name within it.",inputSchema:{type:"object",properties:{collection:n(!0),request:{type:"string",description:"Name of the request to run. Use list_requests or search_requests to find names."},requestId:{type:"string",description:'ID of the request (from list_requests/search_requests). Preferred over "request" name when available \u2014 avoids ambiguity with duplicate names.'},...Wo.properties},required:["collection","request"]},annotations:{readOnlyHint:!1,openWorldHint:!0}},{name:`${r}${x.runFolder}`,description:"Run every request inside a folder of a collection.",inputSchema:{type:"object",properties:{collection:n(!0),folder:{type:"string",description:'Folder path within the collection (e.g. "Auth/Login").'},...Ko.properties},required:["collection","folder"]},annotations:{readOnlyHint:!1,openWorldHint:!0}},{name:`${r}${x.runCollection}`,description:"Run every request in a collection.",inputSchema:{type:"object",properties:{collection:n(!0),...Go.properties},required:["collection"]},annotations:{readOnlyHint:!1,openWorldHint:!0}},{name:`${r}${x.runSuite}`,description:"Run a saved test suite.",inputSchema:{type:"object",properties:{suite:Ue("Name of the test suite to run.",t),...Qo.properties},required:["suite"]},annotations:{readOnlyHint:!1,openWorldHint:!0}},{name:`${r}${x.createCollection}`,description:"Create a new empty collection.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Display name for the new collection."}},required:["name"]},annotations:{idempotentHint:!1}},{name:`${r}${x.renameCollection}`,description:"Rename an existing collection.",inputSchema:{type:"object",properties:{collection:n(!0),newName:{type:"string",description:"New display name for the collection."}},required:["collection","newName"]},annotations:{idempotentHint:!0}},{name:`${r}${x.deleteCollection}`,description:"Permanently delete a collection and all its contents. Set confirm:true to proceed.",inputSchema:{type:"object",properties:{collection:n(!0),confirm:{type:"boolean",description:"Must be true to confirm deletion."}},required:["collection","confirm"]},annotations:{destructiveHint:!0}},{name:`${r}${x.duplicateCollection}`,description:"Clone a collection under a new name (all folders, requests, and scripts are copied).",inputSchema:{type:"object",properties:{collection:n(!0),newName:{type:"string",description:"Name for the duplicated collection."}},required:["collection","newName"]},annotations:{idempotentHint:!1}},{name:`${r}${x.createFolder}`,description:"Create a folder inside a collection (optionally nested inside another folder).",inputSchema:{type:"object",properties:{collection:n(!0),name:{type:"string",description:"Display name for the new folder."},parentFolder:{type:"string",description:"Slash-separated folder path or folder id of the parent. Omit to create at collection root."}},required:["collection","name"]},annotations:{idempotentHint:!1}},{name:`${r}${x.deleteFolder}`,description:"Delete a folder and all its requests. Set confirm:true to proceed.",inputSchema:{type:"object",properties:{collection:n(!0),folder:{type:"string",description:"Slash-separated folder path or folder id to delete."},confirm:{type:"boolean",description:"Must be true to confirm deletion."}},required:["collection","folder","confirm"]},annotations:{destructiveHint:!0}},{name:`${r}${x.createRequest}`,description:"Create a new HTTP request inside a collection (optionally inside a folder).",inputSchema:{type:"object",properties:{collection:n(!0),folder:{type:"string",description:"Folder path or id. Omit to add at collection root."},name:{type:"string",description:"Display name for the request."},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],description:"HTTP method."},url:{type:"string",description:"Request URL, may include {{variable}} placeholders."},headers:{type:"object",description:"Key/value header map.",additionalProperties:{type:"string"}},body:{type:"string",description:"Raw request body (JSON, text, etc.)."},description:{type:"string",description:"Human-readable description."}},required:["collection","name","method","url"]},annotations:{idempotentHint:!1}},{name:`${r}${x.createRequestFromEndpoint}`,description:"Scan a backend project from source code (no OpenAPI involved) and create a working HTTP Forge request from one discovered endpoint. Returns the created request with a provenance label (framework, source file:line, confidence).",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project root to scan (default: workspace folder)."},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],description:"HTTP method of the endpoint to select."},path:{type:"string",description:"Path expression of the endpoint to select (e.g. /api/users/{id})."},endpointId:{type:"string",description:"Discovery endpoint id (from a prior scan) \u2014 preferred over method+path when available."},collection:n(!0),name:{type:"string",description:"Display name for the created request (default: derived from the endpoint)."},baseUrl:{type:"string",description:"Optional base URL to prefix the discovered path with (e.g. https://api.example.com)."},sampleData:{type:"boolean",description:"Pre-fill the request body with a sample JSON derived from the discovered schema (default: false)."}},required:["collection"]},annotations:{idempotentHint:!1}},{name:`${r}${x.generateTestSuite}`,description:"Scan a backend project from source code and generate a runnable test suite (`.suite.json`) with one request node per discovered endpoint, each asserting the discovered status code. Requests are created in the target collection first. Generated suites are tagged ai_generated:true and derived_from:<endpointId> for drift detection.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project root to scan (default: workspace folder)."},collection:n(!0),name:{type:"string",description:'Suite name (default: "Generated from discovery").'},baseUrl:{type:"string",description:"Optional base URL to prefix discovered paths (e.g. https://api.example.com)."},assertBodySchema:{type:"boolean",description:"Also assert JSON array response bodies (default: false)."},dryRun:{type:"boolean",description:"Return the generated suite without saving or creating requests (default: false)."}},required:["collection"]},annotations:{idempotentHint:!1}},{name:`${r}${x.suggestWorkflow}`,description:"Analyze discovered endpoints from a backend project (no OpenAPI involved) and suggest cross-request workflow chains (auth: token-producer \u2192 protected endpoints; CRUD: create \u2192 id-scoped operations). Returns the chains without creating anything \u2014 call generate_workflow to persist them as a suite.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project root to scan (default: workspace folder)."}},required:[]},annotations:{readOnlyHint:!0}},{name:`${r}${x.generateWorkflow}`,description:"Create requests for every endpoint of a project in the target collection, then generate a test suite whose flow-graph encodes the discovered workflow chains (auth + CRUD) using request/if/script nodes. Generated suites are tagged ai_generated:true and derived_from:<endpointId>.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project root to scan (default: workspace folder)."},collection:n(!0),name:{type:"string",description:'Suite name (default: "Generated workflow suite").'},baseUrl:{type:"string",description:"Optional base URL to prefix discovered paths (e.g. https://api.example.com)."},dryRun:{type:"boolean",description:"Return the generated suite without saving or creating requests (default: false)."}},required:["collection"]},annotations:{idempotentHint:!1}},{name:`${r}${x.checkDrift}`,description:"Check whether a backend project has drifted since its discovery index was built. In git work trees, compares the git HEAD hash; otherwise degrades to source-file mtime vs scannedAt. Returns per-project status (current/stale/unknown) \u2014 a stale project should be re-scanned (create_request_from_endpoint / generate_test_suite) and regenerated artifacts 3-way diffed against user edits.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project root to check (default: workspace folder)."}},required:[]},annotations:{readOnlyHint:!0}},{name:`${r}${x.proposeUpdate}`,description:"Phase 2b loop: given a set of stale endpoint ids (from check_drift) and the generated suites that reference them via derived_from, propose a regeneration for each affected suite. Returns a 3-way diff (base vs current vs regenerated) and flags conflicts when user edits overlap regeneration (those require developer approval \u2014 never auto-resolved). Set apply:true to compute the merged content for non-conflicting proposals (the Developer approves step).",inputSchema:{type:"object",properties:{staleEndpointIds:{type:"array",items:{type:"string"},description:"Endpoint ids that drifted (e.g. from check_drift)."},suites:{type:"array",items:{type:"object",properties:{id:{type:"string"},name:{type:"string"},currentContent:{type:"string",description:"Current suite content on disk (may include user edits)."},derivedFrom:{type:"array",items:{type:"string"}}},required:["id","currentContent","derivedFrom"]}},baseContent:{type:"object",description:"Map of suiteId \u2192 last-generated content."},regeneratedContent:{type:"object",description:"Map of suiteId \u2192 freshly regenerated content."},apply:{type:"boolean",description:"Compute merged content for non-conflicting proposals (default: false)."}},required:["staleEndpointIds","suites","baseContent","regeneratedContent"]},annotations:{readOnlyHint:!0}},{name:`${r}${x.qaApi}`,description:"One-shot API quality gate: discover endpoints from backend source code, generate (or reuse) requests in the target collection, run the deterministic QA suite against a live server, and report per-endpoint results. Requests are matched by method + path and reused across runs \u2014 reruns create nothing new unless the source changed. Returns a report with status (pass/fail/drift/dry-run), counts, per-endpoint expected-vs-actual statuses, drift info, and low-confidence discoveries. Set dryRun:true to preview the plan without writing or running.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project root to scan (default: workspace folder)."},collection:n(!0),environment:{type:"string",description:"Environment for variable resolution (default: selected)."},baseUrl:{type:"string",description:"Running server to execute against (required unless dryRun is true)."},variables:{type:"object",description:"Extra variables injected into every request (e.g. auth tokens)."},framework:{type:"string",description:"Restrict discovery (express, nestjs, fastify, lambda, spring, fastapi)."},dryRun:{type:"boolean",description:"Preview the plan without creating requests or running (default: false)."},aiAssertions:{type:"boolean",description:"Propose LLM-written assertions after the run; advisory only (default: false)."},failOnDrift:{type:"boolean",description:"Return drift status instead of proceeding when the project moved (default: false)."},storedGitHash:{type:"string",description:"Git HEAD from a prior scan (enables git-based drift)."},storedScannedAt:{type:"string",description:"Scan time from a prior scan (enables mtime-based drift)."}},required:["collection"]},annotations:{idempotentHint:!0,openWorldHint:!0}},{name:`${r}${x.reviewSuite}`,description:"Phase 3 review gate: run deterministic review rules over a completed suite run (suite + run-results) and return a structured ReviewReport with findings at error/warn/info severity. Rules are pure and repeatable (response leaks, server errors, failed assertions, DELETE!=204, missing assertions, unhandled 401/403, slow responses). When an AI provider is configured, the report is enriched with prose recommendations \u2014 the rules never depend on the LLM. Use as a CI/PR gate: fail on summary.pass === false (errors present).",inputSchema:{type:"object",properties:{runId:{type:"string",description:"Run id from run_suite / run_collection (must be completed)."},suiteId:{type:"string",description:"Optional suite id/label to carry suite context into the review."},slowResponseMs:{type:"number",description:"Slow-response threshold in ms (default: 2000)."}},required:["runId"]},annotations:{readOnlyHint:!0}},{name:`${r}${x.updateRequest}`,description:"Update fields on an existing request (partial update \u2014 omit fields to keep current values).",inputSchema:{type:"object",properties:{collection:n(!0),request:{type:"string",description:"Request name or id."},name:{type:"string",description:"New display name."},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]},url:{type:"string"},headers:{type:"object",additionalProperties:{type:"string"}},body:{type:"string"},description:{type:"string"}},required:["collection","request"]},annotations:{idempotentHint:!0}},{name:`${r}${x.deleteRequest}`,description:"Remove a request from a collection. Set confirm:true to proceed.",inputSchema:{type:"object",properties:{collection:n(!0),request:{type:"string",description:"Request name or id to delete."},confirm:{type:"boolean",description:"Must be true to confirm deletion."}},required:["collection","request","confirm"]},annotations:{destructiveHint:!0}},{name:`${r}${x.getRequestScript}`,description:"Read the pre-request or post-response script of a request.",inputSchema:{type:"object",properties:{collection:n(!0),request:{type:"string",description:"Request name or id."},phase:{type:"string",enum:["pre-request","post-response"],description:"Which script phase to read."}},required:["collection","request","phase"]},annotations:{readOnlyHint:!0}},{name:`${r}${x.setRequestScript}`,description:"Write or replace the pre-request or post-response script of a request.",inputSchema:{type:"object",properties:{collection:n(!0),request:{type:"string",description:"Request name or id."},phase:{type:"string",enum:["pre-request","post-response"],description:"Which script phase to write."},script:{type:"string",description:"Full JavaScript source to write."}},required:["collection","request","phase","script"]},annotations:{idempotentHint:!0}},{name:`${r}${x.reorderCollectionItems}`,description:"Set the execution/display order of direct children of a collection root or folder. Items not listed are appended at the end.",inputSchema:{type:"object",properties:{collection:n(!0),folder:{type:"string",description:"Folder path or id. Omit to reorder collection root."},order:{type:"array",items:{type:"string"},description:"Ordered list of item names or ids."}},required:["collection","order"]},annotations:{idempotentHint:!0}},{name:`${r}${x.listSuites}`,description:"List all test suites with name, id, request count, and configuration summary.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:!0}},{name:`${r}${x.getSuite}`,description:"Get full details of a test suite including flow nodes (suite.nodes) and a flattened request list.",inputSchema:{type:"object",properties:{suite:Ue("Name or id of the test suite.",t)},required:["suite"]},annotations:{readOnlyHint:!0}},{name:`${r}${x.createSuite}`,description:"Create a new test suite (empty, pre-populated from a collection/folder, or initialized with an explicit flow nodes graph).",inputSchema:{type:"object",properties:{name:{type:"string",description:"Display name for the new suite."},description:{type:"string",description:"Optional description."},fromCollection:{type:"string",description:"Collection name or id to seed the suite from (all requests in execution order)."},fromFolder:{type:"string",description:"Folder path within fromCollection to seed from."},nodes:{type:"array",items:{type:"object"},description:"Optional full suite.nodes graph. If provided, this becomes the suite flow definition."},iterations:{type:"number",description:"Number of iterations (default: 1)."},stopOnError:{type:"boolean",description:"Stop on first failure (default: false)."},delayBetweenRequests:{type:"number",description:"Milliseconds delay between requests (default: 0)."}},required:["name"]},annotations:{idempotentHint:!1}},{name:`${r}${x.updateSuiteConfig}`,description:"Change a suite's name/description/run configuration and optionally replace the full suite.nodes flow graph.",inputSchema:{type:"object",properties:{suite:Ue("Name or id of the suite to update.",t),name:{type:"string",description:"New display name."},description:{type:"string",description:"New description."},nodes:{type:"array",items:{type:"object"},description:"Optional full suite.nodes graph replacement."},iterations:{type:"number"},stopOnError:{type:"boolean"},delayBetweenRequests:{type:"number"}},required:["suite"]},annotations:{idempotentHint:!0}},{name:`${r}${x.getSuiteNode}`,description:'Get a single suite flow node by path (for example: "2.then.0" or "1.cases.0.nodes.1").',inputSchema:{type:"object",properties:{suite:Ue("Name or id of the suite.",t),path:{type:"string",description:"Node path to read (dot notation)."}},required:["suite","path"]},annotations:{readOnlyHint:!0}},{name:`${r}${x.listSuiteNodePaths}`,description:"List all node paths and editable branch-array paths for a suite flow graph. Use before add/update/remove/move_suite_node.",inputSchema:{type:"object",properties:{suite:Ue("Name or id of the suite.",t),includeBranches:{type:"boolean",description:"Include branch-array paths (default: true)."}},required:["suite"]},annotations:{readOnlyHint:!0}},{name:`${r}${x.addSuiteNode}`,description:"Add a flow node to a suite. Insert at root or into a branch array of a parent node.",inputSchema:{type:"object",properties:{suite:Ue("Name or id of the suite.",t),node:{type:"object",description:"Node object to insert (request/script/if/switch/for/while/block)."},parentPath:{type:"string",description:'Optional parent node path (for example: "2" or "1.cases.0"). Omit to insert at root.'},branch:{type:"string",description:'Branch array on parent node (for example: "nodes", "then", "else", "default", "cases.0.nodes"). Required when parentPath is provided.'},index:{type:"number",description:"Optional insertion index inside target array. Omit to append."}},required:["suite","node"]},annotations:{idempotentHint:!1}},{name:`${r}${x.updateSuiteNode}`,description:"Replace a flow node at a specific path in suite.nodes.",inputSchema:{type:"object",properties:{suite:Ue("Name or id of the suite.",t),path:{type:"string",description:'Node path to replace (for example: "0" or "2.then.1").'},node:{type:"object",description:"Full replacement node object."}},required:["suite","path","node"]},annotations:{idempotentHint:!0}},{name:`${r}${x.removeSuiteNode}`,description:"Remove a flow node at a specific path from suite.nodes.",inputSchema:{type:"object",properties:{suite:Ue("Name or id of the suite.",t),path:{type:"string",description:'Node path to remove (for example: "0" or "2.else.0").'}},required:["suite","path"]},annotations:{destructiveHint:!0}},{name:`${r}${x.moveSuiteNode}`,description:"Move a flow node from one path to another parent/branch/index within suite.nodes.",inputSchema:{type:"object",properties:{suite:Ue("Name or id of the suite.",t),fromPath:{type:"string",description:'Source node path (for example: "1.then.0").'},toParentPath:{type:"string",description:"Optional destination parent node path. Omit to move to root."},toBranch:{type:"string",description:"Destination branch array on parent node. Required when toParentPath is provided."},toIndex:{type:"number",description:"Optional destination index in target array. Omit to append."}},required:["suite","fromPath"]},annotations:{idempotentHint:!1}},{name:`${r}${x.addSuiteRequests}`,description:'Legacy compatibility helper. Add one or more request nodes at the suite root, using the same insertion semantics as add_suite_node with type:"request".',inputSchema:{type:"object",properties:{suite:Ue("Name or id of the suite.",t),requests:{type:"array",items:{type:"object",properties:{collection:{type:"string",description:"Collection name or id."},request:{type:"string",description:"Request name or id."}},required:["collection","request"]},description:"Requests to add."},insertAt:{type:"number",description:"Zero-based root nodes-array index to insert at. Omit to append at end."}},required:["suite","requests"]},annotations:{idempotentHint:!1}},{name:`${r}${x.removeSuiteRequest}`,description:"Remove a request from a request-only root suite by position (0-based) or by name. For flow suites, edit nodes via get_suite/update_suite_config.",inputSchema:{type:"object",properties:{suite:Ue("Name or id of the suite.",t),index:{type:"number",description:"Zero-based position in the suite requests list."},request:{type:"string",description:"Request name to remove (used if index is not provided)."}},required:["suite"]},annotations:{destructiveHint:!0}},{name:`${r}${x.reorderSuiteRequests}`,description:"Reorder requests in a request-only root suite. Requests not listed are moved to the end. For flow suites, edit nodes via get_suite/update_suite_config.",inputSchema:{type:"object",properties:{suite:Ue("Name or id of the suite.",t),order:{type:"array",items:{type:"string"},description:"Ordered list of request names."}},required:["suite","order"]},annotations:{idempotentHint:!0}},{name:`${r}${x.duplicateSuite}`,description:"Clone an existing suite under a new name.",inputSchema:{type:"object",properties:{suite:Ue("Name or id of the suite to clone.",t),newName:{type:"string",description:"Name for the duplicated suite."}},required:["suite","newName"]},annotations:{idempotentHint:!1}},{name:`${r}${x.deleteSuite}`,description:"Delete a test suite permanently. Set confirm:true to proceed.",inputSchema:{type:"object",properties:{suite:Ue("Name or id of the suite to delete.",t),confirm:{type:"boolean",description:"Must be true to confirm deletion."}},required:["suite","confirm"]},annotations:{destructiveHint:!0}},{name:`${r}${x.listEnvironments}`,description:"List all environments with their variable keys (values hidden). Use get_environment_variables to see values.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:!0}},{name:`${r}${x.getEnvironmentVariables}`,description:"Get the resolved (merged file + session overrides) variables for an environment.",inputSchema:{type:"object",properties:{environment:{type:"string",description:"Environment name (defaults to active environment)."}}},annotations:{readOnlyHint:!0}},{name:`${r}${x.selectEnvironment}`,description:"Set the active environment for all subsequent run_* calls in this session.",inputSchema:{type:"object",properties:{environment:{type:"string",description:"Name of the environment to activate."}},required:["environment"]},annotations:{idempotentHint:!0}},{name:`${r}${x.createEnvironment}`,description:"Create a new environment file, optionally pre-populated with variables.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Environment name (becomes the filename)."},variables:{type:"object",description:"Initial key/value variable map.",additionalProperties:{type:"string"}}},required:["name"]},annotations:{idempotentHint:!1}},{name:`${r}${x.deleteEnvironment}`,description:"Delete an environment file permanently. Set confirm:true to proceed.",inputSchema:{type:"object",properties:{environment:{type:"string",description:"Environment name to delete."},confirm:{type:"boolean",description:"Must be true to confirm deletion."}},required:["environment","confirm"]},annotations:{destructiveHint:!0}},{name:`${r}${x.setEnvironmentVariable}`,description:'Set a variable in an environment. Scope "session" (default) is in-memory only and always temporary (both runtimes). Scope "permanent" writes to the env JSON config file \u2014 source-controlled and shared with the CLI runtime.',inputSchema:{type:"object",properties:{environment:{type:"string",description:"Environment name (defaults to active environment)."},key:{type:"string",description:"Variable name."},value:{type:"string",description:"New value."},scope:{type:"string",enum:["session","permanent"],description:'Storage scope. "permanent" writes to disk.'}},required:["key","value"]},annotations:{idempotentHint:!0}},{name:`${r}${x.unsetEnvironmentVariable}`,description:"Remove a session-scoped variable override, restoring the file value.",inputSchema:{type:"object",properties:{environment:{type:"string",description:"Environment name (defaults to active environment)."},key:{type:"string",description:"Variable name to unset."}},required:["key"]},annotations:{idempotentHint:!0}},{name:`${r}${x.setGlobalVariable}`,description:'Set a global variable visible across all environments. Scope "session" (default) is in-memory only and lost on restart (both runtimes). Scope "permanent" writes to _global.json \u2014 source-controlled and shared with the CLI runtime.',inputSchema:{type:"object",properties:{key:{type:"string",description:"Global variable name."},value:{type:"string",description:"Value to set."},scope:{type:"string",enum:["session","permanent"],description:'Storage scope. "permanent" writes to _global.json.'}},required:["key","value"]},annotations:{idempotentHint:!0}},{name:`${r}${x.getGlobals}`,description:"Return all global variables (merged _global.json + runtime pm.globals.set() values).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:!0}},{name:`${r}${x.scaffoldCollectionFromOpenApi}`,description:"Import an OpenAPI 3.0 spec (JSON or YAML) and scaffold a complete HTTP Forge collection from it. All operations become requests grouped by tag/path. An optional environment is created from the server URL. Returns the new collection id and name. Use this to quickly bootstrap API testing from a spec file.",inputSchema:{type:"object",properties:{specPath:{type:"string",description:"Absolute or workspace-relative path to the OpenAPI 3.0 JSON or YAML file."},collectionName:{type:"string",description:"Override the collection name (defaults to the spec title)."},environmentName:{type:"string",description:"Name for the generated environment that contains the server base URL. Omit to skip environment creation."}},required:["specPath"]},annotations:{idempotentHint:!1}},{name:`${r}${x.suggestAssertions}`,description:"Analyse the last execution history for a request and suggest pm.test() assertions to add to its post-response script. Covers status code, response time, required JSON fields, Content-Type header, and schema conformance. Returns an array of ready-to-paste JavaScript test snippets and a rationale for each.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name or id that owns the request."},request:{type:"string",description:"Request name or id to analyse."},environment:{type:"string",description:"Environment used when the run was recorded (defaults to active environment)."},maxSuggestions:{type:"number",description:"Cap the number of suggestions returned (default: 10)."}},required:["collection","request"]},annotations:{readOnlyHint:!0}},{name:`${r}${x.explainFailure}`,description:"Explain why a specific request failed in a recent run. Returns the full request (URL, method, headers, body), the response received (status, headers, body), all assertion results, any script errors, and a plain-English diagnosis with suggested fixes. Provide either runId (from a prior run_suite/run_collection call) + request name, or the collection and request names to pull the most recent history entry.",inputSchema:{type:"object",properties:{runId:{type:"string",description:"MCP run id (from run_suite or run_collection). Mutually exclusive with collection+request history lookup."},collection:{type:"string",description:"Collection name or id. Required when runId is omitted."},request:{type:"string",description:"Request name or id."},iteration:{type:"number",description:"Iteration number within the run (default: 1)."}}},annotations:{readOnlyHint:!0}},{name:`${r}${x.suggestEnvVars}`,description:`Scan a collection for hardcoded values (API keys, base URLs, tokens, tenant IDs) that should become environment variables.
|
|
693
693
|
|
|
694
694
|
Returns:
|
|
@@ -770,7 +770,7 @@ This tool returns request details AND a structured task. You MUST:
|
|
|
770
770
|
3. Return the rows as a JSON array under the key "iterationData" \u2014 each row is an object whose keys match the {{variable}} placeholders in the request.
|
|
771
771
|
4. Respond with the JSON array directly so the user can pass it to run_collection or the CLI --variables flag.
|
|
772
772
|
|
|
773
|
-
Example: for POST /users with body {"name":"{{name}}","email":"{{email}}"} and iterations=4, generate 4 rows: valid user, duplicate email, missing name, email with invalid format.`,inputSchema:{type:"object",properties:{collection:n(!0),request:{type:"string",description:"Request name, slug, or id."},iterations:{type:"number",description:"Number of test data rows to generate (default: 5, max: 50)."}},required:["collection","request"]},annotations:{readOnlyHint:!0}}]}var Wo,Go,Ko,Qo,x,Fe=k(()=>{"use strict";Wo={type:"object",properties:{environment:{type:"string",description:"Environment name to use (defaults to the currently selected environment)"},variables:{type:"object",description:"Extra variables to inject \u2014 merged with environment variables, {{name}} syntax",additionalProperties:{type:"string"}},headers:{type:"object",description:"Override or add request headers",additionalProperties:{type:"string"}},query:{type:"object",description:"Override query parameters",additionalProperties:{type:"string"}},body:{type:"string",description:"Replace the request body (JSON string). Omit to use the saved body."},include:{type:"array",items:{type:"string",enum:["headers","cookies","tests","consoleOutput","report","fullBody"]},description:"Extra fields to include in the response (default: status, ok, body, allPassed). Use fullBody to disable the 4KB body truncation."}}},Go={type:"object",properties:{environment:{type:"string",description:"Environment name to use"},variables:{type:"object",description:"Extra variables injected into every request",additionalProperties:{type:"string"}},iterations:{type:"number",description:"Number of iterations (default: 1)"},concurrency:{type:"number",description:"Number of parallel virtual users (1\u201350, default: 1). Each VU runs the full request sequence independently, preserving inter-request dependencies."},stopOnError:{type:"boolean",description:"Stop on first failure"},delay:{type:"number",description:"Delay between requests in ms"},include:{type:"array",items:{type:"string",enum:["perRequest","failedOnly","consoleOutput","report"]},description:"Result detail level"},async:{type:"boolean",description:"When true, start the run in the background and return a runId immediately. Use get_run_status / get_failed_requests to poll results. Recommended for folders with many requests."}}},Ko={type:"object",properties:{environment:{type:"string",description:"Environment name to use"},variables:{type:"object",description:"Extra variables injected into every request",additionalProperties:{type:"string"}},iterations:{type:"number",description:"Number of iterations (default: 1)"},concurrency:{type:"number",description:"Number of parallel virtual users (1\u201350, default: 1). Each VU runs the full request sequence independently."},stopOnError:{type:"boolean",description:"Stop on first failure"},delay:{type:"number",description:"Delay between requests in ms"},recursive:{type:"boolean",description:"Include requests in nested subfolders (default: true)"},include:{type:"array",items:{type:"string",enum:["perRequest","failedOnly","consoleOutput","report"]},description:"Result detail level"},async:{type:"boolean",description:"When true, start the run in the background and return a runId immediately. Use get_run_status / get_failed_requests to poll results. Recommended for folders with many requests."}}},Qo={type:"object",properties:{environment:{type:"string",description:"Environment name to use"},iterations:{type:"number",description:"Number of iterations (overrides suite default)"},concurrency:{type:"number",description:"Number of parallel virtual users (1\u201350, default: 1). Each VU runs the full request sequence independently."},stopOnError:{type:"boolean",description:"Stop on first failure"},delay:{type:"number",description:"Delay between requests in ms"},variables:{type:"object",description:"Extra variables injected into every request",additionalProperties:{type:"string"}},async:{type:"boolean",description:"When true, start the run in the background and return a runId immediately. Use get_run_status / get_failed_requests to poll results."},requestFilter:{type:"array",items:{type:"string"},description:"Run only requests whose names match one of these strings (case-insensitive)"},include:{type:"array",items:{type:"string",enum:["perRequest","failedOnly","consoleOutput","report"]},description:"Result detail level (default: summary + failedRequests)"}}},x={listCollections:"list_collections",listFolders:"list_folders",listRequests:"list_requests",searchRequests:"search_requests",getEnvironment:"get_environment",runRequest:"run_request",runFolder:"run_folder",runCollection:"run_collection",runSuite:"run_suite",getRunStatus:"get_run_status",getRunSummary:"get_run_summary",getFailedRequests:"get_failed_requests",getRequestResult:"get_request_result",cancelRun:"cancel_run",setVariable:"set_variable",createCollection:"create_collection",renameCollection:"rename_collection",deleteCollection:"delete_collection",duplicateCollection:"duplicate_collection",createFolder:"create_folder",deleteFolder:"delete_folder",getRequest:"get_request",createRequest:"create_request",updateRequest:"update_request",deleteRequest:"delete_request",createRequestFromEndpoint:"create_request_from_endpoint",generateTestSuite:"generate_test_suite",suggestWorkflow:"suggest_workflow",generateWorkflow:"generate_workflow",checkDrift:"check_drift",proposeUpdate:"propose_update",qaApi:"qa_api",reviewSuite:"review_suite",getRequestScript:"get_request_script",setRequestScript:"set_request_script",reorderCollectionItems:"reorder_collection_items",listSuites:"list_suites",getSuite:"get_suite",createSuite:"create_suite",updateSuiteConfig:"update_suite_config",getSuiteNode:"get_suite_node",listSuiteNodePaths:"list_suite_node_paths",addSuiteNode:"add_suite_node",updateSuiteNode:"update_suite_node",removeSuiteNode:"remove_suite_node",moveSuiteNode:"move_suite_node",addSuiteRequests:"add_suite_requests",removeSuiteRequest:"remove_suite_request",reorderSuiteRequests:"reorder_suite_requests",duplicateSuite:"duplicate_suite",deleteSuite:"delete_suite",listEnvironments:"list_environments",getEnvironmentVariables:"get_environment_variables",selectEnvironment:"select_environment",createEnvironment:"create_environment",deleteEnvironment:"delete_environment",setEnvironmentVariable:"set_environment_variable",unsetEnvironmentVariable:"unset_environment_variable",setGlobalVariable:"set_global_variable",getGlobals:"get_globals",scaffoldCollectionFromOpenApi:"scaffold_collection_from_openapi",suggestAssertions:"suggest_assertions",explainFailure:"explain_failure",suggestEnvVars:"suggest_env_vars",applyEnvVars:"apply_env_vars",getRequestsForEnhancement:"get_requests_for_enhancement",applyRequestEnhancements:"apply_request_enhancements",aiSuggestEnvVars:"ai_suggest_env_vars",aiEnhanceCollection:"ai_enhance_collection",analyzeCoverage:"analyze_coverage",aiAnalyzeCoverage:"ai_analyze_coverage",generateRequestFromIntent:"generate_request_from_intent",designApiFromIntent:"design_api_from_intent",validateAgainstSpec:"validate_against_spec",generateScenarios:"generate_scenarios",healAssertions:"heal_assertions",generateIterationData:"generate_iteration_data"}});function A(r){return new Error(`Bad request: ${r}`)}function W(r,e){if(typeof r!="string"||!r.trim())throw A('the "collection" argument is required');let t=r.toLowerCase(),n=e.find(s=>s.id===r||s.name===r)??e.find(s=>s.name.toLowerCase()===t)??e.find(s=>s.name.toLowerCase().includes(t))??e.find(s=>s.id.toLowerCase().includes(t));if(!n){let s=e.map(i=>`"${i.name}"`).join(", ");throw A(`collection not found: "${r}". Available collections: ${s||"(none)"}. Call list_collections to see all.`)}return n}function We(r,e){if(typeof r!="string"||!r.trim())throw A('the "request" argument is required');let t=X(e),n=r.toLowerCase(),s=t.find(i=>i.request.id===r||i.request.name===r)??t.find(i=>i.request.name.toLowerCase()===n)??t.find(i=>i.request.name.toLowerCase().includes(n));if(!s){let i=t.slice(0,10).map(o=>`"${o.request.name}"`).join(", ");throw A(`request "${r}" not found in collection "${e.name}". First ${Math.min(t.length,10)} requests: ${i||"(none)"}. Call list_requests or search_requests to find the exact name.`)}return s.request}function Vt(r,e,t){return r.collection.getRequestDetail(e,t.id)??t}function $l(r,e){for(let t of r){if(t.type!=="folder")continue;let n=t;if(n.id===e)return n;let s=$l(n.items??[],e);if(s)return s}}async function Ae(r,e){if(typeof r!="string"||!r.trim())throw A('the "suite" argument is required');let t=await e.testSuite.getAllSuites(),n=r.toLowerCase(),s=t.find(i=>i.id===r||i.name===r)??t.find(i=>i.name.toLowerCase()===n);if(!s){let i=t.map(o=>`"${o.name}"`).join(", ");throw A(`suite "${r}" not found. Available suites: ${i||"(none)"}. Call list_suites to see all.`)}return s}function Mp(r,e){if(e.includes("fullBody")||r==null)return r;let t=typeof r=="string"?r:JSON.stringify(r);if(t.length<=Yo)return r;let n;try{n=JSON.parse(t.slice(0,Yo))}catch{n=t.slice(0,Yo)}return{_truncated:!0,excerpt:n,totalLength:t.length,hint:'Body truncated. Pass include:["fullBody"] to get the complete body, or include:["report"] (collection/suite runs only) to generate an HTML report with full details.'}}function zt(r,e){if(e.includes("fullBody")||r==null||typeof r!="object")return r;let t=r,n=!1,s={...t};if("body"in s){let i=Mp(s.body,e);i!==s.body&&(s.body=i,n=!0)}if(Array.isArray(s.failedRequests)){let i=s.failedRequests.map(o=>{if(o==null||typeof o!="object")return o;let a=o;if(!("body"in a))return a;let c=Mp(a.body,e);return c!==a.body?{...a,body:c}:a});s.failedRequests=i,n=!0}return n?s:r}var Yo,Ne=k(()=>{"use strict";tt();tt();Yo=4096});import*as at from"fs";import*as ct from"path";function Nl(r,e){return e&&!ct.isAbsolute(r)?ct.join(e,r):r}async function jp(r){let e=at.readFileSync(r,"utf8");if(r.endsWith(".json"))return JSON.parse(e);let{parse:t}=await import("yaml");return t(e)}function Lp(r){return X(r).map(({request:e,folderPath:t})=>({id:e.id,name:e.name,folder:t,method:e.method,url:e.url,headers:(e.headers??[]).filter(n=>n.enabled!==!1).map(n=>({key:n.key,value:n.value})),query:(e.query??[]).filter(n=>n.enabled!==!1).map(n=>({key:n.key,value:n.value})),bodyExcerpt:e.body?.type==="raw"&&typeof e.body.content=="string"?e.body.content.slice(0,300):void 0}))}function Hp(r,e){return X(r).find(({request:n})=>n.id===e.id||n.name===e.name)?.folderPath}function Ey(r,e){let t=[`Method: ${r.method??"GET"}`,`URL: ${r.url??""}`,...(r.headers??[]).filter(n=>n.enabled!==!1).map(n=>`Header: ${n.key}: ${n.value}`),...(r.query??[]).filter(n=>n.enabled!==!1).map(n=>`Query: ${n.key}: ${n.value}`)];if(r.body?.type==="raw"&&typeof r.body.content=="string"&&t.push(`Body: ${r.body.content.slice(0,300)}`),e){t.push(`Observed status: ${String(e.status??"unknown")}`),e.responseHeaders&&t.push(`Observed headers: ${JSON.stringify(e.responseHeaders).slice(0,400)}`);let n=e.responseBody;n&&t.push(`Observed body: ${n.slice(0,1e3)}`),Array.isArray(e.failedTests)&&t.push(`Failed tests: ${JSON.stringify(e.failedTests).slice(0,400)}`)}return t.join(`
|
|
773
|
+
Example: for POST /users with body {"name":"{{name}}","email":"{{email}}"} and iterations=4, generate 4 rows: valid user, duplicate email, missing name, email with invalid format.`,inputSchema:{type:"object",properties:{collection:n(!0),request:{type:"string",description:"Request name, slug, or id."},iterations:{type:"number",description:"Number of test data rows to generate (default: 5, max: 50)."}},required:["collection","request"]},annotations:{readOnlyHint:!0}}]}var Wo,Go,Ko,Qo,x,Fe=k(()=>{"use strict";Wo={type:"object",properties:{environment:{type:"string",description:"Environment name to use (defaults to the currently selected environment)"},variables:{type:"object",description:"Extra variables to inject \u2014 merged with environment variables, {{name}} syntax",additionalProperties:{type:"string"}},headers:{type:"object",description:"Override or add request headers",additionalProperties:{type:"string"}},query:{type:"object",description:"Override query parameters",additionalProperties:{type:"string"}},body:{type:"string",description:"Replace the request body (JSON string). Omit to use the saved body."},include:{type:"array",items:{type:"string",enum:["headers","cookies","tests","consoleOutput","report","fullBody"]},description:"Extra fields to include in the response (default: status, ok, body, allPassed). Use fullBody to disable the 4KB body truncation."}}},Go={type:"object",properties:{environment:{type:"string",description:"Environment name to use"},variables:{type:"object",description:"Extra variables injected into every request",additionalProperties:{type:"string"}},iterations:{type:"number",description:"Number of iterations (default: 1)"},concurrency:{type:"number",description:"Number of parallel virtual users (1\u201350, default: 1). Each VU runs the full request sequence independently, preserving inter-request dependencies."},stopOnError:{type:"boolean",description:"Stop on first failure"},delay:{type:"number",description:"Delay between requests in ms"},include:{type:"array",items:{type:"string",enum:["perRequest","failedOnly","consoleOutput","report"]},description:"Result detail level"},async:{type:"boolean",description:"When true, start the run in the background and return a runId immediately. Use get_run_status / get_failed_requests to poll results. Recommended for folders with many requests."}}},Ko={type:"object",properties:{environment:{type:"string",description:"Environment name to use"},variables:{type:"object",description:"Extra variables injected into every request",additionalProperties:{type:"string"}},iterations:{type:"number",description:"Number of iterations (default: 1)"},concurrency:{type:"number",description:"Number of parallel virtual users (1\u201350, default: 1). Each VU runs the full request sequence independently."},stopOnError:{type:"boolean",description:"Stop on first failure"},delay:{type:"number",description:"Delay between requests in ms"},recursive:{type:"boolean",description:"Include requests in nested subfolders (default: true)"},include:{type:"array",items:{type:"string",enum:["perRequest","failedOnly","consoleOutput","report"]},description:"Result detail level"},async:{type:"boolean",description:"When true, start the run in the background and return a runId immediately. Use get_run_status / get_failed_requests to poll results. Recommended for folders with many requests."}}},Qo={type:"object",properties:{environment:{type:"string",description:"Environment name to use"},iterations:{type:"number",description:"Number of iterations (overrides suite default)"},concurrency:{type:"number",description:"Number of parallel virtual users (1\u201350, default: 1). Each VU runs the full request sequence independently."},stopOnError:{type:"boolean",description:"Stop on first failure"},delay:{type:"number",description:"Delay between requests in ms"},variables:{type:"object",description:"Extra variables injected into every request",additionalProperties:{type:"string"}},async:{type:"boolean",description:"When true, start the run in the background and return a runId immediately. Use get_run_status / get_failed_requests to poll results."},requestFilter:{type:"array",items:{type:"string"},description:"Run only requests whose names match one of these strings (case-insensitive)"},include:{type:"array",items:{type:"string",enum:["perRequest","failedOnly","consoleOutput","report"]},description:"Result detail level (default: summary + failedRequests)"}}},x={listCollections:"list_collections",listFolders:"list_folders",listRequests:"list_requests",searchRequests:"search_requests",getEnvironment:"get_environment",runRequest:"run_request",runFolder:"run_folder",runCollection:"run_collection",runSuite:"run_suite",getRunStatus:"get_run_status",getRunSummary:"get_run_summary",getFailedRequests:"get_failed_requests",getRequestResult:"get_request_result",cancelRun:"cancel_run",setVariable:"set_variable",createCollection:"create_collection",renameCollection:"rename_collection",deleteCollection:"delete_collection",duplicateCollection:"duplicate_collection",createFolder:"create_folder",deleteFolder:"delete_folder",getRequest:"get_request",createRequest:"create_request",updateRequest:"update_request",deleteRequest:"delete_request",createRequestFromEndpoint:"create_request_from_endpoint",generateTestSuite:"generate_test_suite",suggestWorkflow:"suggest_workflow",generateWorkflow:"generate_workflow",checkDrift:"check_drift",proposeUpdate:"propose_update",qaApi:"qa_api",reviewSuite:"review_suite",getRequestScript:"get_request_script",setRequestScript:"set_request_script",reorderCollectionItems:"reorder_collection_items",listSuites:"list_suites",getSuite:"get_suite",createSuite:"create_suite",updateSuiteConfig:"update_suite_config",getSuiteNode:"get_suite_node",listSuiteNodePaths:"list_suite_node_paths",addSuiteNode:"add_suite_node",updateSuiteNode:"update_suite_node",removeSuiteNode:"remove_suite_node",moveSuiteNode:"move_suite_node",addSuiteRequests:"add_suite_requests",removeSuiteRequest:"remove_suite_request",reorderSuiteRequests:"reorder_suite_requests",duplicateSuite:"duplicate_suite",deleteSuite:"delete_suite",listEnvironments:"list_environments",getEnvironmentVariables:"get_environment_variables",selectEnvironment:"select_environment",createEnvironment:"create_environment",deleteEnvironment:"delete_environment",setEnvironmentVariable:"set_environment_variable",unsetEnvironmentVariable:"unset_environment_variable",setGlobalVariable:"set_global_variable",getGlobals:"get_globals",scaffoldCollectionFromOpenApi:"scaffold_collection_from_openapi",suggestAssertions:"suggest_assertions",explainFailure:"explain_failure",suggestEnvVars:"suggest_env_vars",applyEnvVars:"apply_env_vars",getRequestsForEnhancement:"get_requests_for_enhancement",applyRequestEnhancements:"apply_request_enhancements",aiSuggestEnvVars:"ai_suggest_env_vars",aiEnhanceCollection:"ai_enhance_collection",analyzeCoverage:"analyze_coverage",aiAnalyzeCoverage:"ai_analyze_coverage",generateRequestFromIntent:"generate_request_from_intent",designApiFromIntent:"design_api_from_intent",validateAgainstSpec:"validate_against_spec",generateScenarios:"generate_scenarios",healAssertions:"heal_assertions",generateIterationData:"generate_iteration_data"}});function A(r){return new Error(`Bad request: ${r}`)}function W(r,e){if(typeof r!="string"||!r.trim())throw A('the "collection" argument is required');let t=r.toLowerCase(),n=e.find(s=>s.id===r||s.name===r)??e.find(s=>s.name.toLowerCase()===t)??e.find(s=>s.name.toLowerCase().includes(t))??e.find(s=>s.id.toLowerCase().includes(t));if(!n){let s=e.map(i=>`"${i.name}"`).join(", ");throw A(`collection not found: "${r}". Available collections: ${s||"(none)"}. Call list_collections to see all.`)}return n}function We(r,e){if(typeof r!="string"||!r.trim())throw A('the "request" argument is required');let t=X(e),n=r.toLowerCase(),s=t.find(i=>i.request.id===r||i.request.name===r)??t.find(i=>i.request.name.toLowerCase()===n)??t.find(i=>i.request.name.toLowerCase().includes(n));if(!s){let i=t.slice(0,10).map(o=>`"${o.request.name}"`).join(", ");throw A(`request "${r}" not found in collection "${e.name}". First ${Math.min(t.length,10)} requests: ${i||"(none)"}. Call list_requests or search_requests to find the exact name.`)}return s.request}function Vt(r,e,t){return r.collection.getRequestDetail(e,t.id)??t}function $l(r,e){for(let t of r){if(t.type!=="folder")continue;let n=t;if(n.id===e)return n;let s=$l(n.items??[],e);if(s)return s}}async function Ae(r,e){if(typeof r!="string"||!r.trim())throw A('the "suite" argument is required');let t=await e.testSuite.getAllSuites(),n=r.toLowerCase(),s=t.find(i=>i.id===r||i.name===r)??t.find(i=>i.name.toLowerCase()===n);if(!s){let i=t.map(o=>`"${o.name}"`).join(", ");throw A(`suite "${r}" not found. Available suites: ${i||"(none)"}. Call list_suites to see all.`)}return s}function Mp(r,e){if(e.includes("fullBody")||r==null)return r;let t=typeof r=="string"?r:JSON.stringify(r);if(t.length<=Yo)return r;let n;try{n=JSON.parse(t.slice(0,Yo))}catch{n=t.slice(0,Yo)}return{_truncated:!0,excerpt:n,totalLength:t.length,hint:'Body truncated. Pass include:["fullBody"] to get the complete body, or include:["report"] (collection/suite runs only) to generate an HTML report with full details.'}}function zt(r,e){if(e.includes("fullBody")||r==null||typeof r!="object")return r;let t=r,n=!1,s={...t};if("body"in s){let i=Mp(s.body,e);i!==s.body&&(s.body=i,n=!0)}if(Array.isArray(s.failedRequests)){let i=s.failedRequests.map(o=>{if(o==null||typeof o!="object")return o;let a=o;if(!("body"in a))return a;let c=Mp(a.body,e);return c!==a.body?{...a,body:c}:a});s.failedRequests=i,n=!0}return n?s:r}var Yo,Ne=k(()=>{"use strict";tt();tt();Yo=4096});import*as at from"fs";import*as ct from"path";function Nl(r,e){return e&&!ct.isAbsolute(r)?ct.join(e,r):r}async function jp(r){let e=at.readFileSync(r,"utf8");if(r.endsWith(".json"))return JSON.parse(e);let{parse:t}=await import("yaml");return t(e)}function Lp(r){return X(r).map(({request:e,folderPath:t})=>({id:e.id,name:e.name,folder:t,method:e.method,url:e.url,headers:(e.headers??[]).filter(n=>n.enabled!==!1).map(n=>({key:n.key,value:n.value})),query:(e.query??[]).filter(n=>n.enabled!==!1).map(n=>({key:n.key,value:n.value})),bodyExcerpt:e.body?.type==="raw"&&typeof e.body.content=="string"?e.body.content.slice(0,300):void 0}))}function Hp(r,e){return X(r).find(({request:n})=>n.id===e.id||n.name===e.name)?.folderPath}function qy(r,e){let t=[`Method: ${r.method??"GET"}`,`URL: ${r.url??""}`,...(r.headers??[]).filter(n=>n.enabled!==!1).map(n=>`Header: ${n.key}: ${n.value}`),...(r.query??[]).filter(n=>n.enabled!==!1).map(n=>`Query: ${n.key}: ${n.value}`)];if(r.body?.type==="raw"&&typeof r.body.content=="string"&&t.push(`Body: ${r.body.content.slice(0,300)}`),e){t.push(`Observed status: ${String(e.status??"unknown")}`),e.responseHeaders&&t.push(`Observed headers: ${JSON.stringify(e.responseHeaders).slice(0,400)}`);let n=e.responseBody;n&&t.push(`Observed body: ${n.slice(0,1e3)}`),Array.isArray(e.failedTests)&&t.push(`Failed tests: ${JSON.stringify(e.failedTests).slice(0,400)}`)}return t.join(`
|
|
774
774
|
`)}async function _l(r,e,t,n,s){let i=st(e).snapshot().body,o=`You are an API testing expert. Suggest high-value post-response pm.test() assertions for the request below.
|
|
775
775
|
|
|
776
776
|
`+(i?`Business context for this endpoint (docs, OpenAPI contract, schema):
|
|
@@ -779,7 +779,7 @@ ${i}
|
|
|
779
779
|
`:"")+(s?`Workspace business knowledge (Confluence exports, Jiras, project docs):
|
|
780
780
|
${s}
|
|
781
781
|
|
|
782
|
-
`:"")+`${
|
|
782
|
+
`:"")+`${qy(e,t)}
|
|
783
783
|
|
|
784
784
|
Rules:
|
|
785
785
|
- Prefer business-logic and contract checks (status code, key fields, types, shapes, auth behaviour) over trivial ones.
|
|
@@ -787,7 +787,7 @@ Rules:
|
|
|
787
787
|
- If an observed response body is provided, write assertions that match its actual shape.
|
|
788
788
|
- Return at most ${n} assertions.
|
|
789
789
|
Return ONLY a valid JSON array (no markdown fences):
|
|
790
|
-
[{"snippet":"<full pm.test JS>","rationale":"<one sentence>"}]`;try{let a=await ot(()=>r.complete(o)),c=Ot(a);return Array.isArray(c)?c.filter(l=>l&&typeof l.snippet=="string"&&l.snippet.includes("pm.test")).map(l=>({snippet:l.snippet,rationale:l.rationale??""})):[]}catch{return[]}}async function
|
|
790
|
+
[{"snippet":"<full pm.test JS>","rationale":"<one sentence>"}]`;try{let a=await ot(()=>r.complete(o)),c=Ot(a);return Array.isArray(c)?c.filter(l=>l&&typeof l.snippet=="string"&&l.snippet.includes("pm.test")).map(l=>({snippet:l.snippet,rationale:l.rationale??""})):[]}catch{return[]}}async function Ay(r,e,t){let n=e.assertions?.filter(i=>!i.passed)??[],s=`You are an API testing expert diagnosing a failed HTTP test. Use the request, response, and assertion failures below.
|
|
791
791
|
|
|
792
792
|
`+(t?`Business context for this endpoint (docs, OpenAPI contract, workspace knowledge):
|
|
793
793
|
${t}
|
|
@@ -805,7 +805,7 @@ ${n.map(i=>`- ${i.name}${i.message?`: ${i.message}`:""}`).join(`
|
|
|
805
805
|
`:"")+`
|
|
806
806
|
Diagnose the likely root cause and give concrete, ordered fixes.
|
|
807
807
|
Return ONLY a valid JSON object (no markdown fences):
|
|
808
|
-
{"diagnosis":"<2-4 sentences>","suggestedFixes":["<fix 1>","<fix 2>"]}`;try{let i=await ot(()=>r.complete(s)),o=Ot(i);return!o||typeof o.diagnosis!="string"||!o.diagnosis.trim()?null:{diagnosis:o.diagnosis.trim(),suggestedFixes:Array.isArray(o.suggestedFixes)?o.suggestedFixes.filter(a=>typeof a=="string"):[]}}catch{return null}}function
|
|
808
|
+
{"diagnosis":"<2-4 sentences>","suggestedFixes":["<fix 1>","<fix 2>"]}`;try{let i=await ot(()=>r.complete(s)),o=Ot(i);return!o||typeof o.diagnosis!="string"||!o.diagnosis.trim()?null:{diagnosis:o.diagnosis.trim(),suggestedFixes:Array.isArray(o.suggestedFixes)?o.suggestedFixes.filter(a=>typeof a=="string"):[]}}catch{return null}}function Py(r,e,t){let n=[],s=e?.status;s?n.push({snippet:`pm.test("Status code is ${s}", function () {
|
|
809
809
|
pm.response.to.have.status(${s});
|
|
810
810
|
});`,rationale:`Observed status ${s} in the most recent run.`}):n.push({snippet:`pm.test("Status code is 2xx", function () {
|
|
811
811
|
pm.expect(pm.response.code).to.be.within(200, 299);
|
|
@@ -818,22 +818,22 @@ Return ONLY a valid JSON object (no markdown fences):
|
|
|
818
818
|
pm.expect(${l}).to.have.property("${c}");
|
|
819
819
|
});`,rationale:`Field "${c}" was present in the observed response body.`})}}}catch{n.push({snippet:`pm.test("Response body is not empty", function () {
|
|
820
820
|
pm.expect(pm.response.text()).to.not.be.empty;
|
|
821
|
-
});`,rationale:"Response body was non-JSON text."})}return n}var Fl,Bp,Dl=k(()=>{"use strict";Xn();er();ql();ko();Co();Eo();Ol();Jo();tt();Fe();Ne();Fl=["get","post","put","patch","delete","head","options"];Bp=[{toolNames:[x.scaffoldCollectionFromOpenApi],async handle({args:r,services:e}){let t=typeof r.specPath=="string"?r.specPath.trim():"";if(!t)throw A('"specPath" is required');let n=Nl(t,e.workspaceFolder);if(!at.existsSync(n))throw A(`OpenAPI spec file not found: "${n}"`);let i=await new Lt(e.collection,e.environmentConfig).import(n,{collectionName:typeof r.collectionName=="string"?r.collectionName:void 0,environmentName:typeof r.environmentName=="string"?r.environmentName:void 0});return{collectionId:i.collection.id,collectionName:i.collection.name,requestCount:i.collection.items.filter(o=>o.type==="request").length,environmentCreated:i.environmentCreated??null,hint:"Use list_requests to browse the scaffolded collection, then run_request to test individual endpoints."}}},{toolNames:[x.suggestAssertions],async handle({args:r,services:e,collections:t,runStore:n}){let s=r.collection;if(!(typeof r.request=="string"?r.request.trim():""))throw A('"request" is required');let o=W(s,t),a=We(r.request,o),c=Vt(e,o.id,a),l=typeof r.maxSuggestions=="number"?Math.min(20,Math.max(1,r.maxSuggestions)):10,d=Array.from(n.values()).filter(f=>f.status!=="running").flatMap(f=>f.allResults??[]).filter(f=>f.name===a.name||typeof f.name=="string"&&f.name.toLowerCase()===a.name.toLowerCase()),p=d[d.length-1];if(e.aiProvider){let f=await _l(e.aiProvider,c,p,l,it(e.workspaceFolder).snapshot().body);if(f.length>0)return{collection:o.name,request:a.name,source:"ai",suggestions:f.slice(0,l),hint:"Paste the snippets into the request's post-response script using set_request_script."}}let m=
|
|
821
|
+
});`,rationale:"Response body was non-JSON text."})}return n}var Fl,Bp,Dl=k(()=>{"use strict";Xn();er();ql();ko();Co();Eo();Ol();Jo();tt();Fe();Ne();Fl=["get","post","put","patch","delete","head","options"];Bp=[{toolNames:[x.scaffoldCollectionFromOpenApi],async handle({args:r,services:e}){let t=typeof r.specPath=="string"?r.specPath.trim():"";if(!t)throw A('"specPath" is required');let n=Nl(t,e.workspaceFolder);if(!at.existsSync(n))throw A(`OpenAPI spec file not found: "${n}"`);let i=await new Lt(e.collection,e.environmentConfig).import(n,{collectionName:typeof r.collectionName=="string"?r.collectionName:void 0,environmentName:typeof r.environmentName=="string"?r.environmentName:void 0});return{collectionId:i.collection.id,collectionName:i.collection.name,requestCount:i.collection.items.filter(o=>o.type==="request").length,environmentCreated:i.environmentCreated??null,hint:"Use list_requests to browse the scaffolded collection, then run_request to test individual endpoints."}}},{toolNames:[x.suggestAssertions],async handle({args:r,services:e,collections:t,runStore:n}){let s=r.collection;if(!(typeof r.request=="string"?r.request.trim():""))throw A('"request" is required');let o=W(s,t),a=We(r.request,o),c=Vt(e,o.id,a),l=typeof r.maxSuggestions=="number"?Math.min(20,Math.max(1,r.maxSuggestions)):10,d=Array.from(n.values()).filter(f=>f.status!=="running").flatMap(f=>f.allResults??[]).filter(f=>f.name===a.name||typeof f.name=="string"&&f.name.toLowerCase()===a.name.toLowerCase()),p=d[d.length-1];if(e.aiProvider){let f=await _l(e.aiProvider,c,p,l,it(e.workspaceFolder).snapshot().body);if(f.length>0)return{collection:o.name,request:a.name,source:"ai",suggestions:f.slice(0,l),hint:"Paste the snippets into the request's post-response script using set_request_script."}}let m=Py(c,p,l);return{collection:o.name,request:a.name,source:"heuristic",suggestions:m.slice(0,l),hint:"Paste the snippets into the request's post-response script using set_request_script."}}},{toolNames:[x.explainFailure],async handle({args:r,services:e,collections:t,runStore:n}){let s=typeof r.runId=="string"?r.runId.trim():void 0,i=typeof r.request=="string"?r.request.trim():"",o=typeof r.iteration=="number"?r.iteration:1;if(s){let u=n.require(s);if(u.status==="running")return{runId:s,status:"running",message:"The run has not completed yet. Try again in a moment."};if(!i)throw A('"request" is required when "runId" is provided');let d=u.allResults.find(v=>v.iteration===o&&(v.name===i||typeof v.name=="string"&&v.name.toLowerCase()===i.toLowerCase()));if(!d)throw new Error(`Request "${i}" (iteration ${o}) not found in run "${s}".`);let p=d.assertions?.every(v=>v.passed)??!0,m=d.error,f=d.assertions?.filter(v=>!v.passed)??[],h="",g=[];if(e.aiProvider&&(m||f.length>0)){let v=[it(e.workspaceFolder).snapshot().body,No(n,s).snapshot().body].filter(Boolean).join(`
|
|
822
822
|
|
|
823
|
-
`),y=await qy(e.aiProvider,d,v||void 0);y&&(h=y.diagnosis,g=y.suggestedFixes)}return h||(m?h=`The request itself failed to execute: ${m}. Check the URL, network access, authentication, and that the environment variables are set correctly.`:f.length>0?h=`${f.length} assertion(s) failed. Review the expected vs actual values below and verify the API contract.`:p?h="No failures detected. The request appears to have passed.":h="The request was marked as failed but no specific errors were captured."),{runId:s,request:d.name,iteration:o,status:d.status??"unknown",passed:d.passed??!0,error:m??null,failedAssertions:f,allAssertions:d.assertions??[],requestDetails:{method:d.method,url:d.url,requestBody:d.requestBody},responseDetails:{status:d.responseStatus,headers:d.responseHeaders,body:(()=>{let v=d.responseBody;return!v||v.length<=4096?v??null:{_truncated:!0,excerpt:v.slice(0,4096),totalLength:v.length,hint:'Body truncated. Pass include:["fullBody"] to get the complete body, or include:["report"] to generate an HTML report with full details.'}})()},diagnosis:h,suggestedFixes:g.length>0?g:m?["Verify the URL is correct and reachable","Check all required environment variables are set","Inspect authentication headers"]:f.map(v=>`Fix assertion "${v.name}": ${v.message??"expected value mismatch"}`)}}let a=r.collection;if(!i)throw A('"request" is required');let c=W(a,t);return{request:We(r.request,c).name,collection:c.name,message:"No live run id provided. Run the request first using run_request, then call explain_failure with the runId from the result.",hint:'Use run_request or run_collection with include:["consoleOutput"] to capture a fresh run, then pass the runId here.'}}},{toolNames:[x.aiSuggestEnvVars],handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.minOccurrences=="number"?Math.max(1,r.minOccurrences):1,o=(typeof r.environment=="string"?r.environment:void 0)??e.environmentConfig.getSelectedEnvironment()??void 0,a=Lo(n,s),c=Lp(n);return{task:{action:"analyze_and_apply_env_vars",instructions:["Review requestSummary. Find ALL hardcoded values: base URLs, API keys/tokens, tenant IDs, user IDs, secrets, repeated hostnames.","Skip placeholders ({{...}}), HTTP methods, standard header names, empty strings, booleans, short numbers.","Combine heuristicSuggestions with your own findings into one list.",`Call apply_env_vars immediately with: { collection: "${n.name}", suggestions: [...], ${o?`environment: "${o}"`:""} }`,"Do NOT ask for confirmation. Apply everything at once."],collection:n.name,businessContext:Bt(n).snapshot().body||void 0,heuristicSuggestions:a.map(l=>({varName:l.varName,value:l.value,reason:l.reason})),requestSummary:c,expectedCallAfterThis:"apply_env_vars"}}}},{toolNames:[x.aiEnhanceCollection],handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.offset=="number"?Math.max(0,r.offset):0,i=typeof r.limit=="number"?Math.min(20,Math.max(1,r.limit)):10,o=typeof r.folder=="string"?r.folder.toLowerCase():void 0,a=X(n).filter(({folderPath:u})=>!o||u.toLowerCase().includes(o)),c=a.slice(s,s+i).map(({request:u,folderPath:d})=>{let p=Vt(e,n.id,u);return{id:p.id,name:p.name,folder:d,method:p.method,url:p.url,headers:(p.headers??[]).filter(m=>m.enabled!==!1).map(m=>({key:m.key,value:m.value})),query:(p.query??[]).filter(m=>m.enabled!==!1).map(m=>({key:m.key,value:m.value})),currentBody:p.body?.type==="raw"&&typeof p.body.content=="string"?p.body.content:void 0,currentTestScript:e.collection.getRequestScript(n.id,p.id,"post-response")??void 0,description:p.description?.slice(0,200),doc:p.doc?p.doc.slice(0,600):void 0,operationId:p.operationId}}),l=s+i<a.length;return{task:{action:"enhance_requests",instructions:["For each request in requests, produce body and/or testScript as appropriate:"," body: realistic JSON (or form) example matching the endpoint purpose. Only for POST/PUT/PATCH."," testScript: pm.test() assertions \u2014 check status code, response schema, key fields. Always provide this.",`Call apply_request_enhancements immediately with: { collection: "${n.name}", enhancements: [{ requestId, body?, testScript }] }`,l?`After applying, call ai_enhance_collection again with: { collection: "${n.name}", offset: ${s+i}, limit: ${i} } to continue.`:"This is the last batch \u2014 no further calls needed after applying.","Do NOT ask for confirmation. Apply everything at once."],collection:n.name,total:a.length,offset:s,hasMore:l,nextOffset:l?s+i:void 0,requests:c,expectedCallAfterThis:"apply_request_enhancements"}}}},{toolNames:[x.suggestEnvVars],handle({args:r,collections:e}){let t=W(r.collection,e),n=typeof r.minOccurrences=="number"?Math.max(1,r.minOccurrences):1,s=Lo(t,n),i=Lp(t);return{collection:t.name,businessContext:Bt(t).snapshot().body||void 0,heuristicSuggestions:s.map(o=>({varName:o.varName,value:o.value,reason:o.reason,occurrences:o.occurrences.length})),requestSummary:i,hint:"Review requestSummary for additional hardcoded values, then call apply_env_vars with your combined {value, varName} list."}}},{toolNames:[x.applyEnvVars],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=r.suggestions;if(!Array.isArray(s)||s.length===0)throw A('"suggestions" must be a non-empty array of {value, varName} objects');let i=s,o=El(n.items,i);await e.collection.saveCollection(n);let c=(typeof r.environment=="string"?r.environment:void 0)??e.environmentConfig.getSelectedEnvironment();if(c)for(let u of i)e.environmentConfig.setEnvironmentVariable(u.varName,u.value,c);let l=Object.values(o).reduce((u,d)=>u+d,0);return{collection:n.name,applied:i.map(u=>({varName:u.varName,replacements:o[u.varName]??0})),totalReplacements:l,...c?{writtenToEnvironment:c}:{}}}},{toolNames:[x.getRequestsForEnhancement],handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.offset=="number"?Math.max(0,r.offset):0,i=typeof r.limit=="number"?Math.min(30,Math.max(1,r.limit)):10,o=typeof r.folder=="string"?r.folder.toLowerCase():void 0,a=X(n).filter(({folderPath:l})=>!o||l.toLowerCase().includes(o)),c=a.slice(s,s+i).map(({request:l,folderPath:u})=>{let d=Vt(e,n.id,l);return{id:d.id,name:d.name,folder:u,method:d.method,url:d.url,headers:(d.headers??[]).filter(p=>p.enabled!==!1).map(p=>({key:p.key,value:p.value})),query:(d.query??[]).filter(p=>p.enabled!==!1).map(p=>({key:p.key,value:p.value})),currentBody:d.body?.type==="raw"&&typeof d.body.content=="string"?d.body.content:void 0,currentTestScript:e.collection.getRequestScript(n.id,d.id,"post-response")??void 0}});return{collection:n.name,total:a.length,offset:s,limit:i,requests:c,hasMore:s+i<a.length,hint:"For each request write a realistic body and pm.test() assertions, then call apply_request_enhancements."}}},{toolNames:[x.applyRequestEnhancements],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=r.enhancements;if(!Array.isArray(s)||s.length===0)throw A('"enhancements" must be a non-empty array');let i=[];for(let o of s){let{requestId:a,body:c,testScript:l}=o;if(!X(n).find(({request:p})=>p.id===a)){i.push({requestId:a,applied:["skipped: request not found"]});continue}let d=[];typeof c=="string"&&(await e.collection.updateRequest(n.id,a,{body:{type:"raw",content:c,format:"json"}}),d.push("body")),typeof l=="string"&&(await e.collection.setRequestScript(n.id,a,"post-response",l),d.push("testScript")),i.push({requestId:a,applied:d})}return{collection:n.name,results:i,totalUpdated:i.filter(o=>o.applied.length>0&&!o.applied[0].startsWith("skipped")).length}}},{toolNames:[x.analyzeCoverage,x.aiAnalyzeCoverage],async handle({args:r,services:e,collections:t,tool:n}){let s=W(r.collection,t),i=typeof r.folder=="string"?r.folder.toLowerCase():void 0,o=X(s).filter(({folderPath:f})=>!i||f.toLowerCase().includes(i)),a=o.map(({request:f,folderPath:h})=>{let v=((e.collection.getRequestScript(s.id,f.id,"post-response")??"").match(/pm\.test\s*\(/g)??[]).length;return{id:f.id,name:f.name,method:f.method,folder:h,hasAssertions:v>0,assertionCount:v}}),c=a.filter(f=>f.hasAssertions).length,l=a.length,u=l===0?100:Math.round(c/l*100),d=[],p=typeof r.specPath=="string"?r.specPath.trim():"";if(p)try{let f=Nl(p,e.workspaceFolder),g=(await jp(f)).paths??{};for(let[v,y]of Object.entries(g))for(let S of Fl){if(!(S in y))continue;let b=S.toUpperCase();o.some(({request:w})=>w.method.toUpperCase()===b&&(w.url??"").replace(/\{\{[^}]+\}\}/g,"{param}").includes(v.replace(/\{[^}]+\}/g,"{param}").replace(/^\//,"")))||d.push({method:b,path:v})}}catch{}let m=a.filter(f=>!f.hasAssertions);if(n===x.aiAnalyzeCoverage){let f=[];return m.length>0&&f.push(`${m.length} request(s) have no pm.test() assertions. Call ai_enhance_collection (collection="${s.name}") to add assertions to all of them.`),d.length>0&&f.push(`${d.length} spec operation(s) have no matching collection request. Call generate_scenarios (collection="${s.name}") to generate negative and edge-case requests for them.`),f.length===0&&f.push(`Coverage is ${u}% \u2014 all requests have assertions and all spec operations are covered.`),{task:{action:"ai_analyze_coverage",instructions:["Review the coverage data below.",...f,"Address the highest-impact gap first. Do NOT ask for confirmation \u2014 proceed immediately."],collection:s.name,coveragePct:u,covered:c,total:l,untestedRequests:m,untestedOperations:d,expectedCallAfterThis:m.length>0?"ai_enhance_collection":d.length>0?"generate_scenarios":null}}}return{collection:s.name,coveragePct:u,covered:c,total:l,requests:a,...d.length>0?{untestedOperations:d}:{}}}},{toolNames:[x.generateRequestFromIntent],handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.intent=="string"?r.intent.trim():"";if(!s)throw A('"intent" is required \u2014 describe what to test in plain English');let o=X(n).slice(0,20).map(({request:l,folderPath:u})=>({name:l.name,method:l.method,url:l.url??"",folder:u})),a=Object.keys(e.environmentConfig.getResolvedEnvironment(e.environmentConfig.getSelectedEnvironment())?.variables??{}),c=it(e.workspaceFolder).snapshot().body;return{task:{action:"generate_request_from_intent",instructions:[`Intent: "${s}"`,"Using the collection context below, determine: method, full URL (reuse existing {{vars}} where possible), headers, request body (if applicable), and expected HTTP status.","Then immediately:"," 1. Call create_request with name, method, url, and body.",' 2. Call set_request_script (phase: "post-response") with pm.test() assertions that verify the intent.',"Do NOT ask for confirmation \u2014 implement the full request + assertions in one shot."],collection:n.name,intent:s,businessContext:[Bt(n).snapshot().body,c].filter(Boolean).join(`
|
|
823
|
+
`),y=await Ay(e.aiProvider,d,v||void 0);y&&(h=y.diagnosis,g=y.suggestedFixes)}return h||(m?h=`The request itself failed to execute: ${m}. Check the URL, network access, authentication, and that the environment variables are set correctly.`:f.length>0?h=`${f.length} assertion(s) failed. Review the expected vs actual values below and verify the API contract.`:p?h="No failures detected. The request appears to have passed.":h="The request was marked as failed but no specific errors were captured."),{runId:s,request:d.name,iteration:o,status:d.status??"unknown",passed:d.passed??!0,error:m??null,failedAssertions:f,allAssertions:d.assertions??[],requestDetails:{method:d.method,url:d.url,requestBody:d.requestBody},responseDetails:{status:d.responseStatus,headers:d.responseHeaders,body:(()=>{let v=d.responseBody;return!v||v.length<=4096?v??null:{_truncated:!0,excerpt:v.slice(0,4096),totalLength:v.length,hint:'Body truncated. Pass include:["fullBody"] to get the complete body, or include:["report"] to generate an HTML report with full details.'}})()},diagnosis:h,suggestedFixes:g.length>0?g:m?["Verify the URL is correct and reachable","Check all required environment variables are set","Inspect authentication headers"]:f.map(v=>`Fix assertion "${v.name}": ${v.message??"expected value mismatch"}`)}}let a=r.collection;if(!i)throw A('"request" is required');let c=W(a,t);return{request:We(r.request,c).name,collection:c.name,message:"No live run id provided. Run the request first using run_request, then call explain_failure with the runId from the result.",hint:'Use run_request or run_collection with include:["consoleOutput"] to capture a fresh run, then pass the runId here.'}}},{toolNames:[x.aiSuggestEnvVars],handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.minOccurrences=="number"?Math.max(1,r.minOccurrences):1,o=(typeof r.environment=="string"?r.environment:void 0)??e.environmentConfig.getSelectedEnvironment()??void 0,a=Lo(n,s),c=Lp(n);return{task:{action:"analyze_and_apply_env_vars",instructions:["Review requestSummary. Find ALL hardcoded values: base URLs, API keys/tokens, tenant IDs, user IDs, secrets, repeated hostnames.","Skip placeholders ({{...}}), HTTP methods, standard header names, empty strings, booleans, short numbers.","Combine heuristicSuggestions with your own findings into one list.",`Call apply_env_vars immediately with: { collection: "${n.name}", suggestions: [...], ${o?`environment: "${o}"`:""} }`,"Do NOT ask for confirmation. Apply everything at once."],collection:n.name,businessContext:Bt(n).snapshot().body||void 0,heuristicSuggestions:a.map(l=>({varName:l.varName,value:l.value,reason:l.reason})),requestSummary:c,expectedCallAfterThis:"apply_env_vars"}}}},{toolNames:[x.aiEnhanceCollection],handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.offset=="number"?Math.max(0,r.offset):0,i=typeof r.limit=="number"?Math.min(20,Math.max(1,r.limit)):10,o=typeof r.folder=="string"?r.folder.toLowerCase():void 0,a=X(n).filter(({folderPath:u})=>!o||u.toLowerCase().includes(o)),c=a.slice(s,s+i).map(({request:u,folderPath:d})=>{let p=Vt(e,n.id,u);return{id:p.id,name:p.name,folder:d,method:p.method,url:p.url,headers:(p.headers??[]).filter(m=>m.enabled!==!1).map(m=>({key:m.key,value:m.value})),query:(p.query??[]).filter(m=>m.enabled!==!1).map(m=>({key:m.key,value:m.value})),currentBody:p.body?.type==="raw"&&typeof p.body.content=="string"?p.body.content:void 0,currentTestScript:e.collection.getRequestScript(n.id,p.id,"post-response")??void 0,description:p.description?.slice(0,200),doc:p.doc?p.doc.slice(0,600):void 0,operationId:p.operationId}}),l=s+i<a.length;return{task:{action:"enhance_requests",instructions:["For each request in requests, produce body and/or testScript as appropriate:"," body: realistic JSON (or form) example matching the endpoint purpose. Only for POST/PUT/PATCH."," testScript: pm.test() assertions \u2014 check status code, response schema, key fields. Always provide this.",`Call apply_request_enhancements immediately with: { collection: "${n.name}", enhancements: [{ requestId, body?, testScript }] }`,l?`After applying, call ai_enhance_collection again with: { collection: "${n.name}", offset: ${s+i}, limit: ${i} } to continue.`:"This is the last batch \u2014 no further calls needed after applying.","Do NOT ask for confirmation. Apply everything at once."],collection:n.name,total:a.length,offset:s,hasMore:l,nextOffset:l?s+i:void 0,requests:c,expectedCallAfterThis:"apply_request_enhancements"}}}},{toolNames:[x.suggestEnvVars],handle({args:r,collections:e}){let t=W(r.collection,e),n=typeof r.minOccurrences=="number"?Math.max(1,r.minOccurrences):1,s=Lo(t,n),i=Lp(t);return{collection:t.name,businessContext:Bt(t).snapshot().body||void 0,heuristicSuggestions:s.map(o=>({varName:o.varName,value:o.value,reason:o.reason,occurrences:o.occurrences.length})),requestSummary:i,hint:"Review requestSummary for additional hardcoded values, then call apply_env_vars with your combined {value, varName} list."}}},{toolNames:[x.applyEnvVars],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=r.suggestions;if(!Array.isArray(s)||s.length===0)throw A('"suggestions" must be a non-empty array of {value, varName} objects');let i=s,o=El(n.items,i);await e.collection.saveCollection(n);let c=(typeof r.environment=="string"?r.environment:void 0)??e.environmentConfig.getSelectedEnvironment();if(c)for(let u of i)e.environmentConfig.setEnvironmentVariable(u.varName,u.value,c);let l=Object.values(o).reduce((u,d)=>u+d,0);return{collection:n.name,applied:i.map(u=>({varName:u.varName,replacements:o[u.varName]??0})),totalReplacements:l,...c?{writtenToEnvironment:c}:{}}}},{toolNames:[x.getRequestsForEnhancement],handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.offset=="number"?Math.max(0,r.offset):0,i=typeof r.limit=="number"?Math.min(30,Math.max(1,r.limit)):10,o=typeof r.folder=="string"?r.folder.toLowerCase():void 0,a=X(n).filter(({folderPath:l})=>!o||l.toLowerCase().includes(o)),c=a.slice(s,s+i).map(({request:l,folderPath:u})=>{let d=Vt(e,n.id,l);return{id:d.id,name:d.name,folder:u,method:d.method,url:d.url,headers:(d.headers??[]).filter(p=>p.enabled!==!1).map(p=>({key:p.key,value:p.value})),query:(d.query??[]).filter(p=>p.enabled!==!1).map(p=>({key:p.key,value:p.value})),currentBody:d.body?.type==="raw"&&typeof d.body.content=="string"?d.body.content:void 0,currentTestScript:e.collection.getRequestScript(n.id,d.id,"post-response")??void 0}});return{collection:n.name,total:a.length,offset:s,limit:i,requests:c,hasMore:s+i<a.length,hint:"For each request write a realistic body and pm.test() assertions, then call apply_request_enhancements."}}},{toolNames:[x.applyRequestEnhancements],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=r.enhancements;if(!Array.isArray(s)||s.length===0)throw A('"enhancements" must be a non-empty array');let i=[];for(let o of s){let{requestId:a,body:c,testScript:l}=o;if(!X(n).find(({request:p})=>p.id===a)){i.push({requestId:a,applied:["skipped: request not found"]});continue}let d=[];typeof c=="string"&&(await e.collection.updateRequest(n.id,a,{body:{type:"raw",content:c,format:"json"}}),d.push("body")),typeof l=="string"&&(await e.collection.setRequestScript(n.id,a,"post-response",l),d.push("testScript")),i.push({requestId:a,applied:d})}return{collection:n.name,results:i,totalUpdated:i.filter(o=>o.applied.length>0&&!o.applied[0].startsWith("skipped")).length}}},{toolNames:[x.analyzeCoverage,x.aiAnalyzeCoverage],async handle({args:r,services:e,collections:t,tool:n}){let s=W(r.collection,t),i=typeof r.folder=="string"?r.folder.toLowerCase():void 0,o=X(s).filter(({folderPath:f})=>!i||f.toLowerCase().includes(i)),a=o.map(({request:f,folderPath:h})=>{let v=((e.collection.getRequestScript(s.id,f.id,"post-response")??"").match(/pm\.test\s*\(/g)??[]).length;return{id:f.id,name:f.name,method:f.method,folder:h,hasAssertions:v>0,assertionCount:v}}),c=a.filter(f=>f.hasAssertions).length,l=a.length,u=l===0?100:Math.round(c/l*100),d=[],p=typeof r.specPath=="string"?r.specPath.trim():"";if(p)try{let f=Nl(p,e.workspaceFolder),g=(await jp(f)).paths??{};for(let[v,y]of Object.entries(g))for(let S of Fl){if(!(S in y))continue;let b=S.toUpperCase();o.some(({request:w})=>w.method.toUpperCase()===b&&(w.url??"").replace(/\{\{[^}]+\}\}/g,"{param}").includes(v.replace(/\{[^}]+\}/g,"{param}").replace(/^\//,"")))||d.push({method:b,path:v})}}catch{}let m=a.filter(f=>!f.hasAssertions);if(n===x.aiAnalyzeCoverage){let f=[];return m.length>0&&f.push(`${m.length} request(s) have no pm.test() assertions. Call ai_enhance_collection (collection="${s.name}") to add assertions to all of them.`),d.length>0&&f.push(`${d.length} spec operation(s) have no matching collection request. Call generate_scenarios (collection="${s.name}") to generate negative and edge-case requests for them.`),f.length===0&&f.push(`Coverage is ${u}% \u2014 all requests have assertions and all spec operations are covered.`),{task:{action:"ai_analyze_coverage",instructions:["Review the coverage data below.",...f,"Address the highest-impact gap first. Do NOT ask for confirmation \u2014 proceed immediately."],collection:s.name,coveragePct:u,covered:c,total:l,untestedRequests:m,untestedOperations:d,expectedCallAfterThis:m.length>0?"ai_enhance_collection":d.length>0?"generate_scenarios":null}}}return{collection:s.name,coveragePct:u,covered:c,total:l,requests:a,...d.length>0?{untestedOperations:d}:{}}}},{toolNames:[x.generateRequestFromIntent],handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.intent=="string"?r.intent.trim():"";if(!s)throw A('"intent" is required \u2014 describe what to test in plain English');let o=X(n).slice(0,20).map(({request:l,folderPath:u})=>({name:l.name,method:l.method,url:l.url??"",folder:u})),a=Object.keys(e.environmentConfig.getResolvedEnvironment(e.environmentConfig.getSelectedEnvironment())?.variables??{}),c=it(e.workspaceFolder).snapshot().body;return{task:{action:"generate_request_from_intent",instructions:[`Intent: "${s}"`,"Using the collection context below, determine: method, full URL (reuse existing {{vars}} where possible), headers, request body (if applicable), and expected HTTP status.","Then immediately:"," 1. Call create_request with name, method, url, and body.",' 2. Call set_request_script (phase: "post-response") with pm.test() assertions that verify the intent.',"Do NOT ask for confirmation \u2014 implement the full request + assertions in one shot."],collection:n.name,intent:s,businessContext:[Bt(n).snapshot().body,c].filter(Boolean).join(`
|
|
824
824
|
|
|
825
825
|
`)||void 0,existingRequests:o,availableEnvVars:a,targetFolder:typeof r.folder=="string"?r.folder:void 0,expectedCallAfterThis:"create_request"}}}},{toolNames:[x.designApiFromIntent],async handle({args:r,services:e}){let t=typeof r.intent=="string"?r.intent.trim():"";if(!t)throw A('"intent" is required \u2014 describe the API you want designed');let n=e.aiProvider??yi();if(!n)throw new Error("design_api_from_intent requires an AI provider. Set OPENAI_API_KEY or ANTHROPIC_API_KEY, or use the extension (which wires Copilot).");let s=new Lt(e.collection,e.environmentConfig),i=new un(e.collection,e.environmentConfig,new dn({},{},{})),a=await new hi(s,i,n).designFromIntent(t,{collectionName:typeof r.collectionName=="string"?r.collectionName:void 0,baseUrl:typeof r.baseUrl=="string"?r.baseUrl:void 0,environmentName:typeof r.environmentName=="string"?r.environmentName:void 0,workspaceFolder:e.workspaceFolder}),c=[];if(r.apply===!0&&(await e.testSuite.updateSuite(a.suite),c.push(`suite:${a.suite.id}`),e.workspaceFolder)){let l=u=>ct.isAbsolute(u)?u:ct.join(e.workspaceFolder,u);if(typeof r.flowOut=="string"&&r.flowOut){let u=l(r.flowOut);at.mkdirSync(ct.dirname(u),{recursive:!0}),at.writeFileSync(u,a.flow,"utf-8"),c.push(`flow:${u}`)}if(typeof r.docsOut=="string"&&r.docsOut){let u=l(r.docsOut);at.mkdirSync(ct.dirname(u),{recursive:!0}),at.writeFileSync(u,a.docs,"utf-8"),c.push(`docs:${u}`)}if(typeof r.openapiOut=="string"&&r.openapiOut){let u=l(r.openapiOut);at.mkdirSync(ct.dirname(u),{recursive:!0}),at.writeFileSync(u,a.openapi,"utf-8"),c.push(`openapi:${u}`)}}return{intent:a.intent,collectionId:a.collectionId,collectionName:a.collectionName,environmentCreated:a.environmentCreated??null,aiGenerated:a.ai_generated,endpoints:a.endpoints.map(l=>({id:l.id,method:l.method,path:l.pathExpression,name:l.source?.symbolName??l.pathExpression,auth:l.auth?.required??!1,confidence:l.confidence})),suite:{id:a.suite.id,name:a.suite.name,nodeCount:a.suite.nodes.length},workflowChains:a.workflows.map(l=>({id:l.id,kind:l.kind,name:l.name,producer:{method:l.producer.method,path:l.producer.path},dependents:l.dependents.map(u=>({method:u.method,path:u.path}))})),flow:a.flow,openapi:a.openapi,docs:a.docs,applied:c,hint:r.apply!==!0?'Review the designed package. Call again with "apply": true to persist the suite and byproduct files.':void 0}}},{toolNames:[x.validateAgainstSpec],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.specPath=="string"?r.specPath.trim():"";if(!s)throw A('"specPath" is required');let i=Nl(s,e.workspaceFolder),o;try{o=await jp(i)}catch(f){throw new Error(`Could not load spec at "${i}": ${f instanceof Error?f.message:String(f)}`)}let a=o.paths??{},c=X(n),l=[],u=[],d=[],p=f=>f.replace(/\{\{[^}]+\}\}/g,"{p}").replace(/\{[^}]+\}/g,"{p}").replace(/\/+$/,"");for(let[f,h]of Object.entries(a))for(let g of Fl){if(!(g in h))continue;let v=h[g],y=g.toUpperCase(),S=p(f),b=c.find(({request:C})=>C.method.toUpperCase()===y&&p(C.url??"").includes(S));if(!b)l.push({method:y,path:f,operationId:v.operationId});else{let C=e.collection.getRequestScript(n.id,b.request.id,"post-response")??"";/pm\.test\s*\(/.test(C)||u.push({method:y,path:f,requestName:b.request.name})}}let m=new Set(Object.entries(a).flatMap(([f,h])=>Fl.filter(g=>g in h).map(g=>`${g.toUpperCase()}:${p(f)}`)));for(let{request:f}of c){let h=p(f.url??""),g=`${f.method.toUpperCase()}:`;[...m].some(y=>y.startsWith(g)&&h.includes(y.split(":")[1]))||d.push({method:f.method,url:f.url??"",requestName:f.name})}return{collection:n.name,spec:ct.basename(s),summary:{untestedOperations:l.length,matchedWithoutAssertions:u.length,extraRequests:d.length},untestedOperations:l,matchedWithoutAssertions:u,extraRequests:d,hint:l.length>0?`Call generate_scenarios (collection="${n.name}") to create negative/edge-case requests for untested operations.`:"All spec operations have matching collection requests."}}},{toolNames:[x.generateScenarios],handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.request=="string"?r.request.trim().toLowerCase():void 0,i=typeof r.folder=="string"?r.folder.toLowerCase():void 0,o=typeof r.offset=="number"?Math.max(0,r.offset):0,a=typeof r.limit=="number"?Math.min(10,Math.max(1,r.limit)):5,c=X(n).filter(({request:d,folderPath:p})=>!(s&&d.name.toLowerCase()!==s&&!d.name.toLowerCase().includes(s)||i&&!p.toLowerCase().includes(i))),l=c.slice(o,o+a).map(({request:d,folderPath:p})=>{let m=Vt(e,n.id,d);return{id:m.id,name:m.name,method:m.method,url:m.url??"",folder:p,headers:(m.headers??[]).filter(f=>f.enabled!==!1).map(f=>({key:f.key,value:f.value})),body:m.body?.type==="raw"&&typeof m.body.content=="string"?m.body.content:void 0,currentTestScript:e.collection.getRequestScript(n.id,m.id,"post-response")??void 0,description:m.description?.slice(0,200),doc:m.doc?m.doc.slice(0,600):void 0,operationId:m.operationId}}),u=it(e.workspaceFolder).snapshot().body;return{task:{action:"generate_scenarios",instructions:["For each request below, generate negative and edge-case test scenario variants.","Scenarios to generate per request (as applicable):"," - Missing required fields \u2192 expect 400 or 422"," - Invalid field type or format (e.g. string where number expected) \u2192 expect 400"," - No Authorization header (remove it) \u2192 expect 401"," - Valid auth but insufficient scope/role \u2192 expect 403"," - Non-existent resource ID in URL \u2192 expect 404"," - Boundary values: empty string, max-length string, 0, -1, very large number","For each scenario:",' 1. Call create_request with a descriptive name (e.g. "Create User - Missing Email \u2192 422"), method, url, and body.',' 2. Immediately call set_request_script (phase: "post-response") with the status assertion.'," 3. Place the new request in the same folder as the original (use folder argument in create_request).","If task.hasMore is true, call generate_scenarios again with task.nextOffset after finishing this batch.","Do NOT ask for confirmation \u2014 generate all scenarios autonomously."],collection:n.name,businessContext:[Bt(n).snapshot().body,u].filter(Boolean).join(`
|
|
826
826
|
|
|
827
827
|
`)||void 0,requests:l,total:c.length,offset:o,hasMore:o+a<c.length,nextOffset:o+a,expectedCallAfterThis:"create_request"}}}},{toolNames:[x.healAssertions],handle({args:r,services:e,collections:t,runStore:n}){let s=W(r.collection,t),i=Vt(e,s.id,We(r.request,s)),o=e.collection.getRequestScript(s.id,i.id,"post-response")??"",a,c=typeof r.runId=="string"?r.runId.trim():void 0;if(c)try{let u=n.require(c).allResults.find(d=>typeof d.name=="string"&&d.name.toLowerCase()===i.name.toLowerCase());u&&(a={status:u.status,responseBody:u.responseBody,responseHeaders:u.responseHeaders,failedTests:u.failedTests})}catch{}return{task:{action:"heal_assertions",instructions:[`Request: ${i.method} ${i.url??""}`,"The current test script may have stale or incorrect assertions (e.g. wrong status code, missing/renamed fields).","Compare task.currentScript against task.lastResponse (if available).","Rewrite the complete post-response script so all assertions match the observed response while keeping valid checks.",'Call set_request_script (phase: "post-response") with the updated script immediately.',"Do NOT ask for confirmation."],collection:s.name,request:i.name,method:i.method,url:i.url??"",businessContext:[st(i,Hp(s,i)).snapshot().body,it(e.workspaceFolder).snapshot().body].filter(Boolean).join(`
|
|
828
828
|
|
|
829
|
-
`)||void 0,currentScript:o,lastResponse:a??null,note:a?"Last response data available \u2014 use it to align assertions with actual behavior.":"No run data available \u2014 run the request first with run_request, then call heal_assertions again with the runId.",expectedCallAfterThis:"set_request_script"}}}},{toolNames:[x.generateIterationData],handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=Vt(e,n.id,We(r.request,n)),i=typeof r.iterations=="number"?Math.min(50,Math.max(1,r.iterations)):5,o=s.body?.type==="raw"&&typeof s.body.content=="string"?s.body.content:void 0,a=(s.headers??[]).filter(d=>d.enabled!==!1).map(d=>({key:d.key,value:d.value})),c=(s.query??[]).filter(d=>d.enabled!==!1).map(d=>({key:d.key,value:d.value})),l=/\{\{([^}]+)\}\}/g,u=new Set;for(let d of[s.url??"",o??"",...a.map(p=>p.value),...c.map(p=>p.value)]){let p;for(l.lastIndex=0;(p=l.exec(d))!==null;)u.add(p[1])}return{task:{action:"generate_iteration_data",instructions:[`Generate ${i} test data rows for: ${s.method} ${s.url??""}`,`The request uses these {{variable}} placeholders: ${[...u].join(", ")||"(none detected)"}`,"Each row must be a JSON object whose keys match the placeholder names.","Cover a mix of: (1) valid happy-path data, (2) boundary values, (3) invalid inputs that should fail, (4) edge cases.",'Return the rows as a JSON array in a code block labeled "iterationData".',"This data can be used with: http-forge run-request --collection ... --variables '[...]' or passed to run_request via the variables argument."],collection:n.name,request:s.name,method:s.method,url:s.url??"",businessContext:st(s,Hp(n,s)).snapshot().body||void 0,body:o??null,headers:a,queryParams:c,placeholders:[...u],iterations:i}}}}]});function Up(r,e){for(let t of r){if(t.type!=="folder")continue;let n=t;if(n.name===e||e.endsWith("/"+n.name))return{id:n.id};let s=Up(n.items??[],e);if(s)return s}}var Vp,zp=k(()=>{"use strict";Fe();Ne();Ne();Vp=[{toolNames:[x.createCollection],async handle({args:r,services:e}){let t=typeof r.name=="string"?r.name.trim():"";if(!t)throw A('"name" is required');let n=await e.collection.createCollection(t);return{id:n.id,name:n.name,created:!0,hint:"Collection is empty. Call create_folder to add folders, or create_request to add requests directly."}}},{toolNames:[x.renameCollection],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.newName=="string"?r.newName.trim():"";if(!s)throw A('"newName" is required');return await e.collection.renameCollection(n.id,s),{id:n.id,oldName:n.name,newName:s,renamed:!0}}},{toolNames:[x.deleteCollection],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw A('"confirm" must be true to delete a collection');let n=W(r.collection,t);return await e.collection.deleteCollection(n.id),{deleted:!0,collection:n.name}}},{toolNames:[x.duplicateCollection],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.newName=="string"?r.newName.trim():"";if(!s)throw A('"newName" is required');let i=await e.collection.duplicateCollection(n.id,s);return{id:i.id,name:i.name,duplicatedFrom:n.name}}},{toolNames:[x.createFolder],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.name=="string"?r.name.trim():"";if(!s)throw A('"name" is required');let i;if(typeof r.parentFolder=="string"&&r.parentFolder.trim()){let a=r.parentFolder.toLowerCase(),c=qe(n);if(X(n).map(u=>u.folderPath)&&c.find(u=>u.folderPath===r.parentFolder||u.folderPath.toLowerCase()===a)){let d=qe(n).find(p=>p.folderPath===r.parentFolder||p.folderPath.toLowerCase()===a);if(d){let p=n.items;i=Up(p,d.folderPath)?.id}}}let o=await e.collection.createFolder({collectionId:n.id,name:s,parentId:i});return{id:o.id,name:o.name,created:!0,collection:n.name}}},{toolNames:[x.deleteFolder],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw A('"confirm" must be true to delete a folder');let n=W(r.collection,t);if(typeof r.folder!="string"||!r.folder.trim())throw A('"folder" is required');let s=r.folder.toLowerCase(),i=qe(n).find(c=>c.folderPath===r.folder||c.folderPath.toLowerCase()===s);if(!i)throw A(`folder "${r.folder}" not found in collection "${n.name}"`);let o=$l(n.items,i.folderId);if(!o)throw A(`folder "${r.folder}" could not be resolved`);let a=i.requestCount;return await e.collection.deleteFolder(n.id,o.id),{deleted:!0,folder:i.folderPath,requestsRemoved:a}}}]});var Ml=k(()=>{"use strict"});var Jp=k(()=>{"use strict"});import*as Rt from"fs";import*as Kr from"path";var Py,Iy,Ty,Qr,Xo=k(()=>{"use strict";Py=["package.json","src/main.ts","src/main.js","src/app.ts","src/app.js","pom.xml","build.gradle","build.gradle.kts","settings.gradle","requirements.txt","pyproject.toml","poetry.lock","Pipfile","app/main.py","main.py"],Iy={express:["express","router.","app.use(","app.get(","express.Router"],nestjs:["@nestjs/common","@Controller(","@Get(","@Post("],fastify:["fastify","fastify.route(","fastify.get(","register("],lambda:["exports.handler","event.pathParameters","APIGatewayProxyEvent","aws-lambda"],spring:["@RestController","@Controller","@GetMapping","@PostMapping","@RequestMapping"],fastapi:["from fastapi","import fastapi","@app.get(","@router.get("],unknown:[]},Ty={express:[".ts",".js"],nestjs:[".ts",".js"],fastify:[".ts",".js"],lambda:[".ts",".js"],spring:[".java"],fastapi:[".py"]},Qr=class{buildFingerprint(e){let t=[],n=Kr.join(e,"package.json"),s;for(let i of Py){let o=Kr.join(e,i);Rt.existsSync(o)&&t.push(o)}if(Rt.existsSync(n))try{let i=JSON.parse(Rt.readFileSync(n,"utf-8"));s={dependencies:i.dependencies,devDependencies:i.devDependencies,scripts:i.scripts}}catch{}return{projectRoot:e,packageJsonPath:Rt.existsSync(n)?n:void 0,packageJson:s,evidenceFiles:t}}detectFrameworks(e){let t=[];return(this.hasDependency(e,"express")||this.hasSourceHint(e,"express"))&&t.push("express"),(this.hasDependency(e,"@nestjs/common")||this.hasSourceHint(e,"nestjs"))&&t.push("nestjs"),(this.hasDependency(e,"fastify")||this.hasSourceHint(e,"fastify"))&&t.push("fastify"),(this.hasBuildFile(e,"pom.xml")||this.hasBuildFile(e,"build.gradle")||this.hasBuildFile(e,"build.gradle.kts")||this.hasBuildFile(e,"settings.gradle")||this.hasSourceHint(e,"spring"))&&t.push("spring"),(this.hasBuildFile(e,"requirements.txt")||this.hasBuildFile(e,"pyproject.toml")||this.hasBuildFile(e,"poetry.lock")||this.hasBuildFile(e,"Pipfile")||this.hasSourceHint(e,"fastapi"))&&t.push("fastapi"),t.includes("express")||t.includes("fastify")||(this.hasDependency(e,"@types/aws-lambda")||this.hasDependency(e,"aws-lambda")||this.hasDependency(e,"serverless")||this.hasSourceHint(e,"lambda"))&&t.push("lambda"),t.length>0?t:["unknown"]}hasDependency(e,t){let n=e.packageJson?.dependencies??{},s=e.packageJson?.devDependencies??{};return!!(n[t]||s[t])}hasBuildFile(e,t){return Rt.existsSync(Kr.join(e.projectRoot,t))}hasSourceHint(e,t){let n=["src","app"],s=Iy[t],i=Ty[t],o=0,a=120;for(let c of n){let l=Kr.join(e.projectRoot,c);if(!Rt.existsSync(l))continue;let u=[l];for(;u.length>0&&o<a;){let d=u.shift(),p;try{p=Rt.readdirSync(d,{withFileTypes:!0})}catch{continue}for(let m of p){let f=Kr.join(d,m.name);if(m.isDirectory()){u.push(f);continue}if(!m.isFile()||!i.some(g=>f.endsWith(g)))continue;o+=1;let h="";try{h=Rt.readFileSync(f,"utf-8")}catch{continue}if(s.some(g=>h.includes(g)))return!0}}}return!1}}});import*as Wp from"fs";import*as Gp from"path";function lt(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=Wp.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=Gp.join(n,i.name);if(i.isDirectory()){Oy.has(i.name)||t.push(o);continue}i.isFile()&&($y.test(i.name)||(o.endsWith(".ts")||o.endsWith(".js"))&&e.push(o))}}return e}var Oy,$y,mn=k(()=>{"use strict";Oy=new Set(["node_modules",".git",".next","dist","build","out","coverage","__tests__","__mocks__","__fixtures__"]),$y=/\.(?:test|spec|stories|min)\.[cm]?[tj]sx?$|\.d\.[cm]?ts$/});import*as Kp from"fs";import*as ea from"path";function ta(r,e){let t=e.customSeedLoaderModulePath?.trim();if(!t)return{endpoints:[],warnings:[]};let n=ea.isAbsolute(t)?t:ea.join(r,t);if(!Kp.existsSync(n))return{endpoints:[],warnings:[{code:"seed-loader-failed",filePath:n,message:`Custom seed loader module not found: ${n}`}]};try{let s=pe(n),i=s.loadSeedManifestEndpoints??s.default;if(typeof i!="function")return{endpoints:[],warnings:[{code:"seed-loader-failed",filePath:n,message:"Custom seed loader module must export a function named loadSeedManifestEndpoints or a default function."}]};let o=i(r,e);return Array.isArray(o)?{endpoints:o,warnings:[]}:{endpoints:o?.endpoints??[],warnings:o?.warnings??[]}}catch(s){return{endpoints:[],warnings:[{code:"seed-loader-failed",filePath:n,message:`Custom seed loader failed at ${n}: ${s instanceof Error?s.message:String(s)}`}]}}}var na=k(()=>{"use strict"});function Zp(r,e){let t=r.projectName?.trim();if(t)return t;let n=Qp(r.source.filePath),s=Fy(n);if(s)return s;let i;for(let a of e){let c=Qp(a);(n===c||n.startsWith(`${c}/`))&&(!i||c.length>i.length)&&(i=c)}if(!i)return;let o=i.split("/").filter(Boolean);return o[o.length-1]||void 0}function Fy(r){return r.match(/(?:^|\/)agl-config-([^/]+)(?:\/|$)/)?.[1]}function Qp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var jl=k(()=>{"use strict"});import*as ca from"fs";import*as sr from"path";import*as R from"typescript";function hn(r,e){return r==="high"&&e==="high"?"high":r==="low"||e==="low"?"low":"medium"}function gn(r,e,t){let n=[],s=/:([a-zA-Z_]\w*)/g,i=/\{([a-zA-Z_]\w*)\}/g,o;for(;(o=s.exec(r))!==null;)n.push({name:o[1],location:"path",required:!0,type:"string"});for(;(o=i.exec(r))!==null;)n.push({name:o[1],location:"path",required:!0,type:"string"});return n}function ia(r,e,t,n,s={visitedSymbols:new Set},i,o=["locals"]){let a=[],c=[],l=[],u,d=new Map,p=Zy(o),m=Ky(r,e,p),f=tv(r,e,p);if(i?.requestAliases)for(let w of i.requestAliases)m.add(w);if(i?.responseAliases)for(let w of i.responseAliases)f.add(w);let h=sf(e),g=Ny(e,t),v=Qy(r,t,h,g,m,f),y=(w,E)=>{let F=l.find(N=>N.statusCode===w);return F||(F={statusCode:w},l.push(F)),E&&(F.body={type:E,schema:F.body?.schema}),F};R.isFunctionLike(r)&&Wy(r,e,d,m,f,p);let S=(w,E)=>{let F=h.get(w);if(F){let M=`${t}:${w}`;if(s.visitedSymbols.has(M))return;s.visitedSymbols.add(M);let G=v.get(M),me=E?aa(E,F,m,f):void 0,Ce=rf(G,me),Ie=ia(F,e,t,n,s,Ce,o);Hl({parameters:a,requestBody:u,cookies:c,responses:l},Ie),!u&&Ie.requestBody&&(u=Ie.requestBody);return}let N=g.get(w);if(!N||s.visitedSymbols.has(N.symbolKey))return;s.visitedSymbols.add(N.symbolKey);let j=v.get(N.symbolKey),O=E?aa(E,N.node,m,f):void 0,D=rf(j,O),P=ia(N.node,N.sourceFile,N.filePath,n,s,D,o);Hl({parameters:a,requestBody:u,cookies:c,responses:l},P),!u&&P.requestBody&&(u=P.requestBody)},b=["POST","PUT","PATCH"].includes(n),C=w=>{R.isVariableDeclaration(w)&&Jy(w,e,d,m,f,p),R.isIdentifier(w)&&(R.isCallExpression(w.parent)&&w.parent.expression===w||S(w.text));let E=Zr(w,e,"query",d,m,f,p);if(E){let D=e.getLineAndCharacterOfPosition(w.getStart(e));a.push({name:E.path,location:"query",type:sa(w,e),detectionLocation:{filePath:t,line:D.line+1,column:D.character+1,accessMode:"read"}})}let F=Zr(w,e,"params",d,m,f,p);if(F){let D=e.getLineAndCharacterOfPosition(w.getStart(e));a.push({name:F.path,location:"path",required:!0,type:sa(w,e),detectionLocation:{filePath:t,line:D.line+1,column:D.character+1,accessMode:"read"}})}if(zy(w,e,m)&&!u){let D=e.getLineAndCharacterOfPosition(w.getStart(e));u={type:"json",required:b,detectionLocation:{filePath:t,line:D.line+1,column:D.character+1,accessMode:"read"}}}let N=Zr(w,e,"body",d,m,f,p);if(N){let D=e.getLineAndCharacterOfPosition(w.getStart(e));a.push({name:N.path,location:"body",type:sa(w,e),detectionLocation:{filePath:t,line:D.line+1,column:D.character+1,accessMode:"read"}}),u||(u={type:"json",required:b})}let j=Zr(w,e,"headers",d,m,f,p);if(j){let D=e.getLineAndCharacterOfPosition(w.getStart(e));a.push({name:j.path,location:"header",type:"string",detectionLocation:{filePath:t,line:D.line+1,column:D.character+1,accessMode:"read"}})}let O=Zr(w,e,"cookies",d,m,f,p);if(O){let D=e.getLineAndCharacterOfPosition(w.getStart(e));c.push({name:O.path,type:"request",detectionLocation:{filePath:t,line:D.line+1,column:D.character+1,accessMode:"read"}})}for(let D of p){let P=Zr(w,e,D,d,m,f,p);if(!P)continue;let M=e.getLineAndCharacterOfPosition(w.getStart(e));a.push({name:P.path,location:D,type:sa(w,e),detectionLocation:{filePath:t,line:M.line+1,column:M.character+1,accessMode:"read"}})}if(R.isCallExpression(w)){let D=Yy(w,e,f);D&&y(D.statusCode,D.bodyType)}if(R.isCallExpression(w)){let D=Xy(w,f);if(D){let P=y(D.statusCode);if(!P.headers?.some(M=>M.name===D.headerName)){let M=e.getLineAndCharacterOfPosition(w.getStart(e));P.headers=P.headers??[],P.headers.push({name:D.headerName,location:"header",type:"string",detectionLocation:{filePath:t,line:M.line+1,column:M.character+1,accessMode:"write"}})}}}if(R.isCallExpression(w)&&R.isPropertyAccessExpression(w.expression)&&nv(w.expression.expression,f)&&w.expression.name.text==="cookie"&&w.arguments[0]&&R.isStringLiteral(w.arguments[0])){let D=w.arguments[0].text;if(D&&!c.some(P=>P.name===D&&P.type==="response")){let P=e.getLineAndCharacterOfPosition(w.getStart(e));c.push({name:D,type:"response",httpOnly:!0,detectionLocation:{filePath:t,line:P.line+1,column:P.character+1,accessMode:"write"}})}}R.isCallExpression(w)&&R.isIdentifier(w.expression)&&S(w.expression.text,w),R.forEachChild(w,C)};return r&&C(r),{parameters:a,requestBody:b?u||{type:"json",required:!0}:void 0,cookies:c,responses:l.length>0?l:[{statusCode:200}]}}function bi(r,e,t,n,s=["locals"]){let i={parameters:[],requestBody:void 0,cookies:[],responses:[]};for(let o of r){let a=ia(o,e,t,n,void 0,void 0,s);Hl(i,a)}return i.parameters=yn(i.parameters),i.cookies=Vy(i.cookies),!i.requestBody&&["POST","PUT","PATCH"].includes(n)&&(i.requestBody={type:"json",required:!0}),i.responses.length===0&&(i.responses=[{statusCode:200}]),i}function sf(r){let e=new Map,t=n=>{R.isFunctionDeclaration(n)&&n.name&&e.set(n.name.text,n),R.isVariableDeclaration(n)&&R.isIdentifier(n.name)&&n.initializer&&(R.isArrowFunction(n.initializer)||R.isFunctionExpression(n.initializer))&&e.set(n.name.text,n.initializer),R.forEachChild(n,t)};return t(r),e}function Ny(r,e){let t=new Map,n=(s,i)=>{if(!s.startsWith("."))return;let o=Dy(e,s);if(!o)return;let a=_y(o);if(!a)return;let c=My(a,o);for(let l of i){let u=c.get(l.importedName);u&&t.set(l.localName,{node:u,sourceFile:a,filePath:o,symbolKey:`${o}:${l.importedName}`})}};for(let s of r.statements){if(R.isImportDeclaration(s)&&s.importClause&&R.isStringLiteral(s.moduleSpecifier)){let i=s.moduleSpecifier.text,o=[];s.importClause.name&&o.push({localName:s.importClause.name.text,importedName:"default"});let a=s.importClause.namedBindings;if(a&&R.isNamedImports(a))for(let c of a.elements)o.push({localName:c.name.text,importedName:c.propertyName?c.propertyName.text:c.name.text});n(i,o);continue}if(R.isVariableStatement(s))for(let i of s.declarationList.declarations){if(!i.initializer||!R.isCallExpression(i.initializer)||!R.isIdentifier(i.initializer.expression)||i.initializer.expression.text!=="require")continue;let o=i.initializer.arguments[0];if(!o||!R.isStringLiteral(o))continue;let a=o.text,c=[];if(R.isIdentifier(i.name))c.push({localName:i.name.text,importedName:"default"});else if(R.isObjectBindingPattern(i.name))for(let l of i.name.elements){if(!R.isIdentifier(l.name))continue;let u=l.propertyName&&(R.isIdentifier(l.propertyName)||R.isStringLiteral(l.propertyName))?l.propertyName.text:l.name.text;c.push({localName:l.name.text,importedName:u})}n(a,c)}}return t}function _y(r){let e="";try{e=ca.readFileSync(r,"utf-8")}catch{return}return R.createSourceFile(r,e,R.ScriptTarget.Latest,!0,r.endsWith(".ts")?R.ScriptKind.TS:R.ScriptKind.JS)}function Dy(r,e){let t=sr.resolve(sr.dirname(r),e),n=[t,`${t}.ts`,`${t}.js`,sr.join(t,"index.ts"),sr.join(t,"index.js")];for(let s of n)try{if(ca.statSync(s).isFile())return s}catch{continue}}function My(r,e){let t=new Map,n=sf(r),s=(i,o)=>{t.set(i,o)};for(let i of r.statements){if(R.isFunctionDeclaration(i)&&i.name&&Yp(i)){s(i.name.text,i),Xp(i)&&s("default",i);continue}if(R.isVariableStatement(i)&&Yp(i)){for(let c of i.declarationList.declarations)!R.isIdentifier(c.name)||!c.initializer||(R.isArrowFunction(c.initializer)||R.isFunctionExpression(c.initializer))&&(s(c.name.text,c.initializer),Xp(i)&&s("default",c.initializer));continue}if(R.isExportAssignment(i)){let c=i.expression;if(R.isIdentifier(c)){let l=n.get(c.text);l&&s("default",l)}else(R.isFunctionExpression(c)||R.isArrowFunction(c))&&s("default",c);continue}if(!R.isExpressionStatement(i)||!R.isBinaryExpression(i.expression))continue;let o=i.expression.left,a=i.expression.right;if(R.isPropertyAccessExpression(o)&&o.expression.getText(r)==="module.exports"){let c=o.name.text,l=Ll(a,n);l&&s(c,l);continue}if(o.getText(r)==="module.exports"){let c=Ll(a,n);c&&s("default",c);continue}if(R.isPropertyAccessExpression(o)&&o.expression.getText(r)==="exports"){let c=Ll(a,n);c&&s(o.name.text,c)}}return t}function Ll(r,e){if(R.isFunctionExpression(r)||R.isArrowFunction(r))return r;if(R.isIdentifier(r))return e.get(r.text)}function Yp(r){return R.canHaveModifiers(r)?!!R.getModifiers(r)?.some(e=>e.kind===R.SyntaxKind.ExportKeyword):!1}function Xp(r){return R.canHaveModifiers(r)?!!R.getModifiers(r)?.some(e=>e.kind===R.SyntaxKind.DefaultKeyword):!1}function Hl(r,e){r.parameters.push(...e.parameters),r.cookies.push(...e.cookies),!r.requestBody&&e.requestBody&&(r.requestBody=e.requestBody);for(let t of e.responses){let n=r.responses.find(o=>o.statusCode===t.statusCode);if(!n){r.responses.push({statusCode:t.statusCode,headers:t.headers?[...t.headers]:void 0,body:t.body});continue}let s=n.headers??[],i=t.headers??[];n.headers=yn([...s,...i])}}function yn(r){let e=new Map;for(let i of r){let o=`${i.location}:${i.name}`,a=e.get(o);if(!a){e.set(o,{...i,evidenceLocations:ef([],i)});continue}if(a.required=!!(a.required||i.required),a.evidenceLocations=ef(a.evidenceLocations??[],i),!a.detectionLocation&&i.detectionLocation&&(a.detectionLocation=i.detectionLocation),!a.type&&i.type){a.type=i.type;continue}if(!i.type||!a.type||a.type===i.type)continue;let c=new Set(a.conflictingTypes??[]);c.add(a.type),c.add(i.type),a.conflictingTypes=Array.from(c),a.location==="body"&&(a.type==="object"||i.type==="object")&&(a.type="object")}let t=Array.from(e.values()).map(i=>jy(i)),n=t.filter(i=>i.location==="body"),s=new Map(n.map(i=>[i.name,i]));for(let i of[...n]){let o=ra(i.name);for(;o;){if(!s.has(o)){let a={name:o,location:"body",type:"object"};s.set(o,a),t.push(a)}o=ra(o)}}for(let i of s.values()){let o=ra(i.name);for(;o;){let a=s.get(o);a&&(a.type="object"),o=ra(o)}}return t}function ef(r,e){let t=[...r??[]];e.detectionLocation&&t.push(e.detectionLocation),e.evidenceLocations&&t.push(...e.evidenceLocations);let n=new Set,s=[];for(let i of t){let o=`${i.filePath}:${i.line}:${i.column??0}:${i.symbolName??""}:${i.accessMode??""}`;n.has(o)||(n.add(o),s.push(i))}return s}function jy(r){let e=By([...r.detectionLocation?[r.detectionLocation]:[],...r.evidenceLocations??[]]);if(e.length===0)return{...r,detectionLocation:void 0,evidenceLocations:void 0};let t=Ly(e),n=e.filter(s=>!Uy(s,t));return{...r,detectionLocation:t,evidenceLocations:n.length>0?n:void 0}}function Ly(r){return[...r].sort(Hy)[0]}function Hy(r,e){let t=tf(r),n=tf(e);if(t!==n)return n-t;if(r.line!==e.line)return r.line-e.line;let s=r.column??0,i=e.column??0;return s!==i?s-i:r.filePath.localeCompare(e.filePath)}function tf(r){let e=0;return r.accessMode&&(e+=8),r.symbolName&&(e+=4),typeof r.column=="number"&&(e+=2),e}function By(r){let e=[],t=new Set;for(let n of r){let s=`${n.filePath}:${n.line}:${n.column??0}:${n.symbolName??""}:${n.accessMode??""}`;t.has(s)||(t.add(s),e.push(n))}return e}function Uy(r,e){return r.filePath===e.filePath&&r.line===e.line&&(r.column??0)===(e.column??0)&&(r.symbolName??"")===(e.symbolName??"")&&(r.accessMode??"")===(e.accessMode??"")}function Vy(r){let e=new Set,t=[];for(let n of r){let s=`${n.type??"unknown"}:${n.name}`;e.has(s)||(e.add(s),t.push(n))}return t}function zy(r,e,t){return R.isPropertyAccessExpression(r)&&R.isIdentifier(r.expression)&&t.has(r.expression.text)&&r.name.text==="body"}function Zr(r,e,t,n,s,i,o){return Ul(r,e,t,n,!1,s,i,o)}function Ul(r,e,t,n,s,i,o,a){let c=[],l=r;for(;l&&(R.isPropertyAccessExpression(l)||R.isElementAccessExpression(l)||R.isPropertyAccessChain(l)||R.isElementAccessChain(l));){if(R.isPropertyAccessExpression(l)||R.isPropertyAccessChain(l)){c.unshift(l.name.text),l=l.expression;continue}if(R.isElementAccessExpression(l)||R.isElementAccessChain(l)){let h=l.argumentExpression;if(h&&(R.isStringLiteral(h)||R.isNumericLiteral(h))){let g=h.text;R.isNumericLiteral(h)||/^\d+$/.test(g)?c.unshift("[]"):c.unshift(g)}else return;l=l.expression}}let u=c.indexOf(t),p=a?.has(t)??!1?l&&R.isIdentifier(l)&&((o?.has(l.text)??!1)||(i?.has(l.text)??!1)):l&&R.isIdentifier(l)&&i?.has(l.text)===!0;if(u!==-1&&p){let h=c.slice(u+1);return h.length===0?s?{path:""}:void 0:{path:oa(h)}}if(!l||!R.isIdentifier(l)||!n)return;let m=n.get(l.text);if(!m||m.target!==t)return;let f=oa(c);return m.path?f?{path:`${m.path}.${f}`}:{path:m.path}:f?{path:f}:s?{path:""}:void 0}function Jy(r,e,t,n,s,i){let o=r.initializer;if(!o)return;R.isIdentifier(o)&&n.has(o.text)&&R.isIdentifier(r.name)&&n.add(r.name.text),R.isIdentifier(o)&&s.has(o.text)&&R.isIdentifier(r.name)&&s.add(r.name.text);let a=["body","query","params","headers","cookies",...i],c,l="";for(let u of a){let d=Ul(o,e,u,t,!0,n,s,i);if(d){c=u,l=d.path;break}}if(c){if(R.isIdentifier(r.name)){t.set(r.name.text,{target:c,path:l});return}(R.isObjectBindingPattern(r.name)||R.isArrayBindingPattern(r.name))&&vi(r.name,c,l,t)}}function Wy(r,e,t,n,s,i){let o=["body","query","params","headers","cookies",...i];for(let a of r.parameters){if((R.isObjectBindingPattern(a.name)||R.isArrayBindingPattern(a.name))&&!a.initializer){Gy(a.name,t,i);continue}let c=a.initializer;if(!c)continue;let l,u="";for(let d of o){let p=Ul(c,e,d,t,!0,n,s,i);if(p){l=d,u=p.path;break}}if(l){if(R.isIdentifier(a.name)){t.set(a.name.text,{target:l,path:u});continue}(R.isObjectBindingPattern(a.name)||R.isArrayBindingPattern(a.name))&&vi(a.name,l,u,t)}}}function Gy(r,e,t){if(!R.isObjectBindingPattern(r))return;let n=new Set(["body","query","params","headers","cookies",...t]);for(let s of r.elements){let i=Bl(s);if(!i||!n.has(i))continue;let o=i;if(R.isIdentifier(s.name)){e.set(s.name.text,{target:o,path:""});continue}(R.isObjectBindingPattern(s.name)||R.isArrayBindingPattern(s.name))&&vi(s.name,o,"",e)}}function Ky(r,e,t){let n=new Set,s=new Set(["query","params","body","headers","cookies",...t]),i=o=>{if(R.isPropertyAccessExpression(o)||R.isPropertyAccessChain(o)){let a=o.name.text;if(s.has(a)){let c=rr(o.expression);c&&n.add(c)}}if(R.isElementAccessExpression(o)||R.isElementAccessChain(o)){let a=o.argumentExpression;if(a&&R.isStringLiteral(a)&&s.has(a.text)){let c=rr(o.expression);c&&n.add(c)}}R.isVariableDeclaration(o)&&o.initializer&&R.isIdentifier(o.name)&&R.isIdentifier(o.initializer)&&n.has(o.initializer.text)&&n.add(o.name.text),R.forEachChild(o,i)};return i(r),n}function vi(r,e,t,n){if(R.isObjectBindingPattern(r)){for(let s of r.elements){let i=Bl(s);if(!i)continue;let o=nf(t,i);if(R.isIdentifier(s.name)){n.set(s.name.text,{target:e,path:o});continue}(R.isObjectBindingPattern(s.name)||R.isArrayBindingPattern(s.name))&&vi(s.name,e,o,n)}return}for(let s of r.elements){if(!R.isBindingElement(s))continue;let i=Bl(s)??"[]",o=nf(t,/^\d+$/.test(i)?"[]":i);if(R.isIdentifier(s.name)){n.set(s.name.text,{target:e,path:o});continue}(R.isObjectBindingPattern(s.name)||R.isArrayBindingPattern(s.name))&&vi(s.name,e,o,n)}}function Bl(r){let e=r.propertyName;if(!e)return R.isIdentifier(r.name)?r.name.text:void 0;if(R.isIdentifier(e)||R.isStringLiteral(e)||R.isNumericLiteral(e))return e.text}function nf(r,e){return oa(r?`${r}.${e}`.split("."):[e])}function oa(r){if(r.length===0)return"";let e="";for(let t of r)if(t){if(t==="[]"){e.endsWith("[]")||(e+="[]");continue}e+=e?`.${t}`:t}return e}function ra(r){let e=r.lastIndexOf(".");if(!(e<=0))return r.slice(0,e)}function Qy(r,e,t,n,s,i){let o=new Map,a=(l,u)=>{let d=o.get(l);if(!d){o.set(l,{requestAliases:u.requestAliases?new Set(u.requestAliases):void 0,responseAliases:u.responseAliases?new Set(u.responseAliases):void 0});return}if(u.requestAliases)if(!d.requestAliases)d.requestAliases=new Set(u.requestAliases);else for(let p of u.requestAliases)d.requestAliases.add(p);if(u.responseAliases)if(!d.responseAliases)d.responseAliases=new Set(u.responseAliases);else for(let p of u.responseAliases)d.responseAliases.add(p)},c=l=>{if(R.isCallExpression(l)&&R.isIdentifier(l.expression)){let u=l.expression.text,d=t.get(u);if(d){let m=aa(l,d,s,i);m&&a(`${e}:${u}`,m)}let p=n.get(u);if(p){let m=aa(l,p.node,s,i);m&&a(p.symbolKey,m)}}R.forEachChild(l,c)};return c(r),o}function rf(r,e){if(!r&&!e)return;let t=new Set([...r?.requestAliases??[],...e?.requestAliases??[]]),n=new Set([...r?.responseAliases??[],...e?.responseAliases??[]]);return{requestAliases:t.size>0?t:void 0,responseAliases:n.size>0?n:void 0}}function Zy(r){let e=new Set,t=new Set(["query","params","body","headers","cookies"]);for(let n of r){let s=n.trim();!s||t.has(s)||e.add(s)}return e.size===0&&e.add("locals"),e}function aa(r,e,t,n){let s=new Set,i=new Set,o=Math.min(r.arguments.length,e.parameters.length);for(let a=0;a<o;a+=1){let c=e.parameters[a];if(!R.isIdentifier(c.name))continue;let l=r.arguments[a],u=rr(l);u&&(t.has(u)&&s.add(c.name.text),n.has(u)&&i.add(c.name.text))}if(!(s.size===0&&i.size===0))return{requestAliases:s.size>0?s:void 0,responseAliases:i.size>0?i:void 0}}function sa(r,e){if(!r||!r.parent)return"string";if(R.isCallExpression(r.parent)&&R.isIdentifier(r.parent.expression)){let t=r.parent.expression.text;if(t==="parseInt"||t==="parseFloat")return"number"}if(R.isBinaryExpression(r.parent)&&(r.parent.operatorToken.kind===R.SyntaxKind.EqualsEqualsToken||r.parent.operatorToken.kind===R.SyntaxKind.EqualsEqualsEqualsToken)){let t=r.parent.left===r?r.parent.right:r.parent.left;if(R.isNumericLiteral(t))return"number"}return"string"}function Yy(r,e,t){let n=r.expression;if(!R.isPropertyAccessExpression(n))return;let s=n.name.text;if(s!=="json"&&s!=="send")return;let i=of(r,t);if(i)return{statusCode:i.statusCode,bodyType:s==="json"?"json":ev(r.arguments[0])}}function Xy(r,e){let t=r.expression;if(!R.isPropertyAccessExpression(t))return;let n=t.name.text;if(n!=="header"&&n!=="set")return;let s=r.arguments[0];if(!s||!R.isStringLiteral(s))return;let i=of(r,e);if(i)return{statusCode:i.statusCode,headerName:s.text}}function of(r,e){if(!R.isPropertyAccessExpression(r.expression))return;let t=200,n=r.expression.expression;for(;;){if(R.isIdentifier(n)&&e.has(n.text))return{receiver:n.text,statusCode:t};if(!R.isCallExpression(n)||!R.isPropertyAccessExpression(n.expression))return;let s=n.expression.name.text;if(s==="status"||s==="code"){let i=n.arguments[0];i&&R.isNumericLiteral(i)&&(t=Number(i.text))}n=n.expression.expression}}function ev(r){return r&&(R.isObjectLiteralExpression(r)||R.isArrayLiteralExpression(r))?"json":"text"}function tv(r,e,t){let n=new Set,s=new Set(["status","code","json","send","header","set","cookie"]),i=new Set(t),o=a=>{if(R.isPropertyAccessExpression(a)||R.isPropertyAccessChain(a)){let c=a.name.text;if(i.has(c)){let l=rr(a.expression);l&&n.add(l)}}if(R.isElementAccessExpression(a)||R.isElementAccessChain(a)){let c=a.argumentExpression;if(c&&R.isStringLiteral(c)&&i.has(c.text)){let l=rr(a.expression);l&&n.add(l)}}if(R.isCallExpression(a)&&R.isPropertyAccessExpression(a.expression)){let c=a.expression.name.text;if(s.has(c)){let l=rr(a.expression.expression);l&&n.add(l)}}R.isVariableDeclaration(a)&&a.initializer&&R.isIdentifier(a.name)&&R.isIdentifier(a.initializer)&&n.has(a.initializer.text)&&n.add(a.name.text),R.forEachChild(a,o)};return o(r),n}function nv(r,e){let t=rr(r);return t?e.has(t):!1}function rr(r){let e=r;for(;;){if(R.isIdentifier(e))return e.text;if(R.isPropertyAccessExpression(e)||R.isPropertyAccessChain(e)){e=e.expression;continue}if(R.isElementAccessExpression(e)||R.isElementAccessChain(e)){e=e.expression;continue}if(R.isCallExpression(e)&&R.isPropertyAccessExpression(e.expression)){e=e.expression.expression;continue}return}}var la=k(()=>{"use strict"});import*as fe from"typescript";function Yr(r,e,t){let n={},s=o=>{if(fe.isVariableDeclaration(o)&&fe.isIdentifier(o.name)&&o.initializer){let a=vn(o.initializer,r,{variables:n});a!==void 0&&(n[o.name.text]=a)}fe.forEachChild(o,s)};s(r);let i={...sv(e),...t};return{variables:n,env:i}}function Ct(r,e,t){if(!r)return{pathExpression:"/",resolvedPath:"/",confidence:"high"};let n=vn(r,e,t);if(n!==void 0)return{pathExpression:n,resolvedPath:n,confidence:"high"};if(fe.isStringLiteral(r)||fe.isNoSubstitutionTemplateLiteral(r)){let s=r.text||"/";return{pathExpression:s,resolvedPath:s,confidence:"high"}}if(fe.isTemplateExpression(r)){let s=rv(r,e,t);if(s.resolvedPath)return s;let i=r.head.text;return{pathExpression:r.getText(e),resolvedPath:i||void 0,confidence:i?"medium":"low"}}return fe.isIdentifier(r)?{pathExpression:r.getText(e),confidence:"low"}:{pathExpression:r.getText(e),confidence:"low"}}function Jt(r,e){let t=af(r??""),n=af(e??""),s=cf(`${t}/${n}`);return(r??"").includes("${")||(e??"").includes("${")?{pathExpression:s}:{pathExpression:s,resolvedPath:s}}function af(r){return r?r.replace(/^['"`]/,"").replace(/['"`]$/,"").replace(/^\/+/,"").replace(/\/+$/,""):""}function cf(r){let e=r.replace(/\/{2,}/g,"/").replace(/\/$/,"");return!e||e==="/"?"/":e.startsWith("/")?e:`/${e}`}function vn(r,e,t){if(fe.isStringLiteral(r)||fe.isNoSubstitutionTemplateLiteral(r))return r.text;if(fe.isParenthesizedExpression(r))return vn(r.expression,e,t);if(fe.isIdentifier(r))return t?.variables?.[r.text];if(fe.isBinaryExpression(r)&&r.operatorToken.kind===fe.SyntaxKind.PlusToken){let n=vn(r.left,e,t),s=vn(r.right,e,t);if(n!==void 0&&s!==void 0)return`${n}${s}`}if(fe.isBinaryExpression(r)&&(r.operatorToken.kind===fe.SyntaxKind.BarBarToken||r.operatorToken.kind===fe.SyntaxKind.QuestionQuestionToken))return vn(r.left,e,t)??vn(r.right,e,t);if(fe.isPropertyAccessExpression(r)){let n=r.getText(e);if(n.startsWith("process.env.")){let s=n.substring(12);return t?.env?.[s]}}}function rv(r,e,t){let n=[r.head.text],s=!0;for(let o of r.templateSpans){let a=vn(o.expression,e,t);a===void 0?(s=!1,n.push("${...}")):n.push(a),n.push(o.literal.text)}let i=s?cf(n.join("")):void 0;return{pathExpression:r.getText(e),resolvedPath:i,confidence:s?"high":"medium"}}function sv(r){if(!r)return{};let e=[".env",".env.local",".env.development",".env.production"],t={};for(let n of e){let s=`${r}/${n}`;try{let i=pe("fs").readFileSync(s,"utf-8");for(let o of i.split(/\r?\n/)){let a=o.trim();if(!a||a.startsWith("#"))continue;let c=a.indexOf("=");if(c<=0)continue;let l=a.slice(0,c).trim(),u=a.slice(c+1).trim().replace(/^['"]|['"]$/g,"");t[l]=u}}catch{continue}}return t}var ua=k(()=>{"use strict"});import*as ae from"typescript";function lf(r){return{get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",options:"OPTIONS",head:"HEAD",all:"ALL"}[r]}function iv(r,e){if(r.length<=2)return[];let t=[];for(let n of r.slice(1,-1))t.push({name:n.getText(e)});return t}function ov(r){let e=new Map;for(let s of r){let i=e.get(s.parent)??[];i.push(s),e.set(s.parent,i)}let t=new Map;t.set("app",[{pathExpression:"",resolvedPath:"",confidence:"high",middlewareNodes:[]}]);let n=["app"];for(;n.length>0;){let s=n.shift(),i=t.get(s)??[],o=e.get(s)??[];for(let a of o){let c=t.get(a.child)??[],l=!1;for(let u of i){let d=Jt(u.pathExpression,a.prefix.pathExpression),p=hn(u.confidence,a.prefix.confidence),m={pathExpression:d.pathExpression,resolvedPath:u.resolvedPath&&a.prefix.resolvedPath?d.resolvedPath:void 0,confidence:p,middlewareNodes:[...u.middlewareNodes,...a.middlewareNodes]};c.some(f=>f.pathExpression===m.pathExpression&&f.resolvedPath===m.resolvedPath)||(c.push(m),l=!0)}l&&(t.set(a.child,c),n.push(a.child))}}return t}function av(r){return ae.isStringLiteral(r)||ae.isNoSubstitutionTemplateLiteral(r)||ae.isTemplateExpression(r)}function cv(r){if(ae.isStringLiteral(r)||ae.isNoSubstitutionTemplateLiteral(r))return r.text}function lv(r,e,t,n){let s=new Set(gn(n).map(a=>a.name));if(s.size===0)return[];let i=uv(r,e),o=[];for(let a of i){let c=t.get(a)??[];for(let l of c)s.has(l.paramName)&&o.push(l.node)}return o}function uv(r,e){let t=new Map;for(let o of e){let a=t.get(o.child)??[];a.push(o.parent),t.set(o.child,a)}let n=[],s=new Set,i=o=>{if(!s.has(o)){s.add(o);for(let a of t.get(o)??[])i(a);n.push(o)}};return i(r),n}var Si,uf=k(()=>{"use strict";ua();la();Si=class{async analyzeFile(e,t,n,s){let i=ae.createSourceFile(e,t,ae.ScriptTarget.Latest,!0,e.endsWith(".ts")?ae.ScriptKind.TS:ae.ScriptKind.JS),o=new Set(["app","router"]),a=[],c=[],l=new Map,u=new Map,d=Yr(i,n.projectRoot,s.envOverrides),p=g=>{if(ae.isVariableDeclaration(g)&&ae.isIdentifier(g.name)&&g.initializer){let v=g.initializer.getText(i);(/express\.Router\s*\(/.test(v)||/Router\s*\(/.test(v)||/express\(\)/.test(v))&&o.add(g.name.text)}ae.forEachChild(g,p)};p(i);let m=g=>{if(ae.isCallExpression(g)&&ae.isPropertyAccessExpression(g.expression)){let v=g.expression.expression.getText(i),y=g.expression.name.text;if(y==="use"&&g.arguments.length>=1&&o.has(v)){let b=g.arguments[g.arguments.length-1];if(g.arguments.length>=2&&ae.isIdentifier(b)&&o.has(b.text)&&ae.isIdentifier(b)){let w=Ct(g.arguments[0],i,d);a.push({parent:v,child:b.text,prefix:w,middlewareNodes:g.arguments.slice(1,-1)})}else{let w=av(g.arguments[0])?g.arguments.slice(1):g.arguments.slice(0),E=l.get(v)??[];E.push(...w),l.set(v,E)}}if(y==="param"&&g.arguments.length>=2&&o.has(v)){let b=cv(g.arguments[0]),C=g.arguments[1];if(b&&C&&ae.isExpression(C)){let w=u.get(v)??[];w.push({paramName:b,node:C}),u.set(v,w)}}let S=lf(y);if(S&&o.has(v)&&g.arguments.length>=1){let b=Ct(g.arguments[0],i,d),C=iv(g.arguments,i),w=g.arguments[g.arguments.length-1],E=i.getLineAndCharacterOfPosition(w.getStart(i));c.push({owner:v,method:S,pathExpression:b.pathExpression,resolvedPath:b.resolvedPath,confidence:b.confidence,middleware:C,middlewareNodes:g.arguments.slice(1,-1),handlerNode:w,source:{filePath:e,line:E.line+1,column:E.character+1,symbolName:w.getText(i)}})}if(y==="route"&&g.arguments[0]){let b=Ct(g.arguments[0],i,d),C=g.parent;if(ae.isCallExpression(C)&&ae.isPropertyAccessExpression(C.expression)){let w=lf(C.expression.name.text);if(w){let E=C.arguments[0]??g.arguments[0],F=i.getLineAndCharacterOfPosition(E.getStart(i));c.push({owner:v,method:w,pathExpression:b.pathExpression,resolvedPath:b.resolvedPath,confidence:b.confidence,middleware:[],middlewareNodes:[],handlerNode:E,source:{filePath:e,line:F.line+1,column:F.character+1,symbolName:E.getText(i)}})}}}}ae.forEachChild(g,m)};m(i);let f=[],h=ov(a);for(let g of c){let v=h.get(g.owner)??[],y=v.length>0?v:[{pathExpression:"",confidence:"high",middlewareNodes:[]}];for(let S of y){let b=Jt(S.pathExpression,g.pathExpression),C=hn(S.confidence,g.confidence),w=!!b.resolvedPath,E=gn(b.pathExpression),F=l.get(g.owner)??[],N=lv(g.owner,a,u,b.pathExpression),j=[...S.middlewareNodes,...F,...N,...g.middlewareNodes,g.handlerNode],O=bi(j,i,e,g.method,s.contextProperties);O.parameters.unshift(...E),O.parameters=yn(O.parameters),f.push({id:"",method:g.method,framework:"express",pathExpression:b.pathExpression,resolvedPath:C==="high"&&w?b.resolvedPath:void 0,confidence:C,source:g.source,middleware:g.middleware,params:O.parameters.length>0?O.parameters:void 0,requestBody:O.requestBody,cookies:O.cookies.length>0?O.cookies:void 0,responses:O.responses})}}return f}}});import*as _ from"typescript";function dv(r,e,t,n,s,i){let o=r.arguments[0],a=r.arguments[1],c=pv(a,e,i),l=c?n.map(u=>{let d=Jt(u.pathExpression,c.pathExpression);return{pathExpression:d.pathExpression,resolvedPath:u.resolvedPath&&c.resolvedPath?d.resolvedPath:void 0,confidence:hn(u.confidence,c.confidence)}}):n;if(_.isArrowFunction(o)||_.isFunctionExpression(o)){let u=new Set(t),d=o.parameters[0];d&&_.isIdentifier(d.name)&&u.add(d.name.text),o.body&&_.forEachChild(o.body,p=>s(p,u,l))}}function pv(r,e,t){if(!r||!_.isObjectLiteralExpression(r))return;let n=Pe(r,"prefix");if(!n)return;let s=Ct(n,e,t);return{pathExpression:s.pathExpression,resolvedPath:s.resolvedPath,confidence:s.confidence}}function fv(r){return{get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",options:"OPTIONS",head:"HEAD",all:"ALL"}[r]}function Pe(r,e){for(let t of r.properties){if(!_.isPropertyAssignment(t))continue;if((_.isIdentifier(t.name)||_.isStringLiteral(t.name)?t.name.text:void 0)===e)return t.initializer}}function mv(r,e){return r?_.isStringLiteral(r)||_.isNoSubstitutionTemplateLiteral(r)?[r.text.toUpperCase()]:_.isArrayLiteralExpression(r)?r.elements.map(t=>_.isStringLiteral(t)||_.isNoSubstitutionTemplateLiteral(t)?t.text.toUpperCase():t.getText(e).toUpperCase()).filter(Boolean):[r.getText(e).toUpperCase()]:["GET"]}function df(r,e){return r?_.isArrayLiteralExpression(r)?r.elements.map(t=>({name:`preHandler:${t.getText(e)}`})):[{name:`preHandler:${r.getText(e)}`}]:[]}function pf(r){return r?_.isArrayLiteralExpression(r)?r.elements.filter(e=>_.isExpression(e)):[r]:[]}function hv(r){if(r&&(_.isArrowFunction(r)||_.isFunctionExpression(r))&&r.parameters[0]&&_.isIdentifier(r.parameters[0].name))return r.parameters[0].name.text}function gv(r,e){if(!r||!_.isStringLiteral(r))return!1;let t=r.text;return t==="onRequest"||t==="preParsing"||t==="preValidation"||t==="preHandler"}function yv(r,e,t){let n=[],s=new Set,i=r;for(;i&&!s.has(i);)s.add(i),n.unshift(i),i=t.get(i);let o=[];for(let a of n){let c=e.get(a)??[];o.push(...c)}return o}function vv(r,e){return e?{parameters:yn([...e.parameters,...r.parameters]),requestBody:e.requestBody??r.requestBody,cookies:r.cookies,responses:r.responses}:r}function ff(r,e,t){if(!r||!_.isObjectLiteralExpression(r))return;let n=[],s=Pe(r,"params");s&&n.push(...xi(s,"path",""));let i=Pe(r,"querystring")??Pe(r,"query");i&&n.push(...xi(i,"query",""));let o=Pe(r,"headers");o&&n.push(...xi(o,"header",""));let a=Pe(r,"body");a&&n.push(...xi(a,"body",""));let c=a?mf(a,e):void 0,l=a?{type:"json",required:["POST","PUT","PATCH"].includes(t),schema:c??{type:"object"}}:void 0;return{parameters:n,requestBody:l,cookies:[],responses:[]}}function mf(r,e){if(_.isStringLiteral(r)||_.isNoSubstitutionTemplateLiteral(r))return{type:"string"};if(_.isNumericLiteral(r))return{type:"number"};if(!_.isObjectLiteralExpression(r))return;let t={};for(let n of r.properties){if(!_.isPropertyAssignment(n))continue;let s=n.name,i=_.isIdentifier(s)||_.isStringLiteral(s)||_.isNumericLiteral(s)?s.text:void 0;if(!i)continue;let o=hf(n.initializer,e);o!==void 0&&(t[i]=o)}return Object.keys(t).length>0?t:void 0}function hf(r,e){if(_.isStringLiteral(r)||_.isNoSubstitutionTemplateLiteral(r))return r.text;if(_.isNumericLiteral(r))return Number(r.text);if(r.kind===_.SyntaxKind.TrueKeyword||r.kind===_.SyntaxKind.FalseKeyword)return r.kind===_.SyntaxKind.TrueKeyword;if(r.kind===_.SyntaxKind.NullKeyword)return null;if(_.isArrayLiteralExpression(r)){let t=r.elements.map(n=>hf(n,e));return t.every(n=>n!==void 0)?t:void 0}if(_.isObjectLiteralExpression(r))return mf(r,e)}function xi(r,e,t){if(!_.isObjectLiteralExpression(r))return[];let n=Pe(r,"properties");if(!n||!_.isObjectLiteralExpression(n))return[];let s=Pe(r,"required"),i=new Set;if(s&&_.isArrayLiteralExpression(s))for(let a of s.elements)(_.isStringLiteral(a)||_.isNoSubstitutionTemplateLiteral(a))&&i.add(a.text);let o=[];for(let a of n.properties){if(!_.isPropertyAssignment(a))continue;let c=_.isIdentifier(a.name)||_.isStringLiteral(a.name)||_.isNumericLiteral(a.name)?a.name.text:void 0;if(!c)continue;let l=t?`${t}.${c}`:c,u=bv(a.initializer);o.push({name:l,location:e,type:u,required:i.has(c)}),o.push(...xi(a.initializer,e,l))}return o}function bv(r){if(!_.isObjectLiteralExpression(r))return;let e=Pe(r,"type");if(e&&(_.isStringLiteral(e)||_.isNoSubstitutionTemplateLiteral(e)))return e.text;let t=Pe(r,"properties");if(t&&_.isObjectLiteralExpression(t))return"object"}var wi,gf=k(()=>{"use strict";ua();la();wi=class{async analyzeFile(e,t,n,s){let i=_.createSourceFile(e,t,_.ScriptTarget.Latest,!0,e.endsWith(".ts")?_.ScriptKind.TS:_.ScriptKind.JS),o=new Set(["fastify"]),a=[{pathExpression:"",resolvedPath:"",confidence:"high"}],c=[],l=new Map,u=new Map,d=Yr(i,n.projectRoot,s.envOverrides),p=(f,h,g)=>{if(_.isVariableDeclaration(f)&&_.isIdentifier(f.name)&&f.initializer){let v=f.initializer.getText(i);(v.includes("fastify(")||v.includes("Fastify("))&&h.add(f.name.text)}if(_.isCallExpression(f)&&_.isPropertyAccessExpression(f.expression)){let v=f.expression.expression.getText(i),y=f.expression.name.text;if(y==="register"){let b=hv(f.arguments[0]);b&&u.set(b,v),dv(f,i,h,g,p,d)}if(y==="addHook"&&h.has(v)&&f.arguments.length>=2&&gv(f.arguments[0],i)){let b=l.get(v)??[];b.push(f.arguments[1]),l.set(v,b)}let S=fv(y);if(S&&h.has(v)&&f.arguments[0]){let b=Ct(f.arguments[0],i,d),C=f.arguments.length>=2&&_.isObjectLiteralExpression(f.arguments[1])?f.arguments[1]:void 0,w=C&&f.arguments[2]?f.arguments[2]:f.arguments[f.arguments.length-1],E=i.getLineAndCharacterOfPosition(w.getStart(i)),F=C?Pe(C,"preHandler"):void 0,N=df(F,i),j=pf(F),O=C?ff(Pe(C,"schema"),i,S):void 0;for(let D of g){let P=Jt(D.pathExpression,b.pathExpression),M=hn(D.confidence,b.confidence),G=!!P.resolvedPath;c.push({owner:v,method:S,pathExpression:P.pathExpression,resolvedPath:M==="high"&&G?P.resolvedPath:void 0,confidence:M,handlerNode:w,middlewareNodes:j,schemaMetadata:O,source:{filePath:e,line:E.line+1,column:E.character+1,symbolName:w.getText(i)},middleware:N})}}if(y==="route"&&h.has(v)&&f.arguments[0]&&_.isObjectLiteralExpression(f.arguments[0])){let b=f.arguments[0],C=Pe(b,"method"),w=Pe(b,"url")??Pe(b,"path"),E=Pe(b,"handler"),F=Pe(b,"preHandler"),N=Pe(b,"schema"),j=Ct(w,i,d),O=mv(C,i),D=df(F,i);for(let P of O){let M=E?i.getLineAndCharacterOfPosition(E.getStart(i)):i.getLineAndCharacterOfPosition(b.getStart(i));for(let G of g){let me=Jt(G.pathExpression,j.pathExpression),Ce=hn(G.confidence,j.confidence),Ie=!!me.resolvedPath;c.push({owner:v,method:P,pathExpression:me.pathExpression,resolvedPath:Ce==="high"&&Ie?me.resolvedPath:void 0,confidence:Ce,handlerNode:E??b,middlewareNodes:pf(F),schemaMetadata:ff(N,i,P),source:{filePath:e,line:M.line+1,column:M.character+1,symbolName:E?.getText(i)},middleware:D})}}}}_.forEachChild(f,v=>p(v,h,g))};p(i,o,a);let m=[];for(let f of c){let h=gn(f.pathExpression),v=[...yv(f.owner,l,u),...f.middlewareNodes,f.handlerNode],y=bi(v,i,e,f.method,s.contextProperties);y.parameters.unshift(...h),y.parameters=yn(y.parameters);let S=vv(y,f.schemaMetadata);m.push({id:"",method:f.method,framework:"fastify",pathExpression:f.pathExpression,resolvedPath:f.resolvedPath,confidence:f.confidence,source:f.source,middleware:f.middleware,params:S.parameters.length>0?S.parameters:void 0,requestBody:S.requestBody,cookies:S.cookies.length>0?S.cookies:void 0,responses:S.responses})}return m}}});import*as H from"typescript";function Sv(r,e){H.forEachChild(r,t=>xv(t,r,e))}function xv(r,e,t){if(H.isExpressionStatement(r)&&H.isBinaryExpression(r.expression)&&r.expression.operatorToken.kind===H.SyntaxKind.EqualsToken){let n=r.expression.left,s=r.expression.right;if(H.isPropertyAccessExpression(n)){let i=n.expression.getText(e),o=n.name.text;if(i==="exports"&&da(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=Vl(s,e);t.push({exportName:o,handlerNode:c,middlewareNodes:l,location:{filePath:e.fileName,line:a.line+1,column:a.character+1,symbolName:o}});return}if(i==="module"&&o==="exports"&&da(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=Vl(s,e);t.push({exportName:"handler",handlerNode:c,middlewareNodes:l,location:{filePath:e.fileName,line:a.line+1,column:a.character+1,symbolName:"handler"}});return}}}if(H.isVariableStatement(r)&&yf(r)&&r.declarationList.declarations.length>0){for(let n of r.declarationList.declarations)if(!(!H.isIdentifier(n.name)||!n.initializer)&&da(n.initializer,e)){let s=n.name.text,i=e.getLineAndCharacterOfPosition(n.initializer.getStart(e)),{handlerNode:o,middlewareNodes:a}=Vl(n.initializer,e);t.push({exportName:s,handlerNode:o,middlewareNodes:a,location:{filePath:e.fileName,line:i.line+1,column:i.character+1,symbolName:s}})}return}if(H.isFunctionDeclaration(r)&&yf(r)&&r.name&&wv(r)){let n=r.name.text,s=e.getLineAndCharacterOfPosition(r.getStart(e));t.push({exportName:n,handlerNode:r,middlewareNodes:[],location:{filePath:e.fileName,line:s.line+1,column:s.character+1,symbolName:n}})}}function da(r,e){if(H.isArrowFunction(r)||H.isFunctionExpression(r))return Rv(r);if(H.isCallExpression(r)){let t=r.expression.getText(e);if(t==="middy"||t.endsWith(".middy"))return!0;if(H.isPropertyAccessExpression(r.expression)&&r.expression.name.text==="use")return da(r.expression.expression,e)}return H.isIdentifier(r)?/handler/i.test(r.text):!1}function wv(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function Rv(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function yf(r){return(H.getCombinedModifierFlags(r)&H.ModifierFlags.Export)!==0}function Vl(r,e){let t=[],n=r;for(;H.isCallExpression(n)&&H.isPropertyAccessExpression(n.expression)&&n.expression.name.text==="use";)t.unshift(...n.arguments),n=n.expression.expression;return H.isCallExpression(n)&&(n.expression.getText(e)==="middy"||n.expression.getText(e).endsWith(".middy"))?{handlerNode:n.arguments[0]??n,middlewareNodes:t}:{handlerNode:r,middlewareNodes:[]}}function Cv(r,e,t){return r.map(n=>{let s=kv(n,e),i=e.getLineAndCharacterOfPosition(n.getStart(e));return{name:s,location:{filePath:t,line:i.line+1,column:i.character+1,symbolName:s}}})}function kv(r,e){return H.isIdentifier(r)?r.text:H.isCallExpression(r)&&H.isIdentifier(r.expression)?r.expression.text:H.isCallExpression(r)&&H.isPropertyAccessExpression(r.expression)?r.expression.name.text:r.getText(e).slice(0,40).replace(/\s+/g," ")}function qv(r,e,t){let n=Av(r);if(!n)return[];let s=new Map,i=o=>{if(H.isPropertyAccessExpression(o)||H.isElementAccessExpression(o)){let a=Ri(o,e);if(a.length>=2&&a[0]===n){let c=a[1],l=Ev[c];if(l==="body"){let u="body::body";if(!s.has(u)){let d=e.getLineAndCharacterOfPosition(o.getStart(e));s.set(u,{name:"body",location:"body",detectionLocation:{filePath:t,line:d.line+1,column:d.character+1}})}}else if(l&&a.length>=3){let u=a[2],d=`${l}::${u}`;if(!s.has(d)){let p=e.getLineAndCharacterOfPosition(o.getStart(e));s.set(d,{name:u,location:l,detectionLocation:{filePath:t,line:p.line+1,column:p.character+1}})}}}}if(H.isCallExpression(o)&&H.isPropertyAccessExpression(o.expression)&&o.expression.expression.getText(e)==="JSON"&&o.expression.name.text==="parse"&&o.arguments.length===1){let a=o.arguments[0],c=Ri(a,e);if(c.length===2&&c[0]===n&&c[1]==="body"){let l="body::body";if(!s.has(l)){let u=e.getLineAndCharacterOfPosition(o.getStart(e));s.set(l,{name:"body",location:"body",type:"json",detectionLocation:{filePath:t,line:u.line+1,column:u.character+1}})}}}H.forEachChild(o,i)};return i(r),Array.from(s.values())}function Av(r){if(H.isArrowFunction(r)||H.isFunctionExpression(r)||H.isFunctionDeclaration(r)){let e=r.parameters[0];if(e&&H.isIdentifier(e.name))return e.name.text}return H.isIdentifier(r),"event"}function Ri(r,e){return H.isIdentifier(r)?[r.text]:H.isPropertyAccessExpression(r)?[...Ri(r.expression,e),r.name.text]:r.kind===H.SyntaxKind.PropertyAccessExpression||H.isNonNullExpression(r)?Ri(r.expression,e):H.isElementAccessExpression(r)&&H.isStringLiteral(r.argumentExpression)?[...Ri(r.expression,e),r.argumentExpression.text]:r.getText(e).replace(/\?/g,"").replace(/\s/g,"").split(".")}var Ci,Ev,zl=k(()=>{"use strict";Ci=class{async analyzeFile(e,t,n,s){let i=H.createSourceFile(e,t,H.ScriptTarget.Latest,!0,e.endsWith(".ts")?H.ScriptKind.TS:H.ScriptKind.JS),o=[];return Sv(i,o),o.length===0?[]:o.map(a=>{let c=qv(a.handlerNode,i,e),l=Cv(a.middlewareNodes,i,e);return{id:"",method:"ANY",framework:"lambda",pathExpression:"<unknown-lambda>",resolvedPath:void 0,confidence:"low",source:a.location,middleware:l,params:c.length>0?c:void 0}})}};Ev={pathParameters:"path",queryStringParameters:"query",multiValueQueryStringParameters:"query",headers:"header",multiValueHeaders:"header",body:"body"}});var Xr=k(()=>{"use strict";la();uf();gf();zl()});import*as pa from"fs";function vf(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function Pv(r){let e=[];for(let t of r){t.resolvedPath||e.push({code:"dynamic-path-unresolved",framework:"express",filePath:t.source.filePath,message:`Express route path unresolved for ${t.method} ${t.pathExpression}`});for(let n of t.params??[]){if(!n.conflictingTypes||n.conflictingTypes.length<2)continue;let s=n.detectionLocation?.filePath??n.evidenceLocations?.[0]?.filePath;e.push({code:"parameter-type-conflict",framework:"express",filePath:s,message:`Conflicting inferred types for ${n.location} parameter '${n.name}' on ${t.method} ${t.pathExpression}: ${n.conflictingTypes.join(", ")}`})}}return e}var bn,Jl=k(()=>{"use strict";Xr();mn();bn=class{id="provider.express";framework="express";analyzer=new Si;fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(vf(t)===vf(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){return{...e.packageJson?.dependencies,...e.packageJson?.devDependencies}.express?{supported:!0,confidence:.95,reasons:["express dependency detected"]}:{supported:!1,confidence:0,reasons:["express dependency not found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.sourceFiles??lt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=pa.statSync(a)}catch{continue}let l=this.fileCache.get(a);if(l&&l.mtimeMs===c.mtimeMs&&l.size===c.size){i.push(...l.endpoints.map(m=>structuredClone(m))),s.push(...l.warnings.map(m=>({...m})));continue}let u="";try{u=pa.readFileSync(a,"utf-8")}catch{continue}let d=await this.analyzer.analyzeFile(a,u,t,e),p=Pv(d);i.push(...d),s.push(...p),this.fileCache.set(a,{mtimeMs:c.mtimeMs,size:c.size,endpoints:d.map(m=>structuredClone(m)),warnings:p.map(m=>({...m}))})}return{endpoints:i,warnings:s,stats:{frameworksDetected:["express"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});import*as fa from"fs";function bf(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function Iv(r){let e=[];for(let t of r){t.resolvedPath||e.push({code:"dynamic-path-unresolved",framework:"fastify",filePath:t.source.filePath,message:`Fastify route path unresolved for ${t.method} ${t.pathExpression}`});for(let n of t.params??[]){if(!n.conflictingTypes||n.conflictingTypes.length<2)continue;let s=n.detectionLocation?.filePath??n.evidenceLocations?.[0]?.filePath;e.push({code:"parameter-type-conflict",framework:"fastify",filePath:s,message:`Conflicting inferred types for ${n.location} parameter '${n.name}' on ${t.method} ${t.pathExpression}: ${n.conflictingTypes.join(", ")}`})}}return e}var Sn,Wl=k(()=>{"use strict";Xr();mn();Sn=class{id="provider.fastify";framework="fastify";analyzer=new wi;fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(bf(t)===bf(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){return{...e.packageJson?.dependencies,...e.packageJson?.devDependencies}.fastify?{supported:!0,confidence:.95,reasons:["fastify dependency detected"]}:{supported:!1,confidence:0,reasons:["fastify dependency not found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.sourceFiles??lt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=fa.statSync(a)}catch{continue}let l=this.fileCache.get(a);if(l&&l.mtimeMs===c.mtimeMs&&l.size===c.size){i.push(...l.endpoints.map(m=>structuredClone(m))),s.push(...l.warnings.map(m=>({...m})));continue}let u="";try{u=fa.readFileSync(a,"utf-8")}catch{continue}let d=await this.analyzer.analyzeFile(a,u,t,e),p=Iv(d);i.push(...d),s.push(...p),this.fileCache.set(a,{mtimeMs:c.mtimeMs,size:c.size,endpoints:d.map(m=>structuredClone(m)),warnings:p.map(m=>({...m}))})}return{endpoints:i,warnings:s,stats:{frameworksDetected:["fastify"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});import*as ma from"fs";import*as ye from"typescript";function Sf(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function Gl(r,e){let t=r.expression;if(ye.isCallExpression(t))return ye.isIdentifier(t.expression)?t.expression.text:t.expression.getText(e);if(ye.isIdentifier(t))return t.text}function xf(r){let e=r.expression;if(ye.isCallExpression(e))return e.arguments[0]}function Tv(r){return{Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE",Patch:"PATCH",Options:"OPTIONS",Head:"HEAD",All:"ALL"}[r]}function wf(r){return ye.canHaveDecorators(r)?ye.getDecorators(r)??[]:[]}function Rf(r,e){if(!r||r.length===0)return[];let t=new Set(["UseGuards","UseInterceptors","UsePipes","UseFilters"]),n=[];for(let s of r){let i=Gl(s,e);if(!i||!t.has(i))continue;let o=s.expression;if(!ye.isCallExpression(o)){n.push({name:i});continue}for(let a of o.arguments)n.push({name:`${i}:${a.getText(e)}`})}return n}function Ov(r,e){return r==="low"||e==="low"?"low":r==="medium"||e==="medium"?"medium":"high"}var xn,Kl=k(()=>{"use strict";ua();mn();xn=class{id="provider.nestjs";framework="nestjs";fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(Sf(t)===Sf(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){return{...e.packageJson?.dependencies,...e.packageJson?.devDependencies}["@nestjs/common"]?{supported:!0,confidence:.98,reasons:["@nestjs/common dependency detected"]}:{supported:!1,confidence:0,reasons:["@nestjs/common dependency not found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.sourceFiles??lt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){if(!a.endsWith(".ts")&&!a.endsWith(".js"))continue;let c;try{c=ma.statSync(a)}catch{continue}let l=this.fileCache.get(a);if(l&&l.mtimeMs===c.mtimeMs&&l.size===c.size){i.push(...l.endpoints.map(g=>structuredClone(g))),s.push(...l.warnings.map(g=>({...g})));continue}let u="";try{u=ma.readFileSync(a,"utf-8")}catch{continue}let d=[],p=[],m=ye.createSourceFile(a,u,ye.ScriptTarget.Latest,!0,a.endsWith(".ts")?ye.ScriptKind.TS:ye.ScriptKind.JS),f=Yr(m,t.projectRoot,e.envOverrides),h=g=>{if(ye.isClassDeclaration(g)){let v=wf(g),y=v.find(S=>Gl(S,m)==="Controller");if(y){let S=Ct(xf(y),m,f),b=Rf(v,m);for(let C of g.members){if(!ye.isMethodDeclaration(C))continue;let w=wf(C),E=w.map(F=>({decorator:F,name:Gl(F,m)})).filter(F=>!!F.name);for(let F of E){let N=Tv(F.name);if(!N)continue;let j=Ct(xf(F.decorator),m,f),O=Jt(S.pathExpression,j.pathExpression),D=Rf(w,m),P=C.name?.getText(m),M=C.name??C,G=m.getLineAndCharacterOfPosition(M.getStart(m)),me=Ov(S.confidence,j.confidence);p.push({id:"",method:N,framework:"nestjs",pathExpression:O.pathExpression,resolvedPath:me==="high"?O.resolvedPath:void 0,confidence:me,source:{filePath:a,line:G.line+1,column:G.character+1,symbolName:P},middleware:[...b,...D]}),me!=="high"&&d.push({code:"dynamic-path-unresolved",framework:"nestjs",filePath:a,message:`Dynamic NestJS route path unresolved at ${P??"unknown handler"} in ${a}`})}}}}ye.forEachChild(g,h)};h(m),i.push(...p),s.push(...d),this.fileCache.set(a,{mtimeMs:c.mtimeMs,size:c.size,endpoints:p.map(g=>structuredClone(g)),warnings:d.map(g=>({...g}))})}return{endpoints:i,warnings:s,stats:{frameworksDetected:["nestjs"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});import*as He from"fs";import*as ut from"path";function $v(r,e,t){let n=[],s=r.functions;if(!s||typeof s!="object")return n;for(let[i,o]of Object.entries(s)){if(!o||typeof o!="object")continue;let a=o,c=a.handler;if(!c||typeof c!="string")continue;let{filePath:l,exportName:u}=Ef(c,e),d=qf(l,e);d||t.push({code:"dynamic-path-unresolved",framework:"lambda",message:`Lambda handler file not found for function '${i}': ${c}`});let p=a.events;if(Array.isArray(p))for(let m of p){if(!m||typeof m!="object")continue;let f=m.http;if(!f||typeof f!="object")continue;let h=f.path,g=f.method;if(!h||!g)continue;let v=Af(h),y=[];if(f.authorizer){let S=typeof f.authorizer=="string"?f.authorizer:"authorizer";y.push({name:S})}n.push({id:"",method:g.toUpperCase(),framework:"lambda",pathExpression:v,resolvedPath:v,confidence:"high",source:{filePath:d??l,line:1,column:1,symbolName:u},middleware:y})}}return n}function Cf(r,e,t){let n=[],s=r.Resources;if(!s||typeof s!="object")return n;for(let[i,o]of Object.entries(s)){if(!o||typeof o!="object")continue;let a=o;if(a.Type!=="AWS::Serverless::Function")continue;let c=a.Properties;if(!c)continue;let l=c.Handler;if(!l||typeof l!="string")continue;let{filePath:u,exportName:d}=Ef(l,e),p=qf(u,e);p||t.push({code:"dynamic-path-unresolved",framework:"lambda",message:`Lambda handler file not found for SAM resource '${i}': ${l}`});let m=c.Events;if(!(!m||typeof m!="object"))for(let[,f]of Object.entries(m)){if(!f||typeof f!="object")continue;let h=f;if(h.Type!=="Api"&&h.Type!=="HttpApi")continue;let g=h.Properties;if(!g)continue;let v=g.Path,y=g.Method;if(!v||!y)continue;let S=Af(v),b=g.Auth,C=[];b?.Authorizer&&C.push({name:String(b.Authorizer)}),n.push({id:"",method:y.toUpperCase(),framework:"lambda",pathExpression:S,resolvedPath:S,confidence:"high",source:{filePath:p??u,line:1,column:1,symbolName:d},middleware:C})}}return n}function Ef(r,e){let t=r.lastIndexOf(".");return t===-1?{filePath:r,exportName:"handler"}:{filePath:r.slice(0,t),exportName:r.slice(t+1)}}function qf(r,e){let t=[ut.join(e,`${r}.ts`),ut.join(e,`${r}.js`),ut.join(e,r,"index.ts"),ut.join(e,r,"index.js")];for(let n of t)if(He.existsSync(n))return n}function Af(r){return r.startsWith("/")?r:`/${r}`}function Zl(r){let e=r.split(`
|
|
830
|
-
`);return ki(e,0,-1).value}function ki(r,e,t){let n={},s=[],i=!1,o=e;for(;o<r.length;){let a=r[o],c=a.trimEnd();if(c.trim()===""||c.trimStart().startsWith("#")){o++;continue}let l=Fv(a);if(l<=t)break;let u=c.trimStart();if(u.startsWith("- ")){i=!0;let f=u.slice(2).trim();if(f===""||f.endsWith(":"))if(f.endsWith(":")){let h=f.slice(0,-1).trim(),g=ki(r,o+1,l),v={};v[h]=g.value,s.push(v),o=g.nextLine}else{let h=ki(r,o+1,l);s.push(h.value),o=h.nextLine}else if(f.includes(": ")||f.endsWith(":")){let h={},g=f.indexOf(":"),v=f.slice(0,g).trim(),y=f.slice(g+1).trim();if(y===""){let S=ki(r,o+1,l);h[v]=S.value,s.push(h),o=S.nextLine}else h[v]=Ql(y),s.push(h),o++}else s.push(Ql(f)),o++;continue}let d=u.indexOf(":");if(d===-1){o++;continue}let p=u.slice(0,d).trim(),m=u.slice(d+1).trim();if(m===""||m.startsWith("#")){let f=ki(r,o+1,l);n[p]=f.value,o=f.nextLine}else n[p]=Ql(m),o++}return i?{value:s,nextLine:o}:{value:n,nextLine:o}}function Fv(r){let e=0;for(let t of r)if(t===" ")e++;else if(t===" ")e+=2;else break;return e}function Ql(r){let e=r.indexOf(" #"),t=e!==-1?r.slice(0,e).trim():r.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t==="true"?!0:t==="false"?!1:t==="null"||t==="~"?null:/^-?\d+(\.\d+)?$/.test(t)?Number(t):t}function Nv(r){return Zl(r)}function kf(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var wn,Yl=k(()=>{"use strict";zl();mn();wn=class{id="provider.lambda";framework="lambda";analyzer=new Ci;fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(kf(t)===kf(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){let t={...e.packageJson?.dependencies,...e.packageJson?.devDependencies};if(t.express||t.fastify)return{supported:!1,confidence:0,reasons:["express or fastify detected \u2014 deferring to existing provider"]};let n=!!(t["@types/aws-lambda"]||t["aws-lambda"]||t.serverless),s=He.existsSync(ut.join(e.projectRoot,"serverless.yml"))||He.existsSync(ut.join(e.projectRoot,"serverless.yaml"))||He.existsSync(ut.join(e.projectRoot,"template.yaml"))||He.existsSync(ut.join(e.projectRoot,"template.json"));return n?{supported:!0,confidence:.95,reasons:["lambda-related dependency detected"]}:s?{supported:!0,confidence:.75,reasons:["serverless/SAM config file detected"]}:{supported:!1,confidence:0,reasons:["no lambda indicators found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.projectRoot;for(let a of["serverless.yml","serverless.yaml"]){let c=ut.join(o,a);if(He.existsSync(c)){try{let l=He.readFileSync(c,"utf-8"),u=Nv(l),d=$v(u,o,s);i.push(...d)}catch{s.push({code:"provider-failed",framework:"lambda",filePath:c,message:`Failed to parse Serverless Framework config: ${c}`})}break}}if(i.length===0){let a=ut.join(o,"template.yaml"),c=ut.join(o,"template.json");if(He.existsSync(c))try{let l=He.readFileSync(c,"utf-8"),u=JSON.parse(l),d=Cf(u,o,s);i.push(...d)}catch{s.push({code:"provider-failed",framework:"lambda",filePath:c,message:`Failed to parse SAM template: ${c}`})}else if(He.existsSync(a))try{let l=He.readFileSync(a,"utf-8"),u=Zl(l),d=Cf(u,o,s);i.push(...d)}catch{s.push({code:"provider-failed",framework:"lambda",filePath:a,message:`Failed to parse SAM template: ${a}`})}}if(i.length===0){let a=t.sourceFiles??lt(o);this.pruneDeletedFiles(o,a);for(let c of a){let l;try{l=He.statSync(c)}catch{continue}let u=this.fileCache.get(c);if(u&&u.mtimeMs===l.mtimeMs&&u.size===l.size){i.push(...u.endpoints.map(f=>structuredClone(f))),s.push(...u.warnings.map(f=>({...f})));continue}let d="";try{d=He.readFileSync(c,"utf-8")}catch{continue}let p=await this.analyzer.analyzeFile(c,d,t,e),m=p.map(f=>({code:"seed-endpoint-unmatched",framework:"lambda",filePath:f.source.filePath,message:`Lambda handler '${f.source.symbolName}' found without a config-file route definition. Path is unknown.`}));i.push(...p),s.push(...m),this.fileCache.set(c,{mtimeMs:l.mtimeMs,size:l.size,endpoints:p.map(f=>structuredClone(f)),warnings:m.map(f=>({...f}))})}}return{endpoints:i,warnings:s,stats:{frameworksDetected:["lambda"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});import*as ha from"fs";import*as If from"path";function Dv(r,e){let t=[],n=[r];for(;n.length>0;){let s=n.pop(),i;try{i=ha.readdirSync(s,{withFileTypes:!0})}catch{continue}for(let o of i){let a=If.join(s,o.name);o.isDirectory()?_v.has(o.name)||n.push(a):o.isFile()&&e.test(o.name)&&t.push(a)}}return t}function Ei(r){return Dv(r,/\.java$/)}function qi(r){return ha.promises.readFile(r,"utf-8")}function Xl(r){let e=r.replace(/\\/g,"/");return/^[A-Z]:\//.test(e)&&(e=e[0].toLowerCase()+e.substring(1)),e}function eu(r){return r.replace(/\\/g,"/").split("/").pop()||""}function Tf(r,e){let t=Pf.get(e);if(t&&Date.now()-t.ts<Mv)return Promise.resolve(t.files);let n=new RegExp(`^${e}\\.java$`),s=Ei(r).filter(i=>n.test(eu(i)));return Pf.set(e,{ts:Date.now(),files:s}),Promise.resolve(s)}var _v,Pf,Mv,ga=k(()=>{"use strict";_v=new Set(["target","build","bin","out","dist","node_modules",".git",".svn",".hg",".gradle",".mvn",".idea",".vscode",".settings",".history","__pycache__"]);Pf=new Map,Mv=3e4});function jv(r){if(r.includes("/"))return r;if(Wt[r])return Wt[r];let e=`MediaType.${r}`;if(Wt[e])return Wt[e];for(let[s,i]of Object.entries(Wt))if(s.endsWith(r))return i;let t=r.lastIndexOf(".");if(t>=0){let s=r.substring(t+1),i=`MediaType.${s}`;if(Wt[i])return Wt[i];let o=`MediaType.${s}_VALUE`;if(Wt[o])return Wt[o]}let n=r.toUpperCase();return n.includes("JSON")?"application/json":n.includes("XML")&&!n.includes("HTML")?"application/xml":n.includes("FORM_URLENCODED")?"application/x-www-form-urlencoded":n.includes("MULTIPART")?"multipart/form-data":n.includes("TEXT_PLAIN")||n.includes("PLAIN_TEXT")?"text/plain":n.includes("OCTET_STREAM")?"application/octet-stream":r}function Ai(r){return r.map(jv)}function Gt(r){if(!r)return r;let e=/^([A-Za-z0-9_]+)<(.+)>$/.exec(r);if(!e)return r;let t=e[1],n=e[2];return Lv.has(t)?Gt(n.trim()):r}function es(r){return/MultipartFile/.test(r)}var Wt,Lv,ya=k(()=>{"use strict";Wt={"MediaType.ALL_VALUE":"*/*","MediaType.APPLICATION_ATOM_XML_VALUE":"application/atom+xml","MediaType.APPLICATION_CBOR_VALUE":"application/cbor","MediaType.APPLICATION_FORM_URLENCODED_VALUE":"application/x-www-form-urlencoded","MediaType.APPLICATION_GRAPHQL_VALUE":"application/graphql","MediaType.APPLICATION_GRAPHQL_RESPONSE_VALUE":"application/graphql-response+json","MediaType.APPLICATION_JSON_VALUE":"application/json","MediaType.APPLICATION_JSON_UTF8_VALUE":"application/json;charset=UTF-8","MediaType.APPLICATION_NDJSON_VALUE":"application/x-ndjson","MediaType.APPLICATION_OCTET_STREAM_VALUE":"application/octet-stream","MediaType.APPLICATION_PDF_VALUE":"application/pdf","MediaType.APPLICATION_PROBLEM_JSON_VALUE":"application/problem+json","MediaType.APPLICATION_PROBLEM_XML_VALUE":"application/problem+xml","MediaType.APPLICATION_PROTOBUF_VALUE":"application/x-protobuf","MediaType.APPLICATION_RSS_XML_VALUE":"application/rss+xml","MediaType.APPLICATION_STREAM_JSON_VALUE":"application/stream+json","MediaType.APPLICATION_XHTML_XML_VALUE":"application/xhtml+xml","MediaType.APPLICATION_XML_VALUE":"application/xml","MediaType.APPLICATION_YAML_VALUE":"application/yaml","MediaType.IMAGE_GIF_VALUE":"image/gif","MediaType.IMAGE_JPEG_VALUE":"image/jpeg","MediaType.IMAGE_PNG_VALUE":"image/png","MediaType.MULTIPART_FORM_DATA_VALUE":"multipart/form-data","MediaType.MULTIPART_MIXED_VALUE":"multipart/mixed","MediaType.MULTIPART_RELATED_VALUE":"multipart/related","MediaType.TEXT_EVENT_STREAM_VALUE":"text/event-stream","MediaType.TEXT_HTML_VALUE":"text/html","MediaType.TEXT_MARKDOWN_VALUE":"text/markdown","MediaType.TEXT_PLAIN_VALUE":"text/plain","MediaType.TEXT_XML_VALUE":"text/xml"};Lv=new Set(["HttpEntity","RequestEntity","ResponseEntity","Mono","Flux","Optional","CompletableFuture","DeferredResult","ListenableFuture","Callable"])});var ir,Of=k(()=>{"use strict";ga();ya();ir=class{constructor(e){this.projectRoot=e}projectRoot;cache=new Map;clearCache(){this.cache.clear()}async generate(e){if(!e)return;let t=this.primitiveSchema(e);if(t)return t;let n=e,s=[],i=/^([^<]+)<(.+)>$/.exec(e);i&&(n=i[1].trim(),s=this.splitGenericArgs(i[2]));let o=n.split("."),a=o.pop(),c=o.length?o.join("."):void 0;if(this.cache.has(e))return this.cache.get(e);let l={type:"object",properties:{},required:[]};this.cache.set(e,l);let u=await Tf(this.projectRoot,a);if(u.length>1&&c){let m=/^\s*package\s+([\w.]+);/m;for(let f of u){let h=await qi(f),g=m.exec(h);if(g&&g[1]===c){u=[f];break}}}if(u.length===0){if(s.length>0){let m=await this.generate(s[0]);if(m&&m.properties&&Object.keys(m.properties).length>0)return Object.assign(l,m),l}return{type:"object"}}let d=await qi(u[0]),p=this.buildTypeParamMap(d,a,s);return await this.parseClassToSchema(d,a,l,p),l.required&&l.required.length===0&&delete l.required,l}async generateResponseSchema(e){if(!e||e==="void")return;let t=Gt(e);if(t==="void")return;let n=/(List|Set|Collection)<([^>]+)>/.exec(t);if(n){let s=n[2].trim();return{type:"array",items:await this.generate(s)||{type:"object"}}}if(t.endsWith("[]")){let s=t.replace(/\[\]$/,"");return{type:"array",items:await this.generate(s)||{type:"object"}}}return this.generate(t)}async parseClassToSchema(e,t,n,s){let i=this.extractFieldsRegex(e,t);for(let o of i){s&&s.size>0&&(o.javaType=this.resolveTypeParams(o.javaType,s));let a=await this.fieldToSchema(o),c=o.jsonPropertyName||o.name;n.properties[c]=a,o.required&&n.required.push(c)}}buildTypeParamMap(e,t,n){let s=new Map;if(n.length===0)return s;let i=new RegExp(`class\\s+${t}\\s*<([^{]+?)>\\s*(?:extends|implements|\\{)`).exec(e);return i&&this.splitGenericArgs(i[1]).map(a=>a.trim().split(/\s+/)[0]).forEach((a,c)=>{c<n.length&&s.set(a,n[c])}),s}splitGenericArgs(e){let t=[],n=0,s="";for(let i of e)i==="<"?(n++,s+=i):i===">"?(n--,s+=i):i===","&&n===0?(t.push(s.trim()),s=""):s+=i;return s.trim()&&t.push(s.trim()),t}resolveTypeParams(e,t){let n=e;for(let[s,i]of t)n=n.replace(new RegExp(`\\b${s}\\b`,"g"),i);return n}extractFieldsRegex(e,t){let n=[],s=e.split(/\r?\n/),i=!1,o=0,a=e.search(new RegExp(`class\\s+${t}\\b`)),c=a>=0?e.substring(Math.max(0,a-500),a):"",l=/@(?:lombok\.)?(?:Data|Getter|Value)\b/.test(c),u=/public\s+\S+\s+(?:get|is)[A-Z]\w*\s*\(/.test(e),d=[];for(let p of s){let m=p.trim();if(!i){new RegExp(`class\\s+${t}\\b`).test(m)&&(i=!0,o+=(p.match(/\{/g)||[]).length,o-=(p.match(/\}/g)||[]).length);continue}let f=o;if(o+=(p.match(/\{/g)||[]).length,o-=(p.match(/\}/g)||[]).length,o<=0)break;if(f>1)continue;if(/^@(\w+)/.exec(m)&&!/(?:private|public|protected)\s/.test(m)&&!m.includes(";")){d.push(m);continue}if(/^public\s+\S+\s+(get|is|set)[A-Z]\w*\s*\(/.test(m)){d=[];continue}let g=/(?:(private|public|protected)\s+)?([A-Za-z0-9_<>,\s\[\]?]+?)\s+([A-Za-z0-9_]+)\s*(?:=.*)?;/.exec(m);if(g){let v=g[2].replace(/\b(final)\b/g,"").trim().replace(/@\w+\s*/g,"").trim(),y=g[3],S=g[1]||"";if(v&&y&&!/^(class|interface|enum|return|if|for|while|void)\b/.test(v)){let b=/\bstatic\b/.test(m),C=/\btransient\b/.test(m),w=[...d,m],E=w.join(" ");!b&&!C&&!/@JsonIgnore\b/.test(E)&&(S==="public"||l||u||/@JsonProperty\b/.test(E))&&n.push(this.parseFieldAnnotations(y,v,w))}}d=[]}return n}parseFieldAnnotations(e,t,n){let s=n.join(" "),i={name:e,javaType:t},o=/\bvalue\s*=\s*"([^"]*)"/.exec(s.match(/@JsonProperty\([^)]*\)/)?.[0]||"")||/@JsonProperty\(\s*"([^"]*)"/.exec(s);o&&o[1]&&(i.jsonPropertyName=o[1]),i.description=this.extractAttr(s,"Schema","description"),i.example=this.extractAttr(s,"Schema","example");let a=this.extractAttr(s,"Schema","type");a&&(i.schemaTypeOverride=a);let c=this.extractAttr(s,"Schema","format");c&&(i.format=c),this.extractAttr(s,"Schema","nullable")==="true"&&(i.nullable=!0),this.extractAttr(s,"Schema","readOnly")==="true"&&(i.readOnly=!0),this.extractAttr(s,"Schema","writeOnly")==="true"&&(i.writeOnly=!0),this.extractAttr(s,"Schema","deprecated")==="true"&&(i.deprecated=!0);let m=this.extractAttr(s,"Schema","title");m&&(i.title=m);let f=this.extractAttr(s,"Schema","defaultValue");f&&(i.defaultValue=f);let h=/allowableValues\s*=\s*\{([^}]*)\}/.exec(s);h&&(i.enumValues=h[1].split(",").map(D=>D.trim().replace(/^['"]|['"]$/g,"")).filter(Boolean));let g=this.extractAttr(s,"Schema","minimum");g&&(i.minimum=Number(g));let v=this.extractAttr(s,"Schema","maximum");v&&(i.maximum=Number(v));let y=this.extractAttr(s,"Schema","minLength");y&&(i.minLength=Number(y));let S=this.extractAttr(s,"Schema","maxLength");S&&(i.maxLength=Number(S));let b=this.extractAttr(s,"Schema","pattern");b&&(i.pattern=b),i.description||(i.description=this.extractAttr(s,"ApiModelProperty","value")),i.example||(i.example=this.extractAttr(s,"ApiModelProperty","example")),(/@NotNull\b/.test(s)||/@NotBlank\b/.test(s)||/@NotEmpty\b/.test(s))&&(i.required=!0);let C=this.extractAttr(s,"Size","min");C&&!i.minLength&&(i.minLength=Number(C));let w=this.extractAttr(s,"Size","max");w&&!i.maxLength&&(i.maxLength=Number(w));let E=this.extractAttr(s,"Min","value")||this.extractSingleArg(s,"Min");E&&i.minimum===void 0&&(i.minimum=Number(E));let F=this.extractAttr(s,"Max","value")||this.extractSingleArg(s,"Max");F&&i.maximum===void 0&&(i.maximum=Number(F));let N=this.extractAttr(s,"DecimalMin","value")||this.extractSingleArg(s,"DecimalMin");N&&i.minimum===void 0&&(i.minimum=Number(N));let j=this.extractAttr(s,"DecimalMax","value")||this.extractSingleArg(s,"DecimalMax");j&&i.maximum===void 0&&(i.maximum=Number(j)),/@Email\b/.test(s)&&(i.format=i.format||"email");let O=this.extractAttr(s,"Pattern","regexp");return O&&!i.pattern&&(i.pattern=O),/@PositiveOrZero\b/.test(s)&&i.minimum===void 0&&(i.minimum=0),/@Positive\b/.test(s)&&i.minimum===void 0&&(i.minimum=1),/@NegativeOrZero\b/.test(s)&&i.maximum===void 0&&(i.maximum=0),/@Negative\b/.test(s)&&i.maximum===void 0&&(i.maximum=-1),(/@Past\b/.test(s)||/@PastOrPresent\b/.test(s))&&(i.format=i.format||"date-time"),(/@Future\b/.test(s)||/@FutureOrPresent\b/.test(s))&&(i.format=i.format||"date-time"),i}async fieldToSchema(e){let t={};if(e.schemaTypeOverride?t.type=e.schemaTypeOverride:Object.assign(t,this.javaTypeToJsonSchema(e.javaType)),e.description&&(t.description=e.description),e.title&&(t.title=e.title),e.format&&(t.format=e.format),e.example!==void 0&&(t.example=this.coerceValue(e.example)),e.defaultValue!==void 0&&(t.default=this.coerceValue(e.defaultValue)),e.nullable&&(t.nullable=!0),e.readOnly&&(t.readOnly=!0),e.writeOnly&&(t.writeOnly=!0),e.deprecated&&(t.deprecated=!0),e.enumValues&&(t.enum=e.enumValues),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.pattern&&(t.pattern=e.pattern),t.type==="object"&&!t.properties){let n=await this.generate(e.javaType);n&&n.properties&&(t.properties=n.properties,n.required&&(t.required=n.required))}if(t.type==="array"&&!t.items){let n=/(List|Set|Collection)<([^>]+)>/.exec(e.javaType);if(n){let s=n[2].trim(),i=this.primitiveSchema(s)||await this.generate(s);t.items=i||{type:"object"}}}return t}javaTypeToJsonSchema(e){if(/^(String|CharSequence|char|Character)$/.test(e))return{type:"string"};if(/^(int|Integer|short|Short|byte|Byte)$/.test(e))return{type:"integer",format:"int32"};if(/^(long|Long|BigInteger)$/.test(e))return{type:"integer",format:"int64"};if(/^(float|Float)$/.test(e))return{type:"number",format:"float"};if(/^(double|Double|BigDecimal)$/.test(e))return{type:"number",format:"double"};if(/^(boolean|Boolean)$/.test(e))return{type:"boolean"};if(/^(LocalDate)$/.test(e))return{type:"string",format:"date"};if(/^(LocalDateTime|ZonedDateTime|OffsetDateTime|Instant|Date|Timestamp)$/.test(e))return{type:"string",format:"date-time"};if(/^(LocalTime|OffsetTime)$/.test(e))return{type:"string",format:"time"};if(/^UUID$/.test(e))return{type:"string",format:"uuid"};if(/^(URI|URL)$/.test(e))return{type:"string",format:"uri"};if(/^(byte\[\]|Byte\[\])$/.test(e))return{type:"string",format:"binary"};if(/^Map\b/.test(e))return{type:"object",additionalProperties:!0};if(/(List|Set|Collection)</.test(e))return{type:"array"};if(e.endsWith("[]")){let t=e.replace(/\[\]$/,"");return{type:"array",items:this.primitiveSchema(t)||{type:"object"}}}return{type:"object"}}primitiveSchema(e){let t=this.javaTypeToJsonSchema(e);if(t.type!=="object"||/^Map\b/.test(e))return t}static javaTypeToParamType(e){return/^(int|Integer|long|Long|short|Short|byte|Byte|BigInteger)$/.test(e)?"integer":/^(float|Float|double|Double|BigDecimal)$/.test(e)?"number":/^(boolean|Boolean)$/.test(e)?"boolean":/(List|Set|Collection)</.test(e)||e.endsWith("[]")?"array":"string"}static javaTypeToFormat(e){if(/^(int|Integer|short|Short|byte|Byte)$/.test(e))return"int32";if(/^(long|Long|BigInteger)$/.test(e))return"int64";if(/^(float|Float)$/.test(e))return"float";if(/^(double|Double|BigDecimal)$/.test(e))return"double";if(/^(LocalDate)$/.test(e))return"date";if(/^(LocalDateTime|ZonedDateTime|OffsetDateTime|Instant|Date|Timestamp)$/.test(e))return"date-time";if(/^(LocalTime|OffsetTime)$/.test(e))return"time";if(/^UUID$/.test(e))return"uuid";if(/^(URI|URL)$/.test(e))return"uri"}extractAttr(e,t,n){let i=new RegExp(`@${t}\\b[^)]*\\b${n}\\s*=\\s*"([^"]*)"`,"s").exec(e);return i?i[1]:void 0}extractSingleArg(e,t){let s=new RegExp(`@${t}\\(\\s*([^")]+?)\\s*\\)`).exec(e);if(s&&!/=/.test(s[1]))return s[1].trim()}coerceValue(e){return/^-?\d+$/.test(e)?parseInt(e,10):/^-?\d+\.\d+$/.test(e)?parseFloat(e):e==="true"?!0:e==="false"?!1:e}}});import{BaseJavaCstVisitorWithDefaults as Hv}from"java-parser";function tu(r){let e=[],t=/:(\w+)|\{(\w+)\}/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]||n[2]);return e}var va,$f=k(()=>{"use strict";ya();va=class extends Hv{controllers=[];contextStack=[];constructor(){super(),this.validateVisitor()}annotation(e){if(this.contextStack.length===0)return;let t=e.typeName[0].children.Identifier[0].image,n=new Map;if(e.elementValuePairList){let i=e.elementValuePairList[0].children.elementValuePair;for(let o of i){let a=o.children.Identifier[0].image,c=this.extractElementValue(o.children.elementValue[0]);c!==void 0&&n.set(a,c)}}else if(e.elementValue){let i=this.extractElementValue(e.elementValue[0]);i!==void 0&&n.set("value",i)}this.contextStack[this.contextStack.length-1].annotations.push({name:t,attributes:n}),this.visitNestedAnnotations(e)}visitNestedAnnotations(e){let t=[];if(e.elementValue&&t.push(e.elementValue[0]),e.elementValuePairList){let n=e.elementValuePairList[0].children.elementValuePair||[];for(let s of n)s.children.elementValue&&t.push(s.children.elementValue[0])}for(let n of t){if(n.children?.annotation)for(let i of n.children.annotation)this.annotation(i.children);let s=n.children?.elementValueArrayInitializer?.[0];if(s){let i=s.children?.elementValueList?.[0]?.children?.elementValue||[];for(let o of i)if(o.children?.annotation)for(let a of o.children.annotation)this.annotation(a.children)}}}typeIdentifier(e){if(this.contextStack.length===0)return;let t=e.Identifier[0].image,n=e.Identifier[0].startLine,s=this.contextStack[this.contextStack.length-1];s.name=t,s.line=n}classDeclaration(e){let t={type:"class",name:"",line:0,annotations:[],endpoints:[]};this.contextStack.push(t);for(let i of e.classModifier||[])this.visit(i);let n=t.annotations.find(i=>i.name==="RequestMapping");if(n){let i=n.attributes.get("value")||n.attributes.get("path");i&&typeof i=="string"&&(t.basePath=i.replace(/^['\"]|['\"]$/g,""))}for(let i of e.normalClassDeclaration||[])this.visit(i);if(this.contextStack.pop(),t.annotations.some(i=>i.name==="RestController"||i.name==="Controller")){let i={name:t.name,basePath:t.basePath||"",file:"",line:t.line,endpoints:t.endpoints};this.controllers.push(i)}}methodDeclarator(e){if(this.contextStack.length===0)return;let t=e.Identifier[0].image,n=e.Identifier[0].startLine,s=this.contextStack[this.contextStack.length-1];s.name=t,s.line=n}methodDeclaration(e){if(this.contextStack.length===0||this.contextStack[this.contextStack.length-1].type!=="class")return;let t=this.contextStack[this.contextStack.length-1],n={type:"method",name:"",line:0,annotations:[]};this.contextStack.push(n);for(let i of e.methodHeader||[])this.visit(i);for(let i of e.methodModifier||[])this.visit(i);this.contextStack.pop();let s=n.annotations.filter(i=>/Mapping$/.test(i.name));if(s.length!==0)for(let i of s){let o=this.buildEndpoint(i,n,e,t);o&&t.endpoints.push(o)}}collectTokens(e){if(!e)return[];if(e.image!==void 0)return[e];let t=[];if(e.children)for(let n of Object.keys(e.children))for(let s of e.children[n])t.push(...this.collectTokens(s));return t.sort((n,s)=>n.startOffset-s.startOffset),t}extractElementValue(e){if(!e)return;let t=e.children;if(t){if(t.annotation){let n=this.collectTokens(t.annotation[0]);if(n.length>0)return n.map(s=>s.image).join("")}if(t.elementValueArrayInitializer){let s=t.elementValueArrayInitializer[0].children?.elementValueList?.[0]?.children?.elementValue;return s?s.map(o=>{let a=this.extractElementValue(o);return Array.isArray(a)?a.join(","):a}).filter(o=>typeof o=="string"&&o.length>0):[]}if(t.conditionalExpression){let n=this.collectTokens(t.conditionalExpression[0]);return n.length===0?void 0:n.map(s=>s.image).join("")}}}buildEndpoint(e,t,n,s){let i=e.name.replace("Mapping","").toUpperCase();i==="REQUEST"&&(i="");let o="",a=[],c=[];for(let[m,f]of e.attributes.entries())if(m==="value"||m==="path")typeof f=="string"&&(o=f.replace(/^['\"]|['\"]$/g,""));else if(m==="consumes")Array.isArray(f)?a=Ai(f.map(h=>h.replace(/^['\"]|['\"]$/g,""))):typeof f=="string"&&(a=Ai([f.replace(/^['\"]|['\"]$/g,"")]));else if(m==="produces")Array.isArray(f)?c=f.map(h=>h.replace(/^['\"]|['\"]$/g,"")):typeof f=="string"&&(c=[f.replace(/^['\"]|['\"]$/g,"")]);else if(m==="method"&&e.name==="RequestMapping"&&typeof f=="string"){let h=f.match(/RequestMethod\.([A-Z]+)/);h&&(i=h[1])}!i&&e.name==="RequestMapping"&&(i="GET");let l=o;s.basePath&&(l&&!l.startsWith("/")?l=s.basePath+"/"+l:l=s.basePath+l),l&&!l.startsWith("/")&&(l="/"+l);let u=this.extractParameters(n),d=this.extractReturnType(n),p=this.extractOpenApiAnnotations(t.annotations,s.annotations);return{method:i,path:l,file:"",line:t.line,pathParams:tu(l),consumes:a,produces:c.length>0?c:void 0,headers:u.headers,queryParams:u.queryParams,hasBody:u.hasBody,bodyType:u.bodyType,formParts:u.formParts.length>0?u.formParts:void 0,modelAttributeType:u.modelAttributeType,returnType:d||void 0,summary:p.summary,description:p.description,operationId:p.operationId,tags:p.tags.length>0?p.tags:void 0,deprecated:p.deprecated||void 0,responses:p.responses.length>0?p.responses:void 0,parameterMeta:u.parameterMeta.length>0?u.parameterMeta:void 0,security:p.security.length>0?p.security:void 0}}extractOpenApiAnnotations(e,t){let n,s,i,o=[],a=!1,c=[],l=[];for(let u of t)if(u.name==="Tag"){let d=this.getAnnotationAttrString(u,"name");d&&o.push(d)}for(let u of e)switch(u.name){case"Operation":{n=this.getAnnotationAttrString(u,"summary")||n,s=this.getAnnotationAttrString(u,"description")||s,i=this.getAnnotationAttrString(u,"operationId")||i;let d=u.attributes.get("deprecated");typeof d=="string"&&d==="true"&&(a=!0);let p=u.attributes.get("tags");if(Array.isArray(p))p.forEach(m=>{let f=m.replace(/^['"]|['"]$/g,"");f&&o.push(f)});else if(typeof p=="string"){let m=p.replace(/^['"]|['"]$/g,"");m&&o.push(m)}break}case"ApiOperation":{n=this.getAnnotationAttrString(u,"value")||n,s=this.getAnnotationAttrString(u,"notes")||s;let d=u.attributes.get("tags");Array.isArray(d)&&d.forEach(p=>{let m=p.replace(/^['"]|['"]$/g,"");m&&o.push(m)});break}case"Tag":{let d=this.getAnnotationAttrString(u,"name");d&&o.push(d);break}case"Deprecated":{a=!0;break}case"ApiResponse":{let d=this.parseApiResponse(u);d&&c.push(d);break}case"ApiResponses":break;case"SecurityRequirement":{let d=this.getAnnotationAttrString(u,"name");d&&l.push(d);break}}return{summary:n,description:s,operationId:i,tags:[...new Set(o)],deprecated:a,responses:c,security:l}}parseApiResponse(e){let t=this.getAnnotationAttrString(e,"responseCode")||this.getAnnotationAttrString(e,"code")||"200",n=this.getAnnotationAttrString(e,"description"),s=this.getAnnotationAttrRaw(e,"content"),i=s?this.extractAttrFromRaw(s,"mediaType"):void 0,o=s?this.extractImplementationType(s):this.extractImplementationType(this.getAnnotationAttrRaw(e,"schema")),a=s?this.extractExampleObjects(s):void 0,c=this.getAnnotationAttrRaw(e,"headers"),l=c?this.extractHeaderObjects(c):void 0;return{statusCode:t,description:n,...i&&{contentType:i},...o&&{schemaType:o},...a&&Object.keys(a).length>0&&{examples:a},...l&&Object.keys(l).length>0&&{headers:l}}}getAnnotationAttrRaw(e,t){let n=e.attributes.get(t);if(typeof n=="string")return n;if(Array.isArray(n))return n.join(",")}extractAttrFromRaw(e,t){let n=new RegExp(`${t}\\s*=\\s*(["'])(.*?)\\1`);return e.match(n)?.[2]}extractImplementationType(e){if(!e)return;let t=e.match(/implementation\s*=\s*([A-Za-z0-9_$.<>?]+)\.class/);if(!t?.[1])return;let n=t[1];return n=n.split(".").pop()||n,Gt(n)}extractExampleObjects(e){let t={},n=e.match(/@ExampleObject\(([^)]*)\)/g)||[],s=1;for(let i of n){let a=(i.match(/name\s*=\s*"((?:\\.|[^"\\])*)"/)?.[1]||this.extractAttrFromRaw(i,"name")||`example${s++}`).replace(/\\"/g,'"').replace(/\\\\/g,"\\"),c=i.match(/value\s*=\s*"((?:\\.|[^"\\])*)"/),l=c?.[1]?c[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):this.extractAttrFromRaw(i,"value");if(!l)continue;let u=this.parseExampleValue(l);t[a]=u}return Object.keys(t).length>0?t:void 0}extractHeaderObjects(e){let t={},n=e.match(/@Header\(([^)]*)\)/g)||[];for(let s of n){let i=this.extractAttrFromRaw(s,"name")||this.extractAttrFromRaw(s,"value");if(!i)continue;let o={},a=this.extractAttrFromRaw(s,"description");a&&(o.description=a);let c=this.extractAttrFromRaw(s,"format");c&&(o.format=c);let l=s.match(/required\s*=\s*(true|false)/)?.[1];l&&(o.required=l==="true");let u=s.match(/deprecated\s*=\s*(true|false)/)?.[1];u&&(o.deprecated=u==="true");let d=this.extractAttrFromRaw(s,"type")||this.extractImplementationType(s);d&&(o.schemaType=d),t[i]=o}return Object.keys(t).length>0?t:void 0}parseExampleValue(e){let t=e.trim();if(!t)return"";if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return t}return t}getAnnotationAttrString(e,t){let n=e.attributes.get(t);if(typeof n=="string")return n.replace(/^['"]|['"]$/g,"")||void 0}extractReturnType(e){let t=e.methodHeader?.[0]?.children?.result?.[0];if(!t)return"";if(t.children?.Void)return"void";let n=t.children?.unannType?.[0];if(!n)return"";let s=this.extractUnannTypeName(n);return Gt(s)}extractParameters(e){let t=[],n=[],s=[],i=[],o=!1,a,c,l=e.methodHeader?.[0]?.children?.methodDeclarator?.[0]?.children?.formalParameterList?.[0]?.children?.formalParameter;if(!l)return{headers:t,queryParams:n,hasBody:o,bodyType:a,formParts:s,modelAttributeType:c,parameterMeta:i};for(let u of l){let d=u.children?.variableParaRegularParameter?.[0]?.children;if(!d)continue;let p=d.variableDeclaratorId?.[0]?.children?.Identifier?.[0]?.image||"",m=d.variableModifier||[],f=this.collectAnnotationsFromModifiers(m),h=d.unannType?.[0],g=h?this.extractUnannTypeName(h):"",v=f.find(b=>b.name==="Parameter"),y;for(let b of f)if(b.name==="RequestHeader"){let C=this.getAnnotationStringValue(b)||p;t.push(C),y=this.buildParameterMeta(C,"header",g,v,f);let w=b.attributes.get("required");y&&typeof w=="string"&&(w==="true"||w==="false")&&(y.required=w==="true")}else if(b.name==="RequestParam")if(es(g)){o=!0;let C=this.getAnnotationStringValue(b)||p;s.push({name:C,type:g,isFile:!0})}else{let C=this.getAnnotationStringValue(b)||p;n.push(C);let w=b.attributes.get("required");y=this.buildParameterMeta(C,"query",g,v,f),y&&typeof w=="string"&&(w==="true"||w==="false")&&(y.required=w==="true")}else if(b.name==="RequestBody")o=!0,g&&(a=Gt(g));else if(b.name==="RequestPart"){o=!0;let C=this.getAnnotationStringValue(b)||p,w=es(g);s.push({name:C,type:g,isFile:w})}else b.name==="ModelAttribute"&&(o=!0,g&&(c=g));let S=f.find(b=>b.name==="PathVariable");if(S){let b=this.getAnnotationStringValue(S)||p;y=this.buildParameterMeta(b,"path",g,v,f)}y&&i.push(y)}return{headers:t,queryParams:n,hasBody:o,bodyType:a,formParts:s,modelAttributeType:c,parameterMeta:i}}buildParameterMeta(e,t,n,s,i){let o={name:e,in:t};if(s){let a=this.getAnnotationAttrString(s,"description");a&&(o.description=a);let c=this.getAnnotationAttrString(s,"example");c&&(o.example=c);let l=s.attributes.get("required");typeof l=="string"&&(l==="true"||l==="false")&&(o.required=l==="true");let u=s.attributes.get("deprecated");typeof u=="string"&&u==="true"&&(o.deprecated=!0)}return n&&(o.schemaType=n),i&&this.extractConstraintAnnotations(o,i),o}extractConstraintAnnotations(e,t){for(let n of t)switch(n.name){case"Schema":{let s=this.getAnnotationAttrString(n,"pattern");s&&!e.pattern&&(e.pattern=s);let i=this.getAnnotationAttrString(n,"format");i&&!e.format&&(e.format=i);let o=this.getAnnotationAttrString(n,"minimum");o&&e.minimum===void 0&&(e.minimum=Number(o));let a=this.getAnnotationAttrString(n,"maximum");a&&e.maximum===void 0&&(e.maximum=Number(a));let c=this.getAnnotationAttrString(n,"minLength");c&&e.minLength===void 0&&(e.minLength=Number(c));let l=this.getAnnotationAttrString(n,"maxLength");l&&e.maxLength===void 0&&(e.maxLength=Number(l));let u=n.attributes.get("allowableValues");Array.isArray(u)&&!e.enum&&(e.enum=u.map(d=>d.replace(/^['"]|['"]$/g,"")).filter(Boolean));break}case"Pattern":{let s=this.getAnnotationAttrString(n,"regexp");s&&!e.pattern&&(e.pattern=s);break}case"Size":{let s=this.getAnnotationAttrString(n,"min");s&&e.minLength===void 0&&(e.minLength=Number(s));let i=this.getAnnotationAttrString(n,"max");i&&e.maxLength===void 0&&(e.maxLength=Number(i));break}case"Min":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n);s&&e.minimum===void 0&&(e.minimum=Number(s));break}case"Max":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n);s&&e.maximum===void 0&&(e.maximum=Number(s));break}case"DecimalMin":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n),i=this.getAnnotationAttrString(n,"inclusive");s&&(i==="false"?e.exclusiveMinimum===void 0&&(e.exclusiveMinimum=Number(s)):e.minimum===void 0&&(e.minimum=Number(s)));break}case"DecimalMax":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n),i=this.getAnnotationAttrString(n,"inclusive");s&&(i==="false"?e.exclusiveMaximum===void 0&&(e.exclusiveMaximum=Number(s)):e.maximum===void 0&&(e.maximum=Number(s)));break}case"Email":{e.format||(e.format="email");break}case"Positive":{e.exclusiveMinimum===void 0&&(e.exclusiveMinimum=0);break}case"PositiveOrZero":{e.minimum===void 0&&(e.minimum=0);break}case"Negative":{e.exclusiveMaximum===void 0&&(e.exclusiveMaximum=0);break}case"NegativeOrZero":{e.maximum===void 0&&(e.maximum=0);break}case"NotNull":case"NotBlank":case"NotEmpty":{e.required===void 0&&(e.required=!0);break}}}getAnnotationStringValue(e){let t=e.attributes.get("value");return typeof t=="string"?t.replace(/^['"]|['"]$/g,""):""}extractUnannTypeName(e){return this.collectTokens(e).map(n=>n.image).join("")}collectAnnotationsFromModifiers(e){let t=[];for(let n of e){let s=n.children?.annotation;if(!s)continue;let i=s[0].children,o=i.typeName[0].children.Identifier[0].image,a=new Map;if(i.elementValuePairList){let c=i.elementValuePairList[0].children.elementValuePair;for(let l of c){let u=l.children.Identifier[0].image,d=this.extractElementValue(l.children.elementValue[0]);d!==void 0&&a.set(u,d)}}else if(i.elementValue){let c=this.extractElementValue(i.elementValue[0]);c!==void 0&&a.set("value",c)}t.push({name:o,attributes:a})}return t}extractTypeName(e){if(!e)return"";if(e.primitiveType)return e.primitiveType[0].children?.literal?.[0]?.image||"";if(e.classOrInterfaceType){let t=e.classOrInterfaceType[0],n="",s=t.Identifier||[];for(let o=0;o<s.length;o++)o>0&&(n+="."),n+=s[o].image;let i=t.typeArguments?.[0]?.typeArgument;return i&&(n+="<",n+=i.map(o=>o.typeType?this.extractTypeName(o.typeType[0]):"?").join(","),n+=">"),n}if(e.typeType&&e.dims){let t=this.extractTypeName(e.typeType[0]),n=e.dims.length;return t+"[]".repeat(n)}return""}}});var Ff={};nc(Ff,{EndpointParser:()=>nu});import{parse as Bv}from"java-parser";var nu,Nf=k(()=>{"use strict";ga();ya();$f();nu=class r{fileCache=new Map;generatedRe=/_[0-9a-zA-Z]+\.java$/;clearCache(){this.fileCache.clear()}evictPaths(e){let t=e.map(n=>Xl(n.trim()));for(let n of[...this.fileCache.keys()]){let s=Xl(n);t.some(i=>s.startsWith(i+"/"))&&this.fileCache.delete(n)}}async parseControllers(e){let t=Ei(e),n=[],s=new Set,i=[];for(let a of t)if(!this.generatedRe.test(eu(a))&&!s.has(a)){if(s.add(a),this.fileCache.has(a)){n.push(...this.fileCache.get(a));continue}i.push(a)}let o=30;for(let a=0;a<i.length;a+=o){let c=i.slice(a,a+o),l=await Promise.all(c.map(u=>this.parseFile(u).then(d=>({filePath:u,ctrls:d})).catch(()=>({filePath:u,ctrls:[]}))));for(let{filePath:u,ctrls:d}of l)this.fileCache.set(u,d),n.push(...d)}for(let a of this.fileCache.keys())s.has(a)||this.fileCache.delete(a);return n}removeFile(e){this.fileCache.delete(e)}static CONTROLLER_HINT_RE=/@(?:RestController|Controller)\b|@(?:Request|Get|Post|Put|Delete|Patch)Mapping\b/;looksLikeController(e){return r.CONTROLLER_HINT_RE.test(e)}async parseFile(e){let t=await qi(e);if(!this.looksLikeController(t))return[];let n=this.parseWithAst(t);if(n){for(let s of n){s.file=e;for(let i of s.endpoints)i.file=e}return n}return this.parseWithRegex(t,e)}async findEndpoints(e){return(await this.parseControllers(e)).flatMap(n=>n.endpoints)}parseWithAst(e){try{let t=Bv(e),n=new va;if(n.visit(t),n.controllers.length>0){for(let s of n.controllers){let i=new Set;s.endpoints=s.endpoints.filter(o=>{let a=`${o.method}:${o.path}:${o.line}`;return i.has(a)?!1:(i.add(a),!0)})}return n.controllers}return null}catch{return null}}parseWithRegex(e,t){let n=[],s=e.split(/\r?\n/),i=[],o=new Map,a=null,c=0,l=!1;for(let u=0;u<s.length;u++){let d=s[u],p=d.trim(),m=/^@(\w+)\s*(?:\(([^)]*)\))?/.exec(p);if(m&&!/\b(class|interface|enum)\b/.test(p)&&(i.push(m[1]),m[2]!==void 0&&o.set(m[1],m[2]),!/(private|public|protected|static|final|void|class)\b/.test(p)))continue;let f=/\bclass\s+(\w+)/.exec(p);if(f){if(a&&(this.deduplicateEndpoints(a),n.push(a),a=null),i.some(y=>y==="RestController"||y==="Controller")){let y="",S=o.get("RequestMapping");S!==void 0&&(y=this.extractPathFromArgs(S)),a={name:f[1],basePath:y,file:t,line:u+1,endpoints:[]}}l=!0,c=0,c+=(d.match(/\{/g)||[]).length,c-=(d.match(/\}/g)||[]).length,i=[],o=new Map;continue}if(l&&(c+=(d.match(/\{/g)||[]).length,c-=(d.match(/\}/g)||[]).length,c<=0)){l=!1,a&&(this.deduplicateEndpoints(a),n.push(a),a=null),i=[],o=new Map;continue}if(!a){m||(i=[],o=new Map);continue}let h=i.find(v=>/Mapping$/.test(v)),g=/^@(GetMapping|PostMapping|PutMapping|DeleteMapping|PatchMapping|RequestMapping)\s*(?:\(([^)]*)\))?/.exec(p);if(h||g){let v=u,y=this.collectMethodSignature(s,v),S=[];g&&S.push({name:g[1],args:g[2]||""});for(let b of i)/Mapping$/.test(b)&&(!g||b!==g[1])&&S.push({name:b,args:o.get(b)||""});for(let b of S){let C=b.name.replace("Mapping","").toUpperCase();C==="REQUEST"&&(C="");let w="",E=[],F=b.args;if(F){w=this.extractPathFromArgs(F);let O=/consumes\s*=\s*\{?\s*([^}]*)\}?/.exec(F);if(O){let D=O[1],P=[...D.matchAll(/["']([^"']+)["']/g)].map(G=>G[1]),M=[...D.matchAll(/MediaType\.([A-Z_]+)/g)].map(G=>`MediaType.${G[1]}`);E=Ai([...P,...M])}if(b.name==="RequestMapping"){let D=/method\s*=\s*(?:\{?\s*)?RequestMethod\.([A-Z]+)/.exec(F);D&&(C=D[1])}}!C&&b.name==="RequestMapping"&&(C="GET");let N=w;a.basePath&&(N&&!N.startsWith("/")?N=a.basePath+"/"+N:N=a.basePath+N),N&&!N.startsWith("/")&&(N="/"+N);let j=this.extractParameterMetadataFromSig(y);a.endpoints.push({method:C,path:N,file:t,line:u+1,pathParams:tu(N),consumes:E,bodyType:j.bodyType,headers:j.headers,queryParams:j.queryParams,hasBody:j.hasBody,formParts:j.formParts.length>0?j.formParts:void 0,modelAttributeType:j.modelAttributeType})}i=[],o=new Map;continue}m||(i=[],o=new Map)}return a&&(this.deduplicateEndpoints(a),n.push(a)),n}extractPathFromArgs(e){let t=/(?:value|path)\s*=\s*["']([^"']+)["']/.exec(e);if(t)return t[1];let n=/^\s*["']([^"']+)["']/.exec(e);return n?n[1]:""}collectMethodSignature(e,t){let n="";for(let s=t;s<e.length&&(n+=e[s]+" ",!e[s].includes("{"));s++);return n}extractParameterMetadataFromSig(e){let t=[],n=[],s=[],i=!1,o,a,c=/@RequestHeader\s*(?:\(\s*(?:(?:value|name)\s*=\s*)?["']([^"']+)["']\s*\))?\s+(?:[A-Za-z0-9_<>\[\]]+)\s+(\w+)/g,l;for(;(l=c.exec(e))!==null;)t.push(l[1]||l[2]);let u=/@RequestParam\s*(?:\(\s*(?:(?:value|name)\s*=\s*)?["']([^"']+)["']\s*\))?\s+([A-Za-z0-9_<>\[\]]+)\s+(\w+)/g;for(;(l=u.exec(e))!==null;){let g=l[2];if(es(g)){i=!0;let v=l[1]||l[3];s.push({name:v,type:g,isFile:!0})}else n.push(l[1]||l[3])}let p=/@RequestBody\s+([A-Za-z0-9_<>\[\]]+)\s+\w+/.exec(e);p?(i=!0,o=Gt(p[1])):/@RequestBody/.test(e)&&(i=!0);let m=/@RequestPart\s*(?:\(\s*(?:(?:value|name)\s*=\s*)?["']([^"']+)["']\s*\))?\s+([A-Za-z0-9_<>\[\]]+)\s+(\w+)/g;for(;(l=m.exec(e))!==null;){i=!0;let g=l[1]||l[3],v=l[2],y=es(v);s.push({name:g,type:v,isFile:y})}let h=/@ModelAttribute\s+([A-Za-z0-9_<>\[\]]+)\s+\w+/.exec(e);return h?(i=!0,a=h[1]):/@ModelAttribute/.test(e)&&(i=!0),{headers:t,queryParams:n,hasBody:i,bodyType:o,formParts:s,modelAttributeType:a}}deduplicateEndpoints(e){let t=new Set;e.endpoints=e.endpoints.filter(n=>{let s=`${n.method}:${n.path}:${n.line}`;return t.has(s)?!1:(t.add(s),!0)})}}});import*as ba from"fs";import*as _f from"path";function zv(r){let e=[];for(let t of r.parameterMeta??[]){let n=[];t.required&&n.push("required"),t.pattern&&n.push(`pattern=${t.pattern}`),t.format&&n.push(`format=${t.format}`),t.enum&&t.enum.length>0&&n.push(`enum=[${t.enum.join(", ")}]`),t.minimum!==void 0&&n.push(`min=${t.minimum}`),t.maximum!==void 0&&n.push(`max=${t.maximum}`),t.exclusiveMinimum!==void 0&&n.push(`exclusiveMin=${t.exclusiveMinimum}`),t.exclusiveMaximum!==void 0&&n.push(`exclusiveMax=${t.exclusiveMaximum}`),t.minLength!==void 0&&n.push(`minLength=${t.minLength}`),t.maxLength!==void 0&&n.push(`maxLength=${t.maxLength}`),n.length>0&&e.push(`${t.in==="header"?"header":t.in} ${t.name}: ${n.join(", ")}`)}return e.length>0?e:void 0}var Uv,Vv,Rn,ru=k(()=>{"use strict";ga();Of();Uv=["pom.xml","build.gradle","build.gradle.kts","settings.gradle"],Vv=/@(?:RestController|Controller)\b/,Rn=class{id="provider.spring";framework="spring";parserModule;supports(e){for(let s of Uv)if(ba.existsSync(_f.join(e.projectRoot,s)))return{supported:!0,confidence:.95,reasons:[`${s} detected`]};let t=e.sourceFiles?.filter(s=>s.endsWith(".java"))??[];t.length===0&&(t=Ei(e.projectRoot));let n=0;for(let s of t)if(s.endsWith(".java")){if(n>=40)break;n+=1;try{let i=ba.readFileSync(s,"utf-8");if(Vv.test(i))return{supported:!0,confidence:.8,reasons:["Spring controller annotation found"]}}catch{continue}}return{supported:!1,confidence:0,reasons:["no Spring indicators found"]}}async discover(e,t){let n=Date.now(),s=[],i=t.projectRoot,o=await this.loadParser(),a=new o.EndpointParser,c=[];try{c=await a.parseControllers(i)}catch(d){let p=d instanceof Error?d.message:String(d);s.push({code:"provider-failed",framework:"spring",message:`Spring discovery failed for ${i}: ${p}`})}let l=new ir(i),u=[];for(let d of c)for(let p of d.endpoints)u.push(await this.endpointToDiscoveredApi(p,l));return{endpoints:u,warnings:s,stats:{frameworksDetected:["spring"],providersRun:[this.id],endpointCount:u.length,unresolvedEndpointCount:u.filter(d=>!d.resolvedPath).length,scanDurationMs:Date.now()-n}}}clearCache(){this.parserModule=void 0}async loadParser(){return this.parserModule||(this.parserModule=await Promise.resolve().then(()=>(Nf(),Ff))),this.parserModule}async endpointToDiscoveredApi(e,t){let n=await this.buildParams(e,t),s=await this.buildRequestBody(e,t),i=await this.buildResponses(e,t),o=e.security&&e.security.length>0?{required:!0,type:"oauth2",annotation:e.security.join(", ")}:void 0,a=e.line>0?e.line:1;return{id:"",framework:"spring",method:e.method||"GET",pathExpression:e.path||"/",resolvedPath:e.path||"/",confidence:"high",source:{filePath:e.file,line:a,symbolName:`${e.method||"GET"} ${e.path||"/"}`},params:n.length>0?n:void 0,requestBody:s,responses:i,validation:zv(e),auth:o,tags:e.tags,deprecated:e.deprecated,description:e.summary||e.description}}async buildParams(e,t){let n=[],s=(e.consumes??[]).join(" "),i=s.includes("x-www-form-urlencoded"),o=s.includes("multipart");for(let a of e.headers??[])n.push(this.paramFromMeta(a,"header",e.parameterMeta,!0));for(let a of e.queryParams??[]){let c=i||o?"form":"query",l=e.parameterMeta?.find(u=>u.name===a&&u.in==="query");n.push(this.paramFromMeta(a,c,e.parameterMeta,l?.required))}for(let a of e.formParts??[])n.push({name:a.name,location:"form",type:a.isFile?"file":"string",required:!0});return n}paramFromMeta(e,t,n,s){let i=n?.find(a=>a.name===e&&(a.in===t||t==="form"&&a.in==="query")),o={name:e,location:t};return i&&(o.description=i.description,o.required=i.required??s,o.example=i.example,i.schemaType&&(o.type=ir.javaTypeToParamType(i.schemaType)),o.schema=this.constraintsToSchema(i)),o.required=t==="path"?!0:o.required,o.type=o.type??"string",o}constraintsToSchema(e){let t={};if(e.schemaType){t.type=ir.javaTypeToParamType(e.schemaType);let n=ir.javaTypeToFormat(e.schemaType);n&&(t.format=n)}return e.pattern&&(t.pattern=e.pattern),e.format&&(t.format=e.format),e.enum&&e.enum.length>0&&(t.enum=e.enum),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.exclusiveMinimum!==void 0&&(t.exclusiveMinimum=e.exclusiveMinimum),e.exclusiveMaximum!==void 0&&(t.exclusiveMaximum=e.exclusiveMaximum),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),Object.keys(t).length>0?t:void 0}async buildRequestBody(e,t){let n=e.consumes??[];if(e.formParts&&e.formParts.length>0)return{type:"multipart",required:e.method==="POST"||e.method==="PUT"||e.method==="PATCH"};if(e.modelAttributeType)return{type:"form",required:!0,schema:await this.maybeSchema(t,e.modelAttributeType)};if(n.some(a=>a.includes("x-www-form-urlencoded"))&&(e.queryParams?.length??0)>0)return{type:"form",required:e.method==="POST"||e.method==="PUT"||e.method==="PATCH"};if(!e.hasBody)return;let s=e.bodyType??e.modelAttributeType;if(!s)return{type:"json",required:!0};let i=n.some(a=>a.includes("x-www-form-urlencoded"))?"form":n.some(a=>a.includes("multipart"))?"multipart":"json",o=await this.maybeSchema(t,s);return{type:i,required:!0,schema:o}}async buildResponses(e,t){let n=[];for(let s of e.responses??[]){let i={statusCode:parseInt(s.statusCode,10)||200},o=s.schemaType?await this.maybeSchema(t,s.schemaType):void 0;i.body={type:s.contentType??"json"},o&&(i.body.schema=o),n.push(i)}if(n.length===0){let s=e.returnType;if(s&&s!=="void"){let i=await t.generateResponseSchema(s);n.push({statusCode:200,body:{type:"json",schema:i??{type:"object"}}})}else n.push({statusCode:200})}return n}async maybeSchema(e,t){return await e.generate(t)??{type:"object"}}}});import*as xa from"fs";import*as Hf from"path";function su(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=xa.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=Hf.join(n,i.name);if(i.isDirectory()){Jv.has(i.name)||t.push(o);continue}i.isFile()&&o.endsWith(".py")&&e.push(o)}}return e.sort()}function Bf(r){let e=su(r),t=new Map,n=new Map,s=new Map,i=[];for(let u of e){let d="";try{d=xa.readFileSync(u,"utf-8")}catch{continue}let p=Gv(d,u,t);n.set(u,p);for(let m of p.routers)s.has(m.name)||s.set(m.name,m)}let o=new Map;for(let u of s.values())o.set(u.name,[u.constructorPrefix]);let a=new Map,c=new Set;for(let u of n.values())for(let d of u.includes){let p=Mf(u.imports,d.routerName);if(!s.has(p)){i.push(`include_router references unknown router '${d.routerName}' at ${d.line}`);continue}let m=s.get(p);if(d.prefix){c.add(p);let f=o.get(p),h=`${d.prefix.replace(/\/+$/,"")}/${m.constructorPrefix.replace(/^\/+/,"")}`;f.includes(h)||f.push(h)}d.tags&&d.tags.length>0&&a.set(p,[...a.get(p)??[],...d.tags])}let l=[];for(let[u,d]of n.entries())for(let p of d.routes)for(let m of p.decorators){let f=Mf(d.imports,m.object),h=d.appNames.has(m.object)||d.appNames.has(f),g=s.get(f);if(!h&&!g)continue;let v=Xv(m.method,m.args);if(v.length===0)continue;let y=eb(m.args),S=m.unresolved||y.startsWith("f"),b=g?o.get(f)??[g.constructorPrefix]:[""];for(let C of b){if(g&&c.has(f)&&C===g.constructorPrefix)continue;let w=g?ab(C,y):y,E=cb(p.signature,ob(w)),F=g?a.get(f):void 0,j=Uf(m.args)??F;l.push({methods:v,path:w,file:u,line:m.line,functionName:p.functionName,statusCode:tb(m.args),responseModel:nb(m.args)??Zv(p.signature),tags:j,deprecated:rb(m.args),summary:sb(m.args),params:E.params,security:ib(m.args,p.signature),pathUnresolved:S})}}return{endpoints:l,models:t,warnings:i}}function Mf(r,e){let t=r.find(n=>n.alias===e);return t?t.target:e}function Kt(r,e){let t=r.trim();if(!t||t==="None")return;let n=/^(?:Optional|Union)\[([^\]]*)\](?:\s*\|\s*None)?$/.exec(t)||/^(.+?)(?:\s*\|\s*None)+$/.exec(t);if(n)return Kt(n[1],e);let s=/^Union\[(.+)\]$/.exec(t);if(s){let l=s[1].split(",").map(u=>u.trim())[0];return Kt(l,e)}let i=/^(?:List|list|Sequence)\[(.+)\]$/.exec(t);if(i)return{type:"array",items:Kt(i[1],e)??{type:"object"}};let o=/^(?:Dict|dict)\[([^,]+),\s*(.+)\]$/.exec(t);if(o)return{type:"object",additionalProperties:Kt(o[2],e)??{}};let a={int:{type:"integer"},float:{type:"number"},Decimal:{type:"number"},bool:{type:"boolean"},str:{type:"string"},datetime:{type:"string",format:"date-time"},date:{type:"string",format:"date"},time:{type:"string",format:"time"},UUID:{type:"string",format:"uuid"},bytes:{type:"string",format:"binary"},UploadFile:{type:"string",format:"binary"}};if(t in a)return{...a[t]};let c=e.get(t);if(c){let l={},u=[];for(let p of c.fields){let m=Kt(p.type,e)??{type:"string"};l[p.name]=p.description?{...m,description:p.description}:m,p.required&&u.push(p.name)}let d={type:"object",properties:l};return u.length>0&&(d.required=u),d}return{type:"object"}}function Gv(r,e,t){let n={routes:[],appNames:new Set,routers:[],includes:[],imports:[]},i=db(r).split(/\r?\n/),o=[],a=0;for(;a<i.length;){let c=i[a],l=a+1,u=c.trim();if(a+=1,u==="")continue;let d=/^from\s+[\w.]+(?:\s+import\s+(.+))?$/.exec(u)||/^import\s+([\w.,\s]+)$/.exec(u);if(d){let v=d[1]??"";for(let y of v.split(",")){let S=y.trim();if(!S)continue;let b=/^([\w.]+)\s+as\s+(\w+)$/.exec(S);if(b)n.imports.push({alias:b[2],target:b[1].split(".").pop()});else if(/^[\w.]+$/.test(S)){let C=S.split(".").pop();n.imports.push({alias:C,target:C})}}o=[];continue}if(u.startsWith("@")){let{joined:v,nextIndex:y}=Sa(i,a-1),S=Yv(v,l);S&&o.push(S),a=y+1;continue}let p=/^(?:async\s+)?def\s+(\w+)\s*\(/.exec(u);if(p){let{joined:v,nextIndex:y}=Sa(i,a-1),S=v.slice(v.indexOf("(")),b=Qv(i,a-1,S);o.length>0&&n.routes.push({decorators:o,functionName:p[1],signature:b,line:l}),o=[],a=y+1;continue}let m=/^class\s+(\w+)\s*\(\s*(\w+)\s*\)\s*:/.exec(u);if(m&&(m[2]==="BaseModel"||m[2].endsWith("BaseModel"))){let{nextIndex:v,fields:y}=Kv(i,a);t.set(m[1],{name:m[1],fields:y}),a=v,o=[];continue}let f=/^(\w+)\s*=\s*(?:fastapi\.)?FastAPI\(/.exec(u);if(f){n.appNames.add(f[1]),o=[];continue}let h=/^(\w+)\s*=\s*(?:fastapi\.)?APIRouter\((.*)$/.exec(u);if(h){let{joined:v}=Sa(i,a-1),y=v.slice(v.indexOf("("));n.routers.push({name:h[1],constructorPrefix:Lf(y)}),o=[];continue}let g=/^(\w+)\.include_router\(\s*(\w+)(.*)$/.exec(u);if(g){let{joined:v}=Sa(i,a-1),y=v.slice(v.indexOf("("));n.includes.push({object:g[1],routerName:g[2],prefix:Lf(y),tags:Uf(y),line:l}),o=[];continue}o=[]}return n}function Kv(r,e){let t=[],n=e,s=(r[e-1]||"").match(/^(\s*)/)[1].length;for(;n<r.length;){let i=r[n];if(i.trim()===""){n+=1;continue}if(i.match(/^(\s*)/)[1].length<=s)break;let a=i.trim();if(a.startsWith("#")){n+=1;continue}let c=/^([A-Za-z_]\w*)\s*:\s*(.+?)\s*(?:=\s*(.*))?$/.exec(a);if(c&&!a.startsWith("def ")&&!a.startsWith("class ")){let l=c[2].replace(/,\s*$/,""),u=(c[3]??"").trim(),d=/^Optional\[/.test(l)||/None\s*\|/.test(l)||u==="None"||u.startsWith("None")||u!==""&&!u.startsWith("Field("),p,m=/Field\(([^)]*)\)/.exec(a);if(m){let f=/description\s*=\s*["']([^"']+)["']/.exec(m[1]);f&&(p=f[1])}t.push({name:c[1],type:l,required:!d,description:p})}n+=1}return{nextIndex:n,fields:t}}function Sa(r,e){let t=0,n=r[e]??"",s=e,i=null,o=a=>{for(let c of a){if(i){c===i&&(i=null);continue}c==='"'||c==="'"?i=c:c==="("||c==="["||c==="{"?t+=1:(c===")"||c==="]"||c==="}")&&(t-=1)}};for(o(n);t>0&&s+1<r.length;){s+=1;let a=r[s];o(a),n+=`
|
|
831
|
-
`+a}return{joined:n,nextIndex:s}}function
|
|
829
|
+
`)||void 0,currentScript:o,lastResponse:a??null,note:a?"Last response data available \u2014 use it to align assertions with actual behavior.":"No run data available \u2014 run the request first with run_request, then call heal_assertions again with the runId.",expectedCallAfterThis:"set_request_script"}}}},{toolNames:[x.generateIterationData],handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=Vt(e,n.id,We(r.request,n)),i=typeof r.iterations=="number"?Math.min(50,Math.max(1,r.iterations)):5,o=s.body?.type==="raw"&&typeof s.body.content=="string"?s.body.content:void 0,a=(s.headers??[]).filter(d=>d.enabled!==!1).map(d=>({key:d.key,value:d.value})),c=(s.query??[]).filter(d=>d.enabled!==!1).map(d=>({key:d.key,value:d.value})),l=/\{\{([^}]+)\}\}/g,u=new Set;for(let d of[s.url??"",o??"",...a.map(p=>p.value),...c.map(p=>p.value)]){let p;for(l.lastIndex=0;(p=l.exec(d))!==null;)u.add(p[1])}return{task:{action:"generate_iteration_data",instructions:[`Generate ${i} test data rows for: ${s.method} ${s.url??""}`,`The request uses these {{variable}} placeholders: ${[...u].join(", ")||"(none detected)"}`,"Each row must be a JSON object whose keys match the placeholder names.","Cover a mix of: (1) valid happy-path data, (2) boundary values, (3) invalid inputs that should fail, (4) edge cases.",'Return the rows as a JSON array in a code block labeled "iterationData".',"This data can be used with: http-forge run-request --collection ... --variables '[...]' or passed to run_request via the variables argument."],collection:n.name,request:s.name,method:s.method,url:s.url??"",businessContext:st(s,Hp(n,s)).snapshot().body||void 0,body:o??null,headers:a,queryParams:c,placeholders:[...u],iterations:i}}}}]});function Up(r,e){for(let t of r){if(t.type!=="folder")continue;let n=t;if(n.name===e||e.endsWith("/"+n.name))return{id:n.id};let s=Up(n.items??[],e);if(s)return s}}var Vp,zp=k(()=>{"use strict";Fe();Ne();Ne();Vp=[{toolNames:[x.createCollection],async handle({args:r,services:e}){let t=typeof r.name=="string"?r.name.trim():"";if(!t)throw A('"name" is required');let n=await e.collection.createCollection(t);return{id:n.id,name:n.name,created:!0,hint:"Collection is empty. Call create_folder to add folders, or create_request to add requests directly."}}},{toolNames:[x.renameCollection],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.newName=="string"?r.newName.trim():"";if(!s)throw A('"newName" is required');return await e.collection.renameCollection(n.id,s),{id:n.id,oldName:n.name,newName:s,renamed:!0}}},{toolNames:[x.deleteCollection],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw A('"confirm" must be true to delete a collection');let n=W(r.collection,t);return await e.collection.deleteCollection(n.id),{deleted:!0,collection:n.name}}},{toolNames:[x.duplicateCollection],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.newName=="string"?r.newName.trim():"";if(!s)throw A('"newName" is required');let i=await e.collection.duplicateCollection(n.id,s);return{id:i.id,name:i.name,duplicatedFrom:n.name}}},{toolNames:[x.createFolder],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.name=="string"?r.name.trim():"";if(!s)throw A('"name" is required');let i;if(typeof r.parentFolder=="string"&&r.parentFolder.trim()){let a=r.parentFolder.toLowerCase(),c=qe(n);if(X(n).map(u=>u.folderPath)&&c.find(u=>u.folderPath===r.parentFolder||u.folderPath.toLowerCase()===a)){let d=qe(n).find(p=>p.folderPath===r.parentFolder||p.folderPath.toLowerCase()===a);if(d){let p=n.items;i=Up(p,d.folderPath)?.id}}}let o=await e.collection.createFolder({collectionId:n.id,name:s,parentId:i});return{id:o.id,name:o.name,created:!0,collection:n.name}}},{toolNames:[x.deleteFolder],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw A('"confirm" must be true to delete a folder');let n=W(r.collection,t);if(typeof r.folder!="string"||!r.folder.trim())throw A('"folder" is required');let s=r.folder.toLowerCase(),i=qe(n).find(c=>c.folderPath===r.folder||c.folderPath.toLowerCase()===s);if(!i)throw A(`folder "${r.folder}" not found in collection "${n.name}"`);let o=$l(n.items,i.folderId);if(!o)throw A(`folder "${r.folder}" could not be resolved`);let a=i.requestCount;return await e.collection.deleteFolder(n.id,o.id),{deleted:!0,folder:i.folderPath,requestsRemoved:a}}}]});var Ml=k(()=>{"use strict"});var Jp=k(()=>{"use strict"});import*as Rt from"fs";import*as Kr from"path";var Iy,Ty,Oy,Qr,Xo=k(()=>{"use strict";Iy=["package.json","src/main.ts","src/main.js","src/app.ts","src/app.js","pom.xml","build.gradle","build.gradle.kts","settings.gradle","requirements.txt","pyproject.toml","poetry.lock","Pipfile","app/main.py","main.py"],Ty={express:["express","router.","app.use(","app.get(","express.Router"],nestjs:["@nestjs/common","@Controller(","@Get(","@Post("],fastify:["fastify","fastify.route(","fastify.get(","register("],lambda:["exports.handler","event.pathParameters","APIGatewayProxyEvent","aws-lambda"],spring:["@RestController","@Controller","@GetMapping","@PostMapping","@RequestMapping"],fastapi:["from fastapi","import fastapi","@app.get(","@router.get("],unknown:[]},Oy={express:[".ts",".js"],nestjs:[".ts",".js"],fastify:[".ts",".js"],lambda:[".ts",".js"],spring:[".java"],fastapi:[".py"]},Qr=class{buildFingerprint(e){let t=[],n=Kr.join(e,"package.json"),s;for(let i of Iy){let o=Kr.join(e,i);Rt.existsSync(o)&&t.push(o)}if(Rt.existsSync(n))try{let i=JSON.parse(Rt.readFileSync(n,"utf-8"));s={dependencies:i.dependencies,devDependencies:i.devDependencies,scripts:i.scripts}}catch{}return{projectRoot:e,packageJsonPath:Rt.existsSync(n)?n:void 0,packageJson:s,evidenceFiles:t}}detectFrameworks(e){let t=[];return(this.hasDependency(e,"express")||this.hasSourceHint(e,"express"))&&t.push("express"),(this.hasDependency(e,"@nestjs/common")||this.hasSourceHint(e,"nestjs"))&&t.push("nestjs"),(this.hasDependency(e,"fastify")||this.hasSourceHint(e,"fastify"))&&t.push("fastify"),(this.hasBuildFile(e,"pom.xml")||this.hasBuildFile(e,"build.gradle")||this.hasBuildFile(e,"build.gradle.kts")||this.hasBuildFile(e,"settings.gradle")||this.hasSourceHint(e,"spring"))&&t.push("spring"),(this.hasBuildFile(e,"requirements.txt")||this.hasBuildFile(e,"pyproject.toml")||this.hasBuildFile(e,"poetry.lock")||this.hasBuildFile(e,"Pipfile")||this.hasSourceHint(e,"fastapi"))&&t.push("fastapi"),t.includes("express")||t.includes("fastify")||(this.hasDependency(e,"@types/aws-lambda")||this.hasDependency(e,"aws-lambda")||this.hasDependency(e,"serverless")||this.hasSourceHint(e,"lambda"))&&t.push("lambda"),t.length>0?t:["unknown"]}hasDependency(e,t){let n=e.packageJson?.dependencies??{},s=e.packageJson?.devDependencies??{};return!!(n[t]||s[t])}hasBuildFile(e,t){return Rt.existsSync(Kr.join(e.projectRoot,t))}hasSourceHint(e,t){let n=["src","app"],s=Ty[t],i=Oy[t],o=0,a=120;for(let c of n){let l=Kr.join(e.projectRoot,c);if(!Rt.existsSync(l))continue;let u=[l];for(;u.length>0&&o<a;){let d=u.shift(),p;try{p=Rt.readdirSync(d,{withFileTypes:!0})}catch{continue}for(let m of p){let f=Kr.join(d,m.name);if(m.isDirectory()){u.push(f);continue}if(!m.isFile()||!i.some(g=>f.endsWith(g)))continue;o+=1;let h="";try{h=Rt.readFileSync(f,"utf-8")}catch{continue}if(s.some(g=>h.includes(g)))return!0}}}return!1}}});import*as Wp from"fs";import*as Gp from"path";function lt(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=Wp.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=Gp.join(n,i.name);if(i.isDirectory()){$y.has(i.name)||t.push(o);continue}i.isFile()&&(Fy.test(i.name)||(o.endsWith(".ts")||o.endsWith(".js"))&&e.push(o))}}return e}var $y,Fy,mn=k(()=>{"use strict";$y=new Set(["node_modules",".git",".next","dist","build","out","coverage","__tests__","__mocks__","__fixtures__"]),Fy=/\.(?:test|spec|stories|min)\.[cm]?[tj]sx?$|\.d\.[cm]?ts$/});import*as Kp from"fs";import*as ea from"path";function ta(r,e){let t=e.customSeedLoaderModulePath?.trim();if(!t)return{endpoints:[],warnings:[]};let n=ea.isAbsolute(t)?t:ea.join(r,t);if(!Kp.existsSync(n))return{endpoints:[],warnings:[{code:"seed-loader-failed",filePath:n,message:`Custom seed loader module not found: ${n}`}]};try{let s=pe(n),i=s.loadSeedManifestEndpoints??s.default;if(typeof i!="function")return{endpoints:[],warnings:[{code:"seed-loader-failed",filePath:n,message:"Custom seed loader module must export a function named loadSeedManifestEndpoints or a default function."}]};let o=i(r,e);return Array.isArray(o)?{endpoints:o,warnings:[]}:{endpoints:o?.endpoints??[],warnings:o?.warnings??[]}}catch(s){return{endpoints:[],warnings:[{code:"seed-loader-failed",filePath:n,message:`Custom seed loader failed at ${n}: ${s instanceof Error?s.message:String(s)}`}]}}}var na=k(()=>{"use strict"});function Zp(r,e){let t=r.projectName?.trim();if(t)return t;let n=Qp(r.source.filePath),s=Ny(n);if(s)return s;let i;for(let a of e){let c=Qp(a);(n===c||n.startsWith(`${c}/`))&&(!i||c.length>i.length)&&(i=c)}if(!i)return;let o=i.split("/").filter(Boolean);return o[o.length-1]||void 0}function Ny(r){return r.match(/(?:^|\/)agl-config-([^/]+)(?:\/|$)/)?.[1]}function Qp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var jl=k(()=>{"use strict"});import*as ca from"fs";import*as sr from"path";import*as R from"typescript";function hn(r,e){return r==="high"&&e==="high"?"high":r==="low"||e==="low"?"low":"medium"}function gn(r,e,t){let n=[],s=/:([a-zA-Z_]\w*)/g,i=/\{([a-zA-Z_]\w*)\}/g,o;for(;(o=s.exec(r))!==null;)n.push({name:o[1],location:"path",required:!0,type:"string"});for(;(o=i.exec(r))!==null;)n.push({name:o[1],location:"path",required:!0,type:"string"});return n}function ia(r,e,t,n,s={visitedSymbols:new Set},i,o=["locals"]){let a=[],c=[],l=[],u,d=new Map,p=Yy(o),m=Qy(r,e,p),f=nv(r,e,p);if(i?.requestAliases)for(let w of i.requestAliases)m.add(w);if(i?.responseAliases)for(let w of i.responseAliases)f.add(w);let h=sf(e),g=_y(e,t),v=Zy(r,t,h,g,m,f),y=(w,E)=>{let F=l.find(N=>N.statusCode===w);return F||(F={statusCode:w},l.push(F)),E&&(F.body={type:E,schema:F.body?.schema}),F};R.isFunctionLike(r)&&Gy(r,e,d,m,f,p);let S=(w,E)=>{let F=h.get(w);if(F){let M=`${t}:${w}`;if(s.visitedSymbols.has(M))return;s.visitedSymbols.add(M);let G=v.get(M),me=E?aa(E,F,m,f):void 0,Ce=rf(G,me),Ie=ia(F,e,t,n,s,Ce,o);Hl({parameters:a,requestBody:u,cookies:c,responses:l},Ie),!u&&Ie.requestBody&&(u=Ie.requestBody);return}let N=g.get(w);if(!N||s.visitedSymbols.has(N.symbolKey))return;s.visitedSymbols.add(N.symbolKey);let j=v.get(N.symbolKey),O=E?aa(E,N.node,m,f):void 0,D=rf(j,O),P=ia(N.node,N.sourceFile,N.filePath,n,s,D,o);Hl({parameters:a,requestBody:u,cookies:c,responses:l},P),!u&&P.requestBody&&(u=P.requestBody)},b=["POST","PUT","PATCH"].includes(n),C=w=>{R.isVariableDeclaration(w)&&Wy(w,e,d,m,f,p),R.isIdentifier(w)&&(R.isCallExpression(w.parent)&&w.parent.expression===w||S(w.text));let E=Zr(w,e,"query",d,m,f,p);if(E){let D=e.getLineAndCharacterOfPosition(w.getStart(e));a.push({name:E.path,location:"query",type:sa(w,e),detectionLocation:{filePath:t,line:D.line+1,column:D.character+1,accessMode:"read"}})}let F=Zr(w,e,"params",d,m,f,p);if(F){let D=e.getLineAndCharacterOfPosition(w.getStart(e));a.push({name:F.path,location:"path",required:!0,type:sa(w,e),detectionLocation:{filePath:t,line:D.line+1,column:D.character+1,accessMode:"read"}})}if(Jy(w,e,m)&&!u){let D=e.getLineAndCharacterOfPosition(w.getStart(e));u={type:"json",required:b,detectionLocation:{filePath:t,line:D.line+1,column:D.character+1,accessMode:"read"}}}let N=Zr(w,e,"body",d,m,f,p);if(N){let D=e.getLineAndCharacterOfPosition(w.getStart(e));a.push({name:N.path,location:"body",type:sa(w,e),detectionLocation:{filePath:t,line:D.line+1,column:D.character+1,accessMode:"read"}}),u||(u={type:"json",required:b})}let j=Zr(w,e,"headers",d,m,f,p);if(j){let D=e.getLineAndCharacterOfPosition(w.getStart(e));a.push({name:j.path,location:"header",type:"string",detectionLocation:{filePath:t,line:D.line+1,column:D.character+1,accessMode:"read"}})}let O=Zr(w,e,"cookies",d,m,f,p);if(O){let D=e.getLineAndCharacterOfPosition(w.getStart(e));c.push({name:O.path,type:"request",detectionLocation:{filePath:t,line:D.line+1,column:D.character+1,accessMode:"read"}})}for(let D of p){let P=Zr(w,e,D,d,m,f,p);if(!P)continue;let M=e.getLineAndCharacterOfPosition(w.getStart(e));a.push({name:P.path,location:D,type:sa(w,e),detectionLocation:{filePath:t,line:M.line+1,column:M.character+1,accessMode:"read"}})}if(R.isCallExpression(w)){let D=Xy(w,e,f);D&&y(D.statusCode,D.bodyType)}if(R.isCallExpression(w)){let D=ev(w,f);if(D){let P=y(D.statusCode);if(!P.headers?.some(M=>M.name===D.headerName)){let M=e.getLineAndCharacterOfPosition(w.getStart(e));P.headers=P.headers??[],P.headers.push({name:D.headerName,location:"header",type:"string",detectionLocation:{filePath:t,line:M.line+1,column:M.character+1,accessMode:"write"}})}}}if(R.isCallExpression(w)&&R.isPropertyAccessExpression(w.expression)&&rv(w.expression.expression,f)&&w.expression.name.text==="cookie"&&w.arguments[0]&&R.isStringLiteral(w.arguments[0])){let D=w.arguments[0].text;if(D&&!c.some(P=>P.name===D&&P.type==="response")){let P=e.getLineAndCharacterOfPosition(w.getStart(e));c.push({name:D,type:"response",httpOnly:!0,detectionLocation:{filePath:t,line:P.line+1,column:P.character+1,accessMode:"write"}})}}R.isCallExpression(w)&&R.isIdentifier(w.expression)&&S(w.expression.text,w),R.forEachChild(w,C)};return r&&C(r),{parameters:a,requestBody:b?u||{type:"json",required:!0}:void 0,cookies:c,responses:l.length>0?l:[{statusCode:200}]}}function bi(r,e,t,n,s=["locals"]){let i={parameters:[],requestBody:void 0,cookies:[],responses:[]};for(let o of r){let a=ia(o,e,t,n,void 0,void 0,s);Hl(i,a)}return i.parameters=yn(i.parameters),i.cookies=zy(i.cookies),!i.requestBody&&["POST","PUT","PATCH"].includes(n)&&(i.requestBody={type:"json",required:!0}),i.responses.length===0&&(i.responses=[{statusCode:200}]),i}function sf(r){let e=new Map,t=n=>{R.isFunctionDeclaration(n)&&n.name&&e.set(n.name.text,n),R.isVariableDeclaration(n)&&R.isIdentifier(n.name)&&n.initializer&&(R.isArrowFunction(n.initializer)||R.isFunctionExpression(n.initializer))&&e.set(n.name.text,n.initializer),R.forEachChild(n,t)};return t(r),e}function _y(r,e){let t=new Map,n=(s,i)=>{if(!s.startsWith("."))return;let o=My(e,s);if(!o)return;let a=Dy(o);if(!a)return;let c=jy(a,o);for(let l of i){let u=c.get(l.importedName);u&&t.set(l.localName,{node:u,sourceFile:a,filePath:o,symbolKey:`${o}:${l.importedName}`})}};for(let s of r.statements){if(R.isImportDeclaration(s)&&s.importClause&&R.isStringLiteral(s.moduleSpecifier)){let i=s.moduleSpecifier.text,o=[];s.importClause.name&&o.push({localName:s.importClause.name.text,importedName:"default"});let a=s.importClause.namedBindings;if(a&&R.isNamedImports(a))for(let c of a.elements)o.push({localName:c.name.text,importedName:c.propertyName?c.propertyName.text:c.name.text});n(i,o);continue}if(R.isVariableStatement(s))for(let i of s.declarationList.declarations){if(!i.initializer||!R.isCallExpression(i.initializer)||!R.isIdentifier(i.initializer.expression)||i.initializer.expression.text!=="require")continue;let o=i.initializer.arguments[0];if(!o||!R.isStringLiteral(o))continue;let a=o.text,c=[];if(R.isIdentifier(i.name))c.push({localName:i.name.text,importedName:"default"});else if(R.isObjectBindingPattern(i.name))for(let l of i.name.elements){if(!R.isIdentifier(l.name))continue;let u=l.propertyName&&(R.isIdentifier(l.propertyName)||R.isStringLiteral(l.propertyName))?l.propertyName.text:l.name.text;c.push({localName:l.name.text,importedName:u})}n(a,c)}}return t}function Dy(r){let e="";try{e=ca.readFileSync(r,"utf-8")}catch{return}return R.createSourceFile(r,e,R.ScriptTarget.Latest,!0,r.endsWith(".ts")?R.ScriptKind.TS:R.ScriptKind.JS)}function My(r,e){let t=sr.resolve(sr.dirname(r),e),n=[t,`${t}.ts`,`${t}.js`,sr.join(t,"index.ts"),sr.join(t,"index.js")];for(let s of n)try{if(ca.statSync(s).isFile())return s}catch{continue}}function jy(r,e){let t=new Map,n=sf(r),s=(i,o)=>{t.set(i,o)};for(let i of r.statements){if(R.isFunctionDeclaration(i)&&i.name&&Yp(i)){s(i.name.text,i),Xp(i)&&s("default",i);continue}if(R.isVariableStatement(i)&&Yp(i)){for(let c of i.declarationList.declarations)!R.isIdentifier(c.name)||!c.initializer||(R.isArrowFunction(c.initializer)||R.isFunctionExpression(c.initializer))&&(s(c.name.text,c.initializer),Xp(i)&&s("default",c.initializer));continue}if(R.isExportAssignment(i)){let c=i.expression;if(R.isIdentifier(c)){let l=n.get(c.text);l&&s("default",l)}else(R.isFunctionExpression(c)||R.isArrowFunction(c))&&s("default",c);continue}if(!R.isExpressionStatement(i)||!R.isBinaryExpression(i.expression))continue;let o=i.expression.left,a=i.expression.right;if(R.isPropertyAccessExpression(o)&&o.expression.getText(r)==="module.exports"){let c=o.name.text,l=Ll(a,n);l&&s(c,l);continue}if(o.getText(r)==="module.exports"){let c=Ll(a,n);c&&s("default",c);continue}if(R.isPropertyAccessExpression(o)&&o.expression.getText(r)==="exports"){let c=Ll(a,n);c&&s(o.name.text,c)}}return t}function Ll(r,e){if(R.isFunctionExpression(r)||R.isArrowFunction(r))return r;if(R.isIdentifier(r))return e.get(r.text)}function Yp(r){return R.canHaveModifiers(r)?!!R.getModifiers(r)?.some(e=>e.kind===R.SyntaxKind.ExportKeyword):!1}function Xp(r){return R.canHaveModifiers(r)?!!R.getModifiers(r)?.some(e=>e.kind===R.SyntaxKind.DefaultKeyword):!1}function Hl(r,e){r.parameters.push(...e.parameters),r.cookies.push(...e.cookies),!r.requestBody&&e.requestBody&&(r.requestBody=e.requestBody);for(let t of e.responses){let n=r.responses.find(o=>o.statusCode===t.statusCode);if(!n){r.responses.push({statusCode:t.statusCode,headers:t.headers?[...t.headers]:void 0,body:t.body});continue}let s=n.headers??[],i=t.headers??[];n.headers=yn([...s,...i])}}function yn(r){let e=new Map;for(let i of r){let o=`${i.location}:${i.name}`,a=e.get(o);if(!a){e.set(o,{...i,evidenceLocations:ef([],i)});continue}if(a.required=!!(a.required||i.required),a.evidenceLocations=ef(a.evidenceLocations??[],i),!a.detectionLocation&&i.detectionLocation&&(a.detectionLocation=i.detectionLocation),!a.type&&i.type){a.type=i.type;continue}if(!i.type||!a.type||a.type===i.type)continue;let c=new Set(a.conflictingTypes??[]);c.add(a.type),c.add(i.type),a.conflictingTypes=Array.from(c),a.location==="body"&&(a.type==="object"||i.type==="object")&&(a.type="object")}let t=Array.from(e.values()).map(i=>Ly(i)),n=t.filter(i=>i.location==="body"),s=new Map(n.map(i=>[i.name,i]));for(let i of[...n]){let o=ra(i.name);for(;o;){if(!s.has(o)){let a={name:o,location:"body",type:"object"};s.set(o,a),t.push(a)}o=ra(o)}}for(let i of s.values()){let o=ra(i.name);for(;o;){let a=s.get(o);a&&(a.type="object"),o=ra(o)}}return t}function ef(r,e){let t=[...r??[]];e.detectionLocation&&t.push(e.detectionLocation),e.evidenceLocations&&t.push(...e.evidenceLocations);let n=new Set,s=[];for(let i of t){let o=`${i.filePath}:${i.line}:${i.column??0}:${i.symbolName??""}:${i.accessMode??""}`;n.has(o)||(n.add(o),s.push(i))}return s}function Ly(r){let e=Uy([...r.detectionLocation?[r.detectionLocation]:[],...r.evidenceLocations??[]]);if(e.length===0)return{...r,detectionLocation:void 0,evidenceLocations:void 0};let t=Hy(e),n=e.filter(s=>!Vy(s,t));return{...r,detectionLocation:t,evidenceLocations:n.length>0?n:void 0}}function Hy(r){return[...r].sort(By)[0]}function By(r,e){let t=tf(r),n=tf(e);if(t!==n)return n-t;if(r.line!==e.line)return r.line-e.line;let s=r.column??0,i=e.column??0;return s!==i?s-i:r.filePath.localeCompare(e.filePath)}function tf(r){let e=0;return r.accessMode&&(e+=8),r.symbolName&&(e+=4),typeof r.column=="number"&&(e+=2),e}function Uy(r){let e=[],t=new Set;for(let n of r){let s=`${n.filePath}:${n.line}:${n.column??0}:${n.symbolName??""}:${n.accessMode??""}`;t.has(s)||(t.add(s),e.push(n))}return e}function Vy(r,e){return r.filePath===e.filePath&&r.line===e.line&&(r.column??0)===(e.column??0)&&(r.symbolName??"")===(e.symbolName??"")&&(r.accessMode??"")===(e.accessMode??"")}function zy(r){let e=new Set,t=[];for(let n of r){let s=`${n.type??"unknown"}:${n.name}`;e.has(s)||(e.add(s),t.push(n))}return t}function Jy(r,e,t){return R.isPropertyAccessExpression(r)&&R.isIdentifier(r.expression)&&t.has(r.expression.text)&&r.name.text==="body"}function Zr(r,e,t,n,s,i,o){return Ul(r,e,t,n,!1,s,i,o)}function Ul(r,e,t,n,s,i,o,a){let c=[],l=r;for(;l&&(R.isPropertyAccessExpression(l)||R.isElementAccessExpression(l)||R.isPropertyAccessChain(l)||R.isElementAccessChain(l));){if(R.isPropertyAccessExpression(l)||R.isPropertyAccessChain(l)){c.unshift(l.name.text),l=l.expression;continue}if(R.isElementAccessExpression(l)||R.isElementAccessChain(l)){let h=l.argumentExpression;if(h&&(R.isStringLiteral(h)||R.isNumericLiteral(h))){let g=h.text;R.isNumericLiteral(h)||/^\d+$/.test(g)?c.unshift("[]"):c.unshift(g)}else return;l=l.expression}}let u=c.indexOf(t),p=a?.has(t)??!1?l&&R.isIdentifier(l)&&((o?.has(l.text)??!1)||(i?.has(l.text)??!1)):l&&R.isIdentifier(l)&&i?.has(l.text)===!0;if(u!==-1&&p){let h=c.slice(u+1);return h.length===0?s?{path:""}:void 0:{path:oa(h)}}if(!l||!R.isIdentifier(l)||!n)return;let m=n.get(l.text);if(!m||m.target!==t)return;let f=oa(c);return m.path?f?{path:`${m.path}.${f}`}:{path:m.path}:f?{path:f}:s?{path:""}:void 0}function Wy(r,e,t,n,s,i){let o=r.initializer;if(!o)return;R.isIdentifier(o)&&n.has(o.text)&&R.isIdentifier(r.name)&&n.add(r.name.text),R.isIdentifier(o)&&s.has(o.text)&&R.isIdentifier(r.name)&&s.add(r.name.text);let a=["body","query","params","headers","cookies",...i],c,l="";for(let u of a){let d=Ul(o,e,u,t,!0,n,s,i);if(d){c=u,l=d.path;break}}if(c){if(R.isIdentifier(r.name)){t.set(r.name.text,{target:c,path:l});return}(R.isObjectBindingPattern(r.name)||R.isArrayBindingPattern(r.name))&&vi(r.name,c,l,t)}}function Gy(r,e,t,n,s,i){let o=["body","query","params","headers","cookies",...i];for(let a of r.parameters){if((R.isObjectBindingPattern(a.name)||R.isArrayBindingPattern(a.name))&&!a.initializer){Ky(a.name,t,i);continue}let c=a.initializer;if(!c)continue;let l,u="";for(let d of o){let p=Ul(c,e,d,t,!0,n,s,i);if(p){l=d,u=p.path;break}}if(l){if(R.isIdentifier(a.name)){t.set(a.name.text,{target:l,path:u});continue}(R.isObjectBindingPattern(a.name)||R.isArrayBindingPattern(a.name))&&vi(a.name,l,u,t)}}}function Ky(r,e,t){if(!R.isObjectBindingPattern(r))return;let n=new Set(["body","query","params","headers","cookies",...t]);for(let s of r.elements){let i=Bl(s);if(!i||!n.has(i))continue;let o=i;if(R.isIdentifier(s.name)){e.set(s.name.text,{target:o,path:""});continue}(R.isObjectBindingPattern(s.name)||R.isArrayBindingPattern(s.name))&&vi(s.name,o,"",e)}}function Qy(r,e,t){let n=new Set,s=new Set(["query","params","body","headers","cookies",...t]),i=o=>{if(R.isPropertyAccessExpression(o)||R.isPropertyAccessChain(o)){let a=o.name.text;if(s.has(a)){let c=rr(o.expression);c&&n.add(c)}}if(R.isElementAccessExpression(o)||R.isElementAccessChain(o)){let a=o.argumentExpression;if(a&&R.isStringLiteral(a)&&s.has(a.text)){let c=rr(o.expression);c&&n.add(c)}}R.isVariableDeclaration(o)&&o.initializer&&R.isIdentifier(o.name)&&R.isIdentifier(o.initializer)&&n.has(o.initializer.text)&&n.add(o.name.text),R.forEachChild(o,i)};return i(r),n}function vi(r,e,t,n){if(R.isObjectBindingPattern(r)){for(let s of r.elements){let i=Bl(s);if(!i)continue;let o=nf(t,i);if(R.isIdentifier(s.name)){n.set(s.name.text,{target:e,path:o});continue}(R.isObjectBindingPattern(s.name)||R.isArrayBindingPattern(s.name))&&vi(s.name,e,o,n)}return}for(let s of r.elements){if(!R.isBindingElement(s))continue;let i=Bl(s)??"[]",o=nf(t,/^\d+$/.test(i)?"[]":i);if(R.isIdentifier(s.name)){n.set(s.name.text,{target:e,path:o});continue}(R.isObjectBindingPattern(s.name)||R.isArrayBindingPattern(s.name))&&vi(s.name,e,o,n)}}function Bl(r){let e=r.propertyName;if(!e)return R.isIdentifier(r.name)?r.name.text:void 0;if(R.isIdentifier(e)||R.isStringLiteral(e)||R.isNumericLiteral(e))return e.text}function nf(r,e){return oa(r?`${r}.${e}`.split("."):[e])}function oa(r){if(r.length===0)return"";let e="";for(let t of r)if(t){if(t==="[]"){e.endsWith("[]")||(e+="[]");continue}e+=e?`.${t}`:t}return e}function ra(r){let e=r.lastIndexOf(".");if(!(e<=0))return r.slice(0,e)}function Zy(r,e,t,n,s,i){let o=new Map,a=(l,u)=>{let d=o.get(l);if(!d){o.set(l,{requestAliases:u.requestAliases?new Set(u.requestAliases):void 0,responseAliases:u.responseAliases?new Set(u.responseAliases):void 0});return}if(u.requestAliases)if(!d.requestAliases)d.requestAliases=new Set(u.requestAliases);else for(let p of u.requestAliases)d.requestAliases.add(p);if(u.responseAliases)if(!d.responseAliases)d.responseAliases=new Set(u.responseAliases);else for(let p of u.responseAliases)d.responseAliases.add(p)},c=l=>{if(R.isCallExpression(l)&&R.isIdentifier(l.expression)){let u=l.expression.text,d=t.get(u);if(d){let m=aa(l,d,s,i);m&&a(`${e}:${u}`,m)}let p=n.get(u);if(p){let m=aa(l,p.node,s,i);m&&a(p.symbolKey,m)}}R.forEachChild(l,c)};return c(r),o}function rf(r,e){if(!r&&!e)return;let t=new Set([...r?.requestAliases??[],...e?.requestAliases??[]]),n=new Set([...r?.responseAliases??[],...e?.responseAliases??[]]);return{requestAliases:t.size>0?t:void 0,responseAliases:n.size>0?n:void 0}}function Yy(r){let e=new Set,t=new Set(["query","params","body","headers","cookies"]);for(let n of r){let s=n.trim();!s||t.has(s)||e.add(s)}return e.size===0&&e.add("locals"),e}function aa(r,e,t,n){let s=new Set,i=new Set,o=Math.min(r.arguments.length,e.parameters.length);for(let a=0;a<o;a+=1){let c=e.parameters[a];if(!R.isIdentifier(c.name))continue;let l=r.arguments[a],u=rr(l);u&&(t.has(u)&&s.add(c.name.text),n.has(u)&&i.add(c.name.text))}if(!(s.size===0&&i.size===0))return{requestAliases:s.size>0?s:void 0,responseAliases:i.size>0?i:void 0}}function sa(r,e){if(!r||!r.parent)return"string";if(R.isCallExpression(r.parent)&&R.isIdentifier(r.parent.expression)){let t=r.parent.expression.text;if(t==="parseInt"||t==="parseFloat")return"number"}if(R.isBinaryExpression(r.parent)&&(r.parent.operatorToken.kind===R.SyntaxKind.EqualsEqualsToken||r.parent.operatorToken.kind===R.SyntaxKind.EqualsEqualsEqualsToken)){let t=r.parent.left===r?r.parent.right:r.parent.left;if(R.isNumericLiteral(t))return"number"}return"string"}function Xy(r,e,t){let n=r.expression;if(!R.isPropertyAccessExpression(n))return;let s=n.name.text;if(s!=="json"&&s!=="send")return;let i=of(r,t);if(i)return{statusCode:i.statusCode,bodyType:s==="json"?"json":tv(r.arguments[0])}}function ev(r,e){let t=r.expression;if(!R.isPropertyAccessExpression(t))return;let n=t.name.text;if(n!=="header"&&n!=="set")return;let s=r.arguments[0];if(!s||!R.isStringLiteral(s))return;let i=of(r,e);if(i)return{statusCode:i.statusCode,headerName:s.text}}function of(r,e){if(!R.isPropertyAccessExpression(r.expression))return;let t=200,n=r.expression.expression;for(;;){if(R.isIdentifier(n)&&e.has(n.text))return{receiver:n.text,statusCode:t};if(!R.isCallExpression(n)||!R.isPropertyAccessExpression(n.expression))return;let s=n.expression.name.text;if(s==="status"||s==="code"){let i=n.arguments[0];i&&R.isNumericLiteral(i)&&(t=Number(i.text))}n=n.expression.expression}}function tv(r){return r&&(R.isObjectLiteralExpression(r)||R.isArrayLiteralExpression(r))?"json":"text"}function nv(r,e,t){let n=new Set,s=new Set(["status","code","json","send","header","set","cookie"]),i=new Set(t),o=a=>{if(R.isPropertyAccessExpression(a)||R.isPropertyAccessChain(a)){let c=a.name.text;if(i.has(c)){let l=rr(a.expression);l&&n.add(l)}}if(R.isElementAccessExpression(a)||R.isElementAccessChain(a)){let c=a.argumentExpression;if(c&&R.isStringLiteral(c)&&i.has(c.text)){let l=rr(a.expression);l&&n.add(l)}}if(R.isCallExpression(a)&&R.isPropertyAccessExpression(a.expression)){let c=a.expression.name.text;if(s.has(c)){let l=rr(a.expression.expression);l&&n.add(l)}}R.isVariableDeclaration(a)&&a.initializer&&R.isIdentifier(a.name)&&R.isIdentifier(a.initializer)&&n.has(a.initializer.text)&&n.add(a.name.text),R.forEachChild(a,o)};return o(r),n}function rv(r,e){let t=rr(r);return t?e.has(t):!1}function rr(r){let e=r;for(;;){if(R.isIdentifier(e))return e.text;if(R.isPropertyAccessExpression(e)||R.isPropertyAccessChain(e)){e=e.expression;continue}if(R.isElementAccessExpression(e)||R.isElementAccessChain(e)){e=e.expression;continue}if(R.isCallExpression(e)&&R.isPropertyAccessExpression(e.expression)){e=e.expression.expression;continue}return}}var la=k(()=>{"use strict"});import*as fe from"typescript";function Yr(r,e,t){let n={},s=o=>{if(fe.isVariableDeclaration(o)&&fe.isIdentifier(o.name)&&o.initializer){let a=vn(o.initializer,r,{variables:n});a!==void 0&&(n[o.name.text]=a)}fe.forEachChild(o,s)};s(r);let i={...iv(e),...t};return{variables:n,env:i}}function Ct(r,e,t){if(!r)return{pathExpression:"/",resolvedPath:"/",confidence:"high"};let n=vn(r,e,t);if(n!==void 0)return{pathExpression:n,resolvedPath:n,confidence:"high"};if(fe.isStringLiteral(r)||fe.isNoSubstitutionTemplateLiteral(r)){let s=r.text||"/";return{pathExpression:s,resolvedPath:s,confidence:"high"}}if(fe.isTemplateExpression(r)){let s=sv(r,e,t);if(s.resolvedPath)return s;let i=r.head.text;return{pathExpression:r.getText(e),resolvedPath:i||void 0,confidence:i?"medium":"low"}}return fe.isIdentifier(r)?{pathExpression:r.getText(e),confidence:"low"}:{pathExpression:r.getText(e),confidence:"low"}}function Jt(r,e){let t=af(r??""),n=af(e??""),s=cf(`${t}/${n}`);return(r??"").includes("${")||(e??"").includes("${")?{pathExpression:s}:{pathExpression:s,resolvedPath:s}}function af(r){return r?r.replace(/^['"`]/,"").replace(/['"`]$/,"").replace(/^\/+/,"").replace(/\/+$/,""):""}function cf(r){let e=r.replace(/\/{2,}/g,"/").replace(/\/$/,"");return!e||e==="/"?"/":e.startsWith("/")?e:`/${e}`}function vn(r,e,t){if(fe.isStringLiteral(r)||fe.isNoSubstitutionTemplateLiteral(r))return r.text;if(fe.isParenthesizedExpression(r))return vn(r.expression,e,t);if(fe.isIdentifier(r))return t?.variables?.[r.text];if(fe.isBinaryExpression(r)&&r.operatorToken.kind===fe.SyntaxKind.PlusToken){let n=vn(r.left,e,t),s=vn(r.right,e,t);if(n!==void 0&&s!==void 0)return`${n}${s}`}if(fe.isBinaryExpression(r)&&(r.operatorToken.kind===fe.SyntaxKind.BarBarToken||r.operatorToken.kind===fe.SyntaxKind.QuestionQuestionToken))return vn(r.left,e,t)??vn(r.right,e,t);if(fe.isPropertyAccessExpression(r)){let n=r.getText(e);if(n.startsWith("process.env.")){let s=n.substring(12);return t?.env?.[s]}}}function sv(r,e,t){let n=[r.head.text],s=!0;for(let o of r.templateSpans){let a=vn(o.expression,e,t);a===void 0?(s=!1,n.push("${...}")):n.push(a),n.push(o.literal.text)}let i=s?cf(n.join("")):void 0;return{pathExpression:r.getText(e),resolvedPath:i,confidence:s?"high":"medium"}}function iv(r){if(!r)return{};let e=[".env",".env.local",".env.development",".env.production"],t={};for(let n of e){let s=`${r}/${n}`;try{let i=pe("fs").readFileSync(s,"utf-8");for(let o of i.split(/\r?\n/)){let a=o.trim();if(!a||a.startsWith("#"))continue;let c=a.indexOf("=");if(c<=0)continue;let l=a.slice(0,c).trim(),u=a.slice(c+1).trim().replace(/^['"]|['"]$/g,"");t[l]=u}}catch{continue}}return t}var ua=k(()=>{"use strict"});import*as ae from"typescript";function lf(r){return{get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",options:"OPTIONS",head:"HEAD",all:"ALL"}[r]}function ov(r,e){if(r.length<=2)return[];let t=[];for(let n of r.slice(1,-1))t.push({name:n.getText(e)});return t}function av(r){let e=new Map;for(let s of r){let i=e.get(s.parent)??[];i.push(s),e.set(s.parent,i)}let t=new Map;t.set("app",[{pathExpression:"",resolvedPath:"",confidence:"high",middlewareNodes:[]}]);let n=["app"];for(;n.length>0;){let s=n.shift(),i=t.get(s)??[],o=e.get(s)??[];for(let a of o){let c=t.get(a.child)??[],l=!1;for(let u of i){let d=Jt(u.pathExpression,a.prefix.pathExpression),p=hn(u.confidence,a.prefix.confidence),m={pathExpression:d.pathExpression,resolvedPath:u.resolvedPath&&a.prefix.resolvedPath?d.resolvedPath:void 0,confidence:p,middlewareNodes:[...u.middlewareNodes,...a.middlewareNodes]};c.some(f=>f.pathExpression===m.pathExpression&&f.resolvedPath===m.resolvedPath)||(c.push(m),l=!0)}l&&(t.set(a.child,c),n.push(a.child))}}return t}function cv(r){return ae.isStringLiteral(r)||ae.isNoSubstitutionTemplateLiteral(r)||ae.isTemplateExpression(r)}function lv(r){if(ae.isStringLiteral(r)||ae.isNoSubstitutionTemplateLiteral(r))return r.text}function uv(r,e,t,n){let s=new Set(gn(n).map(a=>a.name));if(s.size===0)return[];let i=dv(r,e),o=[];for(let a of i){let c=t.get(a)??[];for(let l of c)s.has(l.paramName)&&o.push(l.node)}return o}function dv(r,e){let t=new Map;for(let o of e){let a=t.get(o.child)??[];a.push(o.parent),t.set(o.child,a)}let n=[],s=new Set,i=o=>{if(!s.has(o)){s.add(o);for(let a of t.get(o)??[])i(a);n.push(o)}};return i(r),n}var Si,uf=k(()=>{"use strict";ua();la();Si=class{async analyzeFile(e,t,n,s){let i=ae.createSourceFile(e,t,ae.ScriptTarget.Latest,!0,e.endsWith(".ts")?ae.ScriptKind.TS:ae.ScriptKind.JS),o=new Set(["app","router"]),a=[],c=[],l=new Map,u=new Map,d=Yr(i,n.projectRoot,s.envOverrides),p=g=>{if(ae.isVariableDeclaration(g)&&ae.isIdentifier(g.name)&&g.initializer){let v=g.initializer.getText(i);(/express\.Router\s*\(/.test(v)||/Router\s*\(/.test(v)||/express\(\)/.test(v))&&o.add(g.name.text)}ae.forEachChild(g,p)};p(i);let m=g=>{if(ae.isCallExpression(g)&&ae.isPropertyAccessExpression(g.expression)){let v=g.expression.expression.getText(i),y=g.expression.name.text;if(y==="use"&&g.arguments.length>=1&&o.has(v)){let b=g.arguments[g.arguments.length-1];if(g.arguments.length>=2&&ae.isIdentifier(b)&&o.has(b.text)&&ae.isIdentifier(b)){let w=Ct(g.arguments[0],i,d);a.push({parent:v,child:b.text,prefix:w,middlewareNodes:g.arguments.slice(1,-1)})}else{let w=cv(g.arguments[0])?g.arguments.slice(1):g.arguments.slice(0),E=l.get(v)??[];E.push(...w),l.set(v,E)}}if(y==="param"&&g.arguments.length>=2&&o.has(v)){let b=lv(g.arguments[0]),C=g.arguments[1];if(b&&C&&ae.isExpression(C)){let w=u.get(v)??[];w.push({paramName:b,node:C}),u.set(v,w)}}let S=lf(y);if(S&&o.has(v)&&g.arguments.length>=1){let b=Ct(g.arguments[0],i,d),C=ov(g.arguments,i),w=g.arguments[g.arguments.length-1],E=i.getLineAndCharacterOfPosition(w.getStart(i));c.push({owner:v,method:S,pathExpression:b.pathExpression,resolvedPath:b.resolvedPath,confidence:b.confidence,middleware:C,middlewareNodes:g.arguments.slice(1,-1),handlerNode:w,source:{filePath:e,line:E.line+1,column:E.character+1,symbolName:w.getText(i)}})}if(y==="route"&&g.arguments[0]){let b=Ct(g.arguments[0],i,d),C=g.parent;if(ae.isCallExpression(C)&&ae.isPropertyAccessExpression(C.expression)){let w=lf(C.expression.name.text);if(w){let E=C.arguments[0]??g.arguments[0],F=i.getLineAndCharacterOfPosition(E.getStart(i));c.push({owner:v,method:w,pathExpression:b.pathExpression,resolvedPath:b.resolvedPath,confidence:b.confidence,middleware:[],middlewareNodes:[],handlerNode:E,source:{filePath:e,line:F.line+1,column:F.character+1,symbolName:E.getText(i)}})}}}}ae.forEachChild(g,m)};m(i);let f=[],h=av(a);for(let g of c){let v=h.get(g.owner)??[],y=v.length>0?v:[{pathExpression:"",confidence:"high",middlewareNodes:[]}];for(let S of y){let b=Jt(S.pathExpression,g.pathExpression),C=hn(S.confidence,g.confidence),w=!!b.resolvedPath,E=gn(b.pathExpression),F=l.get(g.owner)??[],N=uv(g.owner,a,u,b.pathExpression),j=[...S.middlewareNodes,...F,...N,...g.middlewareNodes,g.handlerNode],O=bi(j,i,e,g.method,s.contextProperties);O.parameters.unshift(...E),O.parameters=yn(O.parameters),f.push({id:"",method:g.method,framework:"express",pathExpression:b.pathExpression,resolvedPath:C==="high"&&w?b.resolvedPath:void 0,confidence:C,source:g.source,middleware:g.middleware,params:O.parameters.length>0?O.parameters:void 0,requestBody:O.requestBody,cookies:O.cookies.length>0?O.cookies:void 0,responses:O.responses})}}return f}}});import*as _ from"typescript";function pv(r,e,t,n,s,i){let o=r.arguments[0],a=r.arguments[1],c=fv(a,e,i),l=c?n.map(u=>{let d=Jt(u.pathExpression,c.pathExpression);return{pathExpression:d.pathExpression,resolvedPath:u.resolvedPath&&c.resolvedPath?d.resolvedPath:void 0,confidence:hn(u.confidence,c.confidence)}}):n;if(_.isArrowFunction(o)||_.isFunctionExpression(o)){let u=new Set(t),d=o.parameters[0];d&&_.isIdentifier(d.name)&&u.add(d.name.text),o.body&&_.forEachChild(o.body,p=>s(p,u,l))}}function fv(r,e,t){if(!r||!_.isObjectLiteralExpression(r))return;let n=Pe(r,"prefix");if(!n)return;let s=Ct(n,e,t);return{pathExpression:s.pathExpression,resolvedPath:s.resolvedPath,confidence:s.confidence}}function mv(r){return{get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",options:"OPTIONS",head:"HEAD",all:"ALL"}[r]}function Pe(r,e){for(let t of r.properties){if(!_.isPropertyAssignment(t))continue;if((_.isIdentifier(t.name)||_.isStringLiteral(t.name)?t.name.text:void 0)===e)return t.initializer}}function hv(r,e){return r?_.isStringLiteral(r)||_.isNoSubstitutionTemplateLiteral(r)?[r.text.toUpperCase()]:_.isArrayLiteralExpression(r)?r.elements.map(t=>_.isStringLiteral(t)||_.isNoSubstitutionTemplateLiteral(t)?t.text.toUpperCase():t.getText(e).toUpperCase()).filter(Boolean):[r.getText(e).toUpperCase()]:["GET"]}function df(r,e){return r?_.isArrayLiteralExpression(r)?r.elements.map(t=>({name:`preHandler:${t.getText(e)}`})):[{name:`preHandler:${r.getText(e)}`}]:[]}function pf(r){return r?_.isArrayLiteralExpression(r)?r.elements.filter(e=>_.isExpression(e)):[r]:[]}function gv(r){if(r&&(_.isArrowFunction(r)||_.isFunctionExpression(r))&&r.parameters[0]&&_.isIdentifier(r.parameters[0].name))return r.parameters[0].name.text}function yv(r,e){if(!r||!_.isStringLiteral(r))return!1;let t=r.text;return t==="onRequest"||t==="preParsing"||t==="preValidation"||t==="preHandler"}function vv(r,e,t){let n=[],s=new Set,i=r;for(;i&&!s.has(i);)s.add(i),n.unshift(i),i=t.get(i);let o=[];for(let a of n){let c=e.get(a)??[];o.push(...c)}return o}function bv(r,e){return e?{parameters:yn([...e.parameters,...r.parameters]),requestBody:e.requestBody??r.requestBody,cookies:r.cookies,responses:r.responses}:r}function ff(r,e,t){if(!r||!_.isObjectLiteralExpression(r))return;let n=[],s=Pe(r,"params");s&&n.push(...xi(s,"path",""));let i=Pe(r,"querystring")??Pe(r,"query");i&&n.push(...xi(i,"query",""));let o=Pe(r,"headers");o&&n.push(...xi(o,"header",""));let a=Pe(r,"body");a&&n.push(...xi(a,"body",""));let c=a?mf(a,e):void 0,l=a?{type:"json",required:["POST","PUT","PATCH"].includes(t),schema:c??{type:"object"}}:void 0;return{parameters:n,requestBody:l,cookies:[],responses:[]}}function mf(r,e){if(_.isStringLiteral(r)||_.isNoSubstitutionTemplateLiteral(r))return{type:"string"};if(_.isNumericLiteral(r))return{type:"number"};if(!_.isObjectLiteralExpression(r))return;let t={};for(let n of r.properties){if(!_.isPropertyAssignment(n))continue;let s=n.name,i=_.isIdentifier(s)||_.isStringLiteral(s)||_.isNumericLiteral(s)?s.text:void 0;if(!i)continue;let o=hf(n.initializer,e);o!==void 0&&(t[i]=o)}return Object.keys(t).length>0?t:void 0}function hf(r,e){if(_.isStringLiteral(r)||_.isNoSubstitutionTemplateLiteral(r))return r.text;if(_.isNumericLiteral(r))return Number(r.text);if(r.kind===_.SyntaxKind.TrueKeyword||r.kind===_.SyntaxKind.FalseKeyword)return r.kind===_.SyntaxKind.TrueKeyword;if(r.kind===_.SyntaxKind.NullKeyword)return null;if(_.isArrayLiteralExpression(r)){let t=r.elements.map(n=>hf(n,e));return t.every(n=>n!==void 0)?t:void 0}if(_.isObjectLiteralExpression(r))return mf(r,e)}function xi(r,e,t){if(!_.isObjectLiteralExpression(r))return[];let n=Pe(r,"properties");if(!n||!_.isObjectLiteralExpression(n))return[];let s=Pe(r,"required"),i=new Set;if(s&&_.isArrayLiteralExpression(s))for(let a of s.elements)(_.isStringLiteral(a)||_.isNoSubstitutionTemplateLiteral(a))&&i.add(a.text);let o=[];for(let a of n.properties){if(!_.isPropertyAssignment(a))continue;let c=_.isIdentifier(a.name)||_.isStringLiteral(a.name)||_.isNumericLiteral(a.name)?a.name.text:void 0;if(!c)continue;let l=t?`${t}.${c}`:c,u=Sv(a.initializer);o.push({name:l,location:e,type:u,required:i.has(c)}),o.push(...xi(a.initializer,e,l))}return o}function Sv(r){if(!_.isObjectLiteralExpression(r))return;let e=Pe(r,"type");if(e&&(_.isStringLiteral(e)||_.isNoSubstitutionTemplateLiteral(e)))return e.text;let t=Pe(r,"properties");if(t&&_.isObjectLiteralExpression(t))return"object"}var wi,gf=k(()=>{"use strict";ua();la();wi=class{async analyzeFile(e,t,n,s){let i=_.createSourceFile(e,t,_.ScriptTarget.Latest,!0,e.endsWith(".ts")?_.ScriptKind.TS:_.ScriptKind.JS),o=new Set(["fastify"]),a=[{pathExpression:"",resolvedPath:"",confidence:"high"}],c=[],l=new Map,u=new Map,d=Yr(i,n.projectRoot,s.envOverrides),p=(f,h,g)=>{if(_.isVariableDeclaration(f)&&_.isIdentifier(f.name)&&f.initializer){let v=f.initializer.getText(i);(v.includes("fastify(")||v.includes("Fastify("))&&h.add(f.name.text)}if(_.isCallExpression(f)&&_.isPropertyAccessExpression(f.expression)){let v=f.expression.expression.getText(i),y=f.expression.name.text;if(y==="register"){let b=gv(f.arguments[0]);b&&u.set(b,v),pv(f,i,h,g,p,d)}if(y==="addHook"&&h.has(v)&&f.arguments.length>=2&&yv(f.arguments[0],i)){let b=l.get(v)??[];b.push(f.arguments[1]),l.set(v,b)}let S=mv(y);if(S&&h.has(v)&&f.arguments[0]){let b=Ct(f.arguments[0],i,d),C=f.arguments.length>=2&&_.isObjectLiteralExpression(f.arguments[1])?f.arguments[1]:void 0,w=C&&f.arguments[2]?f.arguments[2]:f.arguments[f.arguments.length-1],E=i.getLineAndCharacterOfPosition(w.getStart(i)),F=C?Pe(C,"preHandler"):void 0,N=df(F,i),j=pf(F),O=C?ff(Pe(C,"schema"),i,S):void 0;for(let D of g){let P=Jt(D.pathExpression,b.pathExpression),M=hn(D.confidence,b.confidence),G=!!P.resolvedPath;c.push({owner:v,method:S,pathExpression:P.pathExpression,resolvedPath:M==="high"&&G?P.resolvedPath:void 0,confidence:M,handlerNode:w,middlewareNodes:j,schemaMetadata:O,source:{filePath:e,line:E.line+1,column:E.character+1,symbolName:w.getText(i)},middleware:N})}}if(y==="route"&&h.has(v)&&f.arguments[0]&&_.isObjectLiteralExpression(f.arguments[0])){let b=f.arguments[0],C=Pe(b,"method"),w=Pe(b,"url")??Pe(b,"path"),E=Pe(b,"handler"),F=Pe(b,"preHandler"),N=Pe(b,"schema"),j=Ct(w,i,d),O=hv(C,i),D=df(F,i);for(let P of O){let M=E?i.getLineAndCharacterOfPosition(E.getStart(i)):i.getLineAndCharacterOfPosition(b.getStart(i));for(let G of g){let me=Jt(G.pathExpression,j.pathExpression),Ce=hn(G.confidence,j.confidence),Ie=!!me.resolvedPath;c.push({owner:v,method:P,pathExpression:me.pathExpression,resolvedPath:Ce==="high"&&Ie?me.resolvedPath:void 0,confidence:Ce,handlerNode:E??b,middlewareNodes:pf(F),schemaMetadata:ff(N,i,P),source:{filePath:e,line:M.line+1,column:M.character+1,symbolName:E?.getText(i)},middleware:D})}}}}_.forEachChild(f,v=>p(v,h,g))};p(i,o,a);let m=[];for(let f of c){let h=gn(f.pathExpression),v=[...vv(f.owner,l,u),...f.middlewareNodes,f.handlerNode],y=bi(v,i,e,f.method,s.contextProperties);y.parameters.unshift(...h),y.parameters=yn(y.parameters);let S=bv(y,f.schemaMetadata);m.push({id:"",method:f.method,framework:"fastify",pathExpression:f.pathExpression,resolvedPath:f.resolvedPath,confidence:f.confidence,source:f.source,middleware:f.middleware,params:S.parameters.length>0?S.parameters:void 0,requestBody:S.requestBody,cookies:S.cookies.length>0?S.cookies:void 0,responses:S.responses})}return m}}});import*as H from"typescript";function xv(r,e){H.forEachChild(r,t=>wv(t,r,e))}function wv(r,e,t){if(H.isExpressionStatement(r)&&H.isBinaryExpression(r.expression)&&r.expression.operatorToken.kind===H.SyntaxKind.EqualsToken){let n=r.expression.left,s=r.expression.right;if(H.isPropertyAccessExpression(n)){let i=n.expression.getText(e),o=n.name.text;if(i==="exports"&&da(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=Vl(s,e);t.push({exportName:o,handlerNode:c,middlewareNodes:l,location:{filePath:e.fileName,line:a.line+1,column:a.character+1,symbolName:o}});return}if(i==="module"&&o==="exports"&&da(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=Vl(s,e);t.push({exportName:"handler",handlerNode:c,middlewareNodes:l,location:{filePath:e.fileName,line:a.line+1,column:a.character+1,symbolName:"handler"}});return}}}if(H.isVariableStatement(r)&&yf(r)&&r.declarationList.declarations.length>0){for(let n of r.declarationList.declarations)if(!(!H.isIdentifier(n.name)||!n.initializer)&&da(n.initializer,e)){let s=n.name.text,i=e.getLineAndCharacterOfPosition(n.initializer.getStart(e)),{handlerNode:o,middlewareNodes:a}=Vl(n.initializer,e);t.push({exportName:s,handlerNode:o,middlewareNodes:a,location:{filePath:e.fileName,line:i.line+1,column:i.character+1,symbolName:s}})}return}if(H.isFunctionDeclaration(r)&&yf(r)&&r.name&&Rv(r)){let n=r.name.text,s=e.getLineAndCharacterOfPosition(r.getStart(e));t.push({exportName:n,handlerNode:r,middlewareNodes:[],location:{filePath:e.fileName,line:s.line+1,column:s.character+1,symbolName:n}})}}function da(r,e){if(H.isArrowFunction(r)||H.isFunctionExpression(r))return Cv(r);if(H.isCallExpression(r)){let t=r.expression.getText(e);if(t==="middy"||t.endsWith(".middy"))return!0;if(H.isPropertyAccessExpression(r.expression)&&r.expression.name.text==="use")return da(r.expression.expression,e)}return H.isIdentifier(r)?/handler/i.test(r.text):!1}function Rv(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function Cv(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function yf(r){return(H.getCombinedModifierFlags(r)&H.ModifierFlags.Export)!==0}function Vl(r,e){let t=[],n=r;for(;H.isCallExpression(n)&&H.isPropertyAccessExpression(n.expression)&&n.expression.name.text==="use";)t.unshift(...n.arguments),n=n.expression.expression;return H.isCallExpression(n)&&(n.expression.getText(e)==="middy"||n.expression.getText(e).endsWith(".middy"))?{handlerNode:n.arguments[0]??n,middlewareNodes:t}:{handlerNode:r,middlewareNodes:[]}}function kv(r,e,t){return r.map(n=>{let s=Ev(n,e),i=e.getLineAndCharacterOfPosition(n.getStart(e));return{name:s,location:{filePath:t,line:i.line+1,column:i.character+1,symbolName:s}}})}function Ev(r,e){return H.isIdentifier(r)?r.text:H.isCallExpression(r)&&H.isIdentifier(r.expression)?r.expression.text:H.isCallExpression(r)&&H.isPropertyAccessExpression(r.expression)?r.expression.name.text:r.getText(e).slice(0,40).replace(/\s+/g," ")}function Av(r,e,t){let n=Pv(r);if(!n)return[];let s=new Map,i=o=>{if(H.isPropertyAccessExpression(o)||H.isElementAccessExpression(o)){let a=Ri(o,e);if(a.length>=2&&a[0]===n){let c=a[1],l=qv[c];if(l==="body"){let u="body::body";if(!s.has(u)){let d=e.getLineAndCharacterOfPosition(o.getStart(e));s.set(u,{name:"body",location:"body",detectionLocation:{filePath:t,line:d.line+1,column:d.character+1}})}}else if(l&&a.length>=3){let u=a[2],d=`${l}::${u}`;if(!s.has(d)){let p=e.getLineAndCharacterOfPosition(o.getStart(e));s.set(d,{name:u,location:l,detectionLocation:{filePath:t,line:p.line+1,column:p.character+1}})}}}}if(H.isCallExpression(o)&&H.isPropertyAccessExpression(o.expression)&&o.expression.expression.getText(e)==="JSON"&&o.expression.name.text==="parse"&&o.arguments.length===1){let a=o.arguments[0],c=Ri(a,e);if(c.length===2&&c[0]===n&&c[1]==="body"){let l="body::body";if(!s.has(l)){let u=e.getLineAndCharacterOfPosition(o.getStart(e));s.set(l,{name:"body",location:"body",type:"json",detectionLocation:{filePath:t,line:u.line+1,column:u.character+1}})}}}H.forEachChild(o,i)};return i(r),Array.from(s.values())}function Pv(r){if(H.isArrowFunction(r)||H.isFunctionExpression(r)||H.isFunctionDeclaration(r)){let e=r.parameters[0];if(e&&H.isIdentifier(e.name))return e.name.text}return H.isIdentifier(r),"event"}function Ri(r,e){return H.isIdentifier(r)?[r.text]:H.isPropertyAccessExpression(r)?[...Ri(r.expression,e),r.name.text]:r.kind===H.SyntaxKind.PropertyAccessExpression||H.isNonNullExpression(r)?Ri(r.expression,e):H.isElementAccessExpression(r)&&H.isStringLiteral(r.argumentExpression)?[...Ri(r.expression,e),r.argumentExpression.text]:r.getText(e).replace(/\?/g,"").replace(/\s/g,"").split(".")}var Ci,qv,zl=k(()=>{"use strict";Ci=class{async analyzeFile(e,t,n,s){let i=H.createSourceFile(e,t,H.ScriptTarget.Latest,!0,e.endsWith(".ts")?H.ScriptKind.TS:H.ScriptKind.JS),o=[];return xv(i,o),o.length===0?[]:o.map(a=>{let c=Av(a.handlerNode,i,e),l=kv(a.middlewareNodes,i,e);return{id:"",method:"ANY",framework:"lambda",pathExpression:"<unknown-lambda>",resolvedPath:void 0,confidence:"low",source:a.location,middleware:l,params:c.length>0?c:void 0}})}};qv={pathParameters:"path",queryStringParameters:"query",multiValueQueryStringParameters:"query",headers:"header",multiValueHeaders:"header",body:"body"}});var Xr=k(()=>{"use strict";la();uf();gf();zl()});import*as pa from"fs";function vf(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function Iv(r){let e=[];for(let t of r){t.resolvedPath||e.push({code:"dynamic-path-unresolved",framework:"express",filePath:t.source.filePath,message:`Express route path unresolved for ${t.method} ${t.pathExpression}`});for(let n of t.params??[]){if(!n.conflictingTypes||n.conflictingTypes.length<2)continue;let s=n.detectionLocation?.filePath??n.evidenceLocations?.[0]?.filePath;e.push({code:"parameter-type-conflict",framework:"express",filePath:s,message:`Conflicting inferred types for ${n.location} parameter '${n.name}' on ${t.method} ${t.pathExpression}: ${n.conflictingTypes.join(", ")}`})}}return e}var bn,Jl=k(()=>{"use strict";Xr();mn();bn=class{id="provider.express";framework="express";analyzer=new Si;fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(vf(t)===vf(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){return{...e.packageJson?.dependencies,...e.packageJson?.devDependencies}.express?{supported:!0,confidence:.95,reasons:["express dependency detected"]}:{supported:!1,confidence:0,reasons:["express dependency not found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.sourceFiles??lt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=pa.statSync(a)}catch{continue}let l=this.fileCache.get(a);if(l&&l.mtimeMs===c.mtimeMs&&l.size===c.size){i.push(...l.endpoints.map(m=>structuredClone(m))),s.push(...l.warnings.map(m=>({...m})));continue}let u="";try{u=pa.readFileSync(a,"utf-8")}catch{continue}let d=await this.analyzer.analyzeFile(a,u,t,e),p=Iv(d);i.push(...d),s.push(...p),this.fileCache.set(a,{mtimeMs:c.mtimeMs,size:c.size,endpoints:d.map(m=>structuredClone(m)),warnings:p.map(m=>({...m}))})}return{endpoints:i,warnings:s,stats:{frameworksDetected:["express"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});import*as fa from"fs";function bf(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function Tv(r){let e=[];for(let t of r){t.resolvedPath||e.push({code:"dynamic-path-unresolved",framework:"fastify",filePath:t.source.filePath,message:`Fastify route path unresolved for ${t.method} ${t.pathExpression}`});for(let n of t.params??[]){if(!n.conflictingTypes||n.conflictingTypes.length<2)continue;let s=n.detectionLocation?.filePath??n.evidenceLocations?.[0]?.filePath;e.push({code:"parameter-type-conflict",framework:"fastify",filePath:s,message:`Conflicting inferred types for ${n.location} parameter '${n.name}' on ${t.method} ${t.pathExpression}: ${n.conflictingTypes.join(", ")}`})}}return e}var Sn,Wl=k(()=>{"use strict";Xr();mn();Sn=class{id="provider.fastify";framework="fastify";analyzer=new wi;fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(bf(t)===bf(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){return{...e.packageJson?.dependencies,...e.packageJson?.devDependencies}.fastify?{supported:!0,confidence:.95,reasons:["fastify dependency detected"]}:{supported:!1,confidence:0,reasons:["fastify dependency not found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.sourceFiles??lt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=fa.statSync(a)}catch{continue}let l=this.fileCache.get(a);if(l&&l.mtimeMs===c.mtimeMs&&l.size===c.size){i.push(...l.endpoints.map(m=>structuredClone(m))),s.push(...l.warnings.map(m=>({...m})));continue}let u="";try{u=fa.readFileSync(a,"utf-8")}catch{continue}let d=await this.analyzer.analyzeFile(a,u,t,e),p=Tv(d);i.push(...d),s.push(...p),this.fileCache.set(a,{mtimeMs:c.mtimeMs,size:c.size,endpoints:d.map(m=>structuredClone(m)),warnings:p.map(m=>({...m}))})}return{endpoints:i,warnings:s,stats:{frameworksDetected:["fastify"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});import*as ma from"fs";import*as ye from"typescript";function Sf(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function Gl(r,e){let t=r.expression;if(ye.isCallExpression(t))return ye.isIdentifier(t.expression)?t.expression.text:t.expression.getText(e);if(ye.isIdentifier(t))return t.text}function xf(r){let e=r.expression;if(ye.isCallExpression(e))return e.arguments[0]}function Ov(r){return{Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE",Patch:"PATCH",Options:"OPTIONS",Head:"HEAD",All:"ALL"}[r]}function wf(r){return ye.canHaveDecorators(r)?ye.getDecorators(r)??[]:[]}function Rf(r,e){if(!r||r.length===0)return[];let t=new Set(["UseGuards","UseInterceptors","UsePipes","UseFilters"]),n=[];for(let s of r){let i=Gl(s,e);if(!i||!t.has(i))continue;let o=s.expression;if(!ye.isCallExpression(o)){n.push({name:i});continue}for(let a of o.arguments)n.push({name:`${i}:${a.getText(e)}`})}return n}function $v(r,e){return r==="low"||e==="low"?"low":r==="medium"||e==="medium"?"medium":"high"}var xn,Kl=k(()=>{"use strict";ua();mn();xn=class{id="provider.nestjs";framework="nestjs";fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(Sf(t)===Sf(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){return{...e.packageJson?.dependencies,...e.packageJson?.devDependencies}["@nestjs/common"]?{supported:!0,confidence:.98,reasons:["@nestjs/common dependency detected"]}:{supported:!1,confidence:0,reasons:["@nestjs/common dependency not found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.sourceFiles??lt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){if(!a.endsWith(".ts")&&!a.endsWith(".js"))continue;let c;try{c=ma.statSync(a)}catch{continue}let l=this.fileCache.get(a);if(l&&l.mtimeMs===c.mtimeMs&&l.size===c.size){i.push(...l.endpoints.map(g=>structuredClone(g))),s.push(...l.warnings.map(g=>({...g})));continue}let u="";try{u=ma.readFileSync(a,"utf-8")}catch{continue}let d=[],p=[],m=ye.createSourceFile(a,u,ye.ScriptTarget.Latest,!0,a.endsWith(".ts")?ye.ScriptKind.TS:ye.ScriptKind.JS),f=Yr(m,t.projectRoot,e.envOverrides),h=g=>{if(ye.isClassDeclaration(g)){let v=wf(g),y=v.find(S=>Gl(S,m)==="Controller");if(y){let S=Ct(xf(y),m,f),b=Rf(v,m);for(let C of g.members){if(!ye.isMethodDeclaration(C))continue;let w=wf(C),E=w.map(F=>({decorator:F,name:Gl(F,m)})).filter(F=>!!F.name);for(let F of E){let N=Ov(F.name);if(!N)continue;let j=Ct(xf(F.decorator),m,f),O=Jt(S.pathExpression,j.pathExpression),D=Rf(w,m),P=C.name?.getText(m),M=C.name??C,G=m.getLineAndCharacterOfPosition(M.getStart(m)),me=$v(S.confidence,j.confidence);p.push({id:"",method:N,framework:"nestjs",pathExpression:O.pathExpression,resolvedPath:me==="high"?O.resolvedPath:void 0,confidence:me,source:{filePath:a,line:G.line+1,column:G.character+1,symbolName:P},middleware:[...b,...D]}),me!=="high"&&d.push({code:"dynamic-path-unresolved",framework:"nestjs",filePath:a,message:`Dynamic NestJS route path unresolved at ${P??"unknown handler"} in ${a}`})}}}}ye.forEachChild(g,h)};h(m),i.push(...p),s.push(...d),this.fileCache.set(a,{mtimeMs:c.mtimeMs,size:c.size,endpoints:p.map(g=>structuredClone(g)),warnings:d.map(g=>({...g}))})}return{endpoints:i,warnings:s,stats:{frameworksDetected:["nestjs"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});import*as He from"fs";import*as ut from"path";function Fv(r,e,t){let n=[],s=r.functions;if(!s||typeof s!="object")return n;for(let[i,o]of Object.entries(s)){if(!o||typeof o!="object")continue;let a=o,c=a.handler;if(!c||typeof c!="string")continue;let{filePath:l,exportName:u}=Ef(c,e),d=qf(l,e);d||t.push({code:"dynamic-path-unresolved",framework:"lambda",message:`Lambda handler file not found for function '${i}': ${c}`});let p=a.events;if(Array.isArray(p))for(let m of p){if(!m||typeof m!="object")continue;let f=m.http;if(!f||typeof f!="object")continue;let h=f.path,g=f.method;if(!h||!g)continue;let v=Af(h),y=[];if(f.authorizer){let S=typeof f.authorizer=="string"?f.authorizer:"authorizer";y.push({name:S})}n.push({id:"",method:g.toUpperCase(),framework:"lambda",pathExpression:v,resolvedPath:v,confidence:"high",source:{filePath:d??l,line:1,column:1,symbolName:u},middleware:y})}}return n}function Cf(r,e,t){let n=[],s=r.Resources;if(!s||typeof s!="object")return n;for(let[i,o]of Object.entries(s)){if(!o||typeof o!="object")continue;let a=o;if(a.Type!=="AWS::Serverless::Function")continue;let c=a.Properties;if(!c)continue;let l=c.Handler;if(!l||typeof l!="string")continue;let{filePath:u,exportName:d}=Ef(l,e),p=qf(u,e);p||t.push({code:"dynamic-path-unresolved",framework:"lambda",message:`Lambda handler file not found for SAM resource '${i}': ${l}`});let m=c.Events;if(!(!m||typeof m!="object"))for(let[,f]of Object.entries(m)){if(!f||typeof f!="object")continue;let h=f;if(h.Type!=="Api"&&h.Type!=="HttpApi")continue;let g=h.Properties;if(!g)continue;let v=g.Path,y=g.Method;if(!v||!y)continue;let S=Af(v),b=g.Auth,C=[];b?.Authorizer&&C.push({name:String(b.Authorizer)}),n.push({id:"",method:y.toUpperCase(),framework:"lambda",pathExpression:S,resolvedPath:S,confidence:"high",source:{filePath:p??u,line:1,column:1,symbolName:d},middleware:C})}}return n}function Ef(r,e){let t=r.lastIndexOf(".");return t===-1?{filePath:r,exportName:"handler"}:{filePath:r.slice(0,t),exportName:r.slice(t+1)}}function qf(r,e){let t=[ut.join(e,`${r}.ts`),ut.join(e,`${r}.js`),ut.join(e,r,"index.ts"),ut.join(e,r,"index.js")];for(let n of t)if(He.existsSync(n))return n}function Af(r){return r.startsWith("/")?r:`/${r}`}function Zl(r){let e=r.split(`
|
|
830
|
+
`);return ki(e,0,-1).value}function ki(r,e,t){let n={},s=[],i=!1,o=e;for(;o<r.length;){let a=r[o],c=a.trimEnd();if(c.trim()===""||c.trimStart().startsWith("#")){o++;continue}let l=Nv(a);if(l<=t)break;let u=c.trimStart();if(u.startsWith("- ")){i=!0;let f=u.slice(2).trim();if(f===""||f.endsWith(":"))if(f.endsWith(":")){let h=f.slice(0,-1).trim(),g=ki(r,o+1,l),v={};v[h]=g.value,s.push(v),o=g.nextLine}else{let h=ki(r,o+1,l);s.push(h.value),o=h.nextLine}else if(f.includes(": ")||f.endsWith(":")){let h={},g=f.indexOf(":"),v=f.slice(0,g).trim(),y=f.slice(g+1).trim();if(y===""){let S=ki(r,o+1,l);h[v]=S.value,s.push(h),o=S.nextLine}else h[v]=Ql(y),s.push(h),o++}else s.push(Ql(f)),o++;continue}let d=u.indexOf(":");if(d===-1){o++;continue}let p=u.slice(0,d).trim(),m=u.slice(d+1).trim();if(m===""||m.startsWith("#")){let f=ki(r,o+1,l);n[p]=f.value,o=f.nextLine}else n[p]=Ql(m),o++}return i?{value:s,nextLine:o}:{value:n,nextLine:o}}function Nv(r){let e=0;for(let t of r)if(t===" ")e++;else if(t===" ")e+=2;else break;return e}function Ql(r){let e=r.indexOf(" #"),t=e!==-1?r.slice(0,e).trim():r.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t==="true"?!0:t==="false"?!1:t==="null"||t==="~"?null:/^-?\d+(\.\d+)?$/.test(t)?Number(t):t}function _v(r){return Zl(r)}function kf(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var wn,Yl=k(()=>{"use strict";zl();mn();wn=class{id="provider.lambda";framework="lambda";analyzer=new Ci;fileCache=new Map;projectFileIndex=new Map;clearCache(e){if(!e){this.fileCache.clear(),this.projectFileIndex.clear();return}for(let[t,n]of this.projectFileIndex.entries())if(kf(t)===kf(e)){for(let s of n)this.fileCache.delete(s);this.projectFileIndex.delete(t)}}supports(e){let t={...e.packageJson?.dependencies,...e.packageJson?.devDependencies};if(t.express||t.fastify)return{supported:!1,confidence:0,reasons:["express or fastify detected \u2014 deferring to existing provider"]};let n=!!(t["@types/aws-lambda"]||t["aws-lambda"]||t.serverless),s=He.existsSync(ut.join(e.projectRoot,"serverless.yml"))||He.existsSync(ut.join(e.projectRoot,"serverless.yaml"))||He.existsSync(ut.join(e.projectRoot,"template.yaml"))||He.existsSync(ut.join(e.projectRoot,"template.json"));return n?{supported:!0,confidence:.95,reasons:["lambda-related dependency detected"]}:s?{supported:!0,confidence:.75,reasons:["serverless/SAM config file detected"]}:{supported:!1,confidence:0,reasons:["no lambda indicators found"]}}async discover(e,t){let n=Date.now(),s=[],i=[],o=t.projectRoot;for(let a of["serverless.yml","serverless.yaml"]){let c=ut.join(o,a);if(He.existsSync(c)){try{let l=He.readFileSync(c,"utf-8"),u=_v(l),d=Fv(u,o,s);i.push(...d)}catch{s.push({code:"provider-failed",framework:"lambda",filePath:c,message:`Failed to parse Serverless Framework config: ${c}`})}break}}if(i.length===0){let a=ut.join(o,"template.yaml"),c=ut.join(o,"template.json");if(He.existsSync(c))try{let l=He.readFileSync(c,"utf-8"),u=JSON.parse(l),d=Cf(u,o,s);i.push(...d)}catch{s.push({code:"provider-failed",framework:"lambda",filePath:c,message:`Failed to parse SAM template: ${c}`})}else if(He.existsSync(a))try{let l=He.readFileSync(a,"utf-8"),u=Zl(l),d=Cf(u,o,s);i.push(...d)}catch{s.push({code:"provider-failed",framework:"lambda",filePath:a,message:`Failed to parse SAM template: ${a}`})}}if(i.length===0){let a=t.sourceFiles??lt(o);this.pruneDeletedFiles(o,a);for(let c of a){let l;try{l=He.statSync(c)}catch{continue}let u=this.fileCache.get(c);if(u&&u.mtimeMs===l.mtimeMs&&u.size===l.size){i.push(...u.endpoints.map(f=>structuredClone(f))),s.push(...u.warnings.map(f=>({...f})));continue}let d="";try{d=He.readFileSync(c,"utf-8")}catch{continue}let p=await this.analyzer.analyzeFile(c,d,t,e),m=p.map(f=>({code:"seed-endpoint-unmatched",framework:"lambda",filePath:f.source.filePath,message:`Lambda handler '${f.source.symbolName}' found without a config-file route definition. Path is unknown.`}));i.push(...p),s.push(...m),this.fileCache.set(c,{mtimeMs:l.mtimeMs,size:l.size,endpoints:p.map(f=>structuredClone(f)),warnings:m.map(f=>({...f}))})}}return{endpoints:i,warnings:s,stats:{frameworksDetected:["lambda"],providersRun:[this.id],endpointCount:i.length,unresolvedEndpointCount:i.filter(a=>!a.resolvedPath).length,scanDurationMs:Date.now()-n}}}pruneDeletedFiles(e,t){let n=new Set(t),s=this.projectFileIndex.get(e);if(s)for(let i of s)n.has(i)||this.fileCache.delete(i);this.projectFileIndex.set(e,n)}}});import*as ha from"fs";import*as If from"path";function Mv(r,e){let t=[],n=[r];for(;n.length>0;){let s=n.pop(),i;try{i=ha.readdirSync(s,{withFileTypes:!0})}catch{continue}for(let o of i){let a=If.join(s,o.name);o.isDirectory()?Dv.has(o.name)||n.push(a):o.isFile()&&e.test(o.name)&&t.push(a)}}return t}function Ei(r){return Mv(r,/\.java$/)}function qi(r){return ha.promises.readFile(r,"utf-8")}function Xl(r){let e=r.replace(/\\/g,"/");return/^[A-Z]:\//.test(e)&&(e=e[0].toLowerCase()+e.substring(1)),e}function eu(r){return r.replace(/\\/g,"/").split("/").pop()||""}function Tf(r,e){let t=Pf.get(e);if(t&&Date.now()-t.ts<jv)return Promise.resolve(t.files);let n=new RegExp(`^${e}\\.java$`),s=Ei(r).filter(i=>n.test(eu(i)));return Pf.set(e,{ts:Date.now(),files:s}),Promise.resolve(s)}var Dv,Pf,jv,ga=k(()=>{"use strict";Dv=new Set(["target","build","bin","out","dist","node_modules",".git",".svn",".hg",".gradle",".mvn",".idea",".vscode",".settings",".history","__pycache__"]);Pf=new Map,jv=3e4});function Lv(r){if(r.includes("/"))return r;if(Wt[r])return Wt[r];let e=`MediaType.${r}`;if(Wt[e])return Wt[e];for(let[s,i]of Object.entries(Wt))if(s.endsWith(r))return i;let t=r.lastIndexOf(".");if(t>=0){let s=r.substring(t+1),i=`MediaType.${s}`;if(Wt[i])return Wt[i];let o=`MediaType.${s}_VALUE`;if(Wt[o])return Wt[o]}let n=r.toUpperCase();return n.includes("JSON")?"application/json":n.includes("XML")&&!n.includes("HTML")?"application/xml":n.includes("FORM_URLENCODED")?"application/x-www-form-urlencoded":n.includes("MULTIPART")?"multipart/form-data":n.includes("TEXT_PLAIN")||n.includes("PLAIN_TEXT")?"text/plain":n.includes("OCTET_STREAM")?"application/octet-stream":r}function Ai(r){return r.map(Lv)}function Gt(r){if(!r)return r;let e=/^([A-Za-z0-9_]+)<(.+)>$/.exec(r);if(!e)return r;let t=e[1],n=e[2];return Hv.has(t)?Gt(n.trim()):r}function es(r){return/MultipartFile/.test(r)}var Wt,Hv,ya=k(()=>{"use strict";Wt={"MediaType.ALL_VALUE":"*/*","MediaType.APPLICATION_ATOM_XML_VALUE":"application/atom+xml","MediaType.APPLICATION_CBOR_VALUE":"application/cbor","MediaType.APPLICATION_FORM_URLENCODED_VALUE":"application/x-www-form-urlencoded","MediaType.APPLICATION_GRAPHQL_VALUE":"application/graphql","MediaType.APPLICATION_GRAPHQL_RESPONSE_VALUE":"application/graphql-response+json","MediaType.APPLICATION_JSON_VALUE":"application/json","MediaType.APPLICATION_JSON_UTF8_VALUE":"application/json;charset=UTF-8","MediaType.APPLICATION_NDJSON_VALUE":"application/x-ndjson","MediaType.APPLICATION_OCTET_STREAM_VALUE":"application/octet-stream","MediaType.APPLICATION_PDF_VALUE":"application/pdf","MediaType.APPLICATION_PROBLEM_JSON_VALUE":"application/problem+json","MediaType.APPLICATION_PROBLEM_XML_VALUE":"application/problem+xml","MediaType.APPLICATION_PROTOBUF_VALUE":"application/x-protobuf","MediaType.APPLICATION_RSS_XML_VALUE":"application/rss+xml","MediaType.APPLICATION_STREAM_JSON_VALUE":"application/stream+json","MediaType.APPLICATION_XHTML_XML_VALUE":"application/xhtml+xml","MediaType.APPLICATION_XML_VALUE":"application/xml","MediaType.APPLICATION_YAML_VALUE":"application/yaml","MediaType.IMAGE_GIF_VALUE":"image/gif","MediaType.IMAGE_JPEG_VALUE":"image/jpeg","MediaType.IMAGE_PNG_VALUE":"image/png","MediaType.MULTIPART_FORM_DATA_VALUE":"multipart/form-data","MediaType.MULTIPART_MIXED_VALUE":"multipart/mixed","MediaType.MULTIPART_RELATED_VALUE":"multipart/related","MediaType.TEXT_EVENT_STREAM_VALUE":"text/event-stream","MediaType.TEXT_HTML_VALUE":"text/html","MediaType.TEXT_MARKDOWN_VALUE":"text/markdown","MediaType.TEXT_PLAIN_VALUE":"text/plain","MediaType.TEXT_XML_VALUE":"text/xml"};Hv=new Set(["HttpEntity","RequestEntity","ResponseEntity","Mono","Flux","Optional","CompletableFuture","DeferredResult","ListenableFuture","Callable"])});var ir,Of=k(()=>{"use strict";ga();ya();ir=class{constructor(e){this.projectRoot=e}projectRoot;cache=new Map;clearCache(){this.cache.clear()}async generate(e){if(!e)return;let t=this.primitiveSchema(e);if(t)return t;let n=e,s=[],i=/^([^<]+)<(.+)>$/.exec(e);i&&(n=i[1].trim(),s=this.splitGenericArgs(i[2]));let o=n.split("."),a=o.pop(),c=o.length?o.join("."):void 0;if(this.cache.has(e))return this.cache.get(e);let l={type:"object",properties:{},required:[]};this.cache.set(e,l);let u=await Tf(this.projectRoot,a);if(u.length>1&&c){let m=/^\s*package\s+([\w.]+);/m;for(let f of u){let h=await qi(f),g=m.exec(h);if(g&&g[1]===c){u=[f];break}}}if(u.length===0){if(s.length>0){let m=await this.generate(s[0]);if(m&&m.properties&&Object.keys(m.properties).length>0)return Object.assign(l,m),l}return{type:"object"}}let d=await qi(u[0]),p=this.buildTypeParamMap(d,a,s);return await this.parseClassToSchema(d,a,l,p),l.required&&l.required.length===0&&delete l.required,l}async generateResponseSchema(e){if(!e||e==="void")return;let t=Gt(e);if(t==="void")return;let n=/(List|Set|Collection)<([^>]+)>/.exec(t);if(n){let s=n[2].trim();return{type:"array",items:await this.generate(s)||{type:"object"}}}if(t.endsWith("[]")){let s=t.replace(/\[\]$/,"");return{type:"array",items:await this.generate(s)||{type:"object"}}}return this.generate(t)}async parseClassToSchema(e,t,n,s){let i=this.extractFieldsRegex(e,t);for(let o of i){s&&s.size>0&&(o.javaType=this.resolveTypeParams(o.javaType,s));let a=await this.fieldToSchema(o),c=o.jsonPropertyName||o.name;n.properties[c]=a,o.required&&n.required.push(c)}}buildTypeParamMap(e,t,n){let s=new Map;if(n.length===0)return s;let i=new RegExp(`class\\s+${t}\\s*<([^{]+?)>\\s*(?:extends|implements|\\{)`).exec(e);return i&&this.splitGenericArgs(i[1]).map(a=>a.trim().split(/\s+/)[0]).forEach((a,c)=>{c<n.length&&s.set(a,n[c])}),s}splitGenericArgs(e){let t=[],n=0,s="";for(let i of e)i==="<"?(n++,s+=i):i===">"?(n--,s+=i):i===","&&n===0?(t.push(s.trim()),s=""):s+=i;return s.trim()&&t.push(s.trim()),t}resolveTypeParams(e,t){let n=e;for(let[s,i]of t)n=n.replace(new RegExp(`\\b${s}\\b`,"g"),i);return n}extractFieldsRegex(e,t){let n=[],s=e.split(/\r?\n/),i=!1,o=0,a=e.search(new RegExp(`class\\s+${t}\\b`)),c=a>=0?e.substring(Math.max(0,a-500),a):"",l=/@(?:lombok\.)?(?:Data|Getter|Value)\b/.test(c),u=/public\s+\S+\s+(?:get|is)[A-Z]\w*\s*\(/.test(e),d=[];for(let p of s){let m=p.trim();if(!i){new RegExp(`class\\s+${t}\\b`).test(m)&&(i=!0,o+=(p.match(/\{/g)||[]).length,o-=(p.match(/\}/g)||[]).length);continue}let f=o;if(o+=(p.match(/\{/g)||[]).length,o-=(p.match(/\}/g)||[]).length,o<=0)break;if(f>1)continue;if(/^@(\w+)/.exec(m)&&!/(?:private|public|protected)\s/.test(m)&&!m.includes(";")){d.push(m);continue}if(/^public\s+\S+\s+(get|is|set)[A-Z]\w*\s*\(/.test(m)){d=[];continue}let g=/(?:(private|public|protected)\s+)?([A-Za-z0-9_<>,\s\[\]?]+?)\s+([A-Za-z0-9_]+)\s*(?:=.*)?;/.exec(m);if(g){let v=g[2].replace(/\b(final)\b/g,"").trim().replace(/@\w+\s*/g,"").trim(),y=g[3],S=g[1]||"";if(v&&y&&!/^(class|interface|enum|return|if|for|while|void)\b/.test(v)){let b=/\bstatic\b/.test(m),C=/\btransient\b/.test(m),w=[...d,m],E=w.join(" ");!b&&!C&&!/@JsonIgnore\b/.test(E)&&(S==="public"||l||u||/@JsonProperty\b/.test(E))&&n.push(this.parseFieldAnnotations(y,v,w))}}d=[]}return n}parseFieldAnnotations(e,t,n){let s=n.join(" "),i={name:e,javaType:t},o=/\bvalue\s*=\s*"([^"]*)"/.exec(s.match(/@JsonProperty\([^)]*\)/)?.[0]||"")||/@JsonProperty\(\s*"([^"]*)"/.exec(s);o&&o[1]&&(i.jsonPropertyName=o[1]),i.description=this.extractAttr(s,"Schema","description"),i.example=this.extractAttr(s,"Schema","example");let a=this.extractAttr(s,"Schema","type");a&&(i.schemaTypeOverride=a);let c=this.extractAttr(s,"Schema","format");c&&(i.format=c),this.extractAttr(s,"Schema","nullable")==="true"&&(i.nullable=!0),this.extractAttr(s,"Schema","readOnly")==="true"&&(i.readOnly=!0),this.extractAttr(s,"Schema","writeOnly")==="true"&&(i.writeOnly=!0),this.extractAttr(s,"Schema","deprecated")==="true"&&(i.deprecated=!0);let m=this.extractAttr(s,"Schema","title");m&&(i.title=m);let f=this.extractAttr(s,"Schema","defaultValue");f&&(i.defaultValue=f);let h=/allowableValues\s*=\s*\{([^}]*)\}/.exec(s);h&&(i.enumValues=h[1].split(",").map(D=>D.trim().replace(/^['"]|['"]$/g,"")).filter(Boolean));let g=this.extractAttr(s,"Schema","minimum");g&&(i.minimum=Number(g));let v=this.extractAttr(s,"Schema","maximum");v&&(i.maximum=Number(v));let y=this.extractAttr(s,"Schema","minLength");y&&(i.minLength=Number(y));let S=this.extractAttr(s,"Schema","maxLength");S&&(i.maxLength=Number(S));let b=this.extractAttr(s,"Schema","pattern");b&&(i.pattern=b),i.description||(i.description=this.extractAttr(s,"ApiModelProperty","value")),i.example||(i.example=this.extractAttr(s,"ApiModelProperty","example")),(/@NotNull\b/.test(s)||/@NotBlank\b/.test(s)||/@NotEmpty\b/.test(s))&&(i.required=!0);let C=this.extractAttr(s,"Size","min");C&&!i.minLength&&(i.minLength=Number(C));let w=this.extractAttr(s,"Size","max");w&&!i.maxLength&&(i.maxLength=Number(w));let E=this.extractAttr(s,"Min","value")||this.extractSingleArg(s,"Min");E&&i.minimum===void 0&&(i.minimum=Number(E));let F=this.extractAttr(s,"Max","value")||this.extractSingleArg(s,"Max");F&&i.maximum===void 0&&(i.maximum=Number(F));let N=this.extractAttr(s,"DecimalMin","value")||this.extractSingleArg(s,"DecimalMin");N&&i.minimum===void 0&&(i.minimum=Number(N));let j=this.extractAttr(s,"DecimalMax","value")||this.extractSingleArg(s,"DecimalMax");j&&i.maximum===void 0&&(i.maximum=Number(j)),/@Email\b/.test(s)&&(i.format=i.format||"email");let O=this.extractAttr(s,"Pattern","regexp");return O&&!i.pattern&&(i.pattern=O),/@PositiveOrZero\b/.test(s)&&i.minimum===void 0&&(i.minimum=0),/@Positive\b/.test(s)&&i.minimum===void 0&&(i.minimum=1),/@NegativeOrZero\b/.test(s)&&i.maximum===void 0&&(i.maximum=0),/@Negative\b/.test(s)&&i.maximum===void 0&&(i.maximum=-1),(/@Past\b/.test(s)||/@PastOrPresent\b/.test(s))&&(i.format=i.format||"date-time"),(/@Future\b/.test(s)||/@FutureOrPresent\b/.test(s))&&(i.format=i.format||"date-time"),i}async fieldToSchema(e){let t={};if(e.schemaTypeOverride?t.type=e.schemaTypeOverride:Object.assign(t,this.javaTypeToJsonSchema(e.javaType)),e.description&&(t.description=e.description),e.title&&(t.title=e.title),e.format&&(t.format=e.format),e.example!==void 0&&(t.example=this.coerceValue(e.example)),e.defaultValue!==void 0&&(t.default=this.coerceValue(e.defaultValue)),e.nullable&&(t.nullable=!0),e.readOnly&&(t.readOnly=!0),e.writeOnly&&(t.writeOnly=!0),e.deprecated&&(t.deprecated=!0),e.enumValues&&(t.enum=e.enumValues),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.pattern&&(t.pattern=e.pattern),t.type==="object"&&!t.properties){let n=await this.generate(e.javaType);n&&n.properties&&(t.properties=n.properties,n.required&&(t.required=n.required))}if(t.type==="array"&&!t.items){let n=/(List|Set|Collection)<([^>]+)>/.exec(e.javaType);if(n){let s=n[2].trim(),i=this.primitiveSchema(s)||await this.generate(s);t.items=i||{type:"object"}}}return t}javaTypeToJsonSchema(e){if(/^(String|CharSequence|char|Character)$/.test(e))return{type:"string"};if(/^(int|Integer|short|Short|byte|Byte)$/.test(e))return{type:"integer",format:"int32"};if(/^(long|Long|BigInteger)$/.test(e))return{type:"integer",format:"int64"};if(/^(float|Float)$/.test(e))return{type:"number",format:"float"};if(/^(double|Double|BigDecimal)$/.test(e))return{type:"number",format:"double"};if(/^(boolean|Boolean)$/.test(e))return{type:"boolean"};if(/^(LocalDate)$/.test(e))return{type:"string",format:"date"};if(/^(LocalDateTime|ZonedDateTime|OffsetDateTime|Instant|Date|Timestamp)$/.test(e))return{type:"string",format:"date-time"};if(/^(LocalTime|OffsetTime)$/.test(e))return{type:"string",format:"time"};if(/^UUID$/.test(e))return{type:"string",format:"uuid"};if(/^(URI|URL)$/.test(e))return{type:"string",format:"uri"};if(/^(byte\[\]|Byte\[\])$/.test(e))return{type:"string",format:"binary"};if(/^Map\b/.test(e))return{type:"object",additionalProperties:!0};if(/(List|Set|Collection)</.test(e))return{type:"array"};if(e.endsWith("[]")){let t=e.replace(/\[\]$/,"");return{type:"array",items:this.primitiveSchema(t)||{type:"object"}}}return{type:"object"}}primitiveSchema(e){let t=this.javaTypeToJsonSchema(e);if(t.type!=="object"||/^Map\b/.test(e))return t}static javaTypeToParamType(e){return/^(int|Integer|long|Long|short|Short|byte|Byte|BigInteger)$/.test(e)?"integer":/^(float|Float|double|Double|BigDecimal)$/.test(e)?"number":/^(boolean|Boolean)$/.test(e)?"boolean":/(List|Set|Collection)</.test(e)||e.endsWith("[]")?"array":"string"}static javaTypeToFormat(e){if(/^(int|Integer|short|Short|byte|Byte)$/.test(e))return"int32";if(/^(long|Long|BigInteger)$/.test(e))return"int64";if(/^(float|Float)$/.test(e))return"float";if(/^(double|Double|BigDecimal)$/.test(e))return"double";if(/^(LocalDate)$/.test(e))return"date";if(/^(LocalDateTime|ZonedDateTime|OffsetDateTime|Instant|Date|Timestamp)$/.test(e))return"date-time";if(/^(LocalTime|OffsetTime)$/.test(e))return"time";if(/^UUID$/.test(e))return"uuid";if(/^(URI|URL)$/.test(e))return"uri"}extractAttr(e,t,n){let i=new RegExp(`@${t}\\b[^)]*\\b${n}\\s*=\\s*"([^"]*)"`,"s").exec(e);return i?i[1]:void 0}extractSingleArg(e,t){let s=new RegExp(`@${t}\\(\\s*([^")]+?)\\s*\\)`).exec(e);if(s&&!/=/.test(s[1]))return s[1].trim()}coerceValue(e){return/^-?\d+$/.test(e)?parseInt(e,10):/^-?\d+\.\d+$/.test(e)?parseFloat(e):e==="true"?!0:e==="false"?!1:e}}});import{BaseJavaCstVisitorWithDefaults as Bv}from"java-parser";function tu(r){let e=[],t=/:(\w+)|\{(\w+)\}/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]||n[2]);return e}var va,$f=k(()=>{"use strict";ya();va=class extends Bv{controllers=[];contextStack=[];constructor(){super(),this.validateVisitor()}annotation(e){if(this.contextStack.length===0)return;let t=e.typeName[0].children.Identifier[0].image,n=new Map;if(e.elementValuePairList){let i=e.elementValuePairList[0].children.elementValuePair;for(let o of i){let a=o.children.Identifier[0].image,c=this.extractElementValue(o.children.elementValue[0]);c!==void 0&&n.set(a,c)}}else if(e.elementValue){let i=this.extractElementValue(e.elementValue[0]);i!==void 0&&n.set("value",i)}this.contextStack[this.contextStack.length-1].annotations.push({name:t,attributes:n}),this.visitNestedAnnotations(e)}visitNestedAnnotations(e){let t=[];if(e.elementValue&&t.push(e.elementValue[0]),e.elementValuePairList){let n=e.elementValuePairList[0].children.elementValuePair||[];for(let s of n)s.children.elementValue&&t.push(s.children.elementValue[0])}for(let n of t){if(n.children?.annotation)for(let i of n.children.annotation)this.annotation(i.children);let s=n.children?.elementValueArrayInitializer?.[0];if(s){let i=s.children?.elementValueList?.[0]?.children?.elementValue||[];for(let o of i)if(o.children?.annotation)for(let a of o.children.annotation)this.annotation(a.children)}}}typeIdentifier(e){if(this.contextStack.length===0)return;let t=e.Identifier[0].image,n=e.Identifier[0].startLine,s=this.contextStack[this.contextStack.length-1];s.name=t,s.line=n}classDeclaration(e){let t={type:"class",name:"",line:0,annotations:[],endpoints:[]};this.contextStack.push(t);for(let i of e.classModifier||[])this.visit(i);let n=t.annotations.find(i=>i.name==="RequestMapping");if(n){let i=n.attributes.get("value")||n.attributes.get("path");i&&typeof i=="string"&&(t.basePath=i.replace(/^['\"]|['\"]$/g,""))}for(let i of e.normalClassDeclaration||[])this.visit(i);if(this.contextStack.pop(),t.annotations.some(i=>i.name==="RestController"||i.name==="Controller")){let i={name:t.name,basePath:t.basePath||"",file:"",line:t.line,endpoints:t.endpoints};this.controllers.push(i)}}methodDeclarator(e){if(this.contextStack.length===0)return;let t=e.Identifier[0].image,n=e.Identifier[0].startLine,s=this.contextStack[this.contextStack.length-1];s.name=t,s.line=n}methodDeclaration(e){if(this.contextStack.length===0||this.contextStack[this.contextStack.length-1].type!=="class")return;let t=this.contextStack[this.contextStack.length-1],n={type:"method",name:"",line:0,annotations:[]};this.contextStack.push(n);for(let i of e.methodHeader||[])this.visit(i);for(let i of e.methodModifier||[])this.visit(i);this.contextStack.pop();let s=n.annotations.filter(i=>/Mapping$/.test(i.name));if(s.length!==0)for(let i of s){let o=this.buildEndpoint(i,n,e,t);o&&t.endpoints.push(o)}}collectTokens(e){if(!e)return[];if(e.image!==void 0)return[e];let t=[];if(e.children)for(let n of Object.keys(e.children))for(let s of e.children[n])t.push(...this.collectTokens(s));return t.sort((n,s)=>n.startOffset-s.startOffset),t}extractElementValue(e){if(!e)return;let t=e.children;if(t){if(t.annotation){let n=this.collectTokens(t.annotation[0]);if(n.length>0)return n.map(s=>s.image).join("")}if(t.elementValueArrayInitializer){let s=t.elementValueArrayInitializer[0].children?.elementValueList?.[0]?.children?.elementValue;return s?s.map(o=>{let a=this.extractElementValue(o);return Array.isArray(a)?a.join(","):a}).filter(o=>typeof o=="string"&&o.length>0):[]}if(t.conditionalExpression){let n=this.collectTokens(t.conditionalExpression[0]);return n.length===0?void 0:n.map(s=>s.image).join("")}}}buildEndpoint(e,t,n,s){let i=e.name.replace("Mapping","").toUpperCase();i==="REQUEST"&&(i="");let o="",a=[],c=[];for(let[m,f]of e.attributes.entries())if(m==="value"||m==="path")typeof f=="string"&&(o=f.replace(/^['\"]|['\"]$/g,""));else if(m==="consumes")Array.isArray(f)?a=Ai(f.map(h=>h.replace(/^['\"]|['\"]$/g,""))):typeof f=="string"&&(a=Ai([f.replace(/^['\"]|['\"]$/g,"")]));else if(m==="produces")Array.isArray(f)?c=f.map(h=>h.replace(/^['\"]|['\"]$/g,"")):typeof f=="string"&&(c=[f.replace(/^['\"]|['\"]$/g,"")]);else if(m==="method"&&e.name==="RequestMapping"&&typeof f=="string"){let h=f.match(/RequestMethod\.([A-Z]+)/);h&&(i=h[1])}!i&&e.name==="RequestMapping"&&(i="GET");let l=o;s.basePath&&(l&&!l.startsWith("/")?l=s.basePath+"/"+l:l=s.basePath+l),l&&!l.startsWith("/")&&(l="/"+l);let u=this.extractParameters(n),d=this.extractReturnType(n),p=this.extractOpenApiAnnotations(t.annotations,s.annotations);return{method:i,path:l,file:"",line:t.line,pathParams:tu(l),consumes:a,produces:c.length>0?c:void 0,headers:u.headers,queryParams:u.queryParams,hasBody:u.hasBody,bodyType:u.bodyType,formParts:u.formParts.length>0?u.formParts:void 0,modelAttributeType:u.modelAttributeType,returnType:d||void 0,summary:p.summary,description:p.description,operationId:p.operationId,tags:p.tags.length>0?p.tags:void 0,deprecated:p.deprecated||void 0,responses:p.responses.length>0?p.responses:void 0,parameterMeta:u.parameterMeta.length>0?u.parameterMeta:void 0,security:p.security.length>0?p.security:void 0}}extractOpenApiAnnotations(e,t){let n,s,i,o=[],a=!1,c=[],l=[];for(let u of t)if(u.name==="Tag"){let d=this.getAnnotationAttrString(u,"name");d&&o.push(d)}for(let u of e)switch(u.name){case"Operation":{n=this.getAnnotationAttrString(u,"summary")||n,s=this.getAnnotationAttrString(u,"description")||s,i=this.getAnnotationAttrString(u,"operationId")||i;let d=u.attributes.get("deprecated");typeof d=="string"&&d==="true"&&(a=!0);let p=u.attributes.get("tags");if(Array.isArray(p))p.forEach(m=>{let f=m.replace(/^['"]|['"]$/g,"");f&&o.push(f)});else if(typeof p=="string"){let m=p.replace(/^['"]|['"]$/g,"");m&&o.push(m)}break}case"ApiOperation":{n=this.getAnnotationAttrString(u,"value")||n,s=this.getAnnotationAttrString(u,"notes")||s;let d=u.attributes.get("tags");Array.isArray(d)&&d.forEach(p=>{let m=p.replace(/^['"]|['"]$/g,"");m&&o.push(m)});break}case"Tag":{let d=this.getAnnotationAttrString(u,"name");d&&o.push(d);break}case"Deprecated":{a=!0;break}case"ApiResponse":{let d=this.parseApiResponse(u);d&&c.push(d);break}case"ApiResponses":break;case"SecurityRequirement":{let d=this.getAnnotationAttrString(u,"name");d&&l.push(d);break}}return{summary:n,description:s,operationId:i,tags:[...new Set(o)],deprecated:a,responses:c,security:l}}parseApiResponse(e){let t=this.getAnnotationAttrString(e,"responseCode")||this.getAnnotationAttrString(e,"code")||"200",n=this.getAnnotationAttrString(e,"description"),s=this.getAnnotationAttrRaw(e,"content"),i=s?this.extractAttrFromRaw(s,"mediaType"):void 0,o=s?this.extractImplementationType(s):this.extractImplementationType(this.getAnnotationAttrRaw(e,"schema")),a=s?this.extractExampleObjects(s):void 0,c=this.getAnnotationAttrRaw(e,"headers"),l=c?this.extractHeaderObjects(c):void 0;return{statusCode:t,description:n,...i&&{contentType:i},...o&&{schemaType:o},...a&&Object.keys(a).length>0&&{examples:a},...l&&Object.keys(l).length>0&&{headers:l}}}getAnnotationAttrRaw(e,t){let n=e.attributes.get(t);if(typeof n=="string")return n;if(Array.isArray(n))return n.join(",")}extractAttrFromRaw(e,t){let n=new RegExp(`${t}\\s*=\\s*(["'])(.*?)\\1`);return e.match(n)?.[2]}extractImplementationType(e){if(!e)return;let t=e.match(/implementation\s*=\s*([A-Za-z0-9_$.<>?]+)\.class/);if(!t?.[1])return;let n=t[1];return n=n.split(".").pop()||n,Gt(n)}extractExampleObjects(e){let t={},n=e.match(/@ExampleObject\(([^)]*)\)/g)||[],s=1;for(let i of n){let a=(i.match(/name\s*=\s*"((?:\\.|[^"\\])*)"/)?.[1]||this.extractAttrFromRaw(i,"name")||`example${s++}`).replace(/\\"/g,'"').replace(/\\\\/g,"\\"),c=i.match(/value\s*=\s*"((?:\\.|[^"\\])*)"/),l=c?.[1]?c[1].replace(/\\"/g,'"').replace(/\\\\/g,"\\"):this.extractAttrFromRaw(i,"value");if(!l)continue;let u=this.parseExampleValue(l);t[a]=u}return Object.keys(t).length>0?t:void 0}extractHeaderObjects(e){let t={},n=e.match(/@Header\(([^)]*)\)/g)||[];for(let s of n){let i=this.extractAttrFromRaw(s,"name")||this.extractAttrFromRaw(s,"value");if(!i)continue;let o={},a=this.extractAttrFromRaw(s,"description");a&&(o.description=a);let c=this.extractAttrFromRaw(s,"format");c&&(o.format=c);let l=s.match(/required\s*=\s*(true|false)/)?.[1];l&&(o.required=l==="true");let u=s.match(/deprecated\s*=\s*(true|false)/)?.[1];u&&(o.deprecated=u==="true");let d=this.extractAttrFromRaw(s,"type")||this.extractImplementationType(s);d&&(o.schemaType=d),t[i]=o}return Object.keys(t).length>0?t:void 0}parseExampleValue(e){let t=e.trim();if(!t)return"";if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return t}return t}getAnnotationAttrString(e,t){let n=e.attributes.get(t);if(typeof n=="string")return n.replace(/^['"]|['"]$/g,"")||void 0}extractReturnType(e){let t=e.methodHeader?.[0]?.children?.result?.[0];if(!t)return"";if(t.children?.Void)return"void";let n=t.children?.unannType?.[0];if(!n)return"";let s=this.extractUnannTypeName(n);return Gt(s)}extractParameters(e){let t=[],n=[],s=[],i=[],o=!1,a,c,l=e.methodHeader?.[0]?.children?.methodDeclarator?.[0]?.children?.formalParameterList?.[0]?.children?.formalParameter;if(!l)return{headers:t,queryParams:n,hasBody:o,bodyType:a,formParts:s,modelAttributeType:c,parameterMeta:i};for(let u of l){let d=u.children?.variableParaRegularParameter?.[0]?.children;if(!d)continue;let p=d.variableDeclaratorId?.[0]?.children?.Identifier?.[0]?.image||"",m=d.variableModifier||[],f=this.collectAnnotationsFromModifiers(m),h=d.unannType?.[0],g=h?this.extractUnannTypeName(h):"",v=f.find(b=>b.name==="Parameter"),y;for(let b of f)if(b.name==="RequestHeader"){let C=this.getAnnotationStringValue(b)||p;t.push(C),y=this.buildParameterMeta(C,"header",g,v,f);let w=b.attributes.get("required");y&&typeof w=="string"&&(w==="true"||w==="false")&&(y.required=w==="true")}else if(b.name==="RequestParam")if(es(g)){o=!0;let C=this.getAnnotationStringValue(b)||p;s.push({name:C,type:g,isFile:!0})}else{let C=this.getAnnotationStringValue(b)||p;n.push(C);let w=b.attributes.get("required");y=this.buildParameterMeta(C,"query",g,v,f),y&&typeof w=="string"&&(w==="true"||w==="false")&&(y.required=w==="true")}else if(b.name==="RequestBody")o=!0,g&&(a=Gt(g));else if(b.name==="RequestPart"){o=!0;let C=this.getAnnotationStringValue(b)||p,w=es(g);s.push({name:C,type:g,isFile:w})}else b.name==="ModelAttribute"&&(o=!0,g&&(c=g));let S=f.find(b=>b.name==="PathVariable");if(S){let b=this.getAnnotationStringValue(S)||p;y=this.buildParameterMeta(b,"path",g,v,f)}y&&i.push(y)}return{headers:t,queryParams:n,hasBody:o,bodyType:a,formParts:s,modelAttributeType:c,parameterMeta:i}}buildParameterMeta(e,t,n,s,i){let o={name:e,in:t};if(s){let a=this.getAnnotationAttrString(s,"description");a&&(o.description=a);let c=this.getAnnotationAttrString(s,"example");c&&(o.example=c);let l=s.attributes.get("required");typeof l=="string"&&(l==="true"||l==="false")&&(o.required=l==="true");let u=s.attributes.get("deprecated");typeof u=="string"&&u==="true"&&(o.deprecated=!0)}return n&&(o.schemaType=n),i&&this.extractConstraintAnnotations(o,i),o}extractConstraintAnnotations(e,t){for(let n of t)switch(n.name){case"Schema":{let s=this.getAnnotationAttrString(n,"pattern");s&&!e.pattern&&(e.pattern=s);let i=this.getAnnotationAttrString(n,"format");i&&!e.format&&(e.format=i);let o=this.getAnnotationAttrString(n,"minimum");o&&e.minimum===void 0&&(e.minimum=Number(o));let a=this.getAnnotationAttrString(n,"maximum");a&&e.maximum===void 0&&(e.maximum=Number(a));let c=this.getAnnotationAttrString(n,"minLength");c&&e.minLength===void 0&&(e.minLength=Number(c));let l=this.getAnnotationAttrString(n,"maxLength");l&&e.maxLength===void 0&&(e.maxLength=Number(l));let u=n.attributes.get("allowableValues");Array.isArray(u)&&!e.enum&&(e.enum=u.map(d=>d.replace(/^['"]|['"]$/g,"")).filter(Boolean));break}case"Pattern":{let s=this.getAnnotationAttrString(n,"regexp");s&&!e.pattern&&(e.pattern=s);break}case"Size":{let s=this.getAnnotationAttrString(n,"min");s&&e.minLength===void 0&&(e.minLength=Number(s));let i=this.getAnnotationAttrString(n,"max");i&&e.maxLength===void 0&&(e.maxLength=Number(i));break}case"Min":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n);s&&e.minimum===void 0&&(e.minimum=Number(s));break}case"Max":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n);s&&e.maximum===void 0&&(e.maximum=Number(s));break}case"DecimalMin":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n),i=this.getAnnotationAttrString(n,"inclusive");s&&(i==="false"?e.exclusiveMinimum===void 0&&(e.exclusiveMinimum=Number(s)):e.minimum===void 0&&(e.minimum=Number(s)));break}case"DecimalMax":{let s=this.getAnnotationAttrString(n,"value")||this.getAnnotationStringValue(n),i=this.getAnnotationAttrString(n,"inclusive");s&&(i==="false"?e.exclusiveMaximum===void 0&&(e.exclusiveMaximum=Number(s)):e.maximum===void 0&&(e.maximum=Number(s)));break}case"Email":{e.format||(e.format="email");break}case"Positive":{e.exclusiveMinimum===void 0&&(e.exclusiveMinimum=0);break}case"PositiveOrZero":{e.minimum===void 0&&(e.minimum=0);break}case"Negative":{e.exclusiveMaximum===void 0&&(e.exclusiveMaximum=0);break}case"NegativeOrZero":{e.maximum===void 0&&(e.maximum=0);break}case"NotNull":case"NotBlank":case"NotEmpty":{e.required===void 0&&(e.required=!0);break}}}getAnnotationStringValue(e){let t=e.attributes.get("value");return typeof t=="string"?t.replace(/^['"]|['"]$/g,""):""}extractUnannTypeName(e){return this.collectTokens(e).map(n=>n.image).join("")}collectAnnotationsFromModifiers(e){let t=[];for(let n of e){let s=n.children?.annotation;if(!s)continue;let i=s[0].children,o=i.typeName[0].children.Identifier[0].image,a=new Map;if(i.elementValuePairList){let c=i.elementValuePairList[0].children.elementValuePair;for(let l of c){let u=l.children.Identifier[0].image,d=this.extractElementValue(l.children.elementValue[0]);d!==void 0&&a.set(u,d)}}else if(i.elementValue){let c=this.extractElementValue(i.elementValue[0]);c!==void 0&&a.set("value",c)}t.push({name:o,attributes:a})}return t}extractTypeName(e){if(!e)return"";if(e.primitiveType)return e.primitiveType[0].children?.literal?.[0]?.image||"";if(e.classOrInterfaceType){let t=e.classOrInterfaceType[0],n="",s=t.Identifier||[];for(let o=0;o<s.length;o++)o>0&&(n+="."),n+=s[o].image;let i=t.typeArguments?.[0]?.typeArgument;return i&&(n+="<",n+=i.map(o=>o.typeType?this.extractTypeName(o.typeType[0]):"?").join(","),n+=">"),n}if(e.typeType&&e.dims){let t=this.extractTypeName(e.typeType[0]),n=e.dims.length;return t+"[]".repeat(n)}return""}}});var Ff={};nc(Ff,{EndpointParser:()=>nu});import{parse as Uv}from"java-parser";var nu,Nf=k(()=>{"use strict";ga();ya();$f();nu=class r{fileCache=new Map;generatedRe=/_[0-9a-zA-Z]+\.java$/;clearCache(){this.fileCache.clear()}evictPaths(e){let t=e.map(n=>Xl(n.trim()));for(let n of[...this.fileCache.keys()]){let s=Xl(n);t.some(i=>s.startsWith(i+"/"))&&this.fileCache.delete(n)}}async parseControllers(e){let t=Ei(e),n=[],s=new Set,i=[];for(let a of t)if(!this.generatedRe.test(eu(a))&&!s.has(a)){if(s.add(a),this.fileCache.has(a)){n.push(...this.fileCache.get(a));continue}i.push(a)}let o=30;for(let a=0;a<i.length;a+=o){let c=i.slice(a,a+o),l=await Promise.all(c.map(u=>this.parseFile(u).then(d=>({filePath:u,ctrls:d})).catch(()=>({filePath:u,ctrls:[]}))));for(let{filePath:u,ctrls:d}of l)this.fileCache.set(u,d),n.push(...d)}for(let a of this.fileCache.keys())s.has(a)||this.fileCache.delete(a);return n}removeFile(e){this.fileCache.delete(e)}static CONTROLLER_HINT_RE=/@(?:RestController|Controller)\b|@(?:Request|Get|Post|Put|Delete|Patch)Mapping\b/;looksLikeController(e){return r.CONTROLLER_HINT_RE.test(e)}async parseFile(e){let t=await qi(e);if(!this.looksLikeController(t))return[];let n=this.parseWithAst(t);if(n){for(let s of n){s.file=e;for(let i of s.endpoints)i.file=e}return n}return this.parseWithRegex(t,e)}async findEndpoints(e){return(await this.parseControllers(e)).flatMap(n=>n.endpoints)}parseWithAst(e){try{let t=Uv(e),n=new va;if(n.visit(t),n.controllers.length>0){for(let s of n.controllers){let i=new Set;s.endpoints=s.endpoints.filter(o=>{let a=`${o.method}:${o.path}:${o.line}`;return i.has(a)?!1:(i.add(a),!0)})}return n.controllers}return null}catch{return null}}parseWithRegex(e,t){let n=[],s=e.split(/\r?\n/),i=[],o=new Map,a=null,c=0,l=!1;for(let u=0;u<s.length;u++){let d=s[u],p=d.trim(),m=/^@(\w+)\s*(?:\(([^)]*)\))?/.exec(p);if(m&&!/\b(class|interface|enum)\b/.test(p)&&(i.push(m[1]),m[2]!==void 0&&o.set(m[1],m[2]),!/(private|public|protected|static|final|void|class)\b/.test(p)))continue;let f=/\bclass\s+(\w+)/.exec(p);if(f){if(a&&(this.deduplicateEndpoints(a),n.push(a),a=null),i.some(y=>y==="RestController"||y==="Controller")){let y="",S=o.get("RequestMapping");S!==void 0&&(y=this.extractPathFromArgs(S)),a={name:f[1],basePath:y,file:t,line:u+1,endpoints:[]}}l=!0,c=0,c+=(d.match(/\{/g)||[]).length,c-=(d.match(/\}/g)||[]).length,i=[],o=new Map;continue}if(l&&(c+=(d.match(/\{/g)||[]).length,c-=(d.match(/\}/g)||[]).length,c<=0)){l=!1,a&&(this.deduplicateEndpoints(a),n.push(a),a=null),i=[],o=new Map;continue}if(!a){m||(i=[],o=new Map);continue}let h=i.find(v=>/Mapping$/.test(v)),g=/^@(GetMapping|PostMapping|PutMapping|DeleteMapping|PatchMapping|RequestMapping)\s*(?:\(([^)]*)\))?/.exec(p);if(h||g){let v=u,y=this.collectMethodSignature(s,v),S=[];g&&S.push({name:g[1],args:g[2]||""});for(let b of i)/Mapping$/.test(b)&&(!g||b!==g[1])&&S.push({name:b,args:o.get(b)||""});for(let b of S){let C=b.name.replace("Mapping","").toUpperCase();C==="REQUEST"&&(C="");let w="",E=[],F=b.args;if(F){w=this.extractPathFromArgs(F);let O=/consumes\s*=\s*\{?\s*([^}]*)\}?/.exec(F);if(O){let D=O[1],P=[...D.matchAll(/["']([^"']+)["']/g)].map(G=>G[1]),M=[...D.matchAll(/MediaType\.([A-Z_]+)/g)].map(G=>`MediaType.${G[1]}`);E=Ai([...P,...M])}if(b.name==="RequestMapping"){let D=/method\s*=\s*(?:\{?\s*)?RequestMethod\.([A-Z]+)/.exec(F);D&&(C=D[1])}}!C&&b.name==="RequestMapping"&&(C="GET");let N=w;a.basePath&&(N&&!N.startsWith("/")?N=a.basePath+"/"+N:N=a.basePath+N),N&&!N.startsWith("/")&&(N="/"+N);let j=this.extractParameterMetadataFromSig(y);a.endpoints.push({method:C,path:N,file:t,line:u+1,pathParams:tu(N),consumes:E,bodyType:j.bodyType,headers:j.headers,queryParams:j.queryParams,hasBody:j.hasBody,formParts:j.formParts.length>0?j.formParts:void 0,modelAttributeType:j.modelAttributeType})}i=[],o=new Map;continue}m||(i=[],o=new Map)}return a&&(this.deduplicateEndpoints(a),n.push(a)),n}extractPathFromArgs(e){let t=/(?:value|path)\s*=\s*["']([^"']+)["']/.exec(e);if(t)return t[1];let n=/^\s*["']([^"']+)["']/.exec(e);return n?n[1]:""}collectMethodSignature(e,t){let n="";for(let s=t;s<e.length&&(n+=e[s]+" ",!e[s].includes("{"));s++);return n}extractParameterMetadataFromSig(e){let t=[],n=[],s=[],i=!1,o,a,c=/@RequestHeader\s*(?:\(\s*(?:(?:value|name)\s*=\s*)?["']([^"']+)["']\s*\))?\s+(?:[A-Za-z0-9_<>\[\]]+)\s+(\w+)/g,l;for(;(l=c.exec(e))!==null;)t.push(l[1]||l[2]);let u=/@RequestParam\s*(?:\(\s*(?:(?:value|name)\s*=\s*)?["']([^"']+)["']\s*\))?\s+([A-Za-z0-9_<>\[\]]+)\s+(\w+)/g;for(;(l=u.exec(e))!==null;){let g=l[2];if(es(g)){i=!0;let v=l[1]||l[3];s.push({name:v,type:g,isFile:!0})}else n.push(l[1]||l[3])}let p=/@RequestBody\s+([A-Za-z0-9_<>\[\]]+)\s+\w+/.exec(e);p?(i=!0,o=Gt(p[1])):/@RequestBody/.test(e)&&(i=!0);let m=/@RequestPart\s*(?:\(\s*(?:(?:value|name)\s*=\s*)?["']([^"']+)["']\s*\))?\s+([A-Za-z0-9_<>\[\]]+)\s+(\w+)/g;for(;(l=m.exec(e))!==null;){i=!0;let g=l[1]||l[3],v=l[2],y=es(v);s.push({name:g,type:v,isFile:y})}let h=/@ModelAttribute\s+([A-Za-z0-9_<>\[\]]+)\s+\w+/.exec(e);return h?(i=!0,a=h[1]):/@ModelAttribute/.test(e)&&(i=!0),{headers:t,queryParams:n,hasBody:i,bodyType:o,formParts:s,modelAttributeType:a}}deduplicateEndpoints(e){let t=new Set;e.endpoints=e.endpoints.filter(n=>{let s=`${n.method}:${n.path}:${n.line}`;return t.has(s)?!1:(t.add(s),!0)})}}});import*as ba from"fs";import*as _f from"path";function Jv(r){let e=[];for(let t of r.parameterMeta??[]){let n=[];t.required&&n.push("required"),t.pattern&&n.push(`pattern=${t.pattern}`),t.format&&n.push(`format=${t.format}`),t.enum&&t.enum.length>0&&n.push(`enum=[${t.enum.join(", ")}]`),t.minimum!==void 0&&n.push(`min=${t.minimum}`),t.maximum!==void 0&&n.push(`max=${t.maximum}`),t.exclusiveMinimum!==void 0&&n.push(`exclusiveMin=${t.exclusiveMinimum}`),t.exclusiveMaximum!==void 0&&n.push(`exclusiveMax=${t.exclusiveMaximum}`),t.minLength!==void 0&&n.push(`minLength=${t.minLength}`),t.maxLength!==void 0&&n.push(`maxLength=${t.maxLength}`),n.length>0&&e.push(`${t.in==="header"?"header":t.in} ${t.name}: ${n.join(", ")}`)}return e.length>0?e:void 0}var Vv,zv,Rn,ru=k(()=>{"use strict";ga();Of();Vv=["pom.xml","build.gradle","build.gradle.kts","settings.gradle"],zv=/@(?:RestController|Controller)\b/,Rn=class{id="provider.spring";framework="spring";parserModule;supports(e){for(let s of Vv)if(ba.existsSync(_f.join(e.projectRoot,s)))return{supported:!0,confidence:.95,reasons:[`${s} detected`]};let t=e.sourceFiles?.filter(s=>s.endsWith(".java"))??[];t.length===0&&(t=Ei(e.projectRoot));let n=0;for(let s of t)if(s.endsWith(".java")){if(n>=40)break;n+=1;try{let i=ba.readFileSync(s,"utf-8");if(zv.test(i))return{supported:!0,confidence:.8,reasons:["Spring controller annotation found"]}}catch{continue}}return{supported:!1,confidence:0,reasons:["no Spring indicators found"]}}async discover(e,t){let n=Date.now(),s=[],i=t.projectRoot,o=await this.loadParser(),a=new o.EndpointParser,c=[];try{c=await a.parseControllers(i)}catch(d){let p=d instanceof Error?d.message:String(d);s.push({code:"provider-failed",framework:"spring",message:`Spring discovery failed for ${i}: ${p}`})}let l=new ir(i),u=[];for(let d of c)for(let p of d.endpoints)u.push(await this.endpointToDiscoveredApi(p,l));return{endpoints:u,warnings:s,stats:{frameworksDetected:["spring"],providersRun:[this.id],endpointCount:u.length,unresolvedEndpointCount:u.filter(d=>!d.resolvedPath).length,scanDurationMs:Date.now()-n}}}clearCache(){this.parserModule=void 0}async loadParser(){return this.parserModule||(this.parserModule=await Promise.resolve().then(()=>(Nf(),Ff))),this.parserModule}async endpointToDiscoveredApi(e,t){let n=await this.buildParams(e,t),s=await this.buildRequestBody(e,t),i=await this.buildResponses(e,t),o=e.security&&e.security.length>0?{required:!0,type:"oauth2",annotation:e.security.join(", ")}:void 0,a=e.line>0?e.line:1;return{id:"",framework:"spring",method:e.method||"GET",pathExpression:e.path||"/",resolvedPath:e.path||"/",confidence:"high",source:{filePath:e.file,line:a,symbolName:`${e.method||"GET"} ${e.path||"/"}`},params:n.length>0?n:void 0,requestBody:s,responses:i,validation:Jv(e),auth:o,tags:e.tags,deprecated:e.deprecated,description:e.summary||e.description}}async buildParams(e,t){let n=[],s=(e.consumes??[]).join(" "),i=s.includes("x-www-form-urlencoded"),o=s.includes("multipart");for(let a of e.headers??[])n.push(this.paramFromMeta(a,"header",e.parameterMeta,!0));for(let a of e.queryParams??[]){let c=i||o?"form":"query",l=e.parameterMeta?.find(u=>u.name===a&&u.in==="query");n.push(this.paramFromMeta(a,c,e.parameterMeta,l?.required))}for(let a of e.formParts??[])n.push({name:a.name,location:"form",type:a.isFile?"file":"string",required:!0});return n}paramFromMeta(e,t,n,s){let i=n?.find(a=>a.name===e&&(a.in===t||t==="form"&&a.in==="query")),o={name:e,location:t};return i&&(o.description=i.description,o.required=i.required??s,o.example=i.example,i.schemaType&&(o.type=ir.javaTypeToParamType(i.schemaType)),o.schema=this.constraintsToSchema(i)),o.required=t==="path"?!0:o.required,o.type=o.type??"string",o}constraintsToSchema(e){let t={};if(e.schemaType){t.type=ir.javaTypeToParamType(e.schemaType);let n=ir.javaTypeToFormat(e.schemaType);n&&(t.format=n)}return e.pattern&&(t.pattern=e.pattern),e.format&&(t.format=e.format),e.enum&&e.enum.length>0&&(t.enum=e.enum),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.exclusiveMinimum!==void 0&&(t.exclusiveMinimum=e.exclusiveMinimum),e.exclusiveMaximum!==void 0&&(t.exclusiveMaximum=e.exclusiveMaximum),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),Object.keys(t).length>0?t:void 0}async buildRequestBody(e,t){let n=e.consumes??[];if(e.formParts&&e.formParts.length>0)return{type:"multipart",required:e.method==="POST"||e.method==="PUT"||e.method==="PATCH"};if(e.modelAttributeType)return{type:"form",required:!0,schema:await this.maybeSchema(t,e.modelAttributeType)};if(n.some(a=>a.includes("x-www-form-urlencoded"))&&(e.queryParams?.length??0)>0)return{type:"form",required:e.method==="POST"||e.method==="PUT"||e.method==="PATCH"};if(!e.hasBody)return;let s=e.bodyType??e.modelAttributeType;if(!s)return{type:"json",required:!0};let i=n.some(a=>a.includes("x-www-form-urlencoded"))?"form":n.some(a=>a.includes("multipart"))?"multipart":"json",o=await this.maybeSchema(t,s);return{type:i,required:!0,schema:o}}async buildResponses(e,t){let n=[];for(let s of e.responses??[]){let i={statusCode:parseInt(s.statusCode,10)||200},o=s.schemaType?await this.maybeSchema(t,s.schemaType):void 0;i.body={type:s.contentType??"json"},o&&(i.body.schema=o),n.push(i)}if(n.length===0){let s=e.returnType;if(s&&s!=="void"){let i=await t.generateResponseSchema(s);n.push({statusCode:200,body:{type:"json",schema:i??{type:"object"}}})}else n.push({statusCode:200})}return n}async maybeSchema(e,t){return await e.generate(t)??{type:"object"}}}});import*as xa from"fs";import*as Hf from"path";function su(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=xa.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=Hf.join(n,i.name);if(i.isDirectory()){Wv.has(i.name)||t.push(o);continue}i.isFile()&&o.endsWith(".py")&&e.push(o)}}return e.sort()}function Bf(r){let e=su(r),t=new Map,n=new Map,s=new Map,i=[];for(let u of e){let d="";try{d=xa.readFileSync(u,"utf-8")}catch{continue}let p=Kv(d,u,t);n.set(u,p);for(let m of p.routers)s.has(m.name)||s.set(m.name,m)}let o=new Map;for(let u of s.values())o.set(u.name,[u.constructorPrefix]);let a=new Map,c=new Set;for(let u of n.values())for(let d of u.includes){let p=Mf(u.imports,d.routerName);if(!s.has(p)){i.push(`include_router references unknown router '${d.routerName}' at ${d.line}`);continue}let m=s.get(p);if(d.prefix){c.add(p);let f=o.get(p),h=`${d.prefix.replace(/\/+$/,"")}/${m.constructorPrefix.replace(/^\/+/,"")}`;f.includes(h)||f.push(h)}d.tags&&d.tags.length>0&&a.set(p,[...a.get(p)??[],...d.tags])}let l=[];for(let[u,d]of n.entries())for(let p of d.routes)for(let m of p.decorators){let f=Mf(d.imports,m.object),h=d.appNames.has(m.object)||d.appNames.has(f),g=s.get(f);if(!h&&!g)continue;let v=eb(m.method,m.args);if(v.length===0)continue;let y=tb(m.args),S=m.unresolved||y.startsWith("f"),b=g?o.get(f)??[g.constructorPrefix]:[""];for(let C of b){if(g&&c.has(f)&&C===g.constructorPrefix)continue;let w=g?cb(C,y):y,E=lb(p.signature,ab(w)),F=g?a.get(f):void 0,j=Uf(m.args)??F;l.push({methods:v,path:w,file:u,line:m.line,functionName:p.functionName,statusCode:nb(m.args),responseModel:rb(m.args)??Yv(p.signature),tags:j,deprecated:sb(m.args),summary:ib(m.args),params:E.params,security:ob(m.args,p.signature),pathUnresolved:S})}}return{endpoints:l,models:t,warnings:i}}function Mf(r,e){let t=r.find(n=>n.alias===e);return t?t.target:e}function Kt(r,e){let t=r.trim();if(!t||t==="None")return;let n=/^(?:Optional|Union)\[([^\]]*)\](?:\s*\|\s*None)?$/.exec(t)||/^(.+?)(?:\s*\|\s*None)+$/.exec(t);if(n)return Kt(n[1],e);let s=/^Union\[(.+)\]$/.exec(t);if(s){let l=s[1].split(",").map(u=>u.trim())[0];return Kt(l,e)}let i=/^(?:List|list|Sequence)\[(.+)\]$/.exec(t);if(i)return{type:"array",items:Kt(i[1],e)??{type:"object"}};let o=/^(?:Dict|dict)\[([^,]+),\s*(.+)\]$/.exec(t);if(o)return{type:"object",additionalProperties:Kt(o[2],e)??{}};let a={int:{type:"integer"},float:{type:"number"},Decimal:{type:"number"},bool:{type:"boolean"},str:{type:"string"},datetime:{type:"string",format:"date-time"},date:{type:"string",format:"date"},time:{type:"string",format:"time"},UUID:{type:"string",format:"uuid"},bytes:{type:"string",format:"binary"},UploadFile:{type:"string",format:"binary"}};if(t in a)return{...a[t]};let c=e.get(t);if(c){let l={},u=[];for(let p of c.fields){let m=Kt(p.type,e)??{type:"string"};l[p.name]=p.description?{...m,description:p.description}:m,p.required&&u.push(p.name)}let d={type:"object",properties:l};return u.length>0&&(d.required=u),d}return{type:"object"}}function Kv(r,e,t){let n={routes:[],appNames:new Set,routers:[],includes:[],imports:[]},i=pb(r).split(/\r?\n/),o=[],a=0;for(;a<i.length;){let c=i[a],l=a+1,u=c.trim();if(a+=1,u==="")continue;let d=/^from\s+[\w.]+(?:\s+import\s+(.+))?$/.exec(u)||/^import\s+([\w.,\s]+)$/.exec(u);if(d){let v=d[1]??"";for(let y of v.split(",")){let S=y.trim();if(!S)continue;let b=/^([\w.]+)\s+as\s+(\w+)$/.exec(S);if(b)n.imports.push({alias:b[2],target:b[1].split(".").pop()});else if(/^[\w.]+$/.test(S)){let C=S.split(".").pop();n.imports.push({alias:C,target:C})}}o=[];continue}if(u.startsWith("@")){let{joined:v,nextIndex:y}=Sa(i,a-1),S=Xv(v,l);S&&o.push(S),a=y+1;continue}let p=/^(?:async\s+)?def\s+(\w+)\s*\(/.exec(u);if(p){let{joined:v,nextIndex:y}=Sa(i,a-1),S=v.slice(v.indexOf("(")),b=Zv(i,a-1,S);o.length>0&&n.routes.push({decorators:o,functionName:p[1],signature:b,line:l}),o=[],a=y+1;continue}let m=/^class\s+(\w+)\s*\(\s*(\w+)\s*\)\s*:/.exec(u);if(m&&(m[2]==="BaseModel"||m[2].endsWith("BaseModel"))){let{nextIndex:v,fields:y}=Qv(i,a);t.set(m[1],{name:m[1],fields:y}),a=v,o=[];continue}let f=/^(\w+)\s*=\s*(?:fastapi\.)?FastAPI\(/.exec(u);if(f){n.appNames.add(f[1]),o=[];continue}let h=/^(\w+)\s*=\s*(?:fastapi\.)?APIRouter\((.*)$/.exec(u);if(h){let{joined:v}=Sa(i,a-1),y=v.slice(v.indexOf("("));n.routers.push({name:h[1],constructorPrefix:Lf(y)}),o=[];continue}let g=/^(\w+)\.include_router\(\s*(\w+)(.*)$/.exec(u);if(g){let{joined:v}=Sa(i,a-1),y=v.slice(v.indexOf("("));n.includes.push({object:g[1],routerName:g[2],prefix:Lf(y),tags:Uf(y),line:l}),o=[];continue}o=[]}return n}function Qv(r,e){let t=[],n=e,s=(r[e-1]||"").match(/^(\s*)/)[1].length;for(;n<r.length;){let i=r[n];if(i.trim()===""){n+=1;continue}if(i.match(/^(\s*)/)[1].length<=s)break;let a=i.trim();if(a.startsWith("#")){n+=1;continue}let c=/^([A-Za-z_]\w*)\s*:\s*(.+?)\s*(?:=\s*(.*))?$/.exec(a);if(c&&!a.startsWith("def ")&&!a.startsWith("class ")){let l=c[2].replace(/,\s*$/,""),u=(c[3]??"").trim(),d=/^Optional\[/.test(l)||/None\s*\|/.test(l)||u==="None"||u.startsWith("None")||u!==""&&!u.startsWith("Field("),p,m=/Field\(([^)]*)\)/.exec(a);if(m){let f=/description\s*=\s*["']([^"']+)["']/.exec(m[1]);f&&(p=f[1])}t.push({name:c[1],type:l,required:!d,description:p})}n+=1}return{nextIndex:n,fields:t}}function Sa(r,e){let t=0,n=r[e]??"",s=e,i=null,o=a=>{for(let c of a){if(i){c===i&&(i=null);continue}c==='"'||c==="'"?i=c:c==="("||c==="["||c==="{"?t+=1:(c===")"||c==="]"||c==="}")&&(t-=1)}};for(o(n);t>0&&s+1<r.length;){s+=1;let a=r[s];o(a),n+=`
|
|
831
|
+
`+a}return{joined:n,nextIndex:s}}function Zv(r,e,t){let n=0,s=null,i=t,o=e,a=l=>{for(let u of l){if(s){u===s&&(s=null);continue}u==='"'||u==="'"?s=u:u==="("||u==="["||u==="{"?n+=1:(u===")"||u==="]"||u==="}")&&(n-=1)}};for(a(t);n>0&&o+1<r.length;){o+=1;let l=r[o];a(l),i+=`
|
|
832
832
|
`+l}let c=jf(i);if(c!==-1)return i.slice(0,c);for(;o+1<r.length;){o+=1;let l=r[o],u=jf(l);if(u!==-1){i+=`
|
|
833
833
|
`+l.slice(0,u);break}i+=`
|
|
834
|
-
`+l}return i}function jf(r){let e=0,t=null;for(let n=0;n<r.length;n++){let s=r[n];if(t){s===t&&(t=null);continue}if(s==='"'||s==="'"){t=s;continue}if(s==="("||s==="["||s==="{"){e+=1;continue}if(s===")"||s==="]"||s==="}"){e-=1;continue}if(s===":"&&e===0)return n}return-1}function
|
|
835
|
-
`)}var
|
|
836
|
-
`)}function Pi(r,e,t=""){let n=(r.resolvedPath??r.pathExpression).replace(/^\/+/,""),s=t?`${t.replace(/\/+$/,"")}/${n}`:r.resolvedPath??r.pathExpression,{headers:i,query:o,params:a,body:c}=ar(r,!0);return{collectionId:e,name:or(r),method:r.method||"GET",url:s,headers:i,query:o,params:a,body:c,description:cr(r)}}var ou=k(()=>{"use strict"});import*as Ra from"fs";import*as Wf from"path";import{execSync as
|
|
834
|
+
`+l}return i}function jf(r){let e=0,t=null;for(let n=0;n<r.length;n++){let s=r[n];if(t){s===t&&(t=null);continue}if(s==='"'||s==="'"){t=s;continue}if(s==="("||s==="["||s==="{"){e+=1;continue}if(s===")"||s==="]"||s==="}"){e-=1;continue}if(s===":"&&e===0)return n}return-1}function Yv(r){let e=/->\s*([^:\n]+?)\s*$/.exec(r.trim());return e?e[1].trim():void 0}function Xv(r,e){let t=/^@([\w.]+)\.(\w+)\((.*)\)$/s.exec(r.trim());if(!t)return null;let n=t[1].split(".")[0],s=t[2];return{object:n,method:s,args:t[3]??"",line:e,unresolved:t[1].includes(".")&&t[1].split(".").length>2}}function eb(r,e){if(r==="api_route"){let n=/methods\s*=\s*\[([^\]]*)\]/.exec(e);if(n){let s=[...n[1].matchAll(/["']([^"']+)["']/g)].map(i=>i[1].toUpperCase());return s.length>0?s:["GET"]}return["GET"]}if(r==="route")return[];let t=Gv[r.toLowerCase()];return t?[t]:[]}function tb(r){let e=i=>{let o=i.exec(r);if(!o)return;let a=o[1].length>1?o[1][0]:"";return a==="f"||a==="F"?`f${o[2]}`:o[2]},t=e(/(?:path|url)\s*=\s*([fFrRbB]?["'])([^"']+)["']/);if(t!==void 0)return t;let n=e(/^\s*([fFrRbB]?["'])([^"']+)["']/);if(n!==void 0)return n;let s=/["']([^"']+)["']/.exec(r);return s?s[1]:""}function nb(r){let e=/status_code\s*=\s*(\d+)/.exec(r);return e?parseInt(e[1],10):void 0}function rb(r){let e=/response_model\s*=\s*([^\s,]+)/.exec(r);return e?e[1]:void 0}function Uf(r){let e=/tags\s*=\s*\[([^\]]*)\]/.exec(r);if(!e)return;let t=[...e[1].matchAll(/["']([^"']+)["']/g)].map(n=>n[1]);return t.length>0?t:void 0}function sb(r){return/deprecated\s*=\s*True/.test(r)?!0:void 0}function ib(r){let e=/summary\s*=\s*["']([^"']+)["']/.exec(r);return e?e[1]:void 0}function ob(r,e){let t=[],n=/dependencies\s*=\s*\[([^\]]*)\]/.exec(r);if(n)for(let i of n[1].split(",")){let o=/Depends\(([^)]+)\)/.exec(i);o&&t.push(o[1].trim())}let s=/:\s*Security\(([^)]+)\)/.exec(e);return s&&t.push(s[1].trim()),t}function Lf(r){let e=/prefix\s*=\s*["']([^"']+)["']/.exec(r);return e?e[1]:""}function ab(r){let e=[],t=/\{([^}:]+)(?::[^}]+)?\}/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]);return e}function cb(r,e){return e?r?`${r.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`:e.startsWith("/")?e:"/"+e:r||"/"}function lb(r,e){let t=[],n=new Set(e),s=r.indexOf("("),i=r.lastIndexOf(")");if(s===-1||i===-1)return{params:t};let o=r.slice(s+1,i),a=db(o,",");for(let c of a){let l=c.trim();if(!l)continue;let u=/^([A-Za-z_]\w*)\s*(?::\s*([^=\n]+))?(?:\s*=\s*(.*))?$/s.exec(l);if(!u)continue;let d=u[1],p=(u[2]??"").trim(),m=(u[3]??"").trim();if(Df.has(d))continue;let f=/^([A-Za-z_]\w*)/.exec(p)?.[1]??"";if(Df.has(f)||/Depends\(|Security\(/.test(m))continue;let h=/^(Path|Query|Header|Cookie|Body|File|Form)\b/.exec(m)?.[1],g;h==="Path"||n.has(d)?g="path":h==="Header"?g="header":h==="Cookie"?g="cookie":h==="Body"?g="body":h==="File"||h==="Form"||f==="UploadFile"?g="form":g="query",g==="query"&&n.has(d)&&(g="path");let v=ub(p,m);t.push({name:d,location:g,type:f||"str",required:!v})}for(let c of n)t.some(l=>l.name===c&&l.location==="path")||t.push({name:c,location:"path",type:"str",required:!0});return{params:t}}function ub(r,e){if(/^Optional\[/.test(r)||/None\s*\|/.test(r))return!0;if(e==="")return!1;if(e==="None")return!0;let t=/^(Path|Query|Header|Cookie|Body|File|Form)\((.*)\)$/s.exec(e);if(t){let n=t[2].trim();return n===""||n.startsWith("...")?!1:(n.startsWith("None")||/default\s*=\s*None\b/.test(n),!0)}return!0}function db(r,e){let t=[],n=0,s=null,i="";for(let o of r){if(s){i+=o,o===s&&(s=null);continue}if(o==='"'||o==="'"){s=o,i+=o;continue}if(o==="("||o==="["||o==="{"){n+=1,i+=o;continue}if(o===")"||o==="]"||o==="}"){n-=1,i+=o;continue}if(o===e&&n===0){t.push(i),i="";continue}i+=o}return i.trim()!==""&&t.push(i),t}function pb(r){return r.split(/\r?\n/).map(t=>{let n=null;for(let s=0;s<t.length;s++){let i=t[s];if(n){i===n&&(n=null);continue}if(i==='"'||i==="'")n=i;else if(i==="#"&&(s===0||t[s-1]!=="\\"))return t.slice(0,s)}return t}).join(`
|
|
835
|
+
`)}var Wv,Gv,Df,Vf=k(()=>{"use strict";Wv=new Set(["node_modules",".git",".venv","venv","env","__pycache__","site-packages",".mypy_cache",".pytest_cache",".tox","dist","build","out"]),Gv={get:"GET",post:"POST",put:"PUT",patch:"PATCH",delete:"DELETE",options:"OPTIONS",head:"HEAD"},Df=new Set(["Request","Response","WebSocket","BackgroundTasks","Depends","Header","Cookie"])});import*as wa from"fs";import*as zf from"path";function gb(r){return{int:"integer",float:"number",Decimal:"number",bool:"boolean",str:"string",datetime:"string",date:"string",time:"string",UUID:"string",bytes:"string",UploadFile:"string"}[r]}var fb,mb,hb,Cn,iu=k(()=>{"use strict";Vf();fb=["requirements.txt","pyproject.toml","poetry.lock","Pipfile","setup.py"],mb=/^\s*from\s+fastapi\s+import|^\s*import\s+fastapi/m,hb=/@[\w.]+\.(get|post|put|patch|delete|options|head|api_route)\(/,Cn=class{id="provider.fastapi";framework="fastapi";supports(e){for(let s of fb)if(wa.existsSync(zf.join(e.projectRoot,s)))return{supported:!0,confidence:.9,reasons:[`${s} detected`]};let t=e.sourceFiles?.filter(s=>s.endsWith(".py"))??[];t.length===0&&(t=su(e.projectRoot));let n=0;for(let s of t)if(s.endsWith(".py")){if(n>=60)break;n+=1;try{let i=wa.readFileSync(s,"utf-8");if(mb.test(i)&&hb.test(i))return{supported:!0,confidence:.9,reasons:["fastapi app decorator found"]}}catch{continue}}return{supported:!1,confidence:0,reasons:["no FastAPI indicators found"]}}async discover(e,t){let n=Date.now(),s=[],i=t.projectRoot,o;try{o=Bf(i)}catch(c){let l=c instanceof Error?c.message:String(c);return s.push({code:"provider-failed",framework:"fastapi",message:`FastAPI discovery failed for ${i}: ${l}`}),{endpoints:[],warnings:s,stats:{frameworksDetected:["fastapi"],providersRun:[this.id],endpointCount:0,unresolvedEndpointCount:0,scanDurationMs:Date.now()-n}}}for(let c of o.warnings)s.push({code:"dynamic-path-unresolved",framework:"fastapi",message:c});let a=o.endpoints.map(c=>this.endpointToDiscoveredApi(c,o.models));return{endpoints:a,warnings:s,stats:{frameworksDetected:["fastapi"],providersRun:[this.id],endpointCount:a.length,unresolvedEndpointCount:a.filter(c=>!c.resolvedPath).length,scanDurationMs:Date.now()-n}}}endpointToDiscoveredApi(e,t){let n=e.methods[0],s=e.pathUnresolved?"low":"high",i=e.params.map(l=>this.paramToDiscovered(l,t)),o=this.buildRequestBody(e,t),a=this.buildResponses(e,t),c=e.security.length>0?{required:!0,type:"jwt",annotation:e.security.join(", ")}:void 0;return{id:"",framework:"fastapi",method:n,pathExpression:e.path,resolvedPath:e.path,confidence:s,source:{filePath:e.file,line:e.line,symbolName:`${n} ${e.path}`},params:i.length>0?i:void 0,requestBody:o,responses:a,auth:c,tags:e.tags,deprecated:e.deprecated,description:e.summary}}paramToDiscovered(e,t){let n=gb(e.type),s=Kt(e.type,t)??(n?{type:n}:void 0),i={name:e.name,location:e.location,required:e.location==="path"?!0:e.required};return n&&(i.type=n),s&&(i.schema=s),i}buildRequestBody(e,t){let n=e.params.filter(i=>i.location==="body");if(n.length===0){let i=e.params.filter(o=>o.location==="form");return i.length>0?{type:"multipart",required:i.some(o=>o.required)}:void 0}let s=Kt(n[0].type,t);return{type:"json",required:n.some(i=>i.required),schema:s??{type:"object"}}}buildResponses(e,t){let s={statusCode:e.statusCode??200};if(e.responseModel){let i=/^(?:List|list|Sequence)\[/.test(e.responseModel),o=i?/^(?:List|list|Sequence)\[(.+)\]$/.exec(e.responseModel)[1]:e.responseModel,a=Kt(o,t);a&&(s.body={type:"json",schema:i?{type:"array",items:a}:a})}return[s]}}});function ts(r){if(!r||typeof r!="object")return null;let e=r.type;if(e==="object"||r.properties&&!e){let t=r.properties??{},n={};for(let[s,i]of Object.entries(t))n[s]=ts(i);return n}if(e==="array"){let t=r.items;return[ts(t)]}return e==="integer"||e==="number"?0:e==="boolean"?!1:e==="string"?r.format==="date-time"?"2024-01-01T00:00:00Z":r.format==="date"?"2024-01-01":r.format==="uuid"?"00000000-0000-0000-0000-000000000000":r.format==="binary"?"<file>":"string":r.enum&&Array.isArray(r.enum)&&r.enum.length>0?r.enum[0]:null}function or(r){let e=r.source?.symbolName||"";return e||`${r.method||"GET"} ${r.pathExpression}`}function ar(r,e){let t=[],n=[],s={};for(let o of r.params??[])o.location==="header"?t.push({name:o.name,value:e?o.example??"":"",enabled:!0}):o.location==="query"?n.push({name:o.name,value:e?o.example??"":"",enabled:!0}):o.location==="path"&&(s[o.name]=o.type==="integer"?"1":o.type==="number"?"1.0":o.example??"test");r.auth?.type==="bearer"||r.auth?.type==="jwt"?t.push({name:"Authorization",value:"Bearer {{TOKEN}}",enabled:!0}):r.auth?.type==="basic"&&t.push({name:"Authorization",value:"Basic {{BASIC_AUTH}}",enabled:!0});let i=yb(r,e);return{headers:t,query:n,params:s,body:i}}function yb(r,e){let t=r.requestBody;if(!t)return;let n=t.type??"json";if(n==="json"){let s=t.schema,i=e&&s?ts(s):void 0;return{type:"raw",format:"json",content:i?JSON.stringify(i,null,2):"{}"}}if(n==="form"||n==="multipart"){let s=(r.params??[]).filter(o=>o.location==="form").map(o=>({name:o.name,value:""}));return s.length===0?void 0:{type:n==="multipart"?"form-data":"x-www-form-urlencoded",content:s.map(o=>({key:o.name,value:o.value,type:"text",enabled:!0}))}}return{type:"raw",format:"text",content:""}}function cr(r){let e=[];return r.description&&e.push(r.description),r.source?.filePath&&e.push(`Discovered from ${r.source.filePath}${r.source.line?`:${r.source.line}`:""}`),e.push(`Framework: ${r.framework} | Confidence: ${r.confidence}`),e.join(`
|
|
836
|
+
`)}function Pi(r,e,t=""){let n=(r.resolvedPath??r.pathExpression).replace(/^\/+/,""),s=t?`${t.replace(/\/+$/,"")}/${n}`:r.resolvedPath??r.pathExpression,{headers:i,query:o,params:a,body:c}=ar(r,!0);return{collectionId:e,name:or(r),method:r.method||"GET",url:s,headers:i,query:o,params:a,body:c,description:cr(r)}}var ou=k(()=>{"use strict"});import*as Ra from"fs";import*as Wf from"path";import{execSync as vb}from"child_process";function lr(r){let e;try{let n=vb("git rev-parse HEAD",{cwd:r,stdio:["ignore","pipe","ignore"],encoding:"utf-8",timeout:3e3}).trim();n&&(e=n)}catch{e=void 0}let t=0;try{let n=[r],s=new Set(["node_modules",".git","target","build","dist","out","__pycache__",".venv","venv"]);for(;n.length>0;){let i=n.shift(),o;try{o=Ra.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let a of o){let c=Wf.join(i,a.name);if(a.isDirectory()){s.has(a.name)||n.push(c);continue}if(!(!a.isFile()||!bb.some(l=>c.endsWith(l))))try{let l=Ra.statSync(c);l.mtimeMs>t&&(t=l.mtimeMs)}catch{}}}}catch{t=0}return{gitHash:e,maxSourceMtime:t}}function ur(r,e){let t=lr(r);if(!e)return{projectRoot:r,status:"unknown",currentFreshness:t,reason:"no stored index entry"};if(t.gitHash&&e.gitHash)return t.gitHash===e.gitHash?{projectRoot:r,status:"current",storedFreshness:{gitHash:e.gitHash,maxSourceMtime:t.maxSourceMtime},currentFreshness:t}:{projectRoot:r,status:"stale",storedFreshness:{gitHash:e.gitHash,maxSourceMtime:t.maxSourceMtime},currentFreshness:t,reason:`git HEAD changed: ${e.gitHash.slice(0,8)} \u2192 ${t.gitHash.slice(0,8)}`};let n=new Date(e.scannedAt).getTime();return t.maxSourceMtime>n?{projectRoot:r,status:"stale",storedFreshness:{gitHash:e.gitHash,maxSourceMtime:t.maxSourceMtime},currentFreshness:t,reason:`source file newer than last scan (${new Date(t.maxSourceMtime).toISOString()} > ${e.scannedAt})`}:{projectRoot:r,status:"current",storedFreshness:{gitHash:e.gitHash,maxSourceMtime:t.maxSourceMtime},currentFreshness:t}}function Gf(r){let e=r.projects.map(t=>ur(t.projectRoot,t.freshness));return{projects:e,staleCount:e.filter(t=>t.status==="stale").length,checkedAt:new Date().toISOString()}}function Ii(r,e){let t=r.split(`
|
|
837
837
|
`),n=e.split(`
|
|
838
838
|
`),s=t.length,i=n.length,o=Array.from({length:s+1},()=>new Array(i+1).fill(0));for(let u=s-1;u>=0;u--)for(let d=i-1;d>=0;d--)o[u][d]=t[u]===n[d]?o[u+1][d+1]+1:Math.max(o[u+1][d],o[u][d+1]);let a=[],c=0,l=0;for(;c<s&&l<i;)t[c]===n[l]?(a.push({type:"same",line:c+1,text:t[c]}),c++,l++):o[c+1][l]>=o[c][l+1]?(a.push({type:"removed",line:c+1,text:t[c]}),c++):(a.push({type:"added",line:l+1,text:n[l]}),l++);for(;c<s;)a.push({type:"removed",line:c+1,text:t[c]}),c++;for(;l<i;)a.push({type:"added",line:l+1,text:n[l]}),l++;return a}function au(r,e,t){let n=Ii(r,e),s=Ii(r,t),i=n.filter(o=>o.type!=="same").length;return{userChanges:n,regeneratedChanges:s,changed:t!==r,userEditedLineCount:i}}function cu(r,e,t){let n=t.split(`
|
|
839
839
|
`),s=r.split(`
|
|
@@ -843,9 +843,9 @@ Return ONLY a valid JSON object (no markdown fences):
|
|
|
843
843
|
`);for(let y of o.insertionsBefore[d])c.push(y);if(g!==v&&v!==""){l.push({type:"removed",line:d+1,text:n[d]});for(let y of a.insertionsBefore[d])c.push(y)}continue}if(f&&!h){for(let g of o.insertionsBefore[d])c.push(g);continue}if(!f&&h){for(let g of a.insertionsBefore[d])c.push(g);continue}for(let g of o.insertionsBefore[d])c.push(g);for(let g of a.insertionsBefore[d])c.push(g);c.push(n[d])}for(let d of o.insertionsBefore[u])c.push(d);for(let d of a.insertionsBefore[u])c.push(d);return{merged:c.join(`
|
|
844
844
|
`),conflicts:l}}function Jf(r,e){let t=r.length,n=new Array(t).fill("kept"),s=Array.from({length:t+1},()=>[]),i=0,o=Ii(r.join(`
|
|
845
845
|
`),e.join(`
|
|
846
|
-
`)),a=0;for(let c of o){if(c.type==="same"){a=c.line;continue}if(c.type==="removed"){let l=c.line-1;n[l]="removed",i++,a=c.line;continue}i++,s[a].push(c.text)}return{byLine:n,insertionsBefore:s,changedCount:i}}function Ca(r,e,t,n){let s=new Set(r),i=[];for(let o of e){let a=o.derivedFrom.filter(d=>s.has(d));if(a.length===0)continue;let c=t[o.id]??"",l=n[o.id];if(l===void 0)continue;let u=au(c,o.currentContent,l);i.push({suiteId:o.id,suiteName:o.name,affectedEndpointIds:a,diff:u,hasConflicts:u.userEditedLineCount>0&&u.changed})}return i}function ka(r,e,t,n){if(r.hasConflicts)return{canApply:!1,merged:e,conflicts:r.diff.userEditedLineCount};if(!r.diff.changed)return{canApply:!1,merged:e,conflicts:0};let{merged:s,conflicts:i}=cu(e,t,n);return{canApply:!0,merged:s,conflicts:i.length}}var
|
|
847
|
-
`)}endpointKey(e){let t=e.resolvedPath??e.pathExpression;return`${e.method.toUpperCase()}::${t}`}mergeSeedIntoEndpoint(e,t){if(e.description=e.description??t.description,!e.source?.filePath&&t.source?.filePath&&(e.source=t.source),!e.middleware||e.middleware.length===0){e.middleware=t.middleware;return}let n=new Set(e.middleware.map(s=>s.name));for(let s of t.middleware??[])n.has(s.name)||e.middleware.push(s)}buildIndex(e,t,n){let s=t.map(i=>{let o=e.filter(a=>(a.projectRoot??i)===i).sort(Yf);return{projectRoot:i,frameworks:Array.from(new Set(o.map(a=>a.framework))),freshness:{scannedAt:n.toISOString()},endpoints:o}});return{version:this.indexVersion,generatedAt:n.toISOString(),projects:s}}dedupeAndSort(e){let t=new Set,n=[];for(let s of e){let i=`${s.framework}:${s.method.toUpperCase()}:${s.resolvedPath??s.pathExpression}`;t.has(i)||(t.add(i),n.push(s))}return n.sort(Yf)}}});var du=k(()=>{"use strict";Ml();Jp();Xo();mn();na();jl();Jl();Wl();Kl();Yl();ru();iu();Xr();ou();Ho();Vo();lu();uu()});async function Ea(r){return{endpoints:(await new kn({providers:qb()}).discover({workspaceFolder:r})).endpoints}}async function Ab(r,e){let{endpoints:t}=await Ea(r);if(e.endpointId){let n=t.find(s=>s.id===e.endpointId);if(n)return n}return t.find(n=>{let s=!e.method||(n.method||"").toUpperCase()===e.method,i=!e.pathExpression||(n.resolvedPath??n.pathExpression)===e.pathExpression||n.pathExpression===e.pathExpression;return s&&i})}var qb,em,tm=k(()=>{"use strict";Fe();du();Ne();qb=()=>[new bn,new xn,new Sn,new wn,new Rn,new Cn],em=[{toolNames:[x.createRequestFromEndpoint],async handle({args:r,services:e,collections:t}){let n=typeof r.projectPath=="string"&&r.projectPath.trim()?r.projectPath.trim():e.workspaceFolder;if(!n)throw A('"projectPath" is required (or set services.workspaceFolder).');let s=(typeof r.method=="string"?r.method.toUpperCase():"")||void 0,i=typeof r.path=="string"&&r.path.trim()?r.path.trim():void 0;if(!s&&!i&&!r.endpointId)throw A('Provide "method" + "path", or "endpointId" to select the endpoint.');let o=await Ab(n,{endpointId:typeof r.endpointId=="string"?r.endpointId:void 0,method:s,pathExpression:i});if(!o)throw A(`No endpoint matched in ${n}`+(s&&i?` for ${s} ${i}`:""));let a=W(r.collection,t),c=typeof r.name=="string"&&r.name.trim()?r.name.trim():or(o),l=typeof r.baseUrl=="string"&&r.baseUrl.trim()?r.baseUrl.trim().replace(/\/+$/,""):"",u=(o.resolvedPath??o.pathExpression).replace(/^\/+/,""),d=l?`${l}/${u}`:o.resolvedPath??o.pathExpression,{headers:p,query:m,params:f,body:h}=ar(o,r.sampleData===!0),g={collectionId:a.id,name:c,method:o.method||"GET",url:d,headers:p,query:m,params:f,body:h,description:cr(o)},v=await e.collection.createRequest(g);return{id:v.id,name:v.name,method:v.method,url:v.url,created:!0,collection:a.name,provenance:{framework:o.framework,source:o.source,confidence:o.confidence},hint:"Request created from a discovered endpoint. Call run_request to execute it."}}},{toolNames:[x.generateTestSuite],async handle({args:r,services:e,collections:t}){let n=typeof r.projectPath=="string"&&r.projectPath.trim()?r.projectPath.trim():e.workspaceFolder;if(!n)throw A('"projectPath" is required (or set services.workspaceFolder).');let s=W(r.collection,t),i=typeof r.baseUrl=="string"&&r.baseUrl.trim()?r.baseUrl.trim().replace(/\/+$/,""):"",o=r.assertBodySchema===!0,a=r.dryRun===!0,c=typeof r.name=="string"&&r.name.trim()?r.name.trim():`Generated ${s.name} suite`,l=await Ea(n);if(l.endpoints.length===0)return{generated:!1,endpointCount:0,message:"No endpoints discovered in "+n};let u=[],d=[];for(let h of l.endpoints){if(a){d.push(h);continue}let{headers:g,query:v,params:y,body:S}=ar(h,r.sampleData===!0),b=(h.resolvedPath??h.pathExpression).replace(/^\/+/,""),C=i?`${i}/${b}`:h.resolvedPath??h.pathExpression,w={collectionId:s.id,name:or(h),method:h.method||"GET",url:C,headers:g,query:v,params:y,body:S,description:cr(h)},E=await e.collection.createRequest(w);d.push({...h,id:E.id}),u.push({name:E.name,id:E.id})}let{suite:p,derived:m}=fn(d,{collectionId:s.id,collectionName:s.name,folderPath:"",name:c,assertBodySchema:o}),f=Gr(d,{requestPathOf:h=>h.source?.symbolName??h.pathExpression,name:`${c} flow`});return!a&&e.testSuite&&await e.testSuite.updateSuite(p),{generated:!0,suite:p.id,name:p.name,collection:s.name,endpointCount:p.nodes.length,dryRun:a,aiGenerated:p.ai_generated,derived:m,flowSource:f,requestsCreated:a?void 0:u,hint:a?"Dry-run: no requests were created. Re-run without dryRun to persist.":"Suite generated. Run it with run_suite to execute the discovered endpoints."}}},{toolNames:[x.suggestWorkflow],async handle({args:r,services:e}){let t=typeof r.projectPath=="string"&&r.projectPath.trim()?r.projectPath.trim():e.workspaceFolder;if(!t)throw A('"projectPath" is required (or set services.workspaceFolder).');let{endpoints:n}=await Ea(t),s=nr(n,{collectionId:"",collectionName:""});return{projectPath:t,chainCount:s.length,chains:s.map(i=>({id:i.id,kind:i.kind,name:i.name,confidence:i.confidence,producer:i.producer,dependents:i.dependents,variableName:i.variableName})),hint:"Call generate_workflow to persist a chain as a runnable suite."}}},{toolNames:[x.generateWorkflow],async handle({args:r,services:e,collections:t}){let n=typeof r.projectPath=="string"&&r.projectPath.trim()?r.projectPath.trim():e.workspaceFolder;if(!n)throw A('"projectPath" is required (or set services.workspaceFolder).');let s=W(r.collection,t),i=typeof r.baseUrl=="string"&&r.baseUrl.trim()?r.baseUrl.trim().replace(/\/+$/,""):"",o=r.dryRun===!0,a=typeof r.name=="string"&&r.name.trim()?r.name.trim():`Generated ${s.name} workflow suite`,{endpoints:c}=await Ea(n);if(c.length===0)return{generated:!1,chainCount:0,message:"No endpoints discovered in "+n};let l=[],u=[];for(let f of c){if(o){u.push(f);continue}let{headers:h,query:g,params:v,body:y}=ar(f,r.sampleData===!0),S=(f.resolvedPath??f.pathExpression).replace(/^\/+/,""),b=i?`${i}/${S}`:f.resolvedPath??f.pathExpression,C={collectionId:s.id,name:or(f),method:f.method||"GET",url:b,headers:h,query:g,params:v,body:y,description:cr(f)},w=await e.collection.createRequest(C);u.push({...f,id:w.id}),l.push({name:w.name,id:w.id})}let d=nr(u,{collectionId:s.id,collectionName:s.name}),p=Date.now(),m={id:`wf_${tr(a)}`,name:a,description:"Workflow chains generated from source-code discovery (Phase 2a L3).",nodes:d.flatMap(f=>f.nodes),config:{iterations:1,delayBetweenRequests:0,stopOnError:!1,readFromSharedSession:!1,writeToSharedSession:!1},ai_generated:!0,derived_from:c.map(f=>f.id).filter(Boolean),createdAt:p,updatedAt:p};return!o&&e.testSuite&&await e.testSuite.updateSuite(m),{generated:d.length>0,suite:m.id,name:m.name,collection:s.name,chainCount:d.length,dryRun:o,aiGenerated:!0,chains:d.map(f=>({id:f.id,kind:f.kind,name:f.name,confidence:f.confidence,producer:f.producer,dependents:f.dependents,nodeCount:f.nodes.length})),requestsCreated:o?void 0:l,hint:o?"Dry-run: no requests were created. Re-run without dryRun to persist.":"Workflow suite generated. Run it with run_suite to execute the chains."}}},{toolNames:[x.checkDrift],async handle({args:r,services:e}){let t=typeof r.projectPath=="string"&&r.projectPath.trim()?r.projectPath.trim():e.workspaceFolder;if(!t)throw A('"projectPath" is required (or set services.workspaceFolder).');let n=typeof r.storedGitHash=="string"?r.storedGitHash:void 0,s=typeof r.storedScannedAt=="string"?r.storedScannedAt:void 0,i=lr(t);if(!n&&!s)return{projectPath:t,freshness:{gitHash:i.gitHash??null,maxSourceMtime:i.maxSourceMtime},status:"unknown",hint:"Pass storedGitHash (and/or storedScannedAt) from a prior scan to get a current/stale verdict."};let o=ur(t,{gitHash:n,scannedAt:s??new Date(0).toISOString()});return{projectPath:t,status:o.status,reason:o.reason,freshness:{gitHash:o.currentFreshness.gitHash??null,maxSourceMtime:o.currentFreshness.maxSourceMtime},stored:o.storedFreshness?{gitHash:o.storedFreshness.gitHash??null}:null,hint:o.status==="stale"?"Project drifted since the last scan. Re-run create_request_from_endpoint or generate_test_suite to regenerate artifacts.":void 0}}},{toolNames:[x.proposeUpdate],handle({args:r}){let e=Array.isArray(r.staleEndpointIds)?r.staleEndpointIds:[],t=Array.isArray(r.suites)?r.suites:[],n=r.baseContent??{},s=r.regeneratedContent??{},i=r.apply===!0;if(e.length===0)throw A('"staleEndpointIds" must be a non-empty array (e.g. from check_drift).');if(t.length===0)throw A('"suites" must be a non-empty array.');let o=t.map(c=>({id:c.id,name:c.name??c.id,currentContent:c.currentContent,derivedFrom:c.derivedFrom??[]})),a=Ca(e,o,n,s);return{proposedCount:a.length,proposals:a.map(c=>{let l=o.find(d=>d.id===c.suiteId),u=i?ka(c,l?.currentContent??"",s[c.suiteId]??"",n[c.suiteId]??""):void 0;return{suiteId:c.suiteId,suiteName:c.suiteName,affectedEndpointIds:c.affectedEndpointIds,changed:c.diff.changed,userEditedLineCount:c.diff.userEditedLineCount,hasConflicts:c.hasConflicts,...u?{canApply:u.canApply,mergedContent:u.canApply?u.merged:void 0,conflictCount:u.conflicts}:{},hint:c.hasConflicts?"User edits overlap regeneration \u2014 requires developer approval (do not auto-apply).":"No conflicts \u2014 safe to regenerate."}})}}}]});var nm,rm=k(()=>{"use strict";Fe();Ne();nm=[{toolNames:[x.getEnvironment],handle({args:r,services:e}){let t=typeof r.environment=="string"&&r.environment.trim()?r.environment.trim():e.environmentConfig.getSelectedEnvironment(),n=e.environmentConfig.getResolvedEnvironment(t);if(!n)throw A(`environment "${t}" not found`);return{name:n.name,variables:n.variables}}},{toolNames:[x.setVariable],handle({args:r,services:e}){let t=typeof r.key=="string"?r.key.trim():"",n=typeof r.value=="string"?r.value:String(r.value??"");if(!t)throw A('"key" is required');let s=typeof r.environment=="string"&&r.environment.trim()?r.environment.trim():e.environmentConfig.getSelectedEnvironment();return e.environmentConfig.setEnvironmentVariable(t,n,s),{set:!0,key:t,environment:s}}}]});var sm,im=k(()=>{"use strict";Fe();Ne();sm=[{toolNames:[x.listEnvironments],handle({services:r}){let e=r.environmentConfig.getAllEnvironments(),t=r.environmentConfig.getSelectedEnvironment();return{environments:e.map(n=>({name:n.name,active:n.active,variableKeys:Object.keys(n.variables)})),active:t}}},{toolNames:[x.getEnvironmentVariables],handle({args:r,services:e}){let t=typeof r.environment=="string"&&r.environment.trim()?r.environment.trim():e.environmentConfig.getSelectedEnvironment(),n=e.environmentConfig.getResolvedEnvironment(t);if(!n)throw A(`environment "${t}" not found`);let i=e.environmentConfig.getSharedConfig()?.environments?.[t]?.variables??{},o=e.environmentConfig.getEnvironmentVariableLocals();return{environment:t,active:e.environmentConfig.getSelectedEnvironment()===t,fileVariables:i,sessionOverrides:o,resolved:n.variables}}},{toolNames:[x.selectEnvironment],async handle({args:r,services:e}){let t=typeof r.environment=="string"?r.environment.trim():"";if(!t)throw A('"environment" is required');return await e.environmentConfig.setSelectedEnvironment(t),{selected:!0,environment:t}}},{toolNames:[x.createEnvironment],async handle({args:r,services:e}){let t=typeof r.name=="string"?r.name.trim():"";if(!t)throw A('"name" is required');if(await e.environmentConfig.createEnvironment(t),r.variables&&typeof r.variables=="object"){let n=r.variables,s=e.environmentConfig.getSharedConfig();s&&(s.environments=s.environments??{},s.environments[t]={...s.environments[t]??{},variables:{...s.environments[t]?.variables??{},...n}},e.environmentConfig.saveSharedConfig(s))}return{created:!0,environment:t}}},{toolNames:[x.deleteEnvironment],async handle({args:r,services:e}){if(r.confirm!==!0)throw A('"confirm" must be true to delete an environment');let t=typeof r.environment=="string"?r.environment.trim():"";if(!t)throw A('"environment" is required');let n=e.environmentConfig.getSelectedEnvironment();return await e.environmentConfig.deleteEnvironment(t),{deleted:!0,environment:t,newActive:n===t?void 0:n}}},{toolNames:[x.setEnvironmentVariable],handle({args:r,services:e}){let t=typeof r.key=="string"?r.key.trim():"",n=typeof r.value=="string"?r.value:String(r.value??"");if(!t)throw A('"key" is required');let s=typeof r.environment=="string"&&r.environment.trim()?r.environment.trim():e.environmentConfig.getSelectedEnvironment(),i=r.scope==="permanent"?"permanent":"session";if(i==="permanent"){let o=e.environmentConfig.getSharedConfig();o&&(o.environments=o.environments??{},o.environments[s]=o.environments[s]??{variables:{}},o.environments[s].variables=o.environments[s].variables??{},o.environments[s].variables[t]=n,e.environmentConfig.saveSharedConfig(o))}else e.environmentConfig.setEnvironmentVariable(t,n,s);return{set:!0,key:t,environment:s,scope:i}}},{toolNames:[x.unsetEnvironmentVariable],handle({args:r,services:e}){let t=typeof r.key=="string"?r.key.trim():"";if(!t)throw A('"key" is required');let n=typeof r.environment=="string"&&r.environment.trim()?r.environment.trim():e.environmentConfig.getSelectedEnvironment();return e.environmentConfig.deleteEnvironmentVariable(t,n),{unset:!0,key:t,environment:n}}},{toolNames:[x.setGlobalVariable],handle({args:r,services:e}){let t=typeof r.key=="string"?r.key.trim():"",n=typeof r.value=="string"?r.value:String(r.value??"");if(!t)throw A('"key" is required');let s=r.scope==="permanent"?"permanent":"session";if(s==="permanent"){let i=e.environmentConfig.getSharedConfig();i&&(i.globalVariables=i.globalVariables??{},i.globalVariables[t]=n,e.environmentConfig.saveSharedConfig(i))}else e.environmentConfig.setGlobalVariable(t,n);return{set:!0,key:t,scope:s}}},{toolNames:[x.getGlobals],handle({services:r}){return{globals:r.environmentConfig.getGlobalVariables()}}}]});var om,am=k(()=>{"use strict";Fe();Ne();om=[{toolNames:[x.runRequest],handle({args:r,services:e,collections:t,callbacks:n}){let s=W(r.collection,t),i=X(s),o=typeof r.requestId=="string"?r.requestId.trim():void 0,a=r.request,c;if(o){if(c=i.find(u=>u.request.id===o),!c)throw A(`request with id "${o}" not found in collection "${s.name}"`)}else{if(typeof a!="string"||!a.trim())throw A('the "request" or "requestId" argument is required');if(c=i.find(u=>u.request.name===a)??i.find(u=>u.request.name.toLowerCase()===a.toLowerCase()),!c)throw A(`request "${a}" not found in collection "${s.name}"`)}let l=Array.isArray(r.include)?r.include:[];return n.runRequest(s,c.request.id,r).then(u=>zt(u,l))}},{toolNames:[x.runFolder],handle({args:r,collections:e,callbacks:t}){let n=W(r.collection,e);if(typeof r.folder!="string"||!r.folder.trim())throw A('the "folder" argument is required');let s=r.folder.toLowerCase(),i=zr(r.folder),o=i.toLowerCase(),a=qe(n).map(u=>u.folderPath),c=a.find(u=>u===i)??a.find(u=>u.toLowerCase()===o)??a.find(u=>u.toLowerCase().includes(o))??a.find(u=>u.split("/").some(d=>d.toLowerCase().includes(o)));if(!c){let u=a.map(d=>`"${d}"`).join(", ");throw A(`folder "${r.folder}" not found in collection "${n.name}". Available folders: ${u||"(none)"}. Call list_folders to see all.`)}let l=Array.isArray(r.include)?r.include:[];return t.runFolder(n,c,r).then(u=>zt(u,l))}},{toolNames:[x.runCollection],handle({args:r,collections:e,callbacks:t}){let n=W(r.collection,e),s=Array.isArray(r.include)?r.include:[];return t.runCollection(n,r).then(i=>zt(i,s))}},{toolNames:[x.runSuite],handle({args:r,services:e,callbacks:t}){let n=r.suite;if(typeof n!="string"||!n.trim())throw A('the "suite" argument is required');return Ae(n,e).then(s=>{let i=Array.isArray(r.include)?r.include:[];return t.runSuite(s.id,s.name,r).then(o=>zt(o,i))})}}]});var cm,lm=k(()=>{"use strict";Fe();Ne();cm=[{toolNames:[x.listCollections],handle({collections:r}){return{collections:r.map(e=>({name:e.name,id:e.id,description:e.description??"",requestCount:X(e).length}))}}},{toolNames:[x.listFolders],handle({args:r,collections:e}){let t=W(r.collection,e);return{collection:t.name,folders:qe(t).map(({folderPath:n,requestCount:s})=>({path:Tt(n),requestCount:s}))}}},{toolNames:[x.listRequests],handle({args:r,collections:e}){let t=W(r.collection,e),n=typeof r.folder=="string"?r.folder.toLowerCase():void 0,s=typeof r.offset=="number"?Math.max(0,r.offset):0,i=typeof r.limit=="number"?Math.min(200,Math.max(1,r.limit)):50,o=X(t).filter(({folderPath:a})=>!n||a.toLowerCase().includes(n)).map(({request:a,folderPath:c})=>({id:a.id,name:a.name,method:a.method,folder:Tt(c),description:a.description??""}));return{collection:t.name,total:o.length,offset:s,limit:i,requests:o.slice(s,s+i)}}},{toolNames:[x.searchRequests],handle({args:r,collections:e}){let t=W(r.collection,e),n=typeof r.query=="string"?r.query.toLowerCase().trim():"";if(!n)throw A('the "query" argument is required');let s=X(t).filter(({request:i,folderPath:o})=>i.name.toLowerCase().includes(n)||(i.url??"").toLowerCase().includes(n)||i.method.toLowerCase().includes(n)||o.toLowerCase().includes(n)||(i.description??"").toLowerCase().includes(n)).map(({request:i,folderPath:o})=>({id:i.id,name:i.name,method:i.method,url:i.url??"",folder:Tt(o),description:i.description??""}));return{collection:t.name,query:r.query,total:s.length,requests:s}}},{toolNames:[x.getRequest],handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=Vt(e,n.id,We(r.request,n)),i=e.collection.getRequestScript(n.id,s.id,"pre-request")??"",o=e.collection.getRequestScript(n.id,s.id,"post-response")??"";return{id:s.id,name:s.name,method:s.method,url:s.url??"",description:s.description??"",headers:s.headers??[],body:s.body??null,auth:s.auth??null,scripts:{preRequest:i,postResponse:o},hint:"Use update_request to modify fields, set_request_script to modify scripts, or run_request to execute it."}}}]});var um,dm=k(()=>{"use strict";Fe();Ne();Ne();um=[{toolNames:[x.createRequest],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.name=="string"?r.name.trim():"";if(!s)throw A('"name" is required');let i=typeof r.method=="string"?r.method.toUpperCase():"GET",o=typeof r.url=="string"?r.url:"";if(!o)throw A('"url" is required');let a;if(typeof r.folder=="string"&&r.folder.trim()){let u=r.folder.toLowerCase(),d=qe(n).find(p=>p.folderPath===r.folder||p.folderPath.toLowerCase()===u);d&&(a=d.folderId)}let c={collectionId:n.id,parentId:a,name:s,method:i,url:o,headers:void 0,body:r.body?{type:"raw",format:"json",content:String(r.body)}:void 0,description:typeof r.description=="string"?r.description:void 0},l=await e.collection.createRequest(c);return{id:l.id,name:l.name,created:!0,collection:n.name,hint:"Request created. Call run_request to execute it, or set_request_script to add pre-request/post-response scripts."}}},{toolNames:[x.updateRequest],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=We(r.request,n),i={};return typeof r.name=="string"&&(i.name=r.name),typeof r.method=="string"&&(i.method=r.method.toUpperCase()),typeof r.url=="string"&&(i.url=r.url),r.headers&&typeof r.headers=="object"&&!Array.isArray(r.headers)&&(i.headers=Object.entries(r.headers).map(([o,a])=>({name:o,value:String(a),enabled:!0}))),typeof r.body=="string"&&(i.body={type:"raw",format:"json",content:r.body}),typeof r.description=="string"&&(i.description=r.description),await e.collection.updateRequest(n.id,s.id,i),{updated:!0,request:s.name}}},{toolNames:[x.deleteRequest],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw A('"confirm" must be true to delete a request');let n=W(r.collection,t),s=We(r.request,n);return await e.collection.deleteRequest(n.id,s.id),{deleted:!0,request:s.name}}},{toolNames:[x.getRequestScript],handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=We(r.request,n),i=r.phase;if(i!=="pre-request"&&i!=="post-response")throw A('"phase" must be "pre-request" or "post-response"');let o=e.collection.getRequestScript(n.id,s.id,i);return{collection:n.name,request:s.name,phase:i,script:o??""}}},{toolNames:[x.setRequestScript],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=We(r.request,n),i=r.phase;if(i!=="pre-request"&&i!=="post-response")throw A('"phase" must be "pre-request" or "post-response"');if(typeof r.script!="string")throw A('"script" is required');return await e.collection.setRequestScript(n.id,s.id,i,r.script),{updated:!0,collection:n.name,request:s.name,phase:i}}},{toolNames:[x.reorderCollectionItems],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t);if(!Array.isArray(r.order))throw A('"order" must be an array');let s;if(typeof r.folder=="string"&&r.folder.trim()){let a=r.folder.toLowerCase(),c=qe(n).find(l=>l.folderPath===r.folder||l.folderPath.toLowerCase()===a);if(!c)throw A(`folder "${r.folder}" not found in collection "${n.name}"`);s=c.folderId}let i=s?n.items.find(a=>a.id===s)?.items??[]:n.items,o=r.order.map(a=>i.find(l=>l.id===a||l.name===a)?.id??a);return await e.collection.reorderItems(n.id,s,o),{reordered:!0,collection:n.name,order:r.order}}}]});function qa(r){return r.status??r.responseStatus}function pu(r){return r.assertions&&r.assertions.length>0?r.assertions:r.failedTests&&r.failedTests.length>0?r.failedTests.map(e=>({name:e.name,passed:!1,message:e.message})):[]}function Tb(r){let e=r.body;if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function Ob(r){let e=pu(r).map(t=>`${t.name} ${t.message??""}`).join(" ");return/401|403|unauthor|forbidden|auth/i.test(e)}function $b(r){return pu(r).length>0}function Fb(r,e){if(qa(r)===void 0&&!r.error)return;let t=Tb(r);t&&Pb.test(t)&&Ib.test(t)&&e.push({rule:"response-leaks-secrets",severity:"error",title:"Response may leak a secret",message:`Response body of "${r.name}" contains both a sensitive key (password/secret/token/api-key) and a secret-looking value (JWT, bearer token, or PEM block).`,requestName:r.name,suggestion:"Redact sensitive fields server-side, or verify this endpoint is meant to return credentials (e.g. a /login response) and assert the exact shape rather than echoing it."})}function Nb(r,e){let t=qa(r);t!==void 0&&t>=500&&e.push({rule:"server-error",severity:"error",title:`Unexpected ${t} server error`,message:`"${r.name}" returned HTTP ${t}.`,requestName:r.name,suggestion:"Check the server logs for the 5xx cause; a passing suite must not contain server errors."})}function _b(r,e){r.error&&e.push({rule:"request-error",severity:"error",title:"Request failed to execute",message:`"${r.name}" failed with: ${r.error}`,requestName:r.name,suggestion:"Fix the URL/connection/script error so the request actually runs."})}function Db(r,e){let t=pu(r).filter(n=>!n.passed);t.length!==0&&e.push({rule:"failed-assertions",severity:"error",title:`${t.length} assertion${t.length===1?"":"s"} failed`,message:`"${r.name}" \u2014 ${t.map(n=>`"${n.name}"${n.message?`: ${n.message}`:""}`).join("; ")}`,requestName:r.name,suggestion:"Fix the failing assertion or the request so the suite is green."})}function Mb(r,e){if((r.method??"").toUpperCase()!=="DELETE")return;let t=qa(r);t!==void 0&&t>=200&&t<300&&t!==204&&e.push({rule:"delete-not-204",severity:"warn",title:"DELETE returned a non-204 success",message:`"${r.name}" returned HTTP ${t} for a DELETE. The REST convention is 204 No Content.`,requestName:r.name,suggestion:"Return 204 (or assert the actual contract if the API intentionally returns a body, e.g. 200 with a deleted resource)."})}function jb(r,e){$b(r)||e.push({rule:"missing-assertions",severity:"warn",title:"No assertions on this request",message:`"${r.name}" executed without any pm.test()/pm.expect() assertion, so a regression would not be caught.`,requestName:r.name,suggestion:"Add assertions for status, body shape, and any side-effect the request produces."})}function Lb(r,e){let t=qa(r);t!==401&&t!==403||Ob(r)||e.push({rule:"auth-failure-unhandled",severity:"warn",title:`Auth failure (${t}) not asserted`,message:`"${r.name}" received HTTP ${t} but no assertion verifies the auth/401/403 path.`,requestName:r.name,suggestion:'Add a pm.test asserting the 401/403 (e.g. pm.test("rejects unauthenticated", () => pm.response.to.have.status(401))) so the auth contract is pinned.'})}function Hb(r,e,t){let n=r.duration;n===void 0||n<t||e.push({rule:"slow-response",severity:"warn",title:`Slow response (${n}ms)`,message:`"${r.name}" took ${n}ms, exceeding the ${t}ms threshold.`,requestName:r.name,suggestion:"Investigate latency (N+1 queries, missing indexes, slow third-party calls) or raise the threshold if this is expected."})}function Aa(r,e,t){let n=t?.slowResponseMs??2e3,s=[];for(let c of e)Fb(c,s),Nb(c,s),_b(c,s),Db(c,s),Mb(c,s),t?.allowNoAssertions||jb(c,s),Lb(c,s),Hb(c,s,n);r&&r.nodes&&r.nodes.length>0&&Ub(r,e,s),s.sort((c,l)=>pm(c.severity)-pm(l.severity)||c.rule.localeCompare(l.rule));let i=s.filter(c=>c.severity==="error").length,o=s.filter(c=>c.severity==="warn").length,a=s.filter(c=>c.severity==="info").length;return{suiteId:r?.id,suiteName:r?.name,generatedAt:Date.now(),summary:{errors:i,warnings:o,infos:a,total:s.length,pass:i===0},findings:s,rulesRun:[...Bb]}}function pm(r){return r==="error"?0:r==="warn"?1:2}function Ub(r,e,t){let n=new Set(e.map(s=>s.name.trim().toLowerCase()).filter(Boolean));for(let s of r.nodes){if(s.type!=="request")continue;let i=s.request?.name;if(!i)continue;let o=i.trim().toLowerCase();if(n.has(o))continue;(s.postResponseScript??[]).some(l=>/pm\.test\s*\(|pm\.expect\s*\(/.test(l))||t.push({rule:"missing-assertions",severity:"warn",title:"Suite request never ran",message:`"${i}" is defined in the suite but did not execute in this run and has no assertions.`,requestName:i,suggestion:"Enable the request in the suite, or add assertions and confirm it executes."})}}function Pa(r){if(Array.isArray(r))return r;if(r&&typeof r=="object"){let e=r;if(Array.isArray(e.allResults))return e.allResults}return[]}var Pb,Ib,Bb,fm=k(()=>{"use strict";Pb=/(password|passwd|pwd|secret|api[_-]?key|auth[_-]?token|access[_-]?token|refresh[_-]?token|client[_-]?secret|authorization|private[_-]?key|cookie|token)\b/i,Ib=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{6,}|bearer\s+[a-z0-9._~+/=-]{12,}|-----BEGIN/i;Bb=["response-leaks-secrets","server-error","request-error","failed-assertions","delete-not-204","missing-assertions","auth-failure-unhandled","slow-response"]});var fu=k(()=>{"use strict";fm()});function En(r,e=2e3){return!r||r.length<=e?r:r.slice(0,e)+`
|
|
848
|
-
\u2026 (truncated, ${r.length-e} chars omitted)`}function Ti(r){return r.replace(/"(Authorization|authorization)"\s*:\s*"[^"]+"/g,'"Authorization": "[REDACTED]"').replace(/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,"Bearer [REDACTED]").replace(/"(password|secret|token|api[-_]?key)"\s*:\s*"[^"]+"/gi,'"$1": "[REDACTED]"')}function mm(r,e){let t=e.getAllCollections(),n=r.toLowerCase(),s=t.find(i=>i.id===r||i.name===r)??t.find(i=>i.name.toLowerCase()===n)??t.find(i=>i.name.toLowerCase().includes(n));if(!s){let i=t.map(o=>`"${o.name}"`).join(", ");throw new Error(`Collection "${r}" not found. Available: ${i||"(none)"}`)}return s}function
|
|
846
|
+
`)),a=0;for(let c of o){if(c.type==="same"){a=c.line;continue}if(c.type==="removed"){let l=c.line-1;n[l]="removed",i++,a=c.line;continue}i++,s[a].push(c.text)}return{byLine:n,insertionsBefore:s,changedCount:i}}function Ca(r,e,t,n){let s=new Set(r),i=[];for(let o of e){let a=o.derivedFrom.filter(d=>s.has(d));if(a.length===0)continue;let c=t[o.id]??"",l=n[o.id];if(l===void 0)continue;let u=au(c,o.currentContent,l);i.push({suiteId:o.id,suiteName:o.name,affectedEndpointIds:a,diff:u,hasConflicts:u.userEditedLineCount>0&&u.changed})}return i}function ka(r,e,t,n){if(r.hasConflicts)return{canApply:!1,merged:e,conflicts:r.diff.userEditedLineCount};if(!r.diff.changed)return{canApply:!1,merged:e,conflicts:0};let{merged:s,conflicts:i}=cu(e,t,n);return{canApply:!0,merged:s,conflicts:i.length}}var bb,lu=k(()=>{"use strict";bb=[".ts",".js",".java",".py"]});function Rb(r){if(!r||r.length===0)return;let e=r.filter(s=>Sb.test(s.name));if(e.length===0)return;let t=e.map(s=>s.name).join(" ");return{required:!0,type:xb.find(s=>s.re.test(t))?.type,annotation:e.map(s=>s.name).join(", ")}}function Cb(r){if(!r||r.length===0)return;let e=r.filter(t=>wb.test(t.name)).map(t=>t.name);if(e.length!==0)return[...new Set(e)]}function kb(r){if(!r||typeof r!="object")return;let e=[];Array.isArray(r.required)&&r.required.length>0&&e.push("required fields");let t=r.properties;if(t&&typeof t=="object")for(let[n,s]of Object.entries(t)){if(!s||typeof s!="object")continue;let i=s;i.minLength!==void 0&&e.push(`${n}: minLength=${String(i.minLength)}`),i.maxLength!==void 0&&e.push(`${n}: maxLength=${String(i.maxLength)}`),i.minimum!==void 0&&e.push(`${n}: minimum=${String(i.minimum)}`),i.maximum!==void 0&&e.push(`${n}: maximum=${String(i.maximum)}`),i.pattern!==void 0&&e.push(`${n}: pattern`),i.format!==void 0&&e.push(`${n}: format=${String(i.format)}`),i.enum!==void 0&&e.push(`${n}: enum(${Array.isArray(i.enum)?i.enum.length:"1"} values)`)}return e.length>0?e:void 0}function Kf(r){r.auth||(r.auth=Rb(r.middleware)),r.validation||(r.validation=Cb(r.middleware)??kb(r.requestBody?.schema))}var Sb,xb,wb,Qf=k(()=>{"use strict";Sb=/(authenticate|authorization|authorise|authorize|requireauth|protect|secured?|guards?|jwt|passport|bearer|token|oauth|sso|auth0|session|basic|apikey|api[_-]?key|firebase|cognito|keycloak|casbin)/i,xb=[{re:/jwt|token|bearer|passport|firebase|cognito|keycloak|casbin/i,type:"jwt"},{re:/oauth|sso|auth0/i,type:"oauth2"},{re:/basic/i,type:"basic"},{re:/apikey|api[_-]?key/i,type:"apiKey"},{re:/session|cookie/i,type:"cookie"}],wb=/(validat|schema|sanitiz|zod|joi|yup|ajv|express-validator|class-validator|validationpipe|dto)/i});function Yf(r,e){let t=(Zf[r.method.toUpperCase()]??99)-(Zf[e.method.toUpperCase()]??99);if(t!==0)return t;let n=r.resolvedPath??r.pathExpression,s=e.resolvedPath??e.pathExpression;return n!==s?n<s?-1:1:r.source.filePath!==e.source.filePath?r.source.filePath<e.source.filePath?-1:1:r.source.line-e.source.line}function Eb(r){let e=r.resolvedPath??r.pathExpression;if(!e)return;let t=new Set;for(let i of r.params??[])t.add(Xf(i.location,i.name));let n=gn(e);if(n.length===0)return;let s=[];for(let i of n){let o=Xf(i.location,i.name);t.has(o)||(t.add(o),s.push(i))}s.length>0&&(r.params=[...r.params??[],...s])}function Xf(r,e){return`${r}:${e.toLowerCase()}`}function qb(r){return`${r.framework}:${r.method.toUpperCase()}:${r.resolvedPath??r.pathExpression}:${r.source.filePath}:${r.source.line}`}var Zf,kn,uu=k(()=>{"use strict";Qf();Xr();Xo();na();mn();Zf={GET:0,POST:1,PUT:2,PATCH:3,DELETE:4,HEAD:5,OPTIONS:6};kn=class{providers;fileSystem;indexFilePath;indexVersion;detector;index;constructor(e={}){this.providers=e.providers??[],this.fileSystem=e.fileSystem,this.indexFilePath=e.indexFilePath,this.indexVersion=e.indexVersion??"1",this.detector=e.detector??new Qr}async discover(e){let t=Date.now(),n=!!e.customSeedLoaderModulePath?.trim(),s=e.includeProjectRoots?.length?e.includeProjectRoots:[e.workspaceFolder],i={endpoints:[],warnings:[],stats:{frameworksDetected:[],providersRun:[],endpointCount:0,unresolvedEndpointCount:0,scanDurationMs:0}};for(let a of s){let c=this.detector.buildFingerprint(a),l=lt(a);l.length>0&&(c.sourceFiles=l);let u=e.frameworksByProjectRoot?.[a]??this.detector.detectFrameworks(c);i.stats.frameworksDetected.push(...u);let d=this.providers.filter(f=>f.framework==="unknown"||u.includes("unknown")||u.includes(f.framework)?f.supports(c).supported||n:!1);i.stats.providersRun.push(...d.map(f=>f.id));let p=await Promise.all(d.map(async f=>{try{return await f.discover(e,c)}catch(h){let g=h instanceof Error?h.message:String(h),v={code:"provider-failed",framework:f.framework,message:`Provider ${f.id} failed: ${g}`};return{endpoints:[],warnings:[v],stats:{frameworksDetected:[],providersRun:[],endpointCount:0,unresolvedEndpointCount:0,scanDurationMs:0}}}}));for(let f of p){for(let h of f.endpoints)h.projectRoot=h.projectRoot??a;i.endpoints.push(...f.endpoints),i.warnings.push(...f.warnings)}let m=ta(a,e);i.warnings.push(...m.warnings);for(let f of m.endpoints){f.projectRoot||(f.projectRoot=a);let h=i.endpoints.find(g=>this.endpointKey(g)===this.endpointKey(f));if(!h){i.endpoints.push(f),i.warnings.push({code:"seed-endpoint-unmatched",framework:f.framework,filePath:f.source.filePath,message:`Seed endpoint ${f.method} ${f.pathExpression} was not matched by auto-discovery and was kept as seed.`});continue}this.mergeSeedIntoEndpoint(h,f)}}for(let a of i.endpoints)Eb(a);for(let a of i.endpoints)Kf(a);let o=this.dedupeAndSort(i.endpoints);for(let a of o)a.id=qb(a);return i.endpoints=o,i.stats.frameworksDetected=Array.from(new Set(i.stats.frameworksDetected)),i.stats.providersRun=Array.from(new Set(i.stats.providersRun)),i.stats.endpointCount=i.endpoints.length,i.stats.unresolvedEndpointCount=i.endpoints.filter(a=>!a.resolvedPath).length,i.stats.scanDurationMs=Date.now()-t,this.index=this.buildIndex(i.endpoints,s,new Date),i}getIndex(){return this.index}getEndpoint(e){if(this.index)for(let t of this.index.projects){let n=t.endpoints.find(s=>s.id===e);if(n)return n}}invalidate(e){if(!e||e.length===0){this.index=void 0;for(let t of this.providers)t.clearCache?.();return}for(let t of this.providers)for(let n of e)t.clearCache?.(n)}async persistIndex(e){if(!this.fileSystem||!this.indexFilePath)throw new Error("ApiDiscoveryService.persistIndex requires fileSystem + indexFilePath");await this.fileSystem.writeFile(this.indexFilePath,`${JSON.stringify(e,null,2)}
|
|
847
|
+
`)}endpointKey(e){let t=e.resolvedPath??e.pathExpression;return`${e.method.toUpperCase()}::${t}`}mergeSeedIntoEndpoint(e,t){if(e.description=e.description??t.description,!e.source?.filePath&&t.source?.filePath&&(e.source=t.source),!e.middleware||e.middleware.length===0){e.middleware=t.middleware;return}let n=new Set(e.middleware.map(s=>s.name));for(let s of t.middleware??[])n.has(s.name)||e.middleware.push(s)}buildIndex(e,t,n){let s=t.map(i=>{let o=e.filter(a=>(a.projectRoot??i)===i).sort(Yf);return{projectRoot:i,frameworks:Array.from(new Set(o.map(a=>a.framework))),freshness:{scannedAt:n.toISOString()},endpoints:o}});return{version:this.indexVersion,generatedAt:n.toISOString(),projects:s}}dedupeAndSort(e){let t=new Set,n=[];for(let s of e){let i=`${s.framework}:${s.method.toUpperCase()}:${s.resolvedPath??s.pathExpression}`;t.has(i)||(t.add(i),n.push(s))}return n.sort(Yf)}}});var du=k(()=>{"use strict";Ml();Jp();Xo();mn();na();jl();Jl();Wl();Kl();Yl();ru();iu();Xr();ou();Ho();Vo();lu();uu()});async function Ea(r){return{endpoints:(await new kn({providers:Ab()}).discover({workspaceFolder:r})).endpoints}}async function Pb(r,e){let{endpoints:t}=await Ea(r);if(e.endpointId){let n=t.find(s=>s.id===e.endpointId);if(n)return n}return t.find(n=>{let s=!e.method||(n.method||"").toUpperCase()===e.method,i=!e.pathExpression||(n.resolvedPath??n.pathExpression)===e.pathExpression||n.pathExpression===e.pathExpression;return s&&i})}var Ab,em,tm=k(()=>{"use strict";Fe();du();Ne();Ab=()=>[new bn,new xn,new Sn,new wn,new Rn,new Cn],em=[{toolNames:[x.createRequestFromEndpoint],async handle({args:r,services:e,collections:t}){let n=typeof r.projectPath=="string"&&r.projectPath.trim()?r.projectPath.trim():e.workspaceFolder;if(!n)throw A('"projectPath" is required (or set services.workspaceFolder).');let s=(typeof r.method=="string"?r.method.toUpperCase():"")||void 0,i=typeof r.path=="string"&&r.path.trim()?r.path.trim():void 0;if(!s&&!i&&!r.endpointId)throw A('Provide "method" + "path", or "endpointId" to select the endpoint.');let o=await Pb(n,{endpointId:typeof r.endpointId=="string"?r.endpointId:void 0,method:s,pathExpression:i});if(!o)throw A(`No endpoint matched in ${n}`+(s&&i?` for ${s} ${i}`:""));let a=W(r.collection,t),c=typeof r.name=="string"&&r.name.trim()?r.name.trim():or(o),l=typeof r.baseUrl=="string"&&r.baseUrl.trim()?r.baseUrl.trim().replace(/\/+$/,""):"",u=(o.resolvedPath??o.pathExpression).replace(/^\/+/,""),d=l?`${l}/${u}`:o.resolvedPath??o.pathExpression,{headers:p,query:m,params:f,body:h}=ar(o,r.sampleData===!0),g={collectionId:a.id,name:c,method:o.method||"GET",url:d,headers:p,query:m,params:f,body:h,description:cr(o)},v=await e.collection.createRequest(g);return{id:v.id,name:v.name,method:v.method,url:v.url,created:!0,collection:a.name,provenance:{framework:o.framework,source:o.source,confidence:o.confidence},hint:"Request created from a discovered endpoint. Call run_request to execute it."}}},{toolNames:[x.generateTestSuite],async handle({args:r,services:e,collections:t}){let n=typeof r.projectPath=="string"&&r.projectPath.trim()?r.projectPath.trim():e.workspaceFolder;if(!n)throw A('"projectPath" is required (or set services.workspaceFolder).');let s=W(r.collection,t),i=typeof r.baseUrl=="string"&&r.baseUrl.trim()?r.baseUrl.trim().replace(/\/+$/,""):"",o=r.assertBodySchema===!0,a=r.dryRun===!0,c=typeof r.name=="string"&&r.name.trim()?r.name.trim():`Generated ${s.name} suite`,l=await Ea(n);if(l.endpoints.length===0)return{generated:!1,endpointCount:0,message:"No endpoints discovered in "+n};let u=[],d=[];for(let h of l.endpoints){if(a){d.push(h);continue}let{headers:g,query:v,params:y,body:S}=ar(h,r.sampleData===!0),b=(h.resolvedPath??h.pathExpression).replace(/^\/+/,""),C=i?`${i}/${b}`:h.resolvedPath??h.pathExpression,w={collectionId:s.id,name:or(h),method:h.method||"GET",url:C,headers:g,query:v,params:y,body:S,description:cr(h)},E=await e.collection.createRequest(w);d.push({...h,id:E.id}),u.push({name:E.name,id:E.id})}let{suite:p,derived:m}=fn(d,{collectionId:s.id,collectionName:s.name,folderPath:"",name:c,assertBodySchema:o}),f=Gr(d,{requestPathOf:h=>h.source?.symbolName??h.pathExpression,name:`${c} flow`});return!a&&e.testSuite&&await e.testSuite.updateSuite(p),{generated:!0,suite:p.id,name:p.name,collection:s.name,endpointCount:p.nodes.length,dryRun:a,aiGenerated:p.ai_generated,derived:m,flowSource:f,requestsCreated:a?void 0:u,hint:a?"Dry-run: no requests were created. Re-run without dryRun to persist.":"Suite generated. Run it with run_suite to execute the discovered endpoints."}}},{toolNames:[x.suggestWorkflow],async handle({args:r,services:e}){let t=typeof r.projectPath=="string"&&r.projectPath.trim()?r.projectPath.trim():e.workspaceFolder;if(!t)throw A('"projectPath" is required (or set services.workspaceFolder).');let{endpoints:n}=await Ea(t),s=nr(n,{collectionId:"",collectionName:""});return{projectPath:t,chainCount:s.length,chains:s.map(i=>({id:i.id,kind:i.kind,name:i.name,confidence:i.confidence,producer:i.producer,dependents:i.dependents,variableName:i.variableName})),hint:"Call generate_workflow to persist a chain as a runnable suite."}}},{toolNames:[x.generateWorkflow],async handle({args:r,services:e,collections:t}){let n=typeof r.projectPath=="string"&&r.projectPath.trim()?r.projectPath.trim():e.workspaceFolder;if(!n)throw A('"projectPath" is required (or set services.workspaceFolder).');let s=W(r.collection,t),i=typeof r.baseUrl=="string"&&r.baseUrl.trim()?r.baseUrl.trim().replace(/\/+$/,""):"",o=r.dryRun===!0,a=typeof r.name=="string"&&r.name.trim()?r.name.trim():`Generated ${s.name} workflow suite`,{endpoints:c}=await Ea(n);if(c.length===0)return{generated:!1,chainCount:0,message:"No endpoints discovered in "+n};let l=[],u=[];for(let f of c){if(o){u.push(f);continue}let{headers:h,query:g,params:v,body:y}=ar(f,r.sampleData===!0),S=(f.resolvedPath??f.pathExpression).replace(/^\/+/,""),b=i?`${i}/${S}`:f.resolvedPath??f.pathExpression,C={collectionId:s.id,name:or(f),method:f.method||"GET",url:b,headers:h,query:g,params:v,body:y,description:cr(f)},w=await e.collection.createRequest(C);u.push({...f,id:w.id}),l.push({name:w.name,id:w.id})}let d=nr(u,{collectionId:s.id,collectionName:s.name}),p=Date.now(),m={id:`wf_${tr(a)}`,name:a,description:"Workflow chains generated from source-code discovery (Phase 2a L3).",nodes:d.flatMap(f=>f.nodes),config:{iterations:1,delayBetweenRequests:0,stopOnError:!1,readFromSharedSession:!1,writeToSharedSession:!1},ai_generated:!0,derived_from:c.map(f=>f.id).filter(Boolean),createdAt:p,updatedAt:p};return!o&&e.testSuite&&await e.testSuite.updateSuite(m),{generated:d.length>0,suite:m.id,name:m.name,collection:s.name,chainCount:d.length,dryRun:o,aiGenerated:!0,chains:d.map(f=>({id:f.id,kind:f.kind,name:f.name,confidence:f.confidence,producer:f.producer,dependents:f.dependents,nodeCount:f.nodes.length})),requestsCreated:o?void 0:l,hint:o?"Dry-run: no requests were created. Re-run without dryRun to persist.":"Workflow suite generated. Run it with run_suite to execute the chains."}}},{toolNames:[x.checkDrift],async handle({args:r,services:e}){let t=typeof r.projectPath=="string"&&r.projectPath.trim()?r.projectPath.trim():e.workspaceFolder;if(!t)throw A('"projectPath" is required (or set services.workspaceFolder).');let n=typeof r.storedGitHash=="string"?r.storedGitHash:void 0,s=typeof r.storedScannedAt=="string"?r.storedScannedAt:void 0,i=lr(t);if(!n&&!s)return{projectPath:t,freshness:{gitHash:i.gitHash??null,maxSourceMtime:i.maxSourceMtime},status:"unknown",hint:"Pass storedGitHash (and/or storedScannedAt) from a prior scan to get a current/stale verdict."};let o=ur(t,{gitHash:n,scannedAt:s??new Date(0).toISOString()});return{projectPath:t,status:o.status,reason:o.reason,freshness:{gitHash:o.currentFreshness.gitHash??null,maxSourceMtime:o.currentFreshness.maxSourceMtime},stored:o.storedFreshness?{gitHash:o.storedFreshness.gitHash??null}:null,hint:o.status==="stale"?"Project drifted since the last scan. Re-run create_request_from_endpoint or generate_test_suite to regenerate artifacts.":void 0}}},{toolNames:[x.proposeUpdate],handle({args:r}){let e=Array.isArray(r.staleEndpointIds)?r.staleEndpointIds:[],t=Array.isArray(r.suites)?r.suites:[],n=r.baseContent??{},s=r.regeneratedContent??{},i=r.apply===!0;if(e.length===0)throw A('"staleEndpointIds" must be a non-empty array (e.g. from check_drift).');if(t.length===0)throw A('"suites" must be a non-empty array.');let o=t.map(c=>({id:c.id,name:c.name??c.id,currentContent:c.currentContent,derivedFrom:c.derivedFrom??[]})),a=Ca(e,o,n,s);return{proposedCount:a.length,proposals:a.map(c=>{let l=o.find(d=>d.id===c.suiteId),u=i?ka(c,l?.currentContent??"",s[c.suiteId]??"",n[c.suiteId]??""):void 0;return{suiteId:c.suiteId,suiteName:c.suiteName,affectedEndpointIds:c.affectedEndpointIds,changed:c.diff.changed,userEditedLineCount:c.diff.userEditedLineCount,hasConflicts:c.hasConflicts,...u?{canApply:u.canApply,mergedContent:u.canApply?u.merged:void 0,conflictCount:u.conflicts}:{},hint:c.hasConflicts?"User edits overlap regeneration \u2014 requires developer approval (do not auto-apply).":"No conflicts \u2014 safe to regenerate."}})}}}]});var nm,rm=k(()=>{"use strict";Fe();Ne();nm=[{toolNames:[x.getEnvironment],handle({args:r,services:e}){let t=typeof r.environment=="string"&&r.environment.trim()?r.environment.trim():e.environmentConfig.getSelectedEnvironment(),n=e.environmentConfig.getResolvedEnvironment(t);if(!n)throw A(`environment "${t}" not found`);return{name:n.name,variables:n.variables}}},{toolNames:[x.setVariable],handle({args:r,services:e}){let t=typeof r.key=="string"?r.key.trim():"",n=typeof r.value=="string"?r.value:String(r.value??"");if(!t)throw A('"key" is required');let s=typeof r.environment=="string"&&r.environment.trim()?r.environment.trim():e.environmentConfig.getSelectedEnvironment();return e.environmentConfig.setEnvironmentVariable(t,n,s),{set:!0,key:t,environment:s}}}]});var sm,im=k(()=>{"use strict";Fe();Ne();sm=[{toolNames:[x.listEnvironments],handle({services:r}){let e=r.environmentConfig.getAllEnvironments(),t=r.environmentConfig.getSelectedEnvironment();return{environments:e.map(n=>({name:n.name,active:n.active,variableKeys:Object.keys(n.variables)})),active:t}}},{toolNames:[x.getEnvironmentVariables],handle({args:r,services:e}){let t=typeof r.environment=="string"&&r.environment.trim()?r.environment.trim():e.environmentConfig.getSelectedEnvironment(),n=e.environmentConfig.getResolvedEnvironment(t);if(!n)throw A(`environment "${t}" not found`);let i=e.environmentConfig.getSharedConfig()?.environments?.[t]?.variables??{},o=e.environmentConfig.getEnvironmentVariableLocals();return{environment:t,active:e.environmentConfig.getSelectedEnvironment()===t,fileVariables:i,sessionOverrides:o,resolved:n.variables}}},{toolNames:[x.selectEnvironment],async handle({args:r,services:e}){let t=typeof r.environment=="string"?r.environment.trim():"";if(!t)throw A('"environment" is required');return await e.environmentConfig.setSelectedEnvironment(t),{selected:!0,environment:t}}},{toolNames:[x.createEnvironment],async handle({args:r,services:e}){let t=typeof r.name=="string"?r.name.trim():"";if(!t)throw A('"name" is required');if(await e.environmentConfig.createEnvironment(t),r.variables&&typeof r.variables=="object"){let n=r.variables,s=e.environmentConfig.getSharedConfig();s&&(s.environments=s.environments??{},s.environments[t]={...s.environments[t]??{},variables:{...s.environments[t]?.variables??{},...n}},e.environmentConfig.saveSharedConfig(s))}return{created:!0,environment:t}}},{toolNames:[x.deleteEnvironment],async handle({args:r,services:e}){if(r.confirm!==!0)throw A('"confirm" must be true to delete an environment');let t=typeof r.environment=="string"?r.environment.trim():"";if(!t)throw A('"environment" is required');let n=e.environmentConfig.getSelectedEnvironment();return await e.environmentConfig.deleteEnvironment(t),{deleted:!0,environment:t,newActive:n===t?void 0:n}}},{toolNames:[x.setEnvironmentVariable],handle({args:r,services:e}){let t=typeof r.key=="string"?r.key.trim():"",n=typeof r.value=="string"?r.value:String(r.value??"");if(!t)throw A('"key" is required');let s=typeof r.environment=="string"&&r.environment.trim()?r.environment.trim():e.environmentConfig.getSelectedEnvironment(),i=r.scope==="permanent"?"permanent":"session";if(i==="permanent"){let o=e.environmentConfig.getSharedConfig();o&&(o.environments=o.environments??{},o.environments[s]=o.environments[s]??{variables:{}},o.environments[s].variables=o.environments[s].variables??{},o.environments[s].variables[t]=n,e.environmentConfig.saveSharedConfig(o))}else e.environmentConfig.setEnvironmentVariable(t,n,s);return{set:!0,key:t,environment:s,scope:i}}},{toolNames:[x.unsetEnvironmentVariable],handle({args:r,services:e}){let t=typeof r.key=="string"?r.key.trim():"";if(!t)throw A('"key" is required');let n=typeof r.environment=="string"&&r.environment.trim()?r.environment.trim():e.environmentConfig.getSelectedEnvironment();return e.environmentConfig.deleteEnvironmentVariable(t,n),{unset:!0,key:t,environment:n}}},{toolNames:[x.setGlobalVariable],handle({args:r,services:e}){let t=typeof r.key=="string"?r.key.trim():"",n=typeof r.value=="string"?r.value:String(r.value??"");if(!t)throw A('"key" is required');let s=r.scope==="permanent"?"permanent":"session";if(s==="permanent"){let i=e.environmentConfig.getSharedConfig();i&&(i.globalVariables=i.globalVariables??{},i.globalVariables[t]=n,e.environmentConfig.saveSharedConfig(i))}else e.environmentConfig.setGlobalVariable(t,n);return{set:!0,key:t,scope:s}}},{toolNames:[x.getGlobals],handle({services:r}){return{globals:r.environmentConfig.getGlobalVariables()}}}]});var om,am=k(()=>{"use strict";Fe();Ne();om=[{toolNames:[x.runRequest],handle({args:r,services:e,collections:t,callbacks:n}){let s=W(r.collection,t),i=X(s),o=typeof r.requestId=="string"?r.requestId.trim():void 0,a=r.request,c;if(o){if(c=i.find(u=>u.request.id===o),!c)throw A(`request with id "${o}" not found in collection "${s.name}"`)}else{if(typeof a!="string"||!a.trim())throw A('the "request" or "requestId" argument is required');if(c=i.find(u=>u.request.name===a)??i.find(u=>u.request.name.toLowerCase()===a.toLowerCase()),!c)throw A(`request "${a}" not found in collection "${s.name}"`)}let l=Array.isArray(r.include)?r.include:[];return n.runRequest(s,c.request.id,r).then(u=>zt(u,l))}},{toolNames:[x.runFolder],handle({args:r,collections:e,callbacks:t}){let n=W(r.collection,e);if(typeof r.folder!="string"||!r.folder.trim())throw A('the "folder" argument is required');let s=r.folder.toLowerCase(),i=zr(r.folder),o=i.toLowerCase(),a=qe(n).map(u=>u.folderPath),c=a.find(u=>u===i)??a.find(u=>u.toLowerCase()===o)??a.find(u=>u.toLowerCase().includes(o))??a.find(u=>u.split("/").some(d=>d.toLowerCase().includes(o)));if(!c){let u=a.map(d=>`"${d}"`).join(", ");throw A(`folder "${r.folder}" not found in collection "${n.name}". Available folders: ${u||"(none)"}. Call list_folders to see all.`)}let l=Array.isArray(r.include)?r.include:[];return t.runFolder(n,c,r).then(u=>zt(u,l))}},{toolNames:[x.runCollection],handle({args:r,collections:e,callbacks:t}){let n=W(r.collection,e),s=Array.isArray(r.include)?r.include:[];return t.runCollection(n,r).then(i=>zt(i,s))}},{toolNames:[x.runSuite],handle({args:r,services:e,callbacks:t}){let n=r.suite;if(typeof n!="string"||!n.trim())throw A('the "suite" argument is required');return Ae(n,e).then(s=>{let i=Array.isArray(r.include)?r.include:[];return t.runSuite(s.id,s.name,r).then(o=>zt(o,i))})}}]});var cm,lm=k(()=>{"use strict";Fe();Ne();cm=[{toolNames:[x.listCollections],handle({collections:r}){return{collections:r.map(e=>({name:e.name,id:e.id,description:e.description??"",requestCount:X(e).length}))}}},{toolNames:[x.listFolders],handle({args:r,collections:e}){let t=W(r.collection,e);return{collection:t.name,folders:qe(t).map(({folderPath:n,requestCount:s})=>({path:Tt(n),requestCount:s}))}}},{toolNames:[x.listRequests],handle({args:r,collections:e}){let t=W(r.collection,e),n=typeof r.folder=="string"?r.folder.toLowerCase():void 0,s=typeof r.offset=="number"?Math.max(0,r.offset):0,i=typeof r.limit=="number"?Math.min(200,Math.max(1,r.limit)):50,o=X(t).filter(({folderPath:a})=>!n||a.toLowerCase().includes(n)).map(({request:a,folderPath:c})=>({id:a.id,name:a.name,method:a.method,folder:Tt(c),description:a.description??""}));return{collection:t.name,total:o.length,offset:s,limit:i,requests:o.slice(s,s+i)}}},{toolNames:[x.searchRequests],handle({args:r,collections:e}){let t=W(r.collection,e),n=typeof r.query=="string"?r.query.toLowerCase().trim():"";if(!n)throw A('the "query" argument is required');let s=X(t).filter(({request:i,folderPath:o})=>i.name.toLowerCase().includes(n)||(i.url??"").toLowerCase().includes(n)||i.method.toLowerCase().includes(n)||o.toLowerCase().includes(n)||(i.description??"").toLowerCase().includes(n)).map(({request:i,folderPath:o})=>({id:i.id,name:i.name,method:i.method,url:i.url??"",folder:Tt(o),description:i.description??""}));return{collection:t.name,query:r.query,total:s.length,requests:s}}},{toolNames:[x.getRequest],handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=Vt(e,n.id,We(r.request,n)),i=e.collection.getRequestScript(n.id,s.id,"pre-request")??"",o=e.collection.getRequestScript(n.id,s.id,"post-response")??"";return{id:s.id,name:s.name,method:s.method,url:s.url??"",description:s.description??"",headers:s.headers??[],body:s.body??null,auth:s.auth??null,scripts:{preRequest:i,postResponse:o},hint:"Use update_request to modify fields, set_request_script to modify scripts, or run_request to execute it."}}}]});var um,dm=k(()=>{"use strict";Fe();Ne();Ne();um=[{toolNames:[x.createRequest],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=typeof r.name=="string"?r.name.trim():"";if(!s)throw A('"name" is required');let i=typeof r.method=="string"?r.method.toUpperCase():"GET",o=typeof r.url=="string"?r.url:"";if(!o)throw A('"url" is required');let a;if(typeof r.folder=="string"&&r.folder.trim()){let u=r.folder.toLowerCase(),d=qe(n).find(p=>p.folderPath===r.folder||p.folderPath.toLowerCase()===u);d&&(a=d.folderId)}let c={collectionId:n.id,parentId:a,name:s,method:i,url:o,headers:void 0,body:r.body?{type:"raw",format:"json",content:String(r.body)}:void 0,description:typeof r.description=="string"?r.description:void 0},l=await e.collection.createRequest(c);return{id:l.id,name:l.name,created:!0,collection:n.name,hint:"Request created. Call run_request to execute it, or set_request_script to add pre-request/post-response scripts."}}},{toolNames:[x.updateRequest],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=We(r.request,n),i={};return typeof r.name=="string"&&(i.name=r.name),typeof r.method=="string"&&(i.method=r.method.toUpperCase()),typeof r.url=="string"&&(i.url=r.url),r.headers&&typeof r.headers=="object"&&!Array.isArray(r.headers)&&(i.headers=Object.entries(r.headers).map(([o,a])=>({name:o,value:String(a),enabled:!0}))),typeof r.body=="string"&&(i.body={type:"raw",format:"json",content:r.body}),typeof r.description=="string"&&(i.description=r.description),await e.collection.updateRequest(n.id,s.id,i),{updated:!0,request:s.name}}},{toolNames:[x.deleteRequest],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw A('"confirm" must be true to delete a request');let n=W(r.collection,t),s=We(r.request,n);return await e.collection.deleteRequest(n.id,s.id),{deleted:!0,request:s.name}}},{toolNames:[x.getRequestScript],handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=We(r.request,n),i=r.phase;if(i!=="pre-request"&&i!=="post-response")throw A('"phase" must be "pre-request" or "post-response"');let o=e.collection.getRequestScript(n.id,s.id,i);return{collection:n.name,request:s.name,phase:i,script:o??""}}},{toolNames:[x.setRequestScript],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t),s=We(r.request,n),i=r.phase;if(i!=="pre-request"&&i!=="post-response")throw A('"phase" must be "pre-request" or "post-response"');if(typeof r.script!="string")throw A('"script" is required');return await e.collection.setRequestScript(n.id,s.id,i,r.script),{updated:!0,collection:n.name,request:s.name,phase:i}}},{toolNames:[x.reorderCollectionItems],async handle({args:r,services:e,collections:t}){let n=W(r.collection,t);if(!Array.isArray(r.order))throw A('"order" must be an array');let s;if(typeof r.folder=="string"&&r.folder.trim()){let a=r.folder.toLowerCase(),c=qe(n).find(l=>l.folderPath===r.folder||l.folderPath.toLowerCase()===a);if(!c)throw A(`folder "${r.folder}" not found in collection "${n.name}"`);s=c.folderId}let i=s?n.items.find(a=>a.id===s)?.items??[]:n.items,o=r.order.map(a=>i.find(l=>l.id===a||l.name===a)?.id??a);return await e.collection.reorderItems(n.id,s,o),{reordered:!0,collection:n.name,order:r.order}}}]});function qa(r){return r.status??r.responseStatus}function pu(r){return r.assertions&&r.assertions.length>0?r.assertions:r.failedTests&&r.failedTests.length>0?r.failedTests.map(e=>({name:e.name,passed:!1,message:e.message})):[]}function Ob(r){let e=r.body;if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function $b(r){let e=pu(r).map(t=>`${t.name} ${t.message??""}`).join(" ");return/401|403|unauthor|forbidden|auth/i.test(e)}function Fb(r){return pu(r).length>0}function Nb(r,e){if(qa(r)===void 0&&!r.error)return;let t=Ob(r);t&&Ib.test(t)&&Tb.test(t)&&e.push({rule:"response-leaks-secrets",severity:"error",title:"Response may leak a secret",message:`Response body of "${r.name}" contains both a sensitive key (password/secret/token/api-key) and a secret-looking value (JWT, bearer token, or PEM block).`,requestName:r.name,suggestion:"Redact sensitive fields server-side, or verify this endpoint is meant to return credentials (e.g. a /login response) and assert the exact shape rather than echoing it."})}function _b(r,e){let t=qa(r);t!==void 0&&t>=500&&e.push({rule:"server-error",severity:"error",title:`Unexpected ${t} server error`,message:`"${r.name}" returned HTTP ${t}.`,requestName:r.name,suggestion:"Check the server logs for the 5xx cause; a passing suite must not contain server errors."})}function Db(r,e){r.error&&e.push({rule:"request-error",severity:"error",title:"Request failed to execute",message:`"${r.name}" failed with: ${r.error}`,requestName:r.name,suggestion:"Fix the URL/connection/script error so the request actually runs."})}function Mb(r,e){let t=pu(r).filter(n=>!n.passed);t.length!==0&&e.push({rule:"failed-assertions",severity:"error",title:`${t.length} assertion${t.length===1?"":"s"} failed`,message:`"${r.name}" \u2014 ${t.map(n=>`"${n.name}"${n.message?`: ${n.message}`:""}`).join("; ")}`,requestName:r.name,suggestion:"Fix the failing assertion or the request so the suite is green."})}function jb(r,e){if((r.method??"").toUpperCase()!=="DELETE")return;let t=qa(r);t!==void 0&&t>=200&&t<300&&t!==204&&e.push({rule:"delete-not-204",severity:"warn",title:"DELETE returned a non-204 success",message:`"${r.name}" returned HTTP ${t} for a DELETE. The REST convention is 204 No Content.`,requestName:r.name,suggestion:"Return 204 (or assert the actual contract if the API intentionally returns a body, e.g. 200 with a deleted resource)."})}function Lb(r,e){Fb(r)||e.push({rule:"missing-assertions",severity:"warn",title:"No assertions on this request",message:`"${r.name}" executed without any pm.test()/pm.expect() assertion, so a regression would not be caught.`,requestName:r.name,suggestion:"Add assertions for status, body shape, and any side-effect the request produces."})}function Hb(r,e){let t=qa(r);t!==401&&t!==403||$b(r)||e.push({rule:"auth-failure-unhandled",severity:"warn",title:`Auth failure (${t}) not asserted`,message:`"${r.name}" received HTTP ${t} but no assertion verifies the auth/401/403 path.`,requestName:r.name,suggestion:'Add a pm.test asserting the 401/403 (e.g. pm.test("rejects unauthenticated", () => pm.response.to.have.status(401))) so the auth contract is pinned.'})}function Bb(r,e,t){let n=r.duration;n===void 0||n<t||e.push({rule:"slow-response",severity:"warn",title:`Slow response (${n}ms)`,message:`"${r.name}" took ${n}ms, exceeding the ${t}ms threshold.`,requestName:r.name,suggestion:"Investigate latency (N+1 queries, missing indexes, slow third-party calls) or raise the threshold if this is expected."})}function Aa(r,e,t){let n=t?.slowResponseMs??2e3,s=[];for(let c of e)Nb(c,s),_b(c,s),Db(c,s),Mb(c,s),jb(c,s),t?.allowNoAssertions||Lb(c,s),Hb(c,s),Bb(c,s,n);r&&r.nodes&&r.nodes.length>0&&Vb(r,e,s),s.sort((c,l)=>pm(c.severity)-pm(l.severity)||c.rule.localeCompare(l.rule));let i=s.filter(c=>c.severity==="error").length,o=s.filter(c=>c.severity==="warn").length,a=s.filter(c=>c.severity==="info").length;return{suiteId:r?.id,suiteName:r?.name,generatedAt:Date.now(),summary:{errors:i,warnings:o,infos:a,total:s.length,pass:i===0},findings:s,rulesRun:[...Ub]}}function pm(r){return r==="error"?0:r==="warn"?1:2}function Vb(r,e,t){let n=new Set(e.map(s=>s.name.trim().toLowerCase()).filter(Boolean));for(let s of r.nodes){if(s.type!=="request")continue;let i=s.request?.name;if(!i)continue;let o=i.trim().toLowerCase();if(n.has(o))continue;(s.postResponseScript??[]).some(l=>/pm\.test\s*\(|pm\.expect\s*\(/.test(l))||t.push({rule:"missing-assertions",severity:"warn",title:"Suite request never ran",message:`"${i}" is defined in the suite but did not execute in this run and has no assertions.`,requestName:i,suggestion:"Enable the request in the suite, or add assertions and confirm it executes."})}}function Pa(r){if(Array.isArray(r))return r;if(r&&typeof r=="object"){let e=r;if(Array.isArray(e.allResults))return e.allResults}return[]}var Ib,Tb,Ub,fm=k(()=>{"use strict";Ib=/(password|passwd|pwd|secret|api[_-]?key|auth[_-]?token|access[_-]?token|refresh[_-]?token|client[_-]?secret|authorization|private[_-]?key|cookie|token)\b/i,Tb=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{6,}|bearer\s+[a-z0-9._~+/=-]{12,}|-----BEGIN/i;Ub=["response-leaks-secrets","server-error","request-error","failed-assertions","delete-not-204","missing-assertions","auth-failure-unhandled","slow-response"]});var fu=k(()=>{"use strict";fm()});function En(r,e=2e3){return!r||r.length<=e?r:r.slice(0,e)+`
|
|
848
|
+
\u2026 (truncated, ${r.length-e} chars omitted)`}function Ti(r){return r.replace(/"(Authorization|authorization)"\s*:\s*"[^"]+"/g,'"Authorization": "[REDACTED]"').replace(/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,"Bearer [REDACTED]").replace(/"(password|secret|token|api[-_]?key)"\s*:\s*"[^"]+"/gi,'"$1": "[REDACTED]"')}function mm(r,e){let t=e.getAllCollections(),n=r.toLowerCase(),s=t.find(i=>i.id===r||i.name===r)??t.find(i=>i.name.toLowerCase()===n)??t.find(i=>i.name.toLowerCase().includes(n));if(!s){let i=t.map(o=>`"${o.name}"`).join(", ");throw new Error(`Collection "${r}" not found. Available: ${i||"(none)"}`)}return s}function zb(r,e,t){let n=r.runId,s=r.request?.toLowerCase(),i=e.get(n);if(!i)throw new Error(`Run "${n}" not found. It may have expired or never existed. Use get_run_status to see recent runs.`);if(i.status==="running")throw new Error(`Run "${n}" is still in progress. Wait for it to complete before analyzing.`);let a=(i.allResults??[]).filter(p=>s&&typeof p.name=="string"&&!p.name.toLowerCase().includes(s)?!1:p.passed===!1||Array.isArray(p.assertions)&&p.assertions.some(m=>!m.passed)),c=i.summary,l=a.length,u=it(t).snapshot().body,d=`I ran an HTTP API test suite and got failures. Please analyze the results and provide:
|
|
849
849
|
|
|
850
850
|
1. **Root cause** for each failure
|
|
851
851
|
2. **Specific fixes** (updated URLs, auth headers, request body, environment variables)
|
|
@@ -880,7 +880,7 @@ ${C}
|
|
|
880
880
|
`}l>20&&(d+=`
|
|
881
881
|
_(${l-20} more failures omitted \u2014 fix the above first)_
|
|
882
882
|
`)}return d+=`
|
|
883
|
-
Please diagnose each failure and provide concrete, actionable fixes.`,{description:`Analyze ${l} failure(s) from run "${n}"`,messages:[{role:"user",content:{type:"text",text:d}}]}}async function
|
|
883
|
+
Please diagnose each failure and provide concrete, actionable fixes.`,{description:`Analyze ${l} failure(s) from run "${n}"`,messages:[{role:"user",content:{type:"text",text:d}}]}}async function Jb(r,e,t,n){let s=mm(r.collection,e),i=X(s),o=r.request.toLowerCase(),a=i.find(v=>v.request.id===r.request||v.request.name===r.request)??i.find(v=>v.request.name.toLowerCase()===o)??i.find(v=>v.request.name.toLowerCase().includes(o));if(!a)throw new Error(`Request "${r.request}" not found in collection "${s.name}"`);let c=e.getRequestDetail(s.id,a.request.id)??a.request,l=e.getRequestScript(s.id,c.id,"pre-request")??"",u=e.getRequestScript(s.id,c.id,"post-response")??"",d=st(c,a.folderPath).snapshot().body,p=it(n).snapshot().body,m="";if(r.runId){let v=t.get(r.runId);if(v&&v.status!=="running"){let S=(v.allResults??[]).find(b=>typeof b.name=="string"&&b.name.toLowerCase()===c.name.toLowerCase());if(S){let b=S.responseStatus??S.status,C=typeof S.responseBody=="string"?En(Ti(S.responseBody),1500):"",w=S.responseHeaders?En(JSON.stringify(S.responseHeaders,null,2),500):"";m=`
|
|
884
884
|
## Observed Response (run ${r.runId})
|
|
885
885
|
- Status: ${b}
|
|
886
886
|
`,w&&(m+=`- Headers:
|
|
@@ -932,7 +932,7 @@ Write comprehensive pm.test() assertions for the **post-response script**. Cover
|
|
|
932
932
|
4. Key response body fields (existence, type, value constraints)
|
|
933
933
|
5. Business logic validations specific to this endpoint
|
|
934
934
|
|
|
935
|
-
Use Chai-style assertions (\`pm.expect(...).to...\`). Output only the JavaScript code block, ready to paste into the post-response script.`;return{description:`Suggest assertions for "${c.name}" in "${s.name}"`,messages:[{role:"user",content:{type:"text",text:g}}]}}async function
|
|
935
|
+
Use Chai-style assertions (\`pm.expect(...).to...\`). Output only the JavaScript code block, ready to paste into the post-response script.`;return{description:`Suggest assertions for "${c.name}" in "${s.name}"`,messages:[{role:"user",content:{type:"text",text:g}}]}}async function Wb(r,e,t){let n=mm(r.collection,e),s=X(n),i=qe(n),o=Bt(n).snapshot().body,a=it(t).snapshot().body,c=s.slice(0,60).map(({request:f,folderPath:h})=>{let g=e.getRequestScript(n.id,f.id,"post-response")??"",v=g.includes("pm.test")||g.includes("pm.expect"),y=!!e.getRequestScript(n.id,f.id,"pre-request");return{name:f.name,method:f.method,url:f.url??"",folder:h||"(root)",hasPreScript:y,hasAssertions:v}}),l=c.filter(f=>!f.hasAssertions),u=c.reduce((f,h)=>(f[h.method]=(f[h.method]??0)+1,f),{}),d=i.map(f=>` ${f.folderPath} (${f.requestCount} requests)`).join(`
|
|
936
936
|
`),p=c.map(f=>` [${f.method}] ${f.folder!=="(root)"?f.folder+" / ":""}${f.name}${f.hasAssertions?" \u2713":" \u26A0 no assertions"}`).join(`
|
|
937
937
|
`),m=`Please review the following HTTP Forge API collection and provide actionable recommendations.
|
|
938
938
|
|
|
@@ -987,7 +987,7 @@ Be specific: name the exact requests or folders that need attention.`;return{des
|
|
|
987
987
|
1. Rank the findings by what to fix first (1 = most important).
|
|
988
988
|
2. For the top 3, give a concrete remediation (exact assertion, config change, or code fix).
|
|
989
989
|
3. Note anything the deterministic rules cannot see (spec compliance, business logic) as a separate "Manual review" section.
|
|
990
|
-
Keep it under 600 words.`}async function mu(r,e,t,n,s){switch(r){case"analyze-test-failure":return Vb(e,n,s);case"suggest-assertions":return zb(e,t,n,s);case"review-collection":return Jb(e,t,s);default:throw new Error(`Unknown prompt: "${r}". Available: ${Ia.map(i=>i.name).join(", ")}`)}}var Ia,Ta=k(()=>{"use strict";Xn();tt();Ia=[{name:"analyze-test-failure",description:"Analyze a failed API test run. Returns a structured prompt the LLM uses to diagnose each failure and suggest concrete fixes \u2014 no extra AI configuration needed.",arguments:[{name:"runId",description:"Run ID returned by run_suite, run_collection, or run_folder",required:!0},{name:"request",description:"Filter analysis to a specific request name (omit to analyze all failures)",required:!1}]},{name:"suggest-assertions",description:"Generate pm.test() assertion scripts for a request. The LLM writes Chai-style assertions based on the request definition and optionally an observed response.",arguments:[{name:"collection",description:"Collection name or id",required:!0},{name:"request",description:"Request name or id",required:!0},{name:"runId",description:"Run ID to use observed response data for more accurate assertions (optional)",required:!1}]},{name:"review-collection",description:"Get an AI review of a collection's structure, naming conventions, test coverage gaps, and assertion quality.",arguments:[{name:"collection",description:"Collection name or id",required:!0}]}]});var gm,ym=k(()=>{"use strict";er();fu();Ta();Fe();Ne();gm=[{toolNames:[x.reviewSuite],async handle({args:r,services:e,runStore:t}){let n=typeof r.runId=="string"?r.runId.trim():void 0;if(!n)throw A('"runId" is required \u2014 the id of a completed suite run.');let s=t.require(n);if(s.status==="running")return{runId:n,status:"running",message:"The run has not completed yet. Wait for it to finish, then review again."};let i=r.suiteId?await Ae(r.suiteId,e):void 0,o=typeof r.slowResponseMs=="number"&&r.slowResponseMs>0?r.slowResponseMs:2e3,a=Aa(i,Pa(s),{slowResponseMs:o}),c;if(e.aiProvider&&a.findings.length>0)try{let l=await hm({rec:s,suite:i,report:a});c=(await ot(()=>e.aiProvider.complete(l))).trim().slice(0,12e3)||void 0}catch{}return{runId:n,suiteId:i?.id,suiteName:i?.name,status:s.status,pass:a.summary.pass,summary:a.summary,findings:a.findings,aiRecommendations:c,hint:a.summary.pass?"No error-severity findings. Use in CI as a gate on summary.pass.":`${a.summary.errors} error(s) found \u2014 fix before merge.`}}}]});var vm,bm=k(()=>{"use strict";Fe();Ne();vm=[{toolNames:[x.getRunStatus],handle({args:r,runStore:e}){let t=e.require(r.runId);return{runId:t.id,status:t.status,suiteName:t.suiteName,progress:t.progress,...t.error?{error:t.error}:{}}}},{toolNames:[x.getRunSummary],handle({args:r,runStore:e}){let t=e.require(r.runId);if(t.status==="running")return{runId:t.id,status:"running",progress:t.progress};let n=(t.summary.failed??0)>0||t.summary.allPassed===!1,s=t.noAssertionExamples??[],i=s.length,o=t.summary.total,a=i>0?i/(o||1)>.5?`${i}/${o} requests have no pm.test() assertions. Invoke the "review-collection" prompt (collection="${t.suiteName}") for a full coverage analysis.`:`${i} request(s) have no pm.test() assertions (e.g. ${s.slice(0,3).map(c=>`"${c}"`).join(", ")}). Invoke the "suggest-assertions" prompt (collection="${t.suiteName}") to add test coverage.`:null;return{runId:t.id,status:t.status,suiteName:t.suiteName,summary:t.summary,...t.reportPath?{report:{uri:`file://${t.reportPath}`}}:{},...n?{failedRequests:zt({failedRequests:t.failedRequests},[]).failedRequests}:{},...n?{_nextStep:`REQUIRED ACTION: ${t.summary.failed} request(s) failed. The failedRequests array above contains the full details (method, url, requestBody, requestHeaders, status, responseBody, failedTests). Immediately analyze each failed request and provide: (1) root cause, (2) specific fix, (3) corrected pm.test() assertions if relevant. Do NOT wait for the user to ask \u2014 diagnose now.`}:{},...a?{_suggestions:[a]}:{}}}},{toolNames:[x.getFailedRequests],handle({args:r,runStore:e}){let t=e.require(r.runId);if(t.status==="running")return{runId:t.id,status:"running",progress:t.progress,failedSoFar:t.failedRequests.length};let n=typeof r.offset=="number"?Math.max(0,r.offset):0,s=typeof r.limit=="number"?Math.min(100,Math.max(1,r.limit)):20;return{runId:t.id,status:t.status,totalFailed:t.failedRequests.length,offset:n,limit:s,failedRequests:t.failedRequests.slice(n,n+s)}}},{toolNames:[x.getRequestResult],handle({args:r,runStore:e}){let t=e.require(r.runId),n=r.request;if(typeof n!="string"||!n)throw A('"request" is required');let s=typeof r.iteration=="number"?r.iteration:1,i=t.allResults.find(o=>o.iteration===s&&(o.name===n||o.name.toLowerCase()===n.toLowerCase()));if(!i){if(t.status==="running")return{runId:t.id,status:"running",message:`Request "${n}" has not completed yet.`};throw new Error(`Request "${n}" (iteration ${s}) not found in run "${t.id}".`)}return{runId:t.id,...i}}},{toolNames:[x.cancelRun],handle({args:r,runStore:e}){let t=e.require(r.runId);if(t.status!=="running")return{runId:t.id,status:t.status,cancelled:!1,message:`Run is already "${t.status}" \u2014 nothing to cancel.`};let n=e.cancel(String(r.runId));return{runId:t.id,status:"cancelled",cancelled:n,progress:t.progress,message:"Cancellation requested. The currently-executing request will finish; remaining requests will be skipped."}}}]});function Sm(r){return(Array.isArray(r.nodes)?r.nodes:[]).every(t=>t?.type==="request")}function kt(r,e=""){let t=[];if(!Array.isArray(r))return t;for(let n=0;n<r.length;n+=1){let s=r[n],i=e?`${e}.${n}`:`${n}`;!s||typeof s!="object"||(s.type==="request"&&t.push({node:s,path:i}),Array.isArray(s.nodes)&&t.push(...kt(s.nodes,`${i}.nodes`)),Array.isArray(s.then)&&t.push(...kt(s.then,`${i}.then`)),Array.isArray(s.else)&&t.push(...kt(s.else,`${i}.else`)),Array.isArray(s.default)&&t.push(...kt(s.default,`${i}.default`)),Array.isArray(s.elseif)&&s.elseif.forEach((o,a)=>{Array.isArray(o?.nodes)&&t.push(...kt(o.nodes,`${i}.elseif.${a}.nodes`)),Array.isArray(o?.then)&&t.push(...kt(o.then,`${i}.elseif.${a}.then`))}),Array.isArray(s.cases)&&s.cases.forEach((o,a)=>{Array.isArray(o?.nodes)&&t.push(...kt(o.nodes,`${i}.cases.${a}.nodes`)),Array.isArray(o?.then)&&t.push(...kt(o.then,`${i}.cases.${a}.then`))}))}return t}function gu(r,e){if(typeof r!="string"||!r.trim())throw A(`"${e}" is required`);let t=r.trim(),n=t.split(".");if(n.some(s=>s===""))throw A(`"${e}" is invalid: "${t}"`);return n.map(s=>/^\d+$/.test(s)?Number(s):s)}function wm(r,e){let t=gu(e,"path"),n=r;for(let s of t)if(typeof s=="number"){if(!Array.isArray(n)||s<0||s>=n.length)throw A(`node path not found: "${String(e)}"`);n=n[s]}else{if(!n||typeof n!="object"||!(s in n))throw A(`node path not found: "${String(e)}"`);n=n[s]}return n}function hu(r,e){let t=gu(e,"path"),n=t[t.length-1];if(typeof n!="number")throw A(`"path" must end with a numeric index: "${String(e)}"`);let s=r;for(let i=0;i<t.length-1;i+=1){let o=t[i];if(typeof o=="number"){if(!Array.isArray(s)||o<0||o>=s.length)throw A(`node path not found: "${String(e)}"`);s=s[o]}else{if(!s||typeof s!="object"||!(o in s))throw A(`node path not found: "${String(e)}"`);s=s[o]}}if(!Array.isArray(s)||n<0||n>=s.length)throw A(`node path not found: "${String(e)}"`);return{array:s,index:n}}function xm(r,e,t,n){if(e==null||e===""){if(t!=null&&t!=="")throw A(`"${n}" is only valid when a parent path is provided`);return{array:r,pathPrefix:""}}if(typeof t!="string"||!t.trim())throw A(`"${n}" is required when parent path is provided`);let s=String(e).trim(),i=t.trim(),o=wm(r,s),a=gu(i,n),c=o;for(let l=0;l<a.length;l+=1){let u=a[l],d=l===a.length-1;if(typeof u=="number"){if(!Array.isArray(c)||u<0||u>=c.length)throw A(`branch path not found: "${i}"`);c=c[u]}else{if(!c||typeof c!="object")throw A(`branch path not found: "${i}"`);if(!(u in c))if(d)c[u]=[];else throw A(`branch path not found: "${i}"`);c=c[u]}}if(!Array.isArray(c))throw A(`target branch must be an array: "${i}"`);return{array:c,pathPrefix:`${s}.${i}`}}function Wb(r,e=""){let t=[],n=[],s=(i,o)=>{if(Array.isArray(i)){o&&n.push(o);for(let a=0;a<i.length;a+=1){let c=i[a],l=o?`${o}.${a}`:`${a}`;t.push({path:l,type:c?.type,name:c?.name}),!(!c||typeof c!="object")&&(Array.isArray(c.nodes)&&s(c.nodes,`${l}.nodes`),Array.isArray(c.then)&&s(c.then,`${l}.then`),Array.isArray(c.else)&&s(c.else,`${l}.else`),Array.isArray(c.default)&&s(c.default,`${l}.default`),Array.isArray(c.cases)&&c.cases.forEach((u,d)=>{Array.isArray(u?.nodes)&&s(u.nodes,`${l}.cases.${d}.nodes`),Array.isArray(u?.then)&&s(u.then,`${l}.cases.${d}.then`)}),Array.isArray(c.elseif)&&c.elseif.forEach((u,d)=>{Array.isArray(u?.nodes)&&s(u.nodes,`${l}.elseif.${d}.nodes`),Array.isArray(u?.then)&&s(u.then,`${l}.elseif.${d}.then`)}))}}};return s(r,e),{nodePaths:t,branchPaths:n}}var Rm,Cm=k(()=>{"use strict";Fe();Ne();Ne();Rm=[{toolNames:[x.listSuites],async handle({services:r}){return{suites:(await r.testSuite.getAllSuites()).map(t=>({id:t.id,name:t.name,description:t.description??"",requestCount:kt(t.nodes||[]).length,flowNodeCount:t.nodes?.length??0,iterations:t.config?.iterations??1}))}}},{toolNames:[x.getSuite],async handle({args:r,services:e}){let t=await Ae(r.suite,e),n=kt(t.nodes||[]);return{id:t.id,name:t.name,description:t.description??"",config:{iterations:t.config?.iterations??1,delayBetweenRequests:t.config?.delayBetweenRequests??0,stopOnError:t.config?.stopOnError??!1},nodes:t.nodes||[],requests:n.map(({node:s,path:i})=>{let o=s.request;return{nodePath:i,slug:o.slug??o.requestId,collectionId:o.collectionId,requestId:o.requestId,name:o.name,method:o.method,folderPath:o.folderPath??"",enabled:s.enabled!==!1}})}}},{toolNames:[x.createSuite],async handle({args:r,services:e,collections:t}){let n=typeof r.name=="string"?r.name.trim():"";if(!n)throw A('"name" is required');let s;if(typeof r.fromCollection=="string"&&r.fromCollection.trim()){let i=W(r.fromCollection,t),o=await e.testSuite.createTempSuiteFromCollection(i.id);if(!o)throw new Error(`Could not build suite from collection "${i.name}"`);if(typeof r.fromFolder=="string"&&r.fromFolder.trim()){let a=zr(r.fromFolder),c=o.nodes||[];o.nodes=c.filter(l=>{if(l.type!=="request")return!0;let u=l.request?.folderPath||"";return u===a||u.startsWith(`${a}/`)})}s=await e.testSuite.saveTempSuite(o,n)}else s=await e.testSuite.createSuite(n);if(r.iterations!==void 0||r.stopOnError!==void 0||r.delayBetweenRequests!==void 0||r.description!==void 0||r.nodes!==void 0){if(r.description!==void 0&&(s.description=String(r.description)),r.nodes!==void 0){if(!Array.isArray(r.nodes))throw A('"nodes" must be an array when provided');s.nodes=r.nodes}s.config={...s.config,...typeof r.iterations=="number"?{iterations:r.iterations}:{},...typeof r.stopOnError=="boolean"?{stopOnError:r.stopOnError}:{},...typeof r.delayBetweenRequests=="number"?{delayBetweenRequests:r.delayBetweenRequests}:{}},await e.testSuite.updateSuite(s)}return{id:s.id,name:s.name,requestCount:s.nodes?.filter(i=>i.type==="request").length??0,created:!0,hint:(s.nodes?.filter(i=>i.type==="request").length??0)===0?"Suite is empty. Call add_suite_requests to populate it with requests from a collection.":"Suite created. Call run_suite to execute it."}}},{toolNames:[x.updateSuiteConfig],async handle({args:r,services:e}){let t=await Ae(r.suite,e);if(typeof r.name=="string"&&r.name.trim()&&(t.name=r.name.trim()),typeof r.description=="string"&&(t.description=r.description),r.nodes!==void 0){if(!Array.isArray(r.nodes))throw A('"nodes" must be an array when provided');t.nodes=r.nodes}return t.config={...t.config,...typeof r.iterations=="number"?{iterations:r.iterations}:{},...typeof r.stopOnError=="boolean"?{stopOnError:r.stopOnError}:{},...typeof r.delayBetweenRequests=="number"?{delayBetweenRequests:r.delayBetweenRequests}:{}},await e.testSuite.updateSuite(t),{updated:!0,suite:t.name}}},{toolNames:[x.getSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);Array.isArray(t.nodes)||(t.nodes=[]);let n=wm(t.nodes,r.path);return{suite:t.name,path:String(r.path),node:n}}},{toolNames:[x.listSuiteNodePaths],async handle({args:r,services:e}){let t=await Ae(r.suite,e);Array.isArray(t.nodes)||(t.nodes=[]);let n=r.includeBranches!==!1,s=Wb(t.nodes);return{suite:t.name,nodeCount:s.nodePaths.length,nodePaths:s.nodePaths,branchPaths:n?s.branchPaths:void 0,rootBranchPath:""}}},{toolNames:[x.addSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);if(Array.isArray(t.nodes)||(t.nodes=[]),!r.node||typeof r.node!="object"||Array.isArray(r.node))throw A('"node" must be an object');let{array:n,pathPrefix:s}=xm(t.nodes,r.parentPath,r.branch,"branch"),i=typeof r.index=="number"?Math.max(0,Math.min(r.index,n.length)):n.length;n.splice(i,0,r.node),await e.testSuite.updateSuite(t);let o=s?`${s}.${i}`:`${i}`;return{added:!0,suite:t.name,path:o}}},{toolNames:[x.updateSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);if(Array.isArray(t.nodes)||(t.nodes=[]),!r.node||typeof r.node!="object"||Array.isArray(r.node))throw A('"node" must be an object');let n=hu(t.nodes,r.path);return n.array[n.index]=r.node,await e.testSuite.updateSuite(t),{updated:!0,suite:t.name,path:String(r.path)}}},{toolNames:[x.removeSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);Array.isArray(t.nodes)||(t.nodes=[]);let n=hu(t.nodes,r.path),[s]=n.array.splice(n.index,1);return await e.testSuite.updateSuite(t),{removed:!0,suite:t.name,path:String(r.path),removedType:s?.type}}},{toolNames:[x.moveSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);Array.isArray(t.nodes)||(t.nodes=[]);let n=hu(t.nodes,r.fromPath),s=n.array[n.index];n.array.splice(n.index,1);let{array:i,pathPrefix:o}=xm(t.nodes,r.toParentPath,r.toBranch,"toBranch"),a=typeof r.toIndex=="number"?Math.max(0,Math.min(r.toIndex,i.length)):i.length;n.array===i&&n.index<a&&(a-=1),i.splice(a,0,s),await e.testSuite.updateSuite(t);let c=o?`${o}.${a}`:`${a}`;return{moved:!0,suite:t.name,fromPath:String(r.fromPath),toPath:c}}},{toolNames:[x.addSuiteRequests],async handle({args:r,services:e,collections:t}){let n=await Ae(r.suite,e),s=Array.isArray(r.requests)?r.requests:[];if(s.length===0)throw A('"requests" array is required and must not be empty');let i=[];for(let c of s){let l=W(c.collection,t),u=We(c.request,l),d=X(l).find(p=>p.request.id===u.id)?.folderPath??"";i.push({slug:u.id,collectionId:l.id,requestId:u.id,name:u.name,method:u.method,collectionName:l.name,folderPath:d,enabled:!0})}n.nodes||(n.nodes=[]);let o=i.map(c=>({type:"request",name:c.name,request:c,enabled:!0})),a=typeof r.insertAt=="number"?Math.max(0,Math.min(r.insertAt,n.nodes.length)):n.nodes.length;return n.nodes.splice(a,0,...o),await e.testSuite.updateSuite(n),{added:i.length,suite:n.name,insertAt:a,addedPaths:o.map((c,l)=>`${a+l}`),newRequestCount:kt(n.nodes||[]).length}}},{toolNames:[x.removeSuiteRequest],async handle({args:r,services:e}){let t=await Ae(r.suite,e);if(!Sm(t))throw A('remove_suite_request currently supports request-only root suites. For flow suites, use get_suite/update_suite_config with the full "nodes" graph.');t.nodes||(t.nodes=[]);let n=t.nodes.filter(i=>i.type==="request"),s;if(typeof r.index=="number"){if(r.index<0||r.index>=n.length)throw A(`index ${r.index} is out of range`);let i=n[r.index];s=i.name||i.request?.name,t.nodes=t.nodes.filter(o=>o!==i)}else if(typeof r.request=="string"){let i=r.request.toLowerCase(),o=n.find(a=>{let c=a.request?.name||a.name||"";return c===r.request||c.toLowerCase()===i});if(!o)throw A(`request "${r.request}" not found in suite "${t.name}"`);s=o.name||o.request?.name,t.nodes=t.nodes.filter(a=>a!==o)}else throw A('either "index" or "request" is required');return await e.testSuite.updateSuite(t),{removed:!0,request:s,newRequestCount:t.nodes.filter(i=>i.type==="request").length}}},{toolNames:[x.reorderSuiteRequests],async handle({args:r,services:e}){let t=await Ae(r.suite,e);if(!Sm(t))throw A('reorder_suite_requests currently supports request-only root suites. For flow suites, use get_suite/update_suite_config with the full "nodes" graph.');if(!Array.isArray(r.order))throw A('"order" must be an array of request names');let n=r.order,s=(t.nodes||[]).filter(a=>a.type==="request"),i=(t.nodes||[]).filter(a=>a.type!=="request"),o=[...s].sort((a,c)=>{let l=a.request?.name||a.name||"",u=c.request?.name||c.name||"",d=n.findIndex(h=>h===l||h.toLowerCase()===l.toLowerCase()),p=n.findIndex(h=>h===u||h.toLowerCase()===u.toLowerCase());return(d===-1?1/0:d)-(p===-1?1/0:p)});return t.nodes=[...o,...i],await e.testSuite.updateSuite(t),{reordered:!0,suite:t.name,newOrder:o.map(a=>a.request?.name||a.name)}}},{toolNames:[x.duplicateSuite],async handle({args:r,services:e}){let t=await Ae(r.suite,e),n=typeof r.newName=="string"?r.newName.trim():"";if(!n)throw A('"newName" is required');let s=await e.testSuite.duplicateSuite(t.id,n);return{id:s.id,name:s.name,duplicatedFrom:t.name,requestCount:s.nodes?.filter(i=>i.type==="request").length??0}}},{toolNames:[x.deleteSuite],async handle({args:r,services:e}){if(r.confirm!==!0)throw A('"confirm" must be true to delete a suite');let t=await Ae(r.suite,e);return await e.testSuite.deleteSuite(t.id),{deleted:!0,suite:t.name}}}]});function Gb(r){let e=[];return r.map(t=>{let n=gt(t,e);return e.push(n),n})}function km(r,e,t,n){let s=r.find(l=>l.id===e);if(s)return{item:s,tier:"id"};let i=Gb(r.map(l=>l.name)),o=r.filter((l,u)=>i[u]===e);if(o.length===1)return{item:o[0],tier:"slug"};if(o.length>1)throw new ns(t,e,o.map(l=>({id:l.id,name:l.name,path:n(l)})));let a=e.toLowerCase(),c=r.filter(l=>l.name.toLowerCase()===a);if(c.length===1)return{item:c[0],tier:"name"};throw c.length>1?new ns(t,e,c.map(l=>({id:l.id,name:l.name,path:n(l)}))):new Error(`${t.charAt(0).toUpperCase()}${t.slice(1)} "${e}" not found`)}function Oi(r,e){let{item:t,tier:n}=km(r,e,"collection",()=>"");return{collection:t,tier:n}}function yu(r,e){let t=e.split("/").map(o=>o.trim()).filter(o=>o.length>0),n=r.items,s=[],i=[];for(let o of t){let a=n.filter(d=>d.type==="folder"),c=s.join("/"),{item:l,tier:u}=km(a,o,"folder",d=>c?`${c}/${d.name}`:d.name);s.push(l.name),i.push(u),n=l.items??[]}return{folderPath:s.map($e).join("/"),tiers:i}}function Em(r,e,t){let n=[];for(let s of r)if(s.type==="request"){let i=gt(s.name,n);n.push(i),t.push({item:s,folderPath:e,slug:i})}for(let s of r)if(s.type==="folder"){let i=s,o=e?`${e}/${$e(i.name)}`:$e(i.name);Em(i.items??[],o,t)}}function vu(r,e,t){let n=[];Em(r.items,"",n);let s=t?t.replace(/\/+$/,""):void 0,i=s?n.filter(p=>p.folderPath===s||p.folderPath.startsWith(`${s}/`)):n,o=p=>p.folderPath?`${p.folderPath}/${p.item.name}`:p.item.name,a=i.find(p=>p.item.id===e);if(a)return{request:a.item,tier:"id",folderPath:a.folderPath};let c=i.filter(p=>p.slug===e);if(c.length===1)return{request:c[0].item,tier:"slug",folderPath:c[0].folderPath};if(c.length>1)throw new ns("request",e,c.map(p=>({id:p.item.id,name:p.item.name,path:o(p)})));let l=e.toLowerCase(),u=i.filter(p=>p.item.name.toLowerCase()===l);if(u.length===1)return{request:u[0].item,tier:"name",folderPath:u[0].folderPath};if(u.length>1)throw new ns("request",e,u.map(p=>({id:p.item.id,name:p.item.name,path:o(p)})));let d=s?` under folder "${s}"`:"";throw new Error(`Request "${e}" not found in collection "${r.name}"${d}`)}var ns,Oa=k(()=>{"use strict";tn();tt();ns=class extends Error{constructor(t,n,s){super(`Ambiguous ${t} reference "${n}" matches ${s.length} items:
|
|
990
|
+
Keep it under 600 words.`}async function mu(r,e,t,n,s){switch(r){case"analyze-test-failure":return zb(e,n,s);case"suggest-assertions":return Jb(e,t,n,s);case"review-collection":return Wb(e,t,s);default:throw new Error(`Unknown prompt: "${r}". Available: ${Ia.map(i=>i.name).join(", ")}`)}}var Ia,Ta=k(()=>{"use strict";Xn();tt();Ia=[{name:"analyze-test-failure",description:"Analyze a failed API test run. Returns a structured prompt the LLM uses to diagnose each failure and suggest concrete fixes \u2014 no extra AI configuration needed.",arguments:[{name:"runId",description:"Run ID returned by run_suite, run_collection, or run_folder",required:!0},{name:"request",description:"Filter analysis to a specific request name (omit to analyze all failures)",required:!1}]},{name:"suggest-assertions",description:"Generate pm.test() assertion scripts for a request. The LLM writes Chai-style assertions based on the request definition and optionally an observed response.",arguments:[{name:"collection",description:"Collection name or id",required:!0},{name:"request",description:"Request name or id",required:!0},{name:"runId",description:"Run ID to use observed response data for more accurate assertions (optional)",required:!1}]},{name:"review-collection",description:"Get an AI review of a collection's structure, naming conventions, test coverage gaps, and assertion quality.",arguments:[{name:"collection",description:"Collection name or id",required:!0}]}]});var gm,ym=k(()=>{"use strict";er();fu();Ta();Fe();Ne();gm=[{toolNames:[x.reviewSuite],async handle({args:r,services:e,runStore:t}){let n=typeof r.runId=="string"?r.runId.trim():void 0;if(!n)throw A('"runId" is required \u2014 the id of a completed suite run.');let s=t.require(n);if(s.status==="running")return{runId:n,status:"running",message:"The run has not completed yet. Wait for it to finish, then review again."};let i=r.suiteId?await Ae(r.suiteId,e):void 0,o=typeof r.slowResponseMs=="number"&&r.slowResponseMs>0?r.slowResponseMs:2e3,a=Aa(i,Pa(s),{slowResponseMs:o}),c;if(e.aiProvider&&a.findings.length>0)try{let l=await hm({rec:s,suite:i,report:a});c=(await ot(()=>e.aiProvider.complete(l))).trim().slice(0,12e3)||void 0}catch{}return{runId:n,suiteId:i?.id,suiteName:i?.name,status:s.status,pass:a.summary.pass,summary:a.summary,findings:a.findings,aiRecommendations:c,hint:a.summary.pass?"No error-severity findings. Use in CI as a gate on summary.pass.":`${a.summary.errors} error(s) found \u2014 fix before merge.`}}}]});var vm,bm=k(()=>{"use strict";Fe();Ne();vm=[{toolNames:[x.getRunStatus],handle({args:r,runStore:e}){let t=e.require(r.runId);return{runId:t.id,status:t.status,suiteName:t.suiteName,progress:t.progress,...t.error?{error:t.error}:{}}}},{toolNames:[x.getRunSummary],handle({args:r,runStore:e}){let t=e.require(r.runId);if(t.status==="running")return{runId:t.id,status:"running",progress:t.progress};let n=(t.summary.failed??0)>0||t.summary.allPassed===!1,s=t.noAssertionExamples??[],i=s.length,o=t.summary.total,a=i>0?i/(o||1)>.5?`${i}/${o} requests have no pm.test() assertions. Invoke the "review-collection" prompt (collection="${t.suiteName}") for a full coverage analysis.`:`${i} request(s) have no pm.test() assertions (e.g. ${s.slice(0,3).map(c=>`"${c}"`).join(", ")}). Invoke the "suggest-assertions" prompt (collection="${t.suiteName}") to add test coverage.`:null;return{runId:t.id,status:t.status,suiteName:t.suiteName,summary:t.summary,...t.reportPath?{report:{uri:`file://${t.reportPath}`}}:{},...n?{failedRequests:zt({failedRequests:t.failedRequests},[]).failedRequests}:{},...n?{_nextStep:`REQUIRED ACTION: ${t.summary.failed} request(s) failed. The failedRequests array above contains the full details (method, url, requestBody, requestHeaders, status, responseBody, failedTests). Immediately analyze each failed request and provide: (1) root cause, (2) specific fix, (3) corrected pm.test() assertions if relevant. Do NOT wait for the user to ask \u2014 diagnose now.`}:{},...a?{_suggestions:[a]}:{}}}},{toolNames:[x.getFailedRequests],handle({args:r,runStore:e}){let t=e.require(r.runId);if(t.status==="running")return{runId:t.id,status:"running",progress:t.progress,failedSoFar:t.failedRequests.length};let n=typeof r.offset=="number"?Math.max(0,r.offset):0,s=typeof r.limit=="number"?Math.min(100,Math.max(1,r.limit)):20;return{runId:t.id,status:t.status,totalFailed:t.failedRequests.length,offset:n,limit:s,failedRequests:t.failedRequests.slice(n,n+s)}}},{toolNames:[x.getRequestResult],handle({args:r,runStore:e}){let t=e.require(r.runId),n=r.request;if(typeof n!="string"||!n)throw A('"request" is required');let s=typeof r.iteration=="number"?r.iteration:1,i=t.allResults.find(o=>o.iteration===s&&(o.name===n||o.name.toLowerCase()===n.toLowerCase()));if(!i){if(t.status==="running")return{runId:t.id,status:"running",message:`Request "${n}" has not completed yet.`};throw new Error(`Request "${n}" (iteration ${s}) not found in run "${t.id}".`)}return{runId:t.id,...i}}},{toolNames:[x.cancelRun],handle({args:r,runStore:e}){let t=e.require(r.runId);if(t.status!=="running")return{runId:t.id,status:t.status,cancelled:!1,message:`Run is already "${t.status}" \u2014 nothing to cancel.`};let n=e.cancel(String(r.runId));return{runId:t.id,status:"cancelled",cancelled:n,progress:t.progress,message:"Cancellation requested. The currently-executing request will finish; remaining requests will be skipped."}}}]});function Sm(r){return(Array.isArray(r.nodes)?r.nodes:[]).every(t=>t?.type==="request")}function kt(r,e=""){let t=[];if(!Array.isArray(r))return t;for(let n=0;n<r.length;n+=1){let s=r[n],i=e?`${e}.${n}`:`${n}`;!s||typeof s!="object"||(s.type==="request"&&t.push({node:s,path:i}),Array.isArray(s.nodes)&&t.push(...kt(s.nodes,`${i}.nodes`)),Array.isArray(s.then)&&t.push(...kt(s.then,`${i}.then`)),Array.isArray(s.else)&&t.push(...kt(s.else,`${i}.else`)),Array.isArray(s.default)&&t.push(...kt(s.default,`${i}.default`)),Array.isArray(s.elseif)&&s.elseif.forEach((o,a)=>{Array.isArray(o?.nodes)&&t.push(...kt(o.nodes,`${i}.elseif.${a}.nodes`)),Array.isArray(o?.then)&&t.push(...kt(o.then,`${i}.elseif.${a}.then`))}),Array.isArray(s.cases)&&s.cases.forEach((o,a)=>{Array.isArray(o?.nodes)&&t.push(...kt(o.nodes,`${i}.cases.${a}.nodes`)),Array.isArray(o?.then)&&t.push(...kt(o.then,`${i}.cases.${a}.then`))}))}return t}function gu(r,e){if(typeof r!="string"||!r.trim())throw A(`"${e}" is required`);let t=r.trim(),n=t.split(".");if(n.some(s=>s===""))throw A(`"${e}" is invalid: "${t}"`);return n.map(s=>/^\d+$/.test(s)?Number(s):s)}function wm(r,e){let t=gu(e,"path"),n=r;for(let s of t)if(typeof s=="number"){if(!Array.isArray(n)||s<0||s>=n.length)throw A(`node path not found: "${String(e)}"`);n=n[s]}else{if(!n||typeof n!="object"||!(s in n))throw A(`node path not found: "${String(e)}"`);n=n[s]}return n}function hu(r,e){let t=gu(e,"path"),n=t[t.length-1];if(typeof n!="number")throw A(`"path" must end with a numeric index: "${String(e)}"`);let s=r;for(let i=0;i<t.length-1;i+=1){let o=t[i];if(typeof o=="number"){if(!Array.isArray(s)||o<0||o>=s.length)throw A(`node path not found: "${String(e)}"`);s=s[o]}else{if(!s||typeof s!="object"||!(o in s))throw A(`node path not found: "${String(e)}"`);s=s[o]}}if(!Array.isArray(s)||n<0||n>=s.length)throw A(`node path not found: "${String(e)}"`);return{array:s,index:n}}function xm(r,e,t,n){if(e==null||e===""){if(t!=null&&t!=="")throw A(`"${n}" is only valid when a parent path is provided`);return{array:r,pathPrefix:""}}if(typeof t!="string"||!t.trim())throw A(`"${n}" is required when parent path is provided`);let s=String(e).trim(),i=t.trim(),o=wm(r,s),a=gu(i,n),c=o;for(let l=0;l<a.length;l+=1){let u=a[l],d=l===a.length-1;if(typeof u=="number"){if(!Array.isArray(c)||u<0||u>=c.length)throw A(`branch path not found: "${i}"`);c=c[u]}else{if(!c||typeof c!="object")throw A(`branch path not found: "${i}"`);if(!(u in c))if(d)c[u]=[];else throw A(`branch path not found: "${i}"`);c=c[u]}}if(!Array.isArray(c))throw A(`target branch must be an array: "${i}"`);return{array:c,pathPrefix:`${s}.${i}`}}function Gb(r,e=""){let t=[],n=[],s=(i,o)=>{if(Array.isArray(i)){o&&n.push(o);for(let a=0;a<i.length;a+=1){let c=i[a],l=o?`${o}.${a}`:`${a}`;t.push({path:l,type:c?.type,name:c?.name}),!(!c||typeof c!="object")&&(Array.isArray(c.nodes)&&s(c.nodes,`${l}.nodes`),Array.isArray(c.then)&&s(c.then,`${l}.then`),Array.isArray(c.else)&&s(c.else,`${l}.else`),Array.isArray(c.default)&&s(c.default,`${l}.default`),Array.isArray(c.cases)&&c.cases.forEach((u,d)=>{Array.isArray(u?.nodes)&&s(u.nodes,`${l}.cases.${d}.nodes`),Array.isArray(u?.then)&&s(u.then,`${l}.cases.${d}.then`)}),Array.isArray(c.elseif)&&c.elseif.forEach((u,d)=>{Array.isArray(u?.nodes)&&s(u.nodes,`${l}.elseif.${d}.nodes`),Array.isArray(u?.then)&&s(u.then,`${l}.elseif.${d}.then`)}))}}};return s(r,e),{nodePaths:t,branchPaths:n}}var Rm,Cm=k(()=>{"use strict";Fe();Ne();Ne();Rm=[{toolNames:[x.listSuites],async handle({services:r}){return{suites:(await r.testSuite.getAllSuites()).map(t=>({id:t.id,name:t.name,description:t.description??"",requestCount:kt(t.nodes||[]).length,flowNodeCount:t.nodes?.length??0,iterations:t.config?.iterations??1}))}}},{toolNames:[x.getSuite],async handle({args:r,services:e}){let t=await Ae(r.suite,e),n=kt(t.nodes||[]);return{id:t.id,name:t.name,description:t.description??"",config:{iterations:t.config?.iterations??1,delayBetweenRequests:t.config?.delayBetweenRequests??0,stopOnError:t.config?.stopOnError??!1},nodes:t.nodes||[],requests:n.map(({node:s,path:i})=>{let o=s.request;return{nodePath:i,slug:o.slug??o.requestId,collectionId:o.collectionId,requestId:o.requestId,name:o.name,method:o.method,folderPath:o.folderPath??"",enabled:s.enabled!==!1}})}}},{toolNames:[x.createSuite],async handle({args:r,services:e,collections:t}){let n=typeof r.name=="string"?r.name.trim():"";if(!n)throw A('"name" is required');let s;if(typeof r.fromCollection=="string"&&r.fromCollection.trim()){let i=W(r.fromCollection,t),o=await e.testSuite.createTempSuiteFromCollection(i.id);if(!o)throw new Error(`Could not build suite from collection "${i.name}"`);if(typeof r.fromFolder=="string"&&r.fromFolder.trim()){let a=zr(r.fromFolder),c=o.nodes||[];o.nodes=c.filter(l=>{if(l.type!=="request")return!0;let u=l.request?.folderPath||"";return u===a||u.startsWith(`${a}/`)})}s=await e.testSuite.saveTempSuite(o,n)}else s=await e.testSuite.createSuite(n);if(r.iterations!==void 0||r.stopOnError!==void 0||r.delayBetweenRequests!==void 0||r.description!==void 0||r.nodes!==void 0){if(r.description!==void 0&&(s.description=String(r.description)),r.nodes!==void 0){if(!Array.isArray(r.nodes))throw A('"nodes" must be an array when provided');s.nodes=r.nodes}s.config={...s.config,...typeof r.iterations=="number"?{iterations:r.iterations}:{},...typeof r.stopOnError=="boolean"?{stopOnError:r.stopOnError}:{},...typeof r.delayBetweenRequests=="number"?{delayBetweenRequests:r.delayBetweenRequests}:{}},await e.testSuite.updateSuite(s)}return{id:s.id,name:s.name,requestCount:s.nodes?.filter(i=>i.type==="request").length??0,created:!0,hint:(s.nodes?.filter(i=>i.type==="request").length??0)===0?"Suite is empty. Call add_suite_requests to populate it with requests from a collection.":"Suite created. Call run_suite to execute it."}}},{toolNames:[x.updateSuiteConfig],async handle({args:r,services:e}){let t=await Ae(r.suite,e);if(typeof r.name=="string"&&r.name.trim()&&(t.name=r.name.trim()),typeof r.description=="string"&&(t.description=r.description),r.nodes!==void 0){if(!Array.isArray(r.nodes))throw A('"nodes" must be an array when provided');t.nodes=r.nodes}return t.config={...t.config,...typeof r.iterations=="number"?{iterations:r.iterations}:{},...typeof r.stopOnError=="boolean"?{stopOnError:r.stopOnError}:{},...typeof r.delayBetweenRequests=="number"?{delayBetweenRequests:r.delayBetweenRequests}:{}},await e.testSuite.updateSuite(t),{updated:!0,suite:t.name}}},{toolNames:[x.getSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);Array.isArray(t.nodes)||(t.nodes=[]);let n=wm(t.nodes,r.path);return{suite:t.name,path:String(r.path),node:n}}},{toolNames:[x.listSuiteNodePaths],async handle({args:r,services:e}){let t=await Ae(r.suite,e);Array.isArray(t.nodes)||(t.nodes=[]);let n=r.includeBranches!==!1,s=Gb(t.nodes);return{suite:t.name,nodeCount:s.nodePaths.length,nodePaths:s.nodePaths,branchPaths:n?s.branchPaths:void 0,rootBranchPath:""}}},{toolNames:[x.addSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);if(Array.isArray(t.nodes)||(t.nodes=[]),!r.node||typeof r.node!="object"||Array.isArray(r.node))throw A('"node" must be an object');let{array:n,pathPrefix:s}=xm(t.nodes,r.parentPath,r.branch,"branch"),i=typeof r.index=="number"?Math.max(0,Math.min(r.index,n.length)):n.length;n.splice(i,0,r.node),await e.testSuite.updateSuite(t);let o=s?`${s}.${i}`:`${i}`;return{added:!0,suite:t.name,path:o}}},{toolNames:[x.updateSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);if(Array.isArray(t.nodes)||(t.nodes=[]),!r.node||typeof r.node!="object"||Array.isArray(r.node))throw A('"node" must be an object');let n=hu(t.nodes,r.path);return n.array[n.index]=r.node,await e.testSuite.updateSuite(t),{updated:!0,suite:t.name,path:String(r.path)}}},{toolNames:[x.removeSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);Array.isArray(t.nodes)||(t.nodes=[]);let n=hu(t.nodes,r.path),[s]=n.array.splice(n.index,1);return await e.testSuite.updateSuite(t),{removed:!0,suite:t.name,path:String(r.path),removedType:s?.type}}},{toolNames:[x.moveSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);Array.isArray(t.nodes)||(t.nodes=[]);let n=hu(t.nodes,r.fromPath),s=n.array[n.index];n.array.splice(n.index,1);let{array:i,pathPrefix:o}=xm(t.nodes,r.toParentPath,r.toBranch,"toBranch"),a=typeof r.toIndex=="number"?Math.max(0,Math.min(r.toIndex,i.length)):i.length;n.array===i&&n.index<a&&(a-=1),i.splice(a,0,s),await e.testSuite.updateSuite(t);let c=o?`${o}.${a}`:`${a}`;return{moved:!0,suite:t.name,fromPath:String(r.fromPath),toPath:c}}},{toolNames:[x.addSuiteRequests],async handle({args:r,services:e,collections:t}){let n=await Ae(r.suite,e),s=Array.isArray(r.requests)?r.requests:[];if(s.length===0)throw A('"requests" array is required and must not be empty');let i=[];for(let c of s){let l=W(c.collection,t),u=We(c.request,l),d=X(l).find(p=>p.request.id===u.id)?.folderPath??"";i.push({slug:u.id,collectionId:l.id,requestId:u.id,name:u.name,method:u.method,collectionName:l.name,folderPath:d,enabled:!0})}n.nodes||(n.nodes=[]);let o=i.map(c=>({type:"request",name:c.name,request:c,enabled:!0})),a=typeof r.insertAt=="number"?Math.max(0,Math.min(r.insertAt,n.nodes.length)):n.nodes.length;return n.nodes.splice(a,0,...o),await e.testSuite.updateSuite(n),{added:i.length,suite:n.name,insertAt:a,addedPaths:o.map((c,l)=>`${a+l}`),newRequestCount:kt(n.nodes||[]).length}}},{toolNames:[x.removeSuiteRequest],async handle({args:r,services:e}){let t=await Ae(r.suite,e);if(!Sm(t))throw A('remove_suite_request currently supports request-only root suites. For flow suites, use get_suite/update_suite_config with the full "nodes" graph.');t.nodes||(t.nodes=[]);let n=t.nodes.filter(i=>i.type==="request"),s;if(typeof r.index=="number"){if(r.index<0||r.index>=n.length)throw A(`index ${r.index} is out of range`);let i=n[r.index];s=i.name||i.request?.name,t.nodes=t.nodes.filter(o=>o!==i)}else if(typeof r.request=="string"){let i=r.request.toLowerCase(),o=n.find(a=>{let c=a.request?.name||a.name||"";return c===r.request||c.toLowerCase()===i});if(!o)throw A(`request "${r.request}" not found in suite "${t.name}"`);s=o.name||o.request?.name,t.nodes=t.nodes.filter(a=>a!==o)}else throw A('either "index" or "request" is required');return await e.testSuite.updateSuite(t),{removed:!0,request:s,newRequestCount:t.nodes.filter(i=>i.type==="request").length}}},{toolNames:[x.reorderSuiteRequests],async handle({args:r,services:e}){let t=await Ae(r.suite,e);if(!Sm(t))throw A('reorder_suite_requests currently supports request-only root suites. For flow suites, use get_suite/update_suite_config with the full "nodes" graph.');if(!Array.isArray(r.order))throw A('"order" must be an array of request names');let n=r.order,s=(t.nodes||[]).filter(a=>a.type==="request"),i=(t.nodes||[]).filter(a=>a.type!=="request"),o=[...s].sort((a,c)=>{let l=a.request?.name||a.name||"",u=c.request?.name||c.name||"",d=n.findIndex(h=>h===l||h.toLowerCase()===l.toLowerCase()),p=n.findIndex(h=>h===u||h.toLowerCase()===u.toLowerCase());return(d===-1?1/0:d)-(p===-1?1/0:p)});return t.nodes=[...o,...i],await e.testSuite.updateSuite(t),{reordered:!0,suite:t.name,newOrder:o.map(a=>a.request?.name||a.name)}}},{toolNames:[x.duplicateSuite],async handle({args:r,services:e}){let t=await Ae(r.suite,e),n=typeof r.newName=="string"?r.newName.trim():"";if(!n)throw A('"newName" is required');let s=await e.testSuite.duplicateSuite(t.id,n);return{id:s.id,name:s.name,duplicatedFrom:t.name,requestCount:s.nodes?.filter(i=>i.type==="request").length??0}}},{toolNames:[x.deleteSuite],async handle({args:r,services:e}){if(r.confirm!==!0)throw A('"confirm" must be true to delete a suite');let t=await Ae(r.suite,e);return await e.testSuite.deleteSuite(t.id),{deleted:!0,suite:t.name}}}]});function Kb(r){let e=[];return r.map(t=>{let n=gt(t,e);return e.push(n),n})}function km(r,e,t,n){let s=r.find(l=>l.id===e);if(s)return{item:s,tier:"id"};let i=Kb(r.map(l=>l.name)),o=r.filter((l,u)=>i[u]===e);if(o.length===1)return{item:o[0],tier:"slug"};if(o.length>1)throw new ns(t,e,o.map(l=>({id:l.id,name:l.name,path:n(l)})));let a=e.toLowerCase(),c=r.filter(l=>l.name.toLowerCase()===a);if(c.length===1)return{item:c[0],tier:"name"};throw c.length>1?new ns(t,e,c.map(l=>({id:l.id,name:l.name,path:n(l)}))):new Error(`${t.charAt(0).toUpperCase()}${t.slice(1)} "${e}" not found`)}function Oi(r,e){let{item:t,tier:n}=km(r,e,"collection",()=>"");return{collection:t,tier:n}}function yu(r,e){let t=e.split("/").map(o=>o.trim()).filter(o=>o.length>0),n=r.items,s=[],i=[];for(let o of t){let a=n.filter(d=>d.type==="folder"),c=s.join("/"),{item:l,tier:u}=km(a,o,"folder",d=>c?`${c}/${d.name}`:d.name);s.push(l.name),i.push(u),n=l.items??[]}return{folderPath:s.map($e).join("/"),tiers:i}}function Em(r,e,t){let n=[];for(let s of r)if(s.type==="request"){let i=gt(s.name,n);n.push(i),t.push({item:s,folderPath:e,slug:i})}for(let s of r)if(s.type==="folder"){let i=s,o=e?`${e}/${$e(i.name)}`:$e(i.name);Em(i.items??[],o,t)}}function vu(r,e,t){let n=[];Em(r.items,"",n);let s=t?t.replace(/\/+$/,""):void 0,i=s?n.filter(p=>p.folderPath===s||p.folderPath.startsWith(`${s}/`)):n,o=p=>p.folderPath?`${p.folderPath}/${p.item.name}`:p.item.name,a=i.find(p=>p.item.id===e);if(a)return{request:a.item,tier:"id",folderPath:a.folderPath};let c=i.filter(p=>p.slug===e);if(c.length===1)return{request:c[0].item,tier:"slug",folderPath:c[0].folderPath};if(c.length>1)throw new ns("request",e,c.map(p=>({id:p.item.id,name:p.item.name,path:o(p)})));let l=e.toLowerCase(),u=i.filter(p=>p.item.name.toLowerCase()===l);if(u.length===1)return{request:u[0].item,tier:"name",folderPath:u[0].folderPath};if(u.length>1)throw new ns("request",e,u.map(p=>({id:p.item.id,name:p.item.name,path:o(p)})));let d=s?` under folder "${s}"`:"";throw new Error(`Request "${e}" not found in collection "${r.name}"${d}`)}var ns,Oa=k(()=>{"use strict";tn();tt();ns=class extends Error{constructor(t,n,s){super(`Ambiguous ${t} reference "${n}" matches ${s.length} items:
|
|
991
991
|
`+s.map(i=>` - ${i.name} (id: ${i.id}, path: ${i.path||"/"})`).join(`
|
|
992
992
|
`)+`
|
|
993
993
|
Disambiguate by passing the id or slug.`);this.kind=t;this.value=n;this.candidates=s;this.name="AmbiguousRefError"}kind;value;candidates}});var dr,$a=k(()=>{"use strict";$n();dr=class{cookies=new Map;getCookieKey(e,t,n){return oe.cookieKey(e,t,n)}getCookiesForDomain(e){let t=[];for(let n of this.cookies.values())oe.isExpired(n)||(!n.domain||oe.domainMatches(e,n.domain))&&t.push(n);return t}has(e,t){return this.get(e,t)!==void 0}get(e,t){let n=this.getCookieKey(e,t),s=this.cookies.get(n);if(s&&!oe.isExpired(s))return s}set(e){let t=this.getCookieKey(e.name,e.domain,e.path);this.cookies.set(t,e)}delete(e,t,n){let s=this.getCookieKey(e,t,n);return this.cookies.delete(s)}getAll(e){if(e)return this.getCookiesForDomain(e);let t=[];for(let n of this.cookies.values())oe.isExpired(n)||t.push(n);return t}setCookiesFromResponse(e,t){let n=oe.extractDomain(e),s=oe.parseCookieHeaders(t,n);for(let i of s){let o=this.getCookieKey(i.name,i.domain,i.path);this.cookies.set(o,i)}}getCookieHeader(e){let t=oe.extractDomain(e),n=oe.extractPath(e),i=this.getCookiesForDomain(t).filter(o=>o.path?n.startsWith(o.path):!0);if(i.length!==0)return oe.formatCookieHeader(i)}clear(){this.cookies.clear()}}});function pr(r,e,t){let n=String(r).padStart(6,"0"),s=String(e).padStart(4,"0");return`result-${n}-iter-${s}-${t}.json`}var bu,dt,rs=k(()=>{"use strict";bu={GET:0,POST:1,PUT:2,DELETE:3,PATCH:4,HEAD:5,OPTIONS:6,TRACE:7,CONNECT:8},dt={0:"GET",1:"POST",2:"PUT",3:"DELETE",4:"PATCH",5:"HEAD",6:"OPTIONS",7:"TRACE",8:"CONNECT"}});import*as is from"fs/promises";import*as ss from"path";function Ge(r){return String(r??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g,"")}function Su(r){return(Math.max(0,r)/1e3).toFixed(3)}var Qt,$i=k(()=>{"use strict";rs();Qt=class{constructor(e){this.basePath=e}basePath;async generate(e,t){let n=ss.join(this.basePath,e,t),s=JSON.parse(await is.readFile(ss.join(n,"manifest.json"),"utf-8")),i=await this.loadAllSummaries(n,s.totalIndexPages),o=await this.loadAllDetails(n,i),a=this.buildXml(s,i,o),c=ss.join(n,"junit.xml");return await is.writeFile(c,a,"utf-8"),c}async loadAllSummaries(e,t){let n=[];for(let s=1;s<=t;s++){let i=ss.join(e,"index",`page-${String(s).padStart(4,"0")}.json`);try{let o=JSON.parse(await is.readFile(i,"utf-8"));n.push(...o.summaries)}catch{}}return n}async loadAllDetails(e,t){let n=new Map;for(let s of t){let i=pr(s.i,s.it,s.r),o=`${s.i}-${s.it}`;try{let a=JSON.parse(await is.readFile(ss.join(e,"results",i),"utf-8"));n.set(o,a)}catch{}}return n}buildGroups(e,t,n){let s=e.config?.iterations>1,i=[],o=new Map;for(let a of t){let c=n.get(`${a.i}-${a.it}`),l=a.cn||c?.collectionName||e.suiteName||"",u=a.fp||c?.folderPath||"",d=`${l}\0${u}`;if(!o.has(d)){let g=[l,u].filter(Boolean).join(" / ")||e.suiteName||"Requests";o.set(d,{label:g,cases:[]}),i.push(d)}let p=a.n||c?.name||dt[a.m]||"request",m=s?`${p} (iteration ${a.it})`:p,f=(c?.assertions??[]).filter(g=>!g.passed&&!g.skipped).map(g=>({name:g.name,message:g.message})),h=(c?.assertions??[]).filter(g=>g.skipped).length||(a.as??0);f.length===0&&a.af>0&&f.push({name:`${a.af} assertion(s) failed`,message:null}),o.get(d).cases.push({name:m,classname:[l,u].filter(Boolean).join(".")||e.suiteName||"http-forge",durationMs:a.d,status:a.s,passed:a.p,error:a.e??c?.error??null,failedAssertions:f,skippedAssertions:h,consoleOutput:c?.consoleOutput})}return i.map(a=>o.get(a))}buildXml(e,t,n){let s=this.buildGroups(e,t,n),i=0,o=0,a=0,c=0,l=0,u=[];s.forEach((m,f)=>{let h=0,g=0,v=0,y=0,S=0,b=[];for(let E of m.cases){h++,S+=E.durationMs;let F=!E.passed&&E.failedAssertions.length===0&&!!E.error,N=!E.passed&&!F;F&&v++,N&&g++,E.skippedAssertions>0&&y++;let j=[];if(N){let D=E.failedAssertions.length>0?E.failedAssertions.map(M=>M.name).join("; "):E.error||"Assertion failed",P=E.failedAssertions.map(M=>M.message?`${M.name}: ${M.message}`:M.name).join(`
|
|
@@ -1009,15 +1009,15 @@ ${u.join(`
|
|
|
1009
1009
|
</testsuites>
|
|
1010
1010
|
`}}});import*as as from"fs/promises";import*as os from"path";function re(r){return String(r??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Im(r,e=Pm){if(r.length<=e)return r;let t=r.length-e;return r.slice(0,e)+`
|
|
1011
1011
|
|
|
1012
|
-
\u2026 [truncated ${t.toLocaleString()} characters \u2014 open the full result file on disk to see the complete body] \u2026`}function nt(r){return r>=1e3?`${(r/1e3).toFixed(2)}s`:`${r}ms`}function Fi(r){try{return new Date(r).toLocaleString()}catch{return r}}function Fa(r){return r>=100&&r<200?"status-1xx":r>=200&&r<300?"status-2xx":r>=300&&r<400?"status-3xx":r>=400&&r<500?"status-4xx":"status-5xx"}function xu(r,e){return e===0?"\u2014":`${Math.round(r/e*100)}%`}function Tm(r){try{return typeof r=="string"&&(r=JSON.parse(r)),JSON.stringify(r,null,2)}catch{return String(r??"")}}function qm(r){return!r||Object.keys(r).length===0?'<span class="dim">\u2014</span>':`<table class="kv-table">${Object.entries(r).map(([t,n])=>{let s=Array.isArray(n)?n.join(", "):String(n??"");return`<tr><td class="kv-key">${re(t)}</td><td class="kv-val">${re(s)}</td></tr>`}).join("")}</table>`}function
|
|
1012
|
+
\u2026 [truncated ${t.toLocaleString()} characters \u2014 open the full result file on disk to see the complete body] \u2026`}function nt(r){return r>=1e3?`${(r/1e3).toFixed(2)}s`:`${r}ms`}function Fi(r){try{return new Date(r).toLocaleString()}catch{return r}}function Fa(r){return r>=100&&r<200?"status-1xx":r>=200&&r<300?"status-2xx":r>=300&&r<400?"status-3xx":r>=400&&r<500?"status-4xx":"status-5xx"}function xu(r,e){return e===0?"\u2014":`${Math.round(r/e*100)}%`}function Tm(r){try{return typeof r=="string"&&(r=JSON.parse(r)),JSON.stringify(r,null,2)}catch{return String(r??"")}}function qm(r){return!r||Object.keys(r).length===0?'<span class="dim">\u2014</span>':`<table class="kv-table">${Object.entries(r).map(([t,n])=>{let s=Array.isArray(n)?n.join(", "):String(n??"");return`<tr><td class="kv-key">${re(t)}</td><td class="kv-val">${re(s)}</td></tr>`}).join("")}</table>`}function Qb(r){return r==null||r===""?'<span class="dim">\u2014</span>':typeof r=="string"?re(r):typeof r=="number"||typeof r=="boolean"?re(String(r)):`<pre class="code">${re(Tm(r))}</pre>`}function wu(r){return!r||Object.keys(r).length===0?'<span class="dim">\u2014</span>':`<table class="kv-table meta-table">${Object.entries(r).map(([t,n])=>`
|
|
1013
1013
|
<tr>
|
|
1014
1014
|
<td class="kv-key">${re(t)}</td>
|
|
1015
|
-
<td class="kv-val">${
|
|
1016
|
-
</tr>`).join("")}</table>`}function
|
|
1015
|
+
<td class="kv-val">${Qb(n)}</td>
|
|
1016
|
+
</tr>`).join("")}</table>`}function Zb(r){return!r||r.length===0?'<span class="dim">\u2014</span>':`<table class="kv-table">${r.map(t=>`
|
|
1017
1017
|
<tr>
|
|
1018
1018
|
<td class="kv-key">${re(t.name??"(unnamed)")}</td>
|
|
1019
1019
|
<td class="kv-val">${re(t.value??"")}</td>
|
|
1020
|
-
</tr>`).join("")}</table>`}function Am(r,e,t){if(r==null||r==="")return'<span class="dim">\u2014 empty \u2014</span>';let n=Im(Tm(r),e);return`<pre class="code">${re(n)}</pre>`}var Pm,
|
|
1020
|
+
</tr>`).join("")}</table>`}function Am(r,e,t){if(r==null||r==="")return'<span class="dim">\u2014 empty \u2014</span>';let n=Im(Tm(r),e);return`<pre class="code">${re(n)}</pre>`}var Pm,Yb,Xb,cs,Ru=k(()=>{"use strict";rs();Pm=1e5;Yb={maxBodyChars:Pm,embedBodies:"failed"},Xb=`
|
|
1021
1021
|
(function(){
|
|
1022
1022
|
var ROOT = {};
|
|
1023
1023
|
try { ROOT = JSON.parse(document.getElementById('hf-details').textContent || '{}'); } catch(e){ ROOT = {}; }
|
|
@@ -1067,7 +1067,7 @@ ${u.join(`
|
|
|
1067
1067
|
b.setAttribute('data-rendered','1');
|
|
1068
1068
|
}, true);
|
|
1069
1069
|
})();
|
|
1070
|
-
`,cs=class{constructor(e,t){this.basePath=e;this.options={...
|
|
1070
|
+
`,cs=class{constructor(e,t){this.basePath=e;this.options={...Yb,...t}}basePath;options;shouldEmbedBody(e){switch(this.options.embedBodies){case"all":return!0;case"none":return!1;default:return!e}}bodyOmittedNote(){return`<span class="dim">\u2014 ${this.options.embedBodies==="none"?"body embedding disabled":"passed request \u2014 body omitted"}; open the full result file on disk to see it \u2014</span>`}async generate(e,t){let n=os.join(this.basePath,e,t),s=JSON.parse(await as.readFile(os.join(n,"manifest.json"),"utf-8")),i=await this.loadAllSummaries(n,s.totalIndexPages),o=await this.loadAllDetails(n,i),a=this.buildHtml(s,i,o),c=os.join(n,this.buildReportFileName(s));return await as.writeFile(c,a,"utf-8"),c}buildReportFileName(e){let t=(e.environment||"default").replace(/\s+/g,"_").replace(/[^\w.-]/g,""),n="unknown";try{let s=new Date(e.startTime),i=s.getFullYear(),o=String(s.getMonth()+1).padStart(2,"0"),a=String(s.getDate()).padStart(2,"0"),c=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");n=`${i}-${o}-${a}-${c}-${l}`}catch{}return`report-${t}-${n}.html`}async loadAllSummaries(e,t){let n=[];for(let s=1;s<=t;s++){let i=os.join(e,"index",`page-${String(s).padStart(4,"0")}.json`);try{let o=JSON.parse(await as.readFile(i,"utf-8"));n.push(...o.summaries)}catch{}}return n}async loadAllDetails(e,t){let n=new Map;for(let s of t){let i=pr(s.i,s.it,s.r),o=`${s.i}-${s.it}`;try{let a=JSON.parse(await as.readFile(os.join(e,"results",i),"utf-8"));this.shouldEmbedBody(s.p)?typeof a.response?.body=="string"&&(a.response.body=Im(a.response.body,this.options.maxBodyChars)):a.response&&(a.response.body=void 0),n.set(o,a)}catch{}}return n}groupByIterCollectionFolder(e){let t=[],n=null,s=null,i=null;for(let o of e){let a=o.cn||"",c=o.gp||o.fp||"",l=o.gt;(!n||n.it!==o.it)&&(n={it:o.it,groups:[]},t.push(n),s=null,i=null);let u=`${l||""}\0${c}`;(!s||u!==i)&&(s={cn:a,fp:c,gt:l,items:[]},n.groups.push(s),i=u),s.items.push(o)}return t}groupLabel(e,t,n,s){let i=String(s).padStart(2,"0"),o="";return n==="block"?o=re(t||"(unnamed block)"):t&&(o=t.split("/").map(c=>re(c.replace(/^\s*\d+\s*-\s*/,""))).join("/")),o||(o="(root)"),`${i} - ${o}`}renderGroupedDetails(e,t,n){return this.groupByIterCollectionFolder(e).map(i=>{let o=i.groups.map((l,u)=>{let d=l.items.filter(g=>g.p).length,p=l.items.length,m=d<p,f=l.items.map(n).join(""),h=l.gt==="block"?"\u{1F9E9}":"\u{1F4C1}";return`
|
|
1071
1071
|
<details class="group-block${m?" group-fail":""}" open>
|
|
1072
1072
|
<summary class="group-head">
|
|
1073
1073
|
<span class="group-title">${h} ${this.groupLabel(l.cn,l.fp,l.gt,u+1)}</span>
|
|
@@ -1110,7 +1110,7 @@ ${u.join(`
|
|
|
1110
1110
|
<span class="assert-icon">${ht.passed?"\u2713":"\u2717"}</span>
|
|
1111
1111
|
${re(ht.name)}
|
|
1112
1112
|
${ht.message?`<span class="assert-msg"> \u2014 ${re(ht.message)}</span>`:""}
|
|
1113
|
-
</li>`).join("")}</ul>`:'<span class="dim">No assertions</span>',ft=qm(B?.request?.headers),Yt=wu(B?{method:B.request?.method,url:B.request?.url,query:B.request?.query,params:B.request?.params,bodyType:B.request?.body?.type,bodyFormat:B.request?.body?.format}:void 0),Se=B?.request?.body,ms=Se&&typeof Se=="object"?Se.type:void 0,Cr=Se&&typeof Se=="object"&&"content"in Se?Se.content:Se,tc=ms!=="none"&&!(Cr==null||Cr===""),mt=this.shouldEmbedBody(q.p),Ui=tc?mt?Am(Cr,this.options.maxBodyChars):this.bodyOmittedNote():"",Pt=qm(B?.response?.headers),T=wu(B?{status:B.status,statusText:B.statusText,durationMs:B.duration,responseTimeMs:B.response?.time,responseSizeBytes:B.response?.size}:void 0),I=mt?B?.response?.body!==void 0&&B.response.body!==null?Am(B.response.body,this.options.maxBodyChars):'<span class="dim">\u2014 no body \u2014</span>':this.bodyOmittedNote(),Q=
|
|
1113
|
+
</li>`).join("")}</ul>`:'<span class="dim">No assertions</span>',ft=qm(B?.request?.headers),Yt=wu(B?{method:B.request?.method,url:B.request?.url,query:B.request?.query,params:B.request?.params,bodyType:B.request?.body?.type,bodyFormat:B.request?.body?.format}:void 0),Se=B?.request?.body,ms=Se&&typeof Se=="object"?Se.type:void 0,Cr=Se&&typeof Se=="object"&&"content"in Se?Se.content:Se,tc=ms!=="none"&&!(Cr==null||Cr===""),mt=this.shouldEmbedBody(q.p),Ui=tc?mt?Am(Cr,this.options.maxBodyChars):this.bodyOmittedNote():"",Pt=qm(B?.response?.headers),T=wu(B?{status:B.status,statusText:B.statusText,durationMs:B.duration,responseTimeMs:B.response?.time,responseSizeBytes:B.response?.size}:void 0),I=mt?B?.response?.body!==void 0&&B.response.body!==null?Am(B.response.body,this.options.maxBodyChars):'<span class="dim">\u2014 no body \u2014</span>':this.bodyOmittedNote(),Q=Zb(B?.response?.cookies),U=wu(B?{timestamp:B.timestamp?new Date(B.timestamp).toISOString():void 0,nextRequest:B.nextRequest,visualizerTemplate:B.visualizerData?.template,visualizerData:B.visualizerData?.data}:void 0),K=`
|
|
1114
1114
|
<div class="detail-section">
|
|
1115
1115
|
<div class="pane-section-title">Assertions
|
|
1116
1116
|
<span class="assert-counts">
|
|
@@ -1695,7 +1695,7 @@ ${u.join(`
|
|
|
1695
1695
|
</p>
|
|
1696
1696
|
</div>
|
|
1697
1697
|
<script id="hf-details" type="application/json">${Ie}</script>
|
|
1698
|
-
<script>${
|
|
1698
|
+
<script>${Xb}</script>
|
|
1699
1699
|
<script>
|
|
1700
1700
|
// \u2500\u2500 Tab switching \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1701
1701
|
function showTab(name, btn) {
|
|
@@ -1779,15 +1779,15 @@ ${u.join(`
|
|
|
1779
1779
|
});
|
|
1780
1780
|
</script>
|
|
1781
1781
|
</body>
|
|
1782
|
-
</html>`}}});import*as mr from"fs/promises";import*as fr from"path";function Om(r){return r>=1e3?`${(r/1e3).toFixed(2)}s`:`${r}ms`}function
|
|
1783
|
-
\u2026 [${t.length-e} chars truncated]`}function $m(r){if(r==null||r==="")return"*(empty)*";try{let e=typeof r=="string"?r:JSON.stringify(r,null,2);return"```json\n"+
|
|
1782
|
+
</html>`}}});import*as mr from"fs/promises";import*as fr from"path";function Om(r){return r>=1e3?`${(r/1e3).toFixed(2)}s`:`${r}ms`}function eS(r){try{return new Date(r).toLocaleString()}catch{return r}}function tS(r,e=Fm){if(!r)return"";let t=typeof r=="string"?r:JSON.stringify(r,null,2);return t.length<=e?t:t.slice(0,e)+`
|
|
1783
|
+
\u2026 [${t.length-e} chars truncated]`}function $m(r){if(r==null||r==="")return"*(empty)*";try{let e=typeof r=="string"?r:JSON.stringify(r,null,2);return"```json\n"+tS(e)+"\n```"}catch{return String(r).slice(0,Fm)}}var Fm,Na,Nm=k(()=>{"use strict";rs();Fm=2e3;Na=class{constructor(e,t){this.basePath=e;this.suitesPath=t}basePath;suitesPath;async generate(e,t){let n=fr.join(this.basePath,e,t),s=JSON.parse(await mr.readFile(fr.join(n,"manifest.json"),"utf-8")),i=await this.loadAllSummaries(n,s.totalIndexPages),o=i.filter(d=>!d.p),a=await this.loadDetails(n,o),c;if(this.suitesPath)try{let d=fr.join(this.suitesPath,`${e}.suite.json`);c=JSON.parse(await mr.readFile(d,"utf-8"))}catch{c=void 0}let l=this.buildMarkdown(s,i,o,a,e,c),u=fr.join(n,"run-summary.md");return await mr.writeFile(u,l,"utf-8"),u}async loadAllSummaries(e,t){let n=[];for(let s=1;s<=t;s++){let i=fr.join(e,"index",`page-${String(s).padStart(4,"0")}.json`);try{let o=JSON.parse(await mr.readFile(i,"utf-8"));n.push(...o.summaries)}catch{}}return n}async loadDetails(e,t){let n=new Map;for(let s of t){let i=pr(s.i,s.it,s.r);try{let o=JSON.parse(await mr.readFile(fr.join(e,"results",i),"utf-8"));n.set(`${s.i}-${s.it}`,o)}catch{}}return n}buildMarkdown(e,t,n,s,i,o){let a=t.length,c=t.filter(y=>y.p).length,l=a-c,u=t.reduce((y,S)=>y+S.d,0),d=a>0?Math.round(c/a*100):0,p=[];p.push("# HTTP Forge Run Summary"),p.push(""),p.push("> **Generated by HTTP Forge** \u2014 for AI tools (Claude Code, GitHub Copilot, Cursor, etc.)"),p.push(""),p.push("| Field | Value |"),p.push("|---|---|"),p.push(`| **Suite** | ${e.suiteName} |`),p.push(`| **Run ID** | ${e.runId} |`),p.push(`| **Environment** | ${e.environment||"\u2014"} |`),p.push(`| **Started** | ${eS(e.startTime)} |`),p.push(`| **Status** | ${e.status} |`),p.push(`| **Duration** | ${Om(u)} |`),p.push(""),p.push("## Results Overview"),p.push(""),p.push("| Metric | Value |"),p.push("|---|---|"),p.push(`| Total Requests | ${a} |`),p.push(`| \u2705 Passed | ${c} |`),p.push(`| \u274C Failed | ${l} |`),p.push(`| Pass Rate | ${d}% |`),p.push(""),l>0&&(p.push("## \u274C Failed Requests"),p.push(""),p.push("> These are the requests that need investigation."),p.push("> Full request/response details are in the `results/` folder alongside this file."),p.push(""),n.forEach((y,S)=>{let b=dt[y.m]??String(y.m),C=s.get(`${y.i}-${y.it}`),w=C?.url??"",E=y.cn||C?.collectionName||"",F=y.fp||C?.folderPath||"";if(p.push(`### ${S+1}. ${y.n}`),p.push(""),p.push(`**Request:** \`${b} ${w}\``),E&&p.push(`**Collection:** ${E}${F?` / ${F.replace(/\//g," / ")}`:""}`),p.push(`**Response status:** ${y.s}`),y.e&&p.push(`**Error:** ${y.e}`),e.config?.iterations>1&&p.push(`**Iteration:** ${y.it} of ${e.config.iterations}`),p.push(""),y.af>0&&C?.assertions?.length){let N=C.assertions.filter(j=>!j.passed&&!j.skipped);N.length&&(p.push(`**Failed assertions (${N.length}):**`),N.forEach(j=>{p.push(`- \`${j.name}\``+(j.message?` \u2192 ${j.message}`:""))}),p.push(""))}if(C?.request?.body){let N=C.request.body,j=typeof N=="object"&&"content"in N?N.content:N,O=typeof N=="object"&&"type"in N?N.type:void 0;j&&O!=="none"&&(p.push("**Request body:**"),p.push($m(j)),p.push(""))}C?.response?.body!==void 0&&C.response.body!==null&&(p.push("**Response body:**"),p.push($m(C.response.body)),p.push("")),C?.consoleOutput?.length&&(p.push("**Console output:**"),p.push("```"),p.push(C.consoleOutput.slice(0,20).join(`
|
|
1784
1784
|
`)),p.push("```"),p.push(""))}));let m=t.filter(y=>y.p);m.length>0&&(p.push("## \u2705 Passed Requests"),p.push(""),m.forEach((y,S)=>{let b=dt[y.m]??String(y.m);p.push(`${S+1}. **${y.n}** \u2014 \`${b}\` \u2192 HTTP ${y.s} (${Om(y.d)})`)}),p.push("")),p.push("## \u{1F4C1} Source Files"),p.push("");let f=e.targetType??(e.folderPath?"folder":e.collectionName?"collection":"suite"),h=e.targetName||e.suiteName,g=e.collectionName||"",v=e.folderPath||"";if(f==="folder"?(p.push("The collection folder definition is in the `.http-forge/assets/collections/<collectionName>/<folderPath>/` path of your HTTP Forge workspace."),p.push(`Run context: ${h}${i?` (${i})`:""}`),g&&p.push(`Collection: ${g}`),v&&p.push(`Folder: ${v.split("/").filter(Boolean).join(" / ")}`)):f==="collection"?(p.push("The collection definition is in the `.http-forge/assets/collections/<collectionName>/` directory of your HTTP Forge workspace."),p.push(`Run context: ${h}${i?` (${i})`:""}`),g&&p.push(`Collection: ${g}`)):(p.push("The suite definition is in the `suites/` directory of your HTTP Forge workspace."),p.push(`Suite ID: \`${i}\``),p.push(`Run context: ${h}${i?` (${i})`:""}`)),p.push(""),p.push("Each request definition (description, scripts, response schema) is in:"),p.push("`.http-forge/assets/collections/<collectionName>/<folderPath>/<requestName>/`"),p.push(""),p.push("## \u{1F4CE} Context Required Before Analysis"),p.push(""),p.push("HTTP Forge provides the test definitions, assertion scripts, and response data above."),p.push("To understand failures from a **business perspective**, you also need:"),p.push(""),p.push("**Ask the user to provide:**"),p.push("1. The backend service/controller handling these endpoints"),p.push(" *(e.g. `BookmarkController.java`, `UserService.ts`)*"),p.push("2. Domain model or entity classes if applicable"),p.push("3. Any relevant unit/integration tests"),p.push(""),p.push("> Without backend code, analysis is limited to HTTP mechanics only."),p.push("> With it, you can identify business rule violations, data dependency issues,"),p.push("> and whether a failure is a real regression or a test data problem."),p.push(""),p.push("## \u{1F916} How to Analyse These Failures"),p.push(""),p.push("**Step 1 \u2014 Gather business context** (in priority order):"),p.push("- Read the source request files linked above (description, scripts, response schema)"),p.push("- Read the workspace collections and test suites \u2014 they are the primary source of truth"),p.push("- Use the response bodies above as context"),p.push("- Optional: if a Confluence/Jira MCP server is configured (and the team keeps"),p.push(" knowledge pages there), search those for acceptance criteria, API specs, or known"),p.push(" issues \u2014 otherwise skip it. A complete analysis is possible from the workspace alone."),p.push(""),p.push("> **Note:** A Confluence/Jira MCP server is an optional extra \u2014 it may help surface"),p.push("> acceptance criteria and API specs if the team keeps knowledge pages there. Without it,"),p.push("> the workspace code, collections, and test suites are sufficient for a full analysis."),p.push(""),p.push("**Step 2 \u2014 Determine root cause for each failure:**"),p.push("- **Test data issue** \u2014 the resource doesn't exist yet or was deleted by a prior request"),p.push("- **API regression** \u2014 the endpoint changed behaviour unexpectedly"),p.push("- **Assertion bug** \u2014 the test expectation itself is wrong"),p.push("- **Environment/config issue** \u2014 wrong base URL, missing auth token, wrong environment"),p.push("- **Sequencing issue** \u2014 depends on a prior request that also failed"),p.push(""),p.push("**Step 3 \u2014 Suggest concrete fixes:**"),p.push("- Corrected `pm.test()` snippets"),p.push("- Request changes (headers, body, URL)"),p.push("- Environment variable adjustments"),p.push(""),p.push("> If source code and documentation conflict, **treat the source code as ground truth**."),p.push("> Do NOT suggest disabling or weakening assertions unless the assertion itself is wrong."),o)try{let y=JSON.stringify(o,null,2);p.push(""),p.push("## \u{1F527} Suite Definition"),p.push(""),p.push("```json");let S=1e4;y.length>S?(p.push(y.slice(0,S)),p.push(`
|
|
1785
1785
|
... [${y.length-S} chars truncated]`)):p.push(y),p.push("```"),p.push("")}catch{}return p.join(`
|
|
1786
1786
|
`)+`
|
|
1787
|
-
`}}});import*as Re from"fs/promises";import*as Ke from"path";function hr(r,e){if(r.length===0)return 0;let t=Math.ceil(e/100*r.length)-1;return r[Math.max(0,Math.min(t,r.length-1))]}var gr,_a=k(()=>{"use strict";Ze();Lr();jr();Ru();$i();Nm();rs();gr=class{constructor(e){this.configService=e;let t=e.getRunnerConfig();this.basePath=e.getResultsPath(),this.indexPageSize=t.indexPageSize,this.recentErrorsLimit=t.recentErrorsLimit}configService;basePath;currentRunPath=null;currentRunId=null;currentSuiteId=null;currentManifest=null;currentIndexPage=[];currentPageNumber=1;indexPageSize;recentErrors=[];recentErrorsLimit;resultIndex=0;requestDurations={};getBasePath(){return this.basePath}async initializeRun(e,t,n,s,i){let o=this.generateRunId();return this.currentRunId=o,this.currentSuiteId=e,this.currentRunPath=Ke.join(this.basePath,e,o),await Re.mkdir(Ke.join(this.currentRunPath,"results"),{recursive:!0}),await Re.mkdir(Ke.join(this.currentRunPath,"index"),{recursive:!0}),this.currentManifest={version:"1.0",runId:o,suiteId:e,suiteName:t,targetType:i?.targetType,targetName:i?.targetName,collectionName:i?.collectionName,folderPath:i?.folderPath,environment:n,startTime:new Date().toISOString(),status:"running",config:s,stats:{totalRequests:0,passed:0,failed:0,skipped:0,totalDuration:0,avgDuration:0,minDuration:Number.MAX_SAFE_INTEGER,maxDuration:0},requestStats:{},totalIndexPages:0,indexPageSize:this.indexPageSize},this.currentIndexPage=[],this.currentPageNumber=1,this.recentErrors=[],this.resultIndex=0,this.requestDurations={},await this.saveManifest(),o}async saveResult(e,t){if(!this.currentRunPath||!this.currentManifest)throw new Error("No active run. Call initializeRun first.");let n=Mr(t.executedRequest),s=t.error?Kn(t.error,n):t.error;this.resultIndex++;let i=Date.now(),o=String(e).padStart(4,"0"),a=String(this.resultIndex).padStart(6,"0"),c=xe(t.requestId),l=`result-${a}-iter-${o}-${c}.json`,u=Ke.join(this.currentRunPath,"results",l),d={index:this.resultIndex,iteration:e,requestId:t.requestId,name:t.name,method:t.executedRequest.method,url:t.executedRequest.url,folderPath:t.folderPath||"",groupPath:t.groupPath||t.folderPath||"",groupType:t.groupType,collectionName:t.collectionName||"",status:t.response.status,statusText:t.response.statusText||"",duration:t.duration,passed:t.passed,timestamp:i,request:{method:t.executedRequest.method,url:t.executedRequest.url,headers:t.executedRequest.headers,query:t.executedRequest.query,params:t.executedRequest.params,body:t.executedRequest.body},response:{headers:t.response.headers,body:t.response.body,time:t.response.time,size:t.response.size,cookies:t.response.cookies},assertions:t.assertions.map(g=>({name:g.name,passed:g.passed,message:g.message||null,...g.skipped?{skipped:!0}:{}})),error:s||null,consoleOutput:t.consoleOutput,nextRequest:t.nextRequest??null,visualizerData:t.visualizerData};await Re.writeFile(u,JSON.stringify(Qc(d,n),null,2),"utf-8");let p=t.assertions.filter(g=>g.passed&&!g.skipped).length,m=t.assertions.filter(g=>!g.passed&&!g.skipped).length,f=t.assertions.filter(g=>g.skipped).length,h={i:this.resultIndex,it:e,n:t.name,m:bu[t.executedRequest.method.toUpperCase()]??0,s:t.response.status,d:t.duration,p:t.passed,ap:p,af:m,...f>0?{as:f}:{},r:t.requestId,e:t.passed?null:s||null,fp:t.folderPath||"",gp:t.groupPath||t.folderPath||"",gt:t.groupType,cn:t.collectionName||""};return this.currentIndexPage.push(h),this.currentIndexPage.length>=this.indexPageSize&&await this.writeCurrentIndexPage(),this.updateStats(t),this.requestDurations[t.requestId]||(this.requestDurations[t.requestId]=[]),this.requestDurations[t.requestId].push(t.duration),t.passed||(this.recentErrors.unshift({timestamp:i,iteration:e,requestName:t.name,status:t.response.status,error:s||`Status ${t.response.status}`,resultFile:l}),this.recentErrors.length>this.recentErrorsLimit&&this.recentErrors.pop()),h}async finalizeRun(e="completed",t=!0){if(!this.currentManifest)return null;this.currentIndexPage.length>0&&await this.writeCurrentIndexPage(),this.currentManifest.endTime=new Date().toISOString(),this.currentManifest.status=e,this.currentManifest.totalIndexPages=this.currentPageNumber-1,this.currentManifest.stats.totalRequests>0&&(this.currentManifest.stats.avgDuration=Math.round(this.currentManifest.stats.totalDuration/this.currentManifest.stats.totalRequests)),this.currentManifest.stats.minDuration===Number.MAX_SAFE_INTEGER&&(this.currentManifest.stats.minDuration=0);for(let c in this.currentManifest.requestStats){let l=this.currentManifest.requestStats[c],u=this.requestDurations[c]||[];l.count>0&&(l.avgDuration=Math.round(l.totalDuration/l.count)),l.minDuration===Number.MAX_SAFE_INTEGER&&(l.minDuration=0),u.length>0&&(u.sort((d,p)=>d-p),l.p50=hr(u,50),l.p90=hr(u,90),l.p95=hr(u,95),l.p99=hr(u,99))}let n=Object.values(this.requestDurations).flat();n.length>0&&(n.sort((c,l)=>c-l),this.currentManifest.stats.p50=hr(n,50),this.currentManifest.stats.p95=hr(n,95),this.currentManifest.stats.p99=hr(n,99)),this.requestDurations={},await this.saveManifest();let s=null,i=this.currentRunPath,o=this.currentSuiteId,a=this.currentRunId;if(this.currentRunPath=null,this.currentRunId=null,this.currentSuiteId=null,this.currentManifest=null,this.currentIndexPage=[],this.recentErrors=[],this.resultIndex=0,t&&o&&a&&i){try{let c=this.configService.getRunnerConfig().report;s=await new cs(this.basePath,c).generate(o,a)}catch(c){console.warn("[ResultStorage] HTML report generation failed:",c)}try{let c=this.configService.getSuitesPath();await new Na(this.basePath,c).generate(o,a)}catch(c){console.warn("[ResultStorage] Markdown summary generation failed:",c)}}return s}getCurrentStats(){return this.currentManifest?{stats:{...this.currentManifest.stats},requestStats:{...this.currentManifest.requestStats},recentErrors:[...this.recentErrors]}:null}getCurrentRunId(){return this.currentRunId}getCurrentSuiteId(){return this.currentSuiteId}async regenerateHtmlReport(e,t){try{let n=this.configService.getRunnerConfig().report;return await new cs(this.basePath,n).generate(e,t)}catch(n){return console.warn("[ResultStorage] HTML report regeneration failed:",n),null}}async generateJunitReport(e,t){try{return await new Qt(this.basePath).generate(e,t)}catch(n){return console.warn("[ResultStorage] JUnit report generation failed:",n),null}}async getResultDetails(e,t,n){let s=Ke.join(this.basePath,e,t,"results",n),i=await Re.readFile(s,"utf-8");return JSON.parse(i)}async getIndexPage(e,t,n){let s=Ke.join(this.basePath,e,t,"index",`page-${String(n).padStart(4,"0")}.json`),i=await Re.readFile(s,"utf-8");return JSON.parse(i)}async getManifest(e,t){let n=Ke.join(this.basePath,e,t,"manifest.json"),s=await Re.readFile(n,"utf-8");return JSON.parse(s)}async listRuns(e){let t=Ke.join(this.basePath,e);try{let n=await Re.readdir(t),s=[];for(let i of n.sort().reverse())try{let o=await this.getManifest(e,i);s.push(o)}catch{}return s}catch{return[]}}async listSuites(){try{return(await Re.readdir(this.basePath,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}async deleteRun(e,t){let n=Ke.join(this.basePath,e,t);await Re.rm(n,{recursive:!0,force:!0})}async cleanupOldRuns(){let t=this.configService.getRunnerConfig().resultsRetentionDays;if(t===0)return{deleted:0,freed:0};let n=new Date;n.setDate(n.getDate()-t);let s=0,i=0,o=await this.listSuites();for(let a of o){let c=await this.listRuns(a);for(let l of c)if(new Date(l.startTime)<n){let u=Ke.join(this.basePath,a,l.runId),d=await this.getDirectorySize(u);await Re.rm(u,{recursive:!0,force:!0}),s++,i+=d}}return{deleted:s,freed:i}}generateRunId(){let e=new Date,t=e.toISOString().slice(0,10).replace(/-/g,""),n=e.toTimeString().slice(0,8).replace(/:/g,""),s=String(e.getMilliseconds()).padStart(3,"0");return`run-${t}-${n}-${s}`}async saveManifest(){if(!this.currentRunPath||!this.currentManifest)return;let e=Ke.join(this.currentRunPath,"manifest.json");await Re.writeFile(e,JSON.stringify(this.currentManifest,null,2),"utf-8")}async writeCurrentIndexPage(){if(!this.currentRunPath||this.currentIndexPage.length===0)return;let e=`page-${String(this.currentPageNumber).padStart(4,"0")}.json`,t=Ke.join(this.currentRunPath,"index",e),n={page:this.currentPageNumber,startIndex:(this.currentPageNumber-1)*this.indexPageSize+1,count:this.currentIndexPage.length,summaries:this.currentIndexPage};await Re.writeFile(t,JSON.stringify(n),"utf-8"),this.currentPageNumber++,this.currentIndexPage=[]}updateStats(e){if(!this.currentManifest)return;let t=this.currentManifest.stats,n=this.currentManifest.requestStats;t.totalRequests++,t.totalDuration+=e.duration,t.minDuration=Math.min(t.minDuration,e.duration),t.maxDuration=Math.max(t.maxDuration,e.duration),e.passed?t.passed++:t.failed++,n[e.requestId]||(n[e.requestId]={name:e.name,count:0,passed:0,failed:0,totalDuration:0,avgDuration:0,minDuration:Number.MAX_SAFE_INTEGER,maxDuration:0});let s=n[e.requestId];s.count++,s.totalDuration+=e.duration,s.minDuration=Math.min(s.minDuration,e.duration),s.maxDuration=Math.max(s.maxDuration,e.duration),e.passed?s.passed++:s.failed++}async getDirectorySize(e){let t=0;try{let n=await Re.readdir(e,{withFileTypes:!0});for(let s of n){let i=Ke.join(e,s.name);if(s.isDirectory())t+=await this.getDirectorySize(i);else{let o=await Re.stat(i);t+=o.size}}}catch{}return t}}});function Ni(r,e,t=r.items,n=[],s=[],i=[]){for(let o of t){if(o.type==="request"&&o.id===e)return{request:o,folderScriptsChain:[...n],folderAuthChain:[...s],folderPath:i.map($e).join("/")};if(o.type==="folder"){let a=o,c=a.scripts?[...n,a.scripts]:[...n],l=a.auth?[...s,a.auth]:[...s],u=[...i,a.name],d=Ni(r,e,a.items??[],c,l,u);if(d)return d}}}function Cu(r,e=r.items,t=[],n=[]){let s=[];for(let i of e)if(i.type==="request")s.push({request:i,folderScriptsChain:[...t],folderPath:n.map($e).join("/")});else{let o=i,a=o.scripts?[...t,o.scripts]:[...t],c=[...n,o.name];s.push(...Cu(r,o.items??[],a,c))}return s}function _m(r,e,t=!0){if(!e)return r;let n=e.replace(/\/+$/,"");return r.filter(({folderPath:s})=>t?s===n||s.startsWith(`${n}/`):s===n)}function Dm(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}var ku=k(()=>{"use strict";tt()});function Da(r){let e=[r.testSuite,r.collection,r.environmentConfig,r.config,r.console];for(let t of e)try{t?.dispose?.()}catch{}}function Mm(r){return r==="1"||r==="true"||r==="yes"||r==="on"}function Ma(r,e){let t=r??0;return e==="websocket"?t===101:t>=200&&t<300}function jm(){return Mm(process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS)}function Lm(){let r=process.env.HTTP_FORGE_MAX_REQUESTS;if(!r||r.trim()==="")return 50;let e=Number(r);if(!Number.isFinite(e)||e<=0)throw new Error("HTTP_FORGE_MAX_REQUESTS must be a positive number when provided");return Math.floor(e)}function ja(r,e=[]){return Mm(process.env.HTTP_FORGE_GENERATE_REPORTS)||e.includes("html")?!0:r.includes("report")}function _i(r){if(typeof r!="string")return r;try{return JSON.parse(r)}catch{return r}}function tS(r){return r?Object.fromEntries(Object.entries(r).filter(([e])=>e.toLowerCase()!=="set-cookie")):{}}function La(r){return St(tS(r))}function Ha(r){return Wc((r??[]).map(e=>({name:e.name,value:e.value})))}function Eu(r){return r.replace(/[^a-zA-Z0-9_-]/g,"_")}function Ba(r){let e=["none","inherit","basic","bearer","apikey","oauth2"],t=r.auth?.type&&e.includes(r.auth.type)?r.auth.type:void 0;return{id:r.id,name:r.name,requestType:r.requestType,method:r.method,url:r.url,websocket:r.websocket,headers:Array.isArray(r.headers)?r.headers.reduce((n,s)=>(s.enabled&&s.key&&(n[s.key]=s.value??""),n),{}):r.headers,query:Array.isArray(r.query)?r.query.reduce((n,s)=>(s.enabled&&s.key&&(n[s.key]=s.value??""),n),{}):r.query,params:r.params?Object.entries(r.params).reduce((n,[s,i])=>(n[s]=typeof i=="string"?i:i.value??"",n),{}):void 0,body:r.body??null,scripts:r.scripts,settings:r.settings,auth:{type:t==="inherit"?"none":t,bearerToken:r.auth?.bearerToken,basicAuth:r.auth?.basicAuth,apikey:r.auth?.apikey,oauth2:r.auth?.oauth2}}}function Ua(r,e){let t={...r};return e.headers&&(t.headers={...r.headers??{},...e.headers}),e.query&&(t.query=e.query),e.body!==void 0&&(t.body={type:"raw",format:"json",content:e.body}),t}function ls(r){return r?Object.fromEntries(Object.entries(r).map(([e,t])=>[e,String(t)])):{}}function Va(r,e,t){if(r&&r.type&&r.type!=="inherit")return r.type==="none"?void 0:r;for(let n=e.length-1;n>=0;n--){let s=e[n];if(s?.type&&s.type!=="inherit")return s.type==="none"?void 0:s}if(t&&t.type&&t.type!=="inherit")return t.type==="none"?void 0:t}var qu=k(()=>{"use strict";Lr()});import*as Et from"fs";import*as yr from"path";var Au,za,Ja,Wa,Hm=k(()=>{"use strict";Au=class{watchers=[];changeCallbacks=[];createCallbacks=[];deleteCallbacks=[];knownPaths=new Set;debounceTimers=new Map;matcher=()=>!0;constructor(e,t){let n=this.resolveWatchTarget(e,t);this.matcher=n.matcher;try{let s=Et.watch(n.watchPath,{recursive:n.recursive},(i,o)=>{if(!o)return;let a=typeof o=="string"?o:String(o),c=yr.resolve(n.watchPath,a);this.matcher(c)&&this.scheduleEvent(c)});this.watchers.push(s)}catch{}}resolveWatchTarget(e,t){if(t.includes("*")){let s=t.includes("**"),i=t.match(/\*\.([A-Za-z0-9]+)$/),o=i?i[1].toLowerCase():null;return{watchPath:e,recursive:s,matcher:o?c=>c.toLowerCase().endsWith("."+o):()=>!0}}let n=yr.resolve(e,t);return{watchPath:yr.dirname(n),recursive:!1,matcher:s=>yr.resolve(s)===n}}scheduleEvent(e){let t=this.debounceTimers.get(e);t&&clearTimeout(t),this.debounceTimers.set(e,setTimeout(()=>{this.debounceTimers.delete(e),this.emitEvent(e)},50))}emitEvent(e){Et.existsSync(e)?this.knownPaths.has(e)?this.changeCallbacks.forEach(n=>n(e)):(this.knownPaths.add(e),this.createCallbacks.forEach(n=>n(e))):(this.knownPaths.delete(e),this.deleteCallbacks.forEach(n=>n(e)))}register(e,t){return e.push(t),{dispose:()=>{let n=e.indexOf(t);n!==-1&&e.splice(n,1)}}}onDidChange(e){return this.register(this.changeCallbacks,e)}onDidCreate(e){return this.register(this.createCallbacks,e)}onDidDelete(e){return this.register(this.deleteCallbacks,e)}dispose(){for(let e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(let e of this.watchers)e.close();this.watchers=[],this.changeCallbacks=[],this.createCallbacks=[],this.deleteCallbacks=[],this.knownPaths.clear()}},za=class{createFileWatcher(e,t){return new Au(e,t)}},Ja=class{data={};storeFile;constructor(e){this.storeFile=e,this.load()}load(){try{if(Et.existsSync(this.storeFile)){let e=Et.readFileSync(this.storeFile,"utf-8");this.data=JSON.parse(e)}}catch{}}save(){try{let e=yr.dirname(this.storeFile);Et.mkdirSync(e,{recursive:!0}),Et.writeFileSync(this.storeFile,JSON.stringify(this.data,null,2),"utf-8")}catch{}}get(e,t){let n=this.data[e];return n!==void 0?n:t}async update(e,t){t===void 0?delete this.data[e]:this.data[e]=t,this.save()}},Wa=class{async showInformation(e){console.log(`[INFO] ${e}`)}async showWarning(e){console.warn(`[WARN] ${e}`)}async showError(e){console.error(`[ERROR] ${e}`)}}});import*as vr from"path";function nS(r){let e=vr.resolve(r.workspaceFolder),{appInfo:t}=r,n=Qn.createFresh(),s=vr.join(e,".http-forge",".cache","stores","global-state.json"),i=r.globalStorePath?vr.isAbsolute(r.globalStorePath)?r.globalStorePath:vr.resolve(e,r.globalStorePath):s,o={workspaceFolder:e,fileWatcherFactory:new za,notificationService:new Wa,globalStore:new Ja(i),applicationInfo:t||{name:"http-forge-cli",version:"0.1.0"},persistOverrides:!1};return $o(n,o),n}function pt(r){return nS({workspaceFolder:r})}var Ga=k(()=>{"use strict";Rl();Cl();Hm()});function Di(r){let e=typeof r.blockLabel=="string"?r.blockLabel.trim():"";if(e)return{groupPath:e,groupType:"block"};let t=typeof r.collectionName=="string"?r.collectionName.trim():"",n=typeof r.folderPath=="string"?r.folderPath.trim():"";return t?{groupPath:n?`${t}/${n}`:t,groupType:"folder"}:{groupPath:n,groupType:n?"folder":void 0}}var Ka=k(()=>{"use strict"});function Mi(r){return typeof r=="string"?r:""+JSON.stringify(r)}function us(r){if(typeof r=="string"&&r.charCodeAt(0)===30)try{return JSON.parse(r.slice(1))}catch{return r}return r}function Pu(r){if(!r)return{};let e={};for(let[t,n]of Object.entries(r))e[t]=us(n);return e}var Iu=k(()=>{"use strict"});var ji,Bm=k(()=>{"use strict";$a();Gs();Lr();$i();_a();bs();Iu();ku();qu();Ka();ji=class{constructor(e){this.container=e}container;async execute(e,t,n){let s=this.container,i=t.environment??s.environmentConfig.getSelectedEnvironment(),o=t.iterations??e.config?.iterations??1,a=t.stopOnError??e.config?.stopOnError??!1,c=t.delay??e.config?.delayBetweenRequests??0,l=Math.max(1,Math.min(50,t.concurrency??1)),u=t.requestFilter,d=t.include??[],p=t.reporters??[],m=p.includes("junit"),f=ls(t.variables),h=jm(),g=ja(d,p),v=Math.max(1,Math.min(1e4,Number(t.maxNodeLoopIterations??100))),y={vars:{...f}};function S(T){if(typeof T=="string")return T;if(Array.isArray(T))return T.filter(Q=>typeof Q=="string").join(`
|
|
1788
|
-
`)}function b(T){if(!(!T||typeof T!="object")){if(T.script!==void 0)return T.script;if(typeof T.scriptRef=="string"&&T.scriptRef.trim()){let I=e?.scripts;if(I&&typeof I=="object")return I[T.scriptRef]}}}function C(T){return T?.name||T?.label||T?.id||"flow-node"}function w(T,I){let Q=s.environmentConfig.getResolvedEnvironment(i),U=Pu(y.vars),De={variables:{get:Z=>us(y.vars[Z]),set:(Z,J)=>{typeof Z=="string"&&Z.trim()&&(y.vars[Z]=Mi(J))},unset:Z=>{typeof Z=="string"&&Z.trim()&&delete y.vars[Z]},has:Z=>Object.prototype.hasOwnProperty.call(y.vars,Z),toObject:()=>({...U})},environment:{get:Z=>us(Q?.variables?.[Z]),set:(Z,J)=>{typeof Z=="string"&&Z.trim()&&s.environmentConfig.setEnvironmentVariable(Z,Mi(J),i)},unset:Z=>{typeof Z=="string"&&Z.trim()&&s.environmentConfig.deleteEnvironmentVariable(Z,i)},clear:()=>{s.environmentConfig.clearEnvironmentVariables(i)}},globals:{get:Z=>us(s.environmentConfig.getGlobalVariables()?.[Z]),set:(Z,J)=>{typeof Z=="string"&&Z.trim()&&s.environmentConfig.setGlobalVariable(Z,Mi(J))},unset:Z=>{typeof Z=="string"&&Z.trim()&&s.environmentConfig.deleteGlobalVariable(Z)},clear:()=>{s.environmentConfig.clearGlobalVariables()}}};return{vars:U,lastResult:y.lastResult,iteration:I,node:T,pm:De,ctx:De,hf:De}}function E(T,I,Q){return typeof T!="string"||!T.trim()?!0:!!It(T,w(I,Q))}function F(T){if(!T)return{};let I={};for(let[Q,U]of Object.entries(T))I[Q]=Array.isArray(U)?U.join("; "):String(U);return I}function N(T){return{executedRequest:T.executedRequest,status:T.response?.status??0,statusText:T.response?.statusText??"",headers:F(T.response?.headers),body:T.response?.body,cookies:T.response?.cookies,responseTime:T.duration,responseSize:typeof T.response?.body=="string"?Buffer.byteLength(T.response.body,"utf8"):0}}async function j(T,I,Q,U,K){let ce=S(T);if(!ce||!ce.trim())return;let ge=s.environmentConfig.getResolvedEnvironment(i),De=s.environmentConfig.getGlobalVariables(),J={request:{url:K?.request?.url??y.lastResult?.executedRequest?.url??"http://flow.local/node",method:K?.request?.method??y.lastResult?.executedRequest?.method??"GET",headers:F(K?.request?.headers),body:K?.request?.body??null,params:K?.request?.params??{},query:K?.request?.query??{}},variables:ls(y.vars),environmentVariables:ge?.variables||{},globals:{...De},environmentName:i,info:{eventName:U==="post"?"test":"prerequest",requestName:C(I),requestId:String(I?.id??C(I)),collectionName:e.name,iteration:Q,iterationCount:o},onEnvironmentChange:(de,we,In)=>{de==="set"&&we&&In!==void 0?s.environmentConfig.setEnvironmentVariable(we,In,i):de==="unset"&&we?s.environmentConfig.deleteEnvironmentVariable(we,i):de==="clear"&&s.environmentConfig.clearEnvironmentVariables(i)},onGlobalsChange:(de,we,In)=>{de==="set"&&we&&In!==void 0?s.environmentConfig.setGlobalVariable(we,In):de==="unset"&&we?s.environmentConfig.deleteGlobalVariable(we):de==="clear"&&s.environmentConfig.clearGlobalVariables()}},Pn=s.scriptExecutor.createRequestSession(J);try{if(U==="post"&&K?.response){let de=await Pn.executePostResponse(ce,K.response),we=de.localVariables??de.modifiedVariables;we&&typeof we=="object"&&(y.vars={...we})}else{let de=await Pn.executePreRequest(ce);if(!de.success)throw new Error(de.error||"Script execution failed");let we=de.localVariables??de.modifiedVariables;we&&typeof we=="object"&&(y.vars={...we})}}catch(de){let we=de instanceof Error?de.message:String(de);throw new Error(`Suite ${U}-script failed on node "${C(I)}": ${we}`)}finally{Pn.dispose?.()}}function O(T){let I=T?.type==="request"&&T?.request?T.request:T;if(!(!I||typeof I!="object")&&!(!I.collectionId||!I.requestId||!I.name))return{collectionId:I.collectionId,requestId:I.requestId,name:I.name,folderPath:I.folderPath,enabled:I.enabled}}function D(T){return!T||typeof T!="object"?!1:T.type==="request"?!!O(T):!!(T.collectionId&&T.requestId&&T.name)}function P(T,I){for(let Q of I){let U=T?.[Q];if(Array.isArray(U))return U}return[]}async function M(T,I,Q){if(ve.signal.aborted||I.enabled===!1||u&&!u.some(de=>I.name.toLowerCase().includes(de.toLowerCase())))return;let U=s.collection.getCollection(I.collectionId);if(!U)return;let K=Ni(U,I.requestId);if(!K)return;let ce=s.collection.findRequest(U.id,I.requestId)??K.request,ge=Va(ce.auth,K.folderAuthChain,U.auth),De=new Dt(s.httpRequest,s.scriptExecutor,s.environmentConfig,s.requestPreparer,i,ft,U.scripts,K.folderScriptsChain,void 0,U.name,U.auth,T,o,s.webSocketClient,s.socketIoClient),Z=Ua(Ba({...ce,auth:ge}),{headers:t.headers,query:t.query,body:t.body,variables:{...y.vars,...t.variables}}),J=await De.execute(Z,ls(y.vars),ve.signal);y.lastResult=J,J.modifiedVariables&&typeof J.modifiedVariables=="object"&&(y.vars={...J.modifiedVariables});let Pn=Di({collectionName:U.name,folderPath:I.folderPath??"",blockLabel:Q});J.folderPath=I.folderPath??"",J.collectionName=U.name,J.groupPath=Pn.groupPath,J.groupType=Pn.groupType,await te.saveResult(T,J),J.assertions?.length||rt.add(I.name),J.passed?Qe++:Te++,d.includes("perRequest")&&B.push({name:I.name,iteration:T,status:J.response?.status,ok:Ma(J.response?.status,Z.requestType),duration:`${J.duration}ms`,allPassed:J.passed,...d.includes("consoleOutput")&&J.consoleOutput?.length?{consoleOutput:J.consoleOutput}:{}}),J.passed||(_e.push({name:I.name,iteration:T,method:J.executedRequest?.method,url:J.executedRequest?.url,requestBody:_i(J.executedRequest?.body?.content)??J.executedRequest?.body?.content??null,requestHeaders:St(J.executedRequest?.headers??{}),status:J.response?.status,duration:`${J.duration}ms`,body:_i(J.response?.body),headers:La(J.response?.headers),cookies:Ha(J.response?.cookies),failedTests:J.assertions?.filter(de=>!de.passed).map(de=>({name:de.name,...de.message?{message:de.message}:{}})),...J.error?{error:J.error}:{},...d.includes("consoleOutput")&&J.consoleOutput?.length?{consoleOutput:J.consoleOutput}:{}}),a&&ve.abort()),c>0&&!ve.signal.aborted&&await new Promise(de=>setTimeout(de,c))}async function G(T,I,Q){for(let U of I){if(ve.signal.aborted)break;await me(T,U,Q)}}async function me(T,I,Q){if(!I||typeof I!="object"||I.enabled===!1||!E(I.condition,I,T))return;if(D(I)){let ce=O(I);ce&&await M(T,ce,Q);return}let U=typeof I.type=="string"?I.type.toLowerCase():"",K=P(I,["then","nodes","body"]);if(U==="block"){let ce=typeof I.name=="string"?I.name.trim():"";await G(T,K,ce||Q);return}if(U==="script"){let ce=b(I),ge=I.phase==="post"?"post":"pre";await j(ce,I,T,ge);return}if(U==="if"){let ce=typeof I.if=="string"?I.if:I.condition;if(E(ce,I,T)){await G(T,K,Q);return}if(Array.isArray(I.elseif)){for(let ge of I.elseif)if(E(ge?.condition,ge,T)){await G(T,P(ge,["then","nodes","body"]),Q);return}}await G(T,P(I,["else","elseNodes"]),Q);return}if(U==="switch"){let ce=It(String(I.expression??""),w(I,T));if(Array.isArray(I.cases)){for(let ge of I.cases)if(Object.prototype.hasOwnProperty.call(ge??{},"equals")?ge.equals===ce:E(ge?.condition,ge,T)){await G(T,P(ge,["then","nodes","body"]),Q);return}}await G(T,P(I,["default","defaultNodes"]),Q);return}if(U==="while"){let ce=typeof I.while=="string"?I.while:I.condition,ge=Math.max(1,Math.min(1e4,Number(I.maxIterations??v))),De=0;for(;E(ce,I,T);){if(De+=1,De>ge)throw new Error(`Suite while loop exceeded maxIterations (${ge}) on node "${C(I)}"`);if(await G(T,K,Q),ve.signal.aborted)break}return}if(U==="for"){let ce=Math.max(1,Math.min(1e4,Number(I.maxIterations??v))),ge=S(I.init),De=S(I.update),Z=typeof I.loopCondition=="string"&&I.loopCondition.trim()?I.loopCondition:typeof I.condition=="string"&&I.condition.trim()?I.condition:"true";ge&&await j(ge,I,T,"pre");let J=0;for(;E(Z,I,T);){if(J+=1,J>ce)throw new Error(`Suite for loop exceeded maxIterations (${ce}) on node "${C(I)}"`);if(await G(T,K,Q),ve.signal.aborted)break;De&&await j(De,I,T,"post")}return}K.length>0&&await G(T,K,Q)}function Ce(T){let I=0,Q=[...T];for(;Q.length>0;){let U=Q.pop();if(!(!U||typeof U!="object"||U.enabled===!1)){if(D(U)){let K=O(U);K&&(!u||u.some(ce=>K.name.toLowerCase().includes(ce.toLowerCase())))&&(I+=1);continue}for(let K of["nodes","then","body","else","elseNodes","default","defaultNodes"])Array.isArray(U[K])&&Q.push(...U[K]);if(Array.isArray(U.elseif))for(let K of U.elseif)Array.isArray(K?.nodes)&&Q.push(...K.nodes),Array.isArray(K?.then)&&Q.push(...K.then);if(Array.isArray(U.cases))for(let K of U.cases)Array.isArray(K?.nodes)&&Q.push(...K.nodes),Array.isArray(K?.then)&&Q.push(...K.then)}}return I}let Ie=Array.isArray(e.nodes)?e.nodes:Array.isArray(e.requests)?e.requests.map(T=>({type:"request",request:T})):[],q=Ce(Ie);if(h){let T=Lm(),I=q*o;if(I>T)throw new Error(`Suite "${e.name}" would execute ${I} request calls (${q} requests \xD7 ${o} iterations), which exceeds HTTP_FORGE_MAX_REQUESTS (${T}). Reduce iterations, use requestFilter, or increase HTTP_FORGE_MAX_REQUESTS.`)}let te=new gr(s.config),ke=await te.initializeRun(e.id,e.name,i,{iterations:o,delayBetweenRequests:c,stopOnError:a},{targetType:n==="suite"?"suite":"collection",targetName:e.name,collectionName:n==="suite"?void 0:e.collectionName,folderPath:n==="suite"?void 0:e.folderPath}),B=[],_e=[],Qe=0,Te=0,rt=new Set,ve=new AbortController,ft=new dr;async function Yt(T){await G(T,Ie)}for(let T=1;T<=o&&!ve.signal.aborted;T+=l){let I=Math.min(T+l-1,o),Q=Array.from({length:I-T+1},(U,K)=>T+K);await Promise.all(Q.map(Yt))}let Se=await te.finalizeRun("completed",g),ms=null;if(m)try{ms=await new Qt(te.getBasePath()).generate(e.id,ke)}catch(T){console.warn("[direct-execution] JUnit report generation failed:",T)}let Cr=n==="collection"?"collection":"suite",mt=te.getCurrentStats()?.stats,Ui=mt?{min:mt.minDuration,max:mt.maxDuration,avg:mt.avgDuration,p50:mt.p50??null,p95:mt.p95??null,p99:mt.p99??null}:null,Pt={[Cr]:e.name,environment:i,summary:{total:Qe+Te,passed:Qe,failed:Te,...o>1?{iterations:o}:{},...l>1?{concurrency:l}:{},allPassed:Te===0,...Ui?{durationMs:Ui}:{}}};if((Te>0||d.includes("failedOnly"))&&(Pt.failedRequests=_e),d.includes("perRequest")&&(Pt.results=B),Se!==null&&(Pt.report={uri:`file://${Se}`,hint:"Click the URI to open the HTML report in your browser"}),ms!==null&&(Pt.junitReport={path:ms}),rt.size>0){let T=Math.max(q,1),I=rt.size,Q=Array.from(rt).slice(0,5);Pt.noAssertionExamples=Q;let U=e.name;if(I/T>.5)Pt._suggestions=[`${I}/${T} requests have no pm.test() assertions. Invoke the "review-collection" prompt (collection="${U}") for a full coverage analysis and to identify assertion gaps.`];else{let K=Q.map(ce=>`"${ce}"`).join(", ");Pt._suggestions=[`${I} request(s) have no pm.test() assertions: ${K}. Invoke the "suggest-assertions" prompt (collection="${U}") to generate test coverage for them.`]}}return Pt}}});var Li={};nc(Li,{runCollection:()=>Zt,runFolder:()=>rS,runRequest:()=>Qa,runSuite:()=>br});function Um(r,e){if(e.collectionId){let t=r.getCollection(e.collectionId);if(!t)throw new Error(`Collection "${e.collectionId}" not found`);return t}if(e.collectionRef){let{collection:t,tier:n}=Oi(r.getAllCollections(),e.collectionRef);return e.onResolve?.({kind:"collection",value:e.collectionRef,tier:n,id:t.id}),t}throw new Error("A collection reference is required (collectionId or collectionRef)")}function Vm(r,e){if(e.folderPath)return e.folderPath;if(e.folderRef){let{folderPath:t}=yu(r,e.folderRef);return e.onResolve?.({kind:"folder",value:e.folderRef,tier:"name",id:t,path:t}),t}}async function Qa(r){let e=pt(r.workspaceFolder),t=r.include??[],n=r.reporters??[],s=n.includes("junit"),i=ja(t,n);try{let o=e.collection,a=Um(o,r),c=Vm(a,r),l=r.requestId;if(!l){if(!r.requestRef)throw new Error("A request reference is required (requestId or requestRef)");let E=vu(a,r.requestRef,c);l=E.request.id,r.onResolve?.({kind:"request",value:r.requestRef,tier:E.tier,id:l,path:E.folderPath?`${E.folderPath}/${E.request.name}`:E.request.name})}let u=Ni(a,l);if(!u)throw new Error(`Request "${l}" not found in collection "${a.name}"`);let p=o.findRequest(a.id,l)??u.request,m=Va(p.auth,u.folderAuthChain,a.auth),f=r.environment||e.environmentConfig.getSelectedEnvironment(),h=Ua(Ba({...p,auth:m}),{headers:r.headers,query:r.query,body:r.body,variables:r.variables}),v=await new Dt(e.httpRequest,e.scriptExecutor,e.environmentConfig,e.requestPreparer,f,new dr,a.scripts,u.folderScriptsChain,void 0,a.name,a.auth,void 0,void 0,e.webSocketClient,e.socketIoClient).execute(h,ls(r.variables)),y=Di({collectionName:a.name,folderPath:u.folderPath});v.folderPath=u.folderPath,v.collectionName=a.name,v.groupPath=y.groupPath,v.groupType=y.groupType;let S=null,b=null;if(i||s){let E=new gr(e.config),F=`request-${Eu(a.id)}-${Eu(l)}`,N=`Request: ${u.request.name}`,j=await E.initializeRun(F,N,f,{iterations:1,delayBetweenRequests:0,stopOnError:!0},{targetType:"collection",targetName:a.name,collectionName:a.name,folderPath:u.folderPath||void 0});if(await E.saveResult(1,v),S=await E.finalizeRun("completed",i),s)try{b=await new Qt(E.getBasePath()).generate(F,j)}catch(O){console.warn("[direct-execution] JUnit report generation failed:",O)}}let C=La(v.response?.headers),w=Ha(v.response?.cookies);return{request:u.request.name,status:v.response?.status||0,ok:Ma(v.response?.status,h.requestType),duration:`${v.duration}ms`,body:_i(v.response?.body),allPassed:v.passed,assertions:v.assertions?.map(E=>({name:E.name,passed:E.passed,message:E.message})),...t.includes("headers")?{headers:C}:{},...t.includes("cookies")?{cookies:w}:{},...t.includes("tests")?{tests:v.assertions?.map(E=>({name:E.name,passed:E.passed,...E.message?{message:E.message}:{}}))}:{},...Object.keys(v.modifiedVariables??{}).length?{modifiedVariables:v.modifiedVariables}:{},...t.includes("consoleOutput")&&v.consoleOutput?.length?{consoleOutput:v.consoleOutput}:{},...S!==null?{report:{uri:`file://${S}`,hint:"Click the URI to open the HTML report in your browser"}}:{},...b!==null?{junitReport:{path:b}}:{},...v.error?{error:v.error}:{}}}catch(o){throw o}finally{Da(e)}}async function Zt(r){let e=pt(r.workspaceFolder);try{let t=e.collection,n=Um(t,r),s=Vm(n,r),i=Cu(n),o=_m(i,s,r.recursive);if(o.length===0&&s)throw new Error(`No requests found under folder "${s}" in collection "${n.name}"`);let a=o.map(({request:l,folderPath:u})=>({id:l.id,slug:l.id.toLowerCase().replace(/\s+/g,"-"),collectionId:n.id,requestId:l.id,name:l.name,method:l.method,collectionName:n.name,folderPath:u,enabled:!0})),c={id:s?`temp-${n.id}-${Dm(s)}`:`temp-${n.id}`,name:s?`${n.name} / ${s}`:n.name,requests:a,config:{iterations:1,delay:0,stopOnError:r.stopOnError??!1,readFromSharedSession:!1,writeToSharedSession:!1},isTemporary:!0,createdAt:Date.now(),updatedAt:Date.now()};return new ji(e).execute(c,{environment:r.environment,iterations:r.iterations,stopOnError:r.stopOnError,delay:r.delay,requestFilter:void 0,include:r.include,reporters:r.reporters,concurrency:r.concurrency,variables:r.variables},"collection")}catch(t){throw t}finally{Da(e)}}async function rS(r){return Zt({recursive:!0,...r})}async function br(r){let e=pt(r.workspaceFolder);try{let n=await e.testSuite.getSuite(r.suiteId);if(!n)throw new Error(`Test suite "${r.suiteId}" not found`);return new ji(e).execute(n,{environment:r.environment,iterations:r.iterations,stopOnError:r.stopOnError,delay:r.delay,requestFilter:r.requestFilter,include:r.include,reporters:r.reporters,concurrency:r.concurrency,variables:r.variables},"suite")}catch(t){throw t}finally{Da(e)}}var Sr=k(()=>{"use strict";$a();Gs();$i();_a();ku();qu();Ga();Oa();Ka();Bm()});function Hi(r){return`${(r.method||"GET").toUpperCase()} ${r.resolvedPath??r.pathExpression}`}function sS(r){return(r.description??"").includes("Discovered from ")}function zm(r){if(!r)return"";try{return new URL(r,"http://qa.local").pathname.replace(/\/+$/,"")||"/"}catch{return r}}function Jm(r,e){for(let t of r)t.type==="request"?e.push(t):t.type==="folder"&&t.items&&Jm(t.items,e)}function iS(r){let e=[new bn,new xn,new Sn,new wn,new Rn,new Cn];if(!r)return e;let t=r.toLowerCase(),n=e.filter(s=>s.framework===t);if(n.length===0)throw new Error(`unknown framework "${r}" (expected one of: ${e.map(s=>s.framework).join(", ")})`);return n}async function Tu(r,e,t){let n=t.dryRun===!0,s=(t.baseUrl??"").replace(/\/+$/,""),i=lr(t.projectPath),o=t.storedGitHash!==void 0||t.storedScannedAt!==void 0,a=ur(t.projectPath,o?{gitHash:t.storedGitHash,scannedAt:t.storedScannedAt??new Date(0).toISOString()}:void 0);if(t.failOnDrift===!0&&a.status==="stale")return{status:"drift",project:{path:t.projectPath,gitHash:i.gitHash,frameworks:[]},drift:{status:a.status,reason:a.reason},discovered:0,reused:0,created:0,updatedUrls:0,results:{passed:0,failed:0,skipped:0},endpoints:[],lowConfidence:[],aiAssertions:{requested:t.aiAssertions===!0,applied:!1},checkedAt:new Date().toISOString()};let c={};try{let P=r.config?.getDiscoveryConfig();P&&(c=P)}catch{}let l=new kn({providers:iS(t.framework)}),u,d;try{let P=await l.discover({workspaceFolder:t.projectPath,...c});u=[...P.endpoints].sort((M,G)=>Hi(M).localeCompare(Hi(G))),d=P.stats?.frameworksDetected??[]}catch(P){throw new Error(`discovery failed for ${t.projectPath}: ${P.message}`)}let{collection:p}=Oi(r.collection.getAllCollections(),t.collectionRef),m=u.filter(P=>P.confidence==="low").map(P=>Hi(P)),f=[];Jm(p.items,f);let h=0,g=0,v=0,y=[],S=new Map;for(let P of u){let M=Hi(P),G=(P.method||"GET").toUpperCase(),me=zm(P.resolvedPath??P.pathExpression),Ce=f.find(q=>(q.method||"GET").toUpperCase()===G&&zm(q.url)===me),Ie=P.responses?.[0]?.statusCode??200;if(Ce){if(h++,!n&&s&&sS(Ce)){let q=Pi(P,p.id,s);Ce.url!==q.url&&(await r.collection.updateRequest(p.id,Ce.id,{url:q.url}),v++)}y.push({...P,id:Ce.id}),S.set(M,{endpointKey:M,method:G,path:P.resolvedPath??P.pathExpression,confidence:P.confidence,requestId:Ce.id,requestName:Ce.name,reused:!0,statusExpected:Ie})}else if(n)y.push(P),S.set(M,{endpointKey:M,method:G,path:P.resolvedPath??P.pathExpression,confidence:P.confidence,requestId:"",requestName:aS(P),reused:!1,statusExpected:Ie});else{if(!s)throw new Error(`base-url is required to create requests (endpoint ${M} has no reusable request). Pass --base-url or re-run with --dry-run to preview.`);let q=await r.collection.createRequest(Pi(P,p.id,s));if(q.type!=="request")throw new Error(`QA check produced a non-request item for endpoint ${M}.`);g++,f.push(q),y.push({...P,id:q.id}),S.set(M,{endpointKey:M,method:G,path:P.resolvedPath??P.pathExpression,confidence:P.confidence,requestId:q.id,requestName:q.name,reused:!1,statusExpected:Ie})}}let b=`QA ${p.name}`,{suite:C}=fn(y,{collectionId:p.id,collectionName:p.name,name:b,id:tr(b),assertBodySchema:t.assertBodySchema});if(n||((g>0||v>0)&&await r.collection.saveCollection(p),await r.testSuite.updateSuite(C)),n)return{status:"dry-run",project:{path:t.projectPath,gitHash:i.gitHash,frameworks:d},drift:{status:a.status,reason:a.reason},discovered:u.length,reused:h,created:g,updatedUrls:v,suite:{id:C.id,name:C.name},results:{passed:0,failed:0,skipped:u.length},endpoints:[...S.values()],lowConfidence:m,aiAssertions:{requested:t.aiAssertions===!0,applied:!1},checkedAt:new Date().toISOString()};if(!s&&g>0)throw new Error("base-url is required to run a QA check (pass --base-url or --dry-run).");let w=await br({workspaceFolder:e,suiteId:C.id,environment:t.environment,variables:t.variables,include:["perRequest","failedOnly"]}),E=new Map((w.failedRequests??[]).map(P=>[P.name??"",P])),F=new Map((w.results??[]).map(P=>[P.name??"",P])),N=0,j=0;for(let P of S.values()){let M=E.get(P.requestName),G=F.get(P.requestName);M?(P.passed=!1,P.statusGot=M.status,P.duration=M.duration,P.error=M.error,P.failures=(M.failedTests??[]).map(me=>me.message?`${me.name??"assertion"}: ${me.message}`:me.name??"assertion"),j++):(P.passed=!0,P.statusGot=G?.status??P.statusExpected,P.duration=G?.duration,N++)}let O,D=!1;if(t.aiAssertions===!0)if(!t.aiProvider)O="ai-assertions requested but no AI provider is available (set OPENAI_API_KEY / ANTHROPIC_API_KEY or configure a provider).";else{let P=[...S.values()].sort((G,me)=>+(G.passed===!1)-+(me.passed===!1)),M=P.slice(0,10);P.length>M.length&&(O=`AI assertion pass capped at 10 of ${P.length} endpoints.`);for(let G of M)try{let me=r.collection.getRequestDetail(p.id,G.requestId);if(!me)continue;let Ce=E.get(G.requestName),Ie=await _l(t.aiProvider,me,oS(Ce,G),t.aiMaxSuggestions??5,void 0);Ie.length>0&&(G.suggestions=Ie,D=!0)}catch{}}return{status:j===0?"pass":"fail",project:{path:t.projectPath,gitHash:i.gitHash,frameworks:d},drift:{status:a.status,reason:a.reason},discovered:u.length,reused:h,created:g,updatedUrls:v,suite:{id:C.id,name:C.name},results:{passed:N,failed:j,skipped:0},endpoints:[...S.values()],lowConfidence:m,aiAssertions:{requested:t.aiAssertions===!0,applied:D,...O?{note:O}:{}},checkedAt:new Date().toISOString()}}function oS(r,e){return r?{status:r.status,responseBody:typeof r.body=="string"?r.body:JSON.stringify(r.body??""),responseHeaders:r.headers,failedTests:r.failedTests}:{status:e.statusGot??e.statusExpected}}function aS(r){return r.source?.symbolName||`${r.method||"GET"} ${r.pathExpression}`}var Ou=k(()=>{"use strict";du();Oa();Sr();Dl()});function xr(r,e){let t=r[e];if(t===void 0)return;if(typeof t!="string")throw A(`"${e}" must be a string.`);let n=t.trim();return n.length>0?n:void 0}var Wm,Gm=k(()=>{"use strict";Ou();Fe();Ne();Wm=[{toolNames:[x.qaApi],async handle({args:r,services:e}){let t=xr(r,"projectPath")??e.workspaceFolder;if(!t)throw A('"projectPath" is required (or set services.workspaceFolder).');let n=xr(r,"collection");if(!n)throw A('"collection" is required.');let s=xr(r,"baseUrl")?.replace(/\/+$/,"")||void 0,i=r.dryRun===!0;if(!i&&!s)throw A('"baseUrl" is required unless dryRun is true.');if(r.variables!==void 0&&(typeof r.variables!="object"||r.variables===null||Array.isArray(r.variables)))throw A('"variables" must be an object.');let o=await Tu({collection:e.collection,testSuite:e.testSuite},e.workspaceFolder??t,{projectPath:t,collectionRef:n,baseUrl:s,environment:xr(r,"environment"),variables:r.variables,framework:xr(r,"framework"),dryRun:i,failOnDrift:r.failOnDrift===!0,storedGitHash:xr(r,"storedGitHash"),storedScannedAt:xr(r,"storedScannedAt"),aiAssertions:r.aiAssertions===!0,aiProvider:e.aiProvider});return{...o,hint:o.status==="fail"?"Fix the failing endpoints, then re-run qa_api (requests are reused, nothing is duplicated).":o.status==="drift"?"Project moved since the stored scan \u2014 review drift, then re-run without failOnDrift to regenerate.":"Use get_request for full detail on any endpoint, or analyze_test_failure for failures."}}}]});function lS(){let r=new Map;for(let e of cS)for(let t of e.toolNames)r.set(t,e);return r}var cS,$u,gT,Km=k(()=>{"use strict";Dl();zp();tm();rm();im();am();lm();dm();ym();bm();Cm();Gm();cS=[...cm,...nm,...vm,...om,...Vp,...um,...gm,...em,...Wm,...Rm,...sm,...Bp];$u=lS(),gT=new Set([...$u.keys()].map(r=>r))});function uS(r){return new Error(`Bad request: ${r}`)}async function Nu(r,e,t,n,s){let i=$u.get(r);if(!i)throw uS(`unknown tool: "${r}"`);let o=t.collection.getAllCollections(),a={tool:r,args:e,services:t,runStore:n,callbacks:s,collections:o};return i.handle(a)}var Fu,_u=k(()=>{"use strict";Km();Fe();Ne();Fu=new Set([x.createCollection,x.renameCollection,x.deleteCollection,x.duplicateCollection,x.createFolder,x.deleteFolder,x.createRequest,x.updateRequest,x.deleteRequest,x.reorderCollectionItems,x.createSuite,x.updateSuiteConfig,x.addSuiteNode,x.updateSuiteNode,x.removeSuiteNode,x.moveSuiteNode,x.duplicateSuite,x.deleteSuite,x.designApiFromIntent])});var Bi,Du=k(()=>{"use strict";Bi=class{store=new Map;newId(){return`run_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}create(e,t){this.prune();let n={id:this.newId(),status:"running",suiteName:e,startedAt:Date.now(),progress:{completed:0,total:t},summary:{passed:0,failed:0,total:0,allPassed:!1},failedRequests:[],allResults:[],reportPath:null};return this.store.set(n.id,n),n}get(e){return this.store.get(e)}require(e){if(typeof e!="string"||!e)throw new Error('"runId" is required');let t=this.store.get(e);if(!t)throw new Error(`Run "${e}" not found. It may have expired (1-hour TTL) or never existed.`);return t}prune(){let e=Date.now()-36e5;for(let[t,n]of this.store)n.startedAt<e&&this.store.delete(t)}values(){return this.store.values()}cancel(e){let t=this.store.get(e);return!t||t.status!=="running"?!1:(t.status="cancelled",t.completedAt=Date.now(),!0)}}});import{createHash as dS}from"crypto";function Qm(r){return dS("sha256").update(r,"utf8").digest("hex").slice(0,pS)}function hS(r){let e=r.replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/__+/g,"_").replace(/^_+|_+$/g,"").toLowerCase();return e?e.slice(0,fS):"id"}function qn(r){return`${hS(r)}_${Qm(r)}`}function gS(r,e){return r.length>0&&r.length<=e&&/^[a-zA-Z0-9_-]+$/.test(r)&&!r.includes("__")}function ds(r,e=mS){return gS(r,e)?r:qn(r)}function Mu(r,e,t){let n=`${r}request__${ds(e)}__${ds(t)}`;return n.length<=Za?n:`${r}request__${qn(e)}__${qn(t)}`}function ju(r,e){let t=`${r}collection__${ds(e,100)}`;return t.length<=Za?t:`${r}collection__${qn(e)}`}function Lu(r,e,t){let n=`${r}folder__${ds(e)}__${ds(t)}`;return n.length<=Za?n:`${r}folder__${qn(e)}__${qn(t)}`}function Hu(r,e){let t=`${r}suite__${ds(e,100)}`;return t.length<=Za?t:`${r}suite__${qn(e)}`}function Bu(r){for(let e of["request","collection","folder","suite"]){let t=`${e}__`;if(r.startsWith(t))return{kind:e,tokens:r.slice(t.length).split("__")}}throw new Error(`Unknown MCP tool name: ${r}`)}function ps(r,e){let t=r.includes("_")?r.slice(r.lastIndexOf("_")+1):r;for(let n of e)if(Qm(n)===t)return n;for(let n of e)if(qn(n)===r)return n;for(let n of e)if(n===r)return n}function Uu(r,e){let t=ps(r,e);if(t!==void 0)return t;try{let n=Buffer.from(r,"base64url").toString("utf8");if(e.includes(n))return n}catch{}}function Vu(r,e,t,n){let s=n?` in folder "${n}"`:"";return`Run the "${e}" request [${r}]${s} of the "${t}" collection.`}function zu(r,e){return`Run all ${e} requests in the "${r}" collection.`}function Ju(r,e,t){return`Run all ${t} requests in folder "${r}" of the "${e}" collection.`}function Wu(r,e,t){return`Run the "${r}" test suite (${e} requests, ${t} iteration(s) by default).`}var pS,fS,mS,Za,Ya=k(()=>{"use strict";pS=12,fS=16,mS=60,Za=126});import*as Zm from"fs";import*as Ym from"path";function Gu(r){let e=new Set,t=[];for(let n of r)e.has(n.name)||(e.add(n.name),t.push(n));return t}function Ku(r){return Buffer.from(String(r)).toString("base64url")}function Qu(r){if(!r)return 0;try{let e=parseInt(Buffer.from(r,"base64url").toString(),10);return Number.isFinite(e)&&e>=0?e:0}catch{return 0}}function Zu(r,e,t,n){let s=t.toolPrefix??"",i=t.toolMode??"auto",o=t.drilldownThreshold??100;if(i==="execution-only"){let u=Zo(s,r.map(d=>d.name),e.map(d=>d.name));return Gu(u.filter(d=>!yS.some(p=>d.name.endsWith(p))).map(d=>({name:d.name,description:d.description,inputSchema:d.inputSchema,...d.annotations&&{annotations:d.annotations}})))}let a=0;for(let u of r)a+=X(u).length;let c=i==="drilldown"||i==="auto"&&a>o;if(c&&i==="auto"&&n){let u=Ym.join(n,".http-forge","AGENTS.md");Zm.existsSync(u)&&(i="execution-only")}if(i==="flat"&&a>500&&console.warn(`[http-forge MCP] WARNING: toolMode is "flat" but ${a} requests would produce ${a}+ tools. This will likely degrade AI tool-selection quality and bloat the context window. Consider setting toolMode to "auto" or "drilldown" in http-forge.config.json.`),c)return Gu(Zo(s,r.map(u=>u.name),e.map(u=>u.name)).map(u=>({name:u.name,description:u.description,inputSchema:u.inputSchema,...u.annotations&&{annotations:u.annotations}})));let l=[];for(let u of r){let d=X(u);for(let{request:p,folderPath:m}of d)l.push({name:Mu(s,u.id,p.id),description:Vu(p.method,p.name,u.name,m),inputSchema:Wo});l.push({name:ju(s,u.id),description:zu(u.name,d.length),inputSchema:Go});for(let{folderPath:p,requestCount:m}of qe(u))m!==0&&l.push({name:Lu(s,u.id,p),description:Ju(p,u.name,m),inputSchema:Ko})}for(let u of e)l.push({name:Hu(s,u.id),description:Wu(u.name,u.nodes.filter(d=>d.type==="request").length,u.config.iterations),inputSchema:Qo});return Gu(l)}var yS,Yu=k(()=>{"use strict";tt();Ya();Fe();yS=["list_collections","list_folders","list_requests","search_requests","get_request","get_request_script","list_environments","get_environment","get_environment_variables","list_suites","get_suite","get_suite_node","list_suite_node_paths","create_collection","rename_collection","delete_collection","duplicate_collection","create_folder","delete_folder","create_request","update_request","delete_request","set_request_script","reorder_collection_items","create_suite","update_suite_config","add_suite_node","update_suite_node","remove_suite_node","move_suite_node","add_suite_requests","remove_suite_request","reorder_suite_requests","duplicate_suite","delete_suite","create_environment","delete_environment","create_request_from_endpoint","generate_test_suite","suggest_workflow","generate_workflow","check_drift","propose_update","qa_api","design_api_from_intent","review_suite"]});var nh={};nc(nh,{createMcpRuntime:()=>OS});import*as th from"fs";import{createServer as vS}from"http";import*as An from"path";async function qt(r){let e=process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS,t=process.env.HTTP_FORGE_GENERATE_REPORTS;process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS="true",process.env.HTTP_FORGE_GENERATE_REPORTS="true";try{return await r()}finally{e===void 0?delete process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS:process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS=e,t===void 0?delete process.env.HTTP_FORGE_GENERATE_REPORTS:process.env.HTTP_FORGE_GENERATE_REPORTS=t}}function fs(r){let e=[r.testSuite,r.collection,r.environmentConfig,r.config,r.console];for(let t of e)try{t?.dispose?.()}catch{}}async function xS(r,e){let t=td.get(r);if(t&&t.expiresAt>Date.now())return t.tools;let n=Xu.get(r);if(n)return n;let s=(async()=>{let i=e.config.getMcpConfig(),o=(l,u)=>!!l?.length&&(l.includes(u.id)||l.includes(u.name)),a=e.collection.getAllCollections().filter(l=>!o(i.excludedCollections,l)),c=(await e.testSuite.getAllSuites()).filter(l=>!o(i.excludedSuites,l));return Zu(a,c,i,r)})().then(i=>(td.set(r,{tools:i,expiresAt:Date.now()+SS}),i)).finally(()=>Xu.delete(r));return Xu.set(r,s),s}function wS(r,e){let t=r.config.getMcpConfig().toolPrefix??"";return t&&e.startsWith(t)?e.slice(t.length):e}function RS(r,e,t){return r.replace(/"uri"\s*:\s*"file:\/\/([^"]+)"/g,(n,s)=>`"uri":"http://${e}:${t}/report?path=${encodeURIComponent(s)}"`)}function Xm(r,e,t,n){wr(r,200,{jsonrpc:"2.0",id:e,error:{code:t,message:n}})}function CS(r){return r.config.getMcpConfig().toolPageSize??200}async function kS(r,e){switch(e.method){case"initialize":return{protocolVersion:"2024-11-05",capabilities:{tools:{},prompts:{}},serverInfo:{name:"http-forge",version:"1.0.0"},instructions:"You are assisting with HTTP API testing via HTTP Forge. When a run_suite, run_collection, or run_folder call completes with failures (summary.failed > 0 or allPassed === false), automatically analyze the 'failedRequests' in the response and provide: (1) root cause for each failure, (2) specific fix recommendations, (3) updated pm.test() assertion scripts where relevant. Do not wait for the user to ask \u2014 proactively diagnose and suggest fixes. For async runs (status: 'running'), poll with get_run_status until complete, then call get_run_summary. When get_run_summary returns a _nextStep field you MUST execute it immediately \u2014 the failedRequests array is already included inline so no extra tool call is needed. Analyze the failures and provide diagnosis without waiting for the user."};case"tools/list":{let t=await xS(r.workspaceFolder,r.container),n=e.params??{},s=typeof n.cursor=="string"?n.cursor:void 0,i=CS(r.container);if(i<=0||t.length<=i)return{tools:t};let o=Qu(s),a=t.slice(o,o+i),c=o+i,l={tools:a};return c<t.length&&(l.nextCursor=Ku(c)),l}case"tools/call":{let t=e.params??{},n=t.name,s=t.arguments;if(!n)throw new Error("Missing tool name");let i=await nd(r,n,s??{}),o=i,a=o?.summary;a&&((a.failed??0)>0||a.allPassed===!1)&&(o._nextStep=`${a.failed??"Some"} request(s) failed. Please analyze the 'failedRequests' above: identify the root cause of each failure, suggest specific fixes (URL, auth, body, environment variables), and provide updated pm.test() assertion scripts where the assertions are incorrect.`);let c=JSON.stringify(i,null,2),l=RS(c,r.host,r.port),u=l.match(/"uri"\s*:\s*"(http:\/\/[^"]+\/report\?[^"]+)"/),d=u?`
|
|
1787
|
+
`}}});import*as Re from"fs/promises";import*as Ke from"path";function hr(r,e){if(r.length===0)return 0;let t=Math.ceil(e/100*r.length)-1;return r[Math.max(0,Math.min(t,r.length-1))]}var gr,_a=k(()=>{"use strict";Ze();Lr();jr();Ru();$i();Nm();rs();gr=class{constructor(e){this.configService=e;let t=e.getRunnerConfig();this.basePath=e.getResultsPath(),this.indexPageSize=t.indexPageSize,this.recentErrorsLimit=t.recentErrorsLimit}configService;basePath;currentRunPath=null;currentRunId=null;currentSuiteId=null;currentManifest=null;currentIndexPage=[];currentPageNumber=1;indexPageSize;recentErrors=[];recentErrorsLimit;resultIndex=0;requestDurations={};getBasePath(){return this.basePath}async initializeRun(e,t,n,s,i){let o=this.generateRunId();return this.currentRunId=o,this.currentSuiteId=e,this.currentRunPath=Ke.join(this.basePath,e,o),await Re.mkdir(Ke.join(this.currentRunPath,"results"),{recursive:!0}),await Re.mkdir(Ke.join(this.currentRunPath,"index"),{recursive:!0}),this.currentManifest={version:"1.0",runId:o,suiteId:e,suiteName:t,targetType:i?.targetType,targetName:i?.targetName,collectionName:i?.collectionName,folderPath:i?.folderPath,environment:n,startTime:new Date().toISOString(),status:"running",config:s,stats:{totalRequests:0,passed:0,failed:0,skipped:0,totalDuration:0,avgDuration:0,minDuration:Number.MAX_SAFE_INTEGER,maxDuration:0},requestStats:{},totalIndexPages:0,indexPageSize:this.indexPageSize},this.currentIndexPage=[],this.currentPageNumber=1,this.recentErrors=[],this.resultIndex=0,this.requestDurations={},await this.saveManifest(),o}async saveResult(e,t){if(!this.currentRunPath||!this.currentManifest)throw new Error("No active run. Call initializeRun first.");let n=Mr(t.executedRequest),s=t.error?Kn(t.error,n):t.error;this.resultIndex++;let i=Date.now(),o=String(e).padStart(4,"0"),a=String(this.resultIndex).padStart(6,"0"),c=xe(t.requestId),l=`result-${a}-iter-${o}-${c}.json`,u=Ke.join(this.currentRunPath,"results",l),d={index:this.resultIndex,iteration:e,requestId:t.requestId,name:t.name,method:t.executedRequest.method,url:t.executedRequest.url,folderPath:t.folderPath||"",groupPath:t.groupPath||t.folderPath||"",groupType:t.groupType,collectionName:t.collectionName||"",status:t.response.status,statusText:t.response.statusText||"",duration:t.duration,passed:t.passed,timestamp:i,request:{method:t.executedRequest.method,url:t.executedRequest.url,headers:t.executedRequest.headers,query:t.executedRequest.query,params:t.executedRequest.params,body:t.executedRequest.body},response:{headers:t.response.headers,body:t.response.body,time:t.response.time,size:t.response.size,cookies:t.response.cookies},assertions:t.assertions.map(g=>({name:g.name,passed:g.passed,message:g.message||null,...g.skipped?{skipped:!0}:{}})),error:s||null,consoleOutput:t.consoleOutput,nextRequest:t.nextRequest??null,visualizerData:t.visualizerData};await Re.writeFile(u,JSON.stringify(Qc(d,n),null,2),"utf-8");let p=t.assertions.filter(g=>g.passed&&!g.skipped).length,m=t.assertions.filter(g=>!g.passed&&!g.skipped).length,f=t.assertions.filter(g=>g.skipped).length,h={i:this.resultIndex,it:e,n:t.name,m:bu[t.executedRequest.method.toUpperCase()]??0,s:t.response.status,d:t.duration,p:t.passed,ap:p,af:m,...f>0?{as:f}:{},r:t.requestId,e:t.passed?null:s||null,fp:t.folderPath||"",gp:t.groupPath||t.folderPath||"",gt:t.groupType,cn:t.collectionName||""};return this.currentIndexPage.push(h),this.currentIndexPage.length>=this.indexPageSize&&await this.writeCurrentIndexPage(),this.updateStats(t),this.requestDurations[t.requestId]||(this.requestDurations[t.requestId]=[]),this.requestDurations[t.requestId].push(t.duration),t.passed||(this.recentErrors.unshift({timestamp:i,iteration:e,requestName:t.name,status:t.response.status,error:s||`Status ${t.response.status}`,resultFile:l}),this.recentErrors.length>this.recentErrorsLimit&&this.recentErrors.pop()),h}async finalizeRun(e="completed",t=!0){if(!this.currentManifest)return null;this.currentIndexPage.length>0&&await this.writeCurrentIndexPage(),this.currentManifest.endTime=new Date().toISOString(),this.currentManifest.status=e,this.currentManifest.totalIndexPages=this.currentPageNumber-1,this.currentManifest.stats.totalRequests>0&&(this.currentManifest.stats.avgDuration=Math.round(this.currentManifest.stats.totalDuration/this.currentManifest.stats.totalRequests)),this.currentManifest.stats.minDuration===Number.MAX_SAFE_INTEGER&&(this.currentManifest.stats.minDuration=0);for(let c in this.currentManifest.requestStats){let l=this.currentManifest.requestStats[c],u=this.requestDurations[c]||[];l.count>0&&(l.avgDuration=Math.round(l.totalDuration/l.count)),l.minDuration===Number.MAX_SAFE_INTEGER&&(l.minDuration=0),u.length>0&&(u.sort((d,p)=>d-p),l.p50=hr(u,50),l.p90=hr(u,90),l.p95=hr(u,95),l.p99=hr(u,99))}let n=Object.values(this.requestDurations).flat();n.length>0&&(n.sort((c,l)=>c-l),this.currentManifest.stats.p50=hr(n,50),this.currentManifest.stats.p95=hr(n,95),this.currentManifest.stats.p99=hr(n,99)),this.requestDurations={},await this.saveManifest();let s=null,i=this.currentRunPath,o=this.currentSuiteId,a=this.currentRunId;if(this.currentRunPath=null,this.currentRunId=null,this.currentSuiteId=null,this.currentManifest=null,this.currentIndexPage=[],this.recentErrors=[],this.resultIndex=0,t&&o&&a&&i){try{let c=this.configService.getRunnerConfig().report;s=await new cs(this.basePath,c).generate(o,a)}catch(c){console.warn("[ResultStorage] HTML report generation failed:",c)}try{let c=this.configService.getSuitesPath();await new Na(this.basePath,c).generate(o,a)}catch(c){console.warn("[ResultStorage] Markdown summary generation failed:",c)}}return s}getCurrentStats(){return this.currentManifest?{stats:{...this.currentManifest.stats},requestStats:{...this.currentManifest.requestStats},recentErrors:[...this.recentErrors]}:null}getCurrentRunId(){return this.currentRunId}getCurrentSuiteId(){return this.currentSuiteId}async regenerateHtmlReport(e,t){try{let n=this.configService.getRunnerConfig().report;return await new cs(this.basePath,n).generate(e,t)}catch(n){return console.warn("[ResultStorage] HTML report regeneration failed:",n),null}}async generateJunitReport(e,t){try{return await new Qt(this.basePath).generate(e,t)}catch(n){return console.warn("[ResultStorage] JUnit report generation failed:",n),null}}async getResultDetails(e,t,n){let s=Ke.join(this.basePath,e,t,"results",n),i=await Re.readFile(s,"utf-8");return JSON.parse(i)}async getIndexPage(e,t,n){let s=Ke.join(this.basePath,e,t,"index",`page-${String(n).padStart(4,"0")}.json`),i=await Re.readFile(s,"utf-8");return JSON.parse(i)}async getManifest(e,t){let n=Ke.join(this.basePath,e,t,"manifest.json"),s=await Re.readFile(n,"utf-8");return JSON.parse(s)}async listRuns(e){let t=Ke.join(this.basePath,e);try{let n=await Re.readdir(t),s=[];for(let i of n.sort().reverse())try{let o=await this.getManifest(e,i);s.push(o)}catch{}return s}catch{return[]}}async listSuites(){try{return(await Re.readdir(this.basePath,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}async deleteRun(e,t){let n=Ke.join(this.basePath,e,t);await Re.rm(n,{recursive:!0,force:!0})}async cleanupOldRuns(){let t=this.configService.getRunnerConfig().resultsRetentionDays;if(t===0)return{deleted:0,freed:0};let n=new Date;n.setDate(n.getDate()-t);let s=0,i=0,o=await this.listSuites();for(let a of o){let c=await this.listRuns(a);for(let l of c)if(new Date(l.startTime)<n){let u=Ke.join(this.basePath,a,l.runId),d=await this.getDirectorySize(u);await Re.rm(u,{recursive:!0,force:!0}),s++,i+=d}}return{deleted:s,freed:i}}generateRunId(){let e=new Date,t=e.toISOString().slice(0,10).replace(/-/g,""),n=e.toTimeString().slice(0,8).replace(/:/g,""),s=String(e.getMilliseconds()).padStart(3,"0");return`run-${t}-${n}-${s}`}async saveManifest(){if(!this.currentRunPath||!this.currentManifest)return;let e=Ke.join(this.currentRunPath,"manifest.json");await Re.writeFile(e,JSON.stringify(this.currentManifest,null,2),"utf-8")}async writeCurrentIndexPage(){if(!this.currentRunPath||this.currentIndexPage.length===0)return;let e=`page-${String(this.currentPageNumber).padStart(4,"0")}.json`,t=Ke.join(this.currentRunPath,"index",e),n={page:this.currentPageNumber,startIndex:(this.currentPageNumber-1)*this.indexPageSize+1,count:this.currentIndexPage.length,summaries:this.currentIndexPage};await Re.writeFile(t,JSON.stringify(n),"utf-8"),this.currentPageNumber++,this.currentIndexPage=[]}updateStats(e){if(!this.currentManifest)return;let t=this.currentManifest.stats,n=this.currentManifest.requestStats;t.totalRequests++,t.totalDuration+=e.duration,t.minDuration=Math.min(t.minDuration,e.duration),t.maxDuration=Math.max(t.maxDuration,e.duration),e.passed?t.passed++:t.failed++,n[e.requestId]||(n[e.requestId]={name:e.name,count:0,passed:0,failed:0,totalDuration:0,avgDuration:0,minDuration:Number.MAX_SAFE_INTEGER,maxDuration:0});let s=n[e.requestId];s.count++,s.totalDuration+=e.duration,s.minDuration=Math.min(s.minDuration,e.duration),s.maxDuration=Math.max(s.maxDuration,e.duration),e.passed?s.passed++:s.failed++}async getDirectorySize(e){let t=0;try{let n=await Re.readdir(e,{withFileTypes:!0});for(let s of n){let i=Ke.join(e,s.name);if(s.isDirectory())t+=await this.getDirectorySize(i);else{let o=await Re.stat(i);t+=o.size}}}catch{}return t}}});function Ni(r,e,t=r.items,n=[],s=[],i=[]){for(let o of t){if(o.type==="request"&&o.id===e)return{request:o,folderScriptsChain:[...n],folderAuthChain:[...s],folderPath:i.map($e).join("/")};if(o.type==="folder"){let a=o,c=a.scripts?[...n,a.scripts]:[...n],l=a.auth?[...s,a.auth]:[...s],u=[...i,a.name],d=Ni(r,e,a.items??[],c,l,u);if(d)return d}}}function Cu(r,e=r.items,t=[],n=[]){let s=[];for(let i of e)if(i.type==="request")s.push({request:i,folderScriptsChain:[...t],folderPath:n.map($e).join("/")});else{let o=i,a=o.scripts?[...t,o.scripts]:[...t],c=[...n,o.name];s.push(...Cu(r,o.items??[],a,c))}return s}function _m(r,e,t=!0){if(!e)return r;let n=e.replace(/\/+$/,"");return r.filter(({folderPath:s})=>t?s===n||s.startsWith(`${n}/`):s===n)}function Dm(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}var ku=k(()=>{"use strict";tt()});function Da(r){let e=[r.testSuite,r.collection,r.environmentConfig,r.config,r.console];for(let t of e)try{t?.dispose?.()}catch{}}function Mm(r){return r==="1"||r==="true"||r==="yes"||r==="on"}function Ma(r,e){let t=r??0;return e==="websocket"?t===101:t>=200&&t<300}function jm(){return Mm(process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS)}function Lm(){let r=process.env.HTTP_FORGE_MAX_REQUESTS;if(!r||r.trim()==="")return 50;let e=Number(r);if(!Number.isFinite(e)||e<=0)throw new Error("HTTP_FORGE_MAX_REQUESTS must be a positive number when provided");return Math.floor(e)}function ja(r,e=[]){return Mm(process.env.HTTP_FORGE_GENERATE_REPORTS)||e.includes("html")?!0:r.includes("report")}function _i(r){if(typeof r!="string")return r;try{return JSON.parse(r)}catch{return r}}function nS(r){return r?Object.fromEntries(Object.entries(r).filter(([e])=>e.toLowerCase()!=="set-cookie")):{}}function La(r){return St(nS(r))}function Ha(r){return Wc((r??[]).map(e=>({name:e.name,value:e.value})))}function Eu(r){return r.replace(/[^a-zA-Z0-9_-]/g,"_")}function Ba(r){let e=["none","inherit","basic","bearer","apikey","oauth2"],t=r.auth?.type&&e.includes(r.auth.type)?r.auth.type:void 0;return{id:r.id,name:r.name,requestType:r.requestType,method:r.method,url:r.url,websocket:r.websocket,headers:Array.isArray(r.headers)?r.headers.reduce((n,s)=>(s.enabled&&s.key&&(n[s.key]=s.value??""),n),{}):r.headers,query:Array.isArray(r.query)?r.query.reduce((n,s)=>(s.enabled&&s.key&&(n[s.key]=s.value??""),n),{}):r.query,params:r.params?Object.entries(r.params).reduce((n,[s,i])=>(n[s]=typeof i=="string"?i:i.value??"",n),{}):void 0,body:r.body??null,scripts:r.scripts,settings:r.settings,auth:{type:t==="inherit"?"none":t,bearerToken:r.auth?.bearerToken,basicAuth:r.auth?.basicAuth,apikey:r.auth?.apikey,oauth2:r.auth?.oauth2}}}function Ua(r,e){let t={...r};return e.headers&&(t.headers={...r.headers??{},...e.headers}),e.query&&(t.query=e.query),e.body!==void 0&&(t.body={type:"raw",format:"json",content:e.body}),t}function ls(r){return r?Object.fromEntries(Object.entries(r).map(([e,t])=>[e,String(t)])):{}}function Va(r,e,t){if(r&&r.type&&r.type!=="inherit")return r.type==="none"?void 0:r;for(let n=e.length-1;n>=0;n--){let s=e[n];if(s?.type&&s.type!=="inherit")return s.type==="none"?void 0:s}if(t&&t.type&&t.type!=="inherit")return t.type==="none"?void 0:t}var qu=k(()=>{"use strict";Lr()});import*as Et from"fs";import*as yr from"path";var Au,za,Ja,Wa,Hm=k(()=>{"use strict";Au=class{watchers=[];changeCallbacks=[];createCallbacks=[];deleteCallbacks=[];knownPaths=new Set;debounceTimers=new Map;matcher=()=>!0;constructor(e,t){let n=this.resolveWatchTarget(e,t);this.matcher=n.matcher;try{let s=Et.watch(n.watchPath,{recursive:n.recursive},(i,o)=>{if(!o)return;let a=typeof o=="string"?o:String(o),c=yr.resolve(n.watchPath,a);this.matcher(c)&&this.scheduleEvent(c)});this.watchers.push(s)}catch{}}resolveWatchTarget(e,t){if(t.includes("*")){let s=t.includes("**"),i=t.match(/\*\.([A-Za-z0-9]+)$/),o=i?i[1].toLowerCase():null;return{watchPath:e,recursive:s,matcher:o?c=>c.toLowerCase().endsWith("."+o):()=>!0}}let n=yr.resolve(e,t);return{watchPath:yr.dirname(n),recursive:!1,matcher:s=>yr.resolve(s)===n}}scheduleEvent(e){let t=this.debounceTimers.get(e);t&&clearTimeout(t),this.debounceTimers.set(e,setTimeout(()=>{this.debounceTimers.delete(e),this.emitEvent(e)},50))}emitEvent(e){Et.existsSync(e)?this.knownPaths.has(e)?this.changeCallbacks.forEach(n=>n(e)):(this.knownPaths.add(e),this.createCallbacks.forEach(n=>n(e))):(this.knownPaths.delete(e),this.deleteCallbacks.forEach(n=>n(e)))}register(e,t){return e.push(t),{dispose:()=>{let n=e.indexOf(t);n!==-1&&e.splice(n,1)}}}onDidChange(e){return this.register(this.changeCallbacks,e)}onDidCreate(e){return this.register(this.createCallbacks,e)}onDidDelete(e){return this.register(this.deleteCallbacks,e)}dispose(){for(let e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(let e of this.watchers)e.close();this.watchers=[],this.changeCallbacks=[],this.createCallbacks=[],this.deleteCallbacks=[],this.knownPaths.clear()}},za=class{createFileWatcher(e,t){return new Au(e,t)}},Ja=class{data={};storeFile;constructor(e){this.storeFile=e,this.load()}load(){try{if(Et.existsSync(this.storeFile)){let e=Et.readFileSync(this.storeFile,"utf-8");this.data=JSON.parse(e)}}catch{}}save(){try{let e=yr.dirname(this.storeFile);Et.mkdirSync(e,{recursive:!0}),Et.writeFileSync(this.storeFile,JSON.stringify(this.data,null,2),"utf-8")}catch{}}get(e,t){let n=this.data[e];return n!==void 0?n:t}async update(e,t){t===void 0?delete this.data[e]:this.data[e]=t,this.save()}},Wa=class{async showInformation(e){console.log(`[INFO] ${e}`)}async showWarning(e){console.warn(`[WARN] ${e}`)}async showError(e){console.error(`[ERROR] ${e}`)}}});import*as vr from"path";function rS(r){let e=vr.resolve(r.workspaceFolder),{appInfo:t}=r,n=Qn.createFresh(),s=vr.join(e,".http-forge",".cache","stores","global-state.json"),i=r.globalStorePath?vr.isAbsolute(r.globalStorePath)?r.globalStorePath:vr.resolve(e,r.globalStorePath):s,o={workspaceFolder:e,fileWatcherFactory:new za,notificationService:new Wa,globalStore:new Ja(i),applicationInfo:t||{name:"http-forge-cli",version:"0.1.0"},persistOverrides:!1};return $o(n,o),n}function pt(r){return rS({workspaceFolder:r})}var Ga=k(()=>{"use strict";Rl();Cl();Hm()});function Di(r){let e=typeof r.blockLabel=="string"?r.blockLabel.trim():"";if(e)return{groupPath:e,groupType:"block"};let t=typeof r.collectionName=="string"?r.collectionName.trim():"",n=typeof r.folderPath=="string"?r.folderPath.trim():"";return t?{groupPath:n?`${t}/${n}`:t,groupType:"folder"}:{groupPath:n,groupType:n?"folder":void 0}}var Ka=k(()=>{"use strict"});function Mi(r){return typeof r=="string"?r:""+JSON.stringify(r)}function us(r){if(typeof r=="string"&&r.charCodeAt(0)===30)try{return JSON.parse(r.slice(1))}catch{return r}return r}function Pu(r){if(!r)return{};let e={};for(let[t,n]of Object.entries(r))e[t]=us(n);return e}var Iu=k(()=>{"use strict"});var ji,Bm=k(()=>{"use strict";$a();Gs();Lr();$i();_a();bs();Iu();ku();qu();Ka();ji=class{constructor(e){this.container=e}container;async execute(e,t,n){let s=this.container,i=t.environment??s.environmentConfig.getSelectedEnvironment(),o=t.iterations??e.config?.iterations??1,a=t.stopOnError??e.config?.stopOnError??!1,c=t.delay??e.config?.delayBetweenRequests??0,l=Math.max(1,Math.min(50,t.concurrency??1)),u=t.requestFilter,d=t.include??[],p=t.reporters??[],m=p.includes("junit"),f=ls(t.variables),h=jm(),g=ja(d,p),v=Math.max(1,Math.min(1e4,Number(t.maxNodeLoopIterations??100))),y={vars:{...f}};function S(T){if(typeof T=="string")return T;if(Array.isArray(T))return T.filter(Q=>typeof Q=="string").join(`
|
|
1788
|
+
`)}function b(T){if(!(!T||typeof T!="object")){if(T.script!==void 0)return T.script;if(typeof T.scriptRef=="string"&&T.scriptRef.trim()){let I=e?.scripts;if(I&&typeof I=="object")return I[T.scriptRef]}}}function C(T){return T?.name||T?.label||T?.id||"flow-node"}function w(T,I){let Q=s.environmentConfig.getResolvedEnvironment(i),U=Pu(y.vars),De={variables:{get:Z=>us(y.vars[Z]),set:(Z,J)=>{typeof Z=="string"&&Z.trim()&&(y.vars[Z]=Mi(J))},unset:Z=>{typeof Z=="string"&&Z.trim()&&delete y.vars[Z]},has:Z=>Object.prototype.hasOwnProperty.call(y.vars,Z),toObject:()=>({...U})},environment:{get:Z=>us(Q?.variables?.[Z]),set:(Z,J)=>{typeof Z=="string"&&Z.trim()&&s.environmentConfig.setEnvironmentVariable(Z,Mi(J),i)},unset:Z=>{typeof Z=="string"&&Z.trim()&&s.environmentConfig.deleteEnvironmentVariable(Z,i)},clear:()=>{s.environmentConfig.clearEnvironmentVariables(i)}},globals:{get:Z=>us(s.environmentConfig.getGlobalVariables()?.[Z]),set:(Z,J)=>{typeof Z=="string"&&Z.trim()&&s.environmentConfig.setGlobalVariable(Z,Mi(J))},unset:Z=>{typeof Z=="string"&&Z.trim()&&s.environmentConfig.deleteGlobalVariable(Z)},clear:()=>{s.environmentConfig.clearGlobalVariables()}}};return{vars:U,lastResult:y.lastResult,iteration:I,node:T,pm:De,ctx:De,hf:De}}function E(T,I,Q){return typeof T!="string"||!T.trim()?!0:!!It(T,w(I,Q))}function F(T){if(!T)return{};let I={};for(let[Q,U]of Object.entries(T))I[Q]=Array.isArray(U)?U.join("; "):String(U);return I}function N(T){return{executedRequest:T.executedRequest,status:T.response?.status??0,statusText:T.response?.statusText??"",headers:F(T.response?.headers),body:T.response?.body,cookies:T.response?.cookies,responseTime:T.duration,responseSize:typeof T.response?.body=="string"?Buffer.byteLength(T.response.body,"utf8"):0}}async function j(T,I,Q,U,K){let ce=S(T);if(!ce||!ce.trim())return;let ge=s.environmentConfig.getResolvedEnvironment(i),De=s.environmentConfig.getGlobalVariables(),J={request:{url:K?.request?.url??y.lastResult?.executedRequest?.url??"http://flow.local/node",method:K?.request?.method??y.lastResult?.executedRequest?.method??"GET",headers:F(K?.request?.headers),body:K?.request?.body??null,params:K?.request?.params??{},query:K?.request?.query??{}},variables:ls(y.vars),environmentVariables:ge?.variables||{},globals:{...De},environmentName:i,info:{eventName:U==="post"?"test":"prerequest",requestName:C(I),requestId:String(I?.id??C(I)),collectionName:e.name,iteration:Q,iterationCount:o},onEnvironmentChange:(de,we,In)=>{de==="set"&&we&&In!==void 0?s.environmentConfig.setEnvironmentVariable(we,In,i):de==="unset"&&we?s.environmentConfig.deleteEnvironmentVariable(we,i):de==="clear"&&s.environmentConfig.clearEnvironmentVariables(i)},onGlobalsChange:(de,we,In)=>{de==="set"&&we&&In!==void 0?s.environmentConfig.setGlobalVariable(we,In):de==="unset"&&we?s.environmentConfig.deleteGlobalVariable(we):de==="clear"&&s.environmentConfig.clearGlobalVariables()}},Pn=s.scriptExecutor.createRequestSession(J);try{if(U==="post"&&K?.response){let de=await Pn.executePostResponse(ce,K.response),we=de.localVariables??de.modifiedVariables;we&&typeof we=="object"&&(y.vars={...we})}else{let de=await Pn.executePreRequest(ce);if(!de.success)throw new Error(de.error||"Script execution failed");let we=de.localVariables??de.modifiedVariables;we&&typeof we=="object"&&(y.vars={...we})}}catch(de){let we=de instanceof Error?de.message:String(de);throw new Error(`Suite ${U}-script failed on node "${C(I)}": ${we}`)}finally{Pn.dispose?.()}}function O(T){let I=T?.type==="request"&&T?.request?T.request:T;if(!(!I||typeof I!="object")&&!(!I.collectionId||!I.requestId||!I.name))return{collectionId:I.collectionId,requestId:I.requestId,name:I.name,folderPath:I.folderPath,enabled:I.enabled}}function D(T){return!T||typeof T!="object"?!1:T.type==="request"?!!O(T):!!(T.collectionId&&T.requestId&&T.name)}function P(T,I){for(let Q of I){let U=T?.[Q];if(Array.isArray(U))return U}return[]}async function M(T,I,Q){if(ve.signal.aborted||I.enabled===!1||u&&!u.some(de=>I.name.toLowerCase().includes(de.toLowerCase())))return;let U=s.collection.getCollection(I.collectionId);if(!U)return;let K=Ni(U,I.requestId);if(!K)return;let ce=s.collection.findRequest(U.id,I.requestId)??K.request,ge=Va(ce.auth,K.folderAuthChain,U.auth),De=new Dt(s.httpRequest,s.scriptExecutor,s.environmentConfig,s.requestPreparer,i,ft,U.scripts,K.folderScriptsChain,void 0,U.name,U.auth,T,o,s.webSocketClient,s.socketIoClient),Z=Ua(Ba({...ce,auth:ge}),{headers:t.headers,query:t.query,body:t.body,variables:{...y.vars,...t.variables}}),J=await De.execute(Z,ls(y.vars),ve.signal);y.lastResult=J,J.modifiedVariables&&typeof J.modifiedVariables=="object"&&(y.vars={...J.modifiedVariables});let Pn=Di({collectionName:U.name,folderPath:I.folderPath??"",blockLabel:Q});J.folderPath=I.folderPath??"",J.collectionName=U.name,J.groupPath=Pn.groupPath,J.groupType=Pn.groupType,await te.saveResult(T,J),J.assertions?.length||rt.add(I.name),J.passed?Qe++:Te++,d.includes("perRequest")&&B.push({name:I.name,iteration:T,status:J.response?.status,ok:Ma(J.response?.status,Z.requestType),duration:`${J.duration}ms`,allPassed:J.passed,...d.includes("consoleOutput")&&J.consoleOutput?.length?{consoleOutput:J.consoleOutput}:{}}),J.passed||(_e.push({name:I.name,iteration:T,method:J.executedRequest?.method,url:J.executedRequest?.url,requestBody:_i(J.executedRequest?.body?.content)??J.executedRequest?.body?.content??null,requestHeaders:St(J.executedRequest?.headers??{}),status:J.response?.status,duration:`${J.duration}ms`,body:_i(J.response?.body),headers:La(J.response?.headers),cookies:Ha(J.response?.cookies),failedTests:J.assertions?.filter(de=>!de.passed).map(de=>({name:de.name,...de.message?{message:de.message}:{}})),...J.error?{error:J.error}:{},...d.includes("consoleOutput")&&J.consoleOutput?.length?{consoleOutput:J.consoleOutput}:{}}),a&&ve.abort()),c>0&&!ve.signal.aborted&&await new Promise(de=>setTimeout(de,c))}async function G(T,I,Q){for(let U of I){if(ve.signal.aborted)break;await me(T,U,Q)}}async function me(T,I,Q){if(!I||typeof I!="object"||I.enabled===!1||!E(I.condition,I,T))return;if(D(I)){let ce=O(I);ce&&await M(T,ce,Q);return}let U=typeof I.type=="string"?I.type.toLowerCase():"",K=P(I,["then","nodes","body"]);if(U==="block"){let ce=typeof I.name=="string"?I.name.trim():"";await G(T,K,ce||Q);return}if(U==="script"){let ce=b(I),ge=I.phase==="post"?"post":"pre";await j(ce,I,T,ge);return}if(U==="if"){let ce=typeof I.if=="string"?I.if:I.condition;if(E(ce,I,T)){await G(T,K,Q);return}if(Array.isArray(I.elseif)){for(let ge of I.elseif)if(E(ge?.condition,ge,T)){await G(T,P(ge,["then","nodes","body"]),Q);return}}await G(T,P(I,["else","elseNodes"]),Q);return}if(U==="switch"){let ce=It(String(I.expression??""),w(I,T));if(Array.isArray(I.cases)){for(let ge of I.cases)if(Object.prototype.hasOwnProperty.call(ge??{},"equals")?ge.equals===ce:E(ge?.condition,ge,T)){await G(T,P(ge,["then","nodes","body"]),Q);return}}await G(T,P(I,["default","defaultNodes"]),Q);return}if(U==="while"){let ce=typeof I.while=="string"?I.while:I.condition,ge=Math.max(1,Math.min(1e4,Number(I.maxIterations??v))),De=0;for(;E(ce,I,T);){if(De+=1,De>ge)throw new Error(`Suite while loop exceeded maxIterations (${ge}) on node "${C(I)}"`);if(await G(T,K,Q),ve.signal.aborted)break}return}if(U==="for"){let ce=Math.max(1,Math.min(1e4,Number(I.maxIterations??v))),ge=S(I.init),De=S(I.update),Z=typeof I.loopCondition=="string"&&I.loopCondition.trim()?I.loopCondition:typeof I.condition=="string"&&I.condition.trim()?I.condition:"true";ge&&await j(ge,I,T,"pre");let J=0;for(;E(Z,I,T);){if(J+=1,J>ce)throw new Error(`Suite for loop exceeded maxIterations (${ce}) on node "${C(I)}"`);if(await G(T,K,Q),ve.signal.aborted)break;De&&await j(De,I,T,"post")}return}K.length>0&&await G(T,K,Q)}function Ce(T){let I=0,Q=[...T];for(;Q.length>0;){let U=Q.pop();if(!(!U||typeof U!="object"||U.enabled===!1)){if(D(U)){let K=O(U);K&&(!u||u.some(ce=>K.name.toLowerCase().includes(ce.toLowerCase())))&&(I+=1);continue}for(let K of["nodes","then","body","else","elseNodes","default","defaultNodes"])Array.isArray(U[K])&&Q.push(...U[K]);if(Array.isArray(U.elseif))for(let K of U.elseif)Array.isArray(K?.nodes)&&Q.push(...K.nodes),Array.isArray(K?.then)&&Q.push(...K.then);if(Array.isArray(U.cases))for(let K of U.cases)Array.isArray(K?.nodes)&&Q.push(...K.nodes),Array.isArray(K?.then)&&Q.push(...K.then)}}return I}let Ie=Array.isArray(e.nodes)?e.nodes:Array.isArray(e.requests)?e.requests.map(T=>({type:"request",request:T})):[],q=Ce(Ie);if(h){let T=Lm(),I=q*o;if(I>T)throw new Error(`Suite "${e.name}" would execute ${I} request calls (${q} requests \xD7 ${o} iterations), which exceeds HTTP_FORGE_MAX_REQUESTS (${T}). Reduce iterations, use requestFilter, or increase HTTP_FORGE_MAX_REQUESTS.`)}let te=new gr(s.config),ke=await te.initializeRun(e.id,e.name,i,{iterations:o,delayBetweenRequests:c,stopOnError:a},{targetType:n==="suite"?"suite":"collection",targetName:e.name,collectionName:n==="suite"?void 0:e.collectionName,folderPath:n==="suite"?void 0:e.folderPath}),B=[],_e=[],Qe=0,Te=0,rt=new Set,ve=new AbortController,ft=new dr;async function Yt(T){await G(T,Ie)}for(let T=1;T<=o&&!ve.signal.aborted;T+=l){let I=Math.min(T+l-1,o),Q=Array.from({length:I-T+1},(U,K)=>T+K);await Promise.all(Q.map(Yt))}let Se=await te.finalizeRun("completed",g),ms=null;if(m)try{ms=await new Qt(te.getBasePath()).generate(e.id,ke)}catch(T){console.warn("[direct-execution] JUnit report generation failed:",T)}let Cr=n==="collection"?"collection":"suite",mt=te.getCurrentStats()?.stats,Ui=mt?{min:mt.minDuration,max:mt.maxDuration,avg:mt.avgDuration,p50:mt.p50??null,p95:mt.p95??null,p99:mt.p99??null}:null,Pt={[Cr]:e.name,environment:i,summary:{total:Qe+Te,passed:Qe,failed:Te,...o>1?{iterations:o}:{},...l>1?{concurrency:l}:{},allPassed:Te===0,...Ui?{durationMs:Ui}:{}}};if((Te>0||d.includes("failedOnly"))&&(Pt.failedRequests=_e),d.includes("perRequest")&&(Pt.results=B),Se!==null&&(Pt.report={uri:`file://${Se}`,hint:"Click the URI to open the HTML report in your browser"}),ms!==null&&(Pt.junitReport={path:ms}),rt.size>0){let T=Math.max(q,1),I=rt.size,Q=Array.from(rt).slice(0,5);Pt.noAssertionExamples=Q;let U=e.name;if(I/T>.5)Pt._suggestions=[`${I}/${T} requests have no pm.test() assertions. Invoke the "review-collection" prompt (collection="${U}") for a full coverage analysis and to identify assertion gaps.`];else{let K=Q.map(ce=>`"${ce}"`).join(", ");Pt._suggestions=[`${I} request(s) have no pm.test() assertions: ${K}. Invoke the "suggest-assertions" prompt (collection="${U}") to generate test coverage for them.`]}}return Pt}}});var Li={};nc(Li,{runCollection:()=>Zt,runFolder:()=>sS,runRequest:()=>Qa,runSuite:()=>br});function Um(r,e){if(e.collectionId){let t=r.getCollection(e.collectionId);if(!t)throw new Error(`Collection "${e.collectionId}" not found`);return t}if(e.collectionRef){let{collection:t,tier:n}=Oi(r.getAllCollections(),e.collectionRef);return e.onResolve?.({kind:"collection",value:e.collectionRef,tier:n,id:t.id}),t}throw new Error("A collection reference is required (collectionId or collectionRef)")}function Vm(r,e){if(e.folderPath)return e.folderPath;if(e.folderRef){let{folderPath:t}=yu(r,e.folderRef);return e.onResolve?.({kind:"folder",value:e.folderRef,tier:"name",id:t,path:t}),t}}async function Qa(r){let e=pt(r.workspaceFolder),t=r.include??[],n=r.reporters??[],s=n.includes("junit"),i=ja(t,n);try{let o=e.collection,a=Um(o,r),c=Vm(a,r),l=r.requestId;if(!l){if(!r.requestRef)throw new Error("A request reference is required (requestId or requestRef)");let E=vu(a,r.requestRef,c);l=E.request.id,r.onResolve?.({kind:"request",value:r.requestRef,tier:E.tier,id:l,path:E.folderPath?`${E.folderPath}/${E.request.name}`:E.request.name})}let u=Ni(a,l);if(!u)throw new Error(`Request "${l}" not found in collection "${a.name}"`);let p=o.findRequest(a.id,l)??u.request,m=Va(p.auth,u.folderAuthChain,a.auth),f=r.environment||e.environmentConfig.getSelectedEnvironment(),h=Ua(Ba({...p,auth:m}),{headers:r.headers,query:r.query,body:r.body,variables:r.variables}),v=await new Dt(e.httpRequest,e.scriptExecutor,e.environmentConfig,e.requestPreparer,f,new dr,a.scripts,u.folderScriptsChain,void 0,a.name,a.auth,void 0,void 0,e.webSocketClient,e.socketIoClient).execute(h,ls(r.variables)),y=Di({collectionName:a.name,folderPath:u.folderPath});v.folderPath=u.folderPath,v.collectionName=a.name,v.groupPath=y.groupPath,v.groupType=y.groupType;let S=null,b=null;if(i||s){let E=new gr(e.config),F=`request-${Eu(a.id)}-${Eu(l)}`,N=`Request: ${u.request.name}`,j=await E.initializeRun(F,N,f,{iterations:1,delayBetweenRequests:0,stopOnError:!0},{targetType:"collection",targetName:a.name,collectionName:a.name,folderPath:u.folderPath||void 0});if(await E.saveResult(1,v),S=await E.finalizeRun("completed",i),s)try{b=await new Qt(E.getBasePath()).generate(F,j)}catch(O){console.warn("[direct-execution] JUnit report generation failed:",O)}}let C=La(v.response?.headers),w=Ha(v.response?.cookies);return{request:u.request.name,status:v.response?.status||0,ok:Ma(v.response?.status,h.requestType),duration:`${v.duration}ms`,body:_i(v.response?.body),allPassed:v.passed,assertions:v.assertions?.map(E=>({name:E.name,passed:E.passed,message:E.message})),...t.includes("headers")?{headers:C}:{},...t.includes("cookies")?{cookies:w}:{},...t.includes("tests")?{tests:v.assertions?.map(E=>({name:E.name,passed:E.passed,...E.message?{message:E.message}:{}}))}:{},...Object.keys(v.modifiedVariables??{}).length?{modifiedVariables:v.modifiedVariables}:{},...t.includes("consoleOutput")&&v.consoleOutput?.length?{consoleOutput:v.consoleOutput}:{},...S!==null?{report:{uri:`file://${S}`,hint:"Click the URI to open the HTML report in your browser"}}:{},...b!==null?{junitReport:{path:b}}:{},...v.error?{error:v.error}:{}}}catch(o){throw o}finally{Da(e)}}async function Zt(r){let e=pt(r.workspaceFolder);try{let t=e.collection,n=Um(t,r),s=Vm(n,r),i=Cu(n),o=_m(i,s,r.recursive);if(o.length===0&&s)throw new Error(`No requests found under folder "${s}" in collection "${n.name}"`);let a=o.map(({request:l,folderPath:u})=>({id:l.id,slug:l.id.toLowerCase().replace(/\s+/g,"-"),collectionId:n.id,requestId:l.id,name:l.name,method:l.method,collectionName:n.name,folderPath:u,enabled:!0})),c={id:s?`temp-${n.id}-${Dm(s)}`:`temp-${n.id}`,name:s?`${n.name} / ${s}`:n.name,requests:a,config:{iterations:1,delay:0,stopOnError:r.stopOnError??!1,readFromSharedSession:!1,writeToSharedSession:!1},isTemporary:!0,createdAt:Date.now(),updatedAt:Date.now()};return new ji(e).execute(c,{environment:r.environment,iterations:r.iterations,stopOnError:r.stopOnError,delay:r.delay,requestFilter:void 0,include:r.include,reporters:r.reporters,concurrency:r.concurrency,variables:r.variables},"collection")}catch(t){throw t}finally{Da(e)}}async function sS(r){return Zt({recursive:!0,...r})}async function br(r){let e=pt(r.workspaceFolder);try{let n=await e.testSuite.getSuite(r.suiteId);if(!n)throw new Error(`Test suite "${r.suiteId}" not found`);return new ji(e).execute(n,{environment:r.environment,iterations:r.iterations,stopOnError:r.stopOnError,delay:r.delay,requestFilter:r.requestFilter,include:r.include,reporters:r.reporters,concurrency:r.concurrency,variables:r.variables},"suite")}catch(t){throw t}finally{Da(e)}}var Sr=k(()=>{"use strict";$a();Gs();$i();_a();ku();qu();Ga();Oa();Ka();Bm()});function Hi(r){return`${(r.method||"GET").toUpperCase()} ${r.resolvedPath??r.pathExpression}`}function iS(r){return(r.description??"").includes("Discovered from ")}function zm(r){if(!r)return"";try{return new URL(r,"http://qa.local").pathname.replace(/\/+$/,"")||"/"}catch{return r}}function Jm(r,e){for(let t of r)t.type==="request"?e.push(t):t.type==="folder"&&t.items&&Jm(t.items,e)}function oS(r){let e=[new bn,new xn,new Sn,new wn,new Rn,new Cn];if(!r)return e;let t=r.toLowerCase(),n=e.filter(s=>s.framework===t);if(n.length===0)throw new Error(`unknown framework "${r}" (expected one of: ${e.map(s=>s.framework).join(", ")})`);return n}async function Tu(r,e,t){let n=t.dryRun===!0,s=(t.baseUrl??"").replace(/\/+$/,""),i=lr(t.projectPath),o=t.storedGitHash!==void 0||t.storedScannedAt!==void 0,a=ur(t.projectPath,o?{gitHash:t.storedGitHash,scannedAt:t.storedScannedAt??new Date(0).toISOString()}:void 0);if(t.failOnDrift===!0&&a.status==="stale")return{status:"drift",project:{path:t.projectPath,gitHash:i.gitHash,frameworks:[]},drift:{status:a.status,reason:a.reason},discovered:0,reused:0,created:0,updatedUrls:0,results:{passed:0,failed:0,skipped:0},endpoints:[],lowConfidence:[],aiAssertions:{requested:t.aiAssertions===!0,applied:!1},checkedAt:new Date().toISOString()};let c={};try{let P=r.config?.getDiscoveryConfig();P&&(c=P)}catch{}let l=new kn({providers:oS(t.framework)}),u,d;try{let P=await l.discover({workspaceFolder:t.projectPath,...c});u=[...P.endpoints].sort((M,G)=>Hi(M).localeCompare(Hi(G))),d=P.stats?.frameworksDetected??[]}catch(P){throw new Error(`discovery failed for ${t.projectPath}: ${P.message}`)}let{collection:p}=Oi(r.collection.getAllCollections(),t.collectionRef),m=u.filter(P=>P.confidence==="low").map(P=>Hi(P)),f=[];Jm(p.items,f);let h=0,g=0,v=0,y=[],S=new Map;for(let P of u){let M=Hi(P),G=(P.method||"GET").toUpperCase(),me=zm(P.resolvedPath??P.pathExpression),Ce=f.find(q=>(q.method||"GET").toUpperCase()===G&&zm(q.url)===me),Ie=P.responses?.[0]?.statusCode??200;if(Ce){if(h++,!n&&s&&iS(Ce)){let q=Pi(P,p.id,s);Ce.url!==q.url&&(await r.collection.updateRequest(p.id,Ce.id,{url:q.url}),v++)}y.push({...P,id:Ce.id}),S.set(M,{endpointKey:M,method:G,path:P.resolvedPath??P.pathExpression,confidence:P.confidence,requestId:Ce.id,requestName:Ce.name,reused:!0,statusExpected:Ie})}else if(n)y.push(P),S.set(M,{endpointKey:M,method:G,path:P.resolvedPath??P.pathExpression,confidence:P.confidence,requestId:"",requestName:cS(P),reused:!1,statusExpected:Ie});else{if(!s)throw new Error(`base-url is required to create requests (endpoint ${M} has no reusable request). Pass --base-url or re-run with --dry-run to preview.`);let q=await r.collection.createRequest(Pi(P,p.id,s));if(q.type!=="request")throw new Error(`QA check produced a non-request item for endpoint ${M}.`);g++,f.push(q),y.push({...P,id:q.id}),S.set(M,{endpointKey:M,method:G,path:P.resolvedPath??P.pathExpression,confidence:P.confidence,requestId:q.id,requestName:q.name,reused:!1,statusExpected:Ie})}}let b=`QA ${p.name}`,{suite:C}=fn(y,{collectionId:p.id,collectionName:p.name,name:b,id:tr(b),assertBodySchema:t.assertBodySchema});if(n||((g>0||v>0)&&await r.collection.saveCollection(p),await r.testSuite.updateSuite(C)),n)return{status:"dry-run",project:{path:t.projectPath,gitHash:i.gitHash,frameworks:d},drift:{status:a.status,reason:a.reason},discovered:u.length,reused:h,created:g,updatedUrls:v,suite:{id:C.id,name:C.name},results:{passed:0,failed:0,skipped:u.length},endpoints:[...S.values()],lowConfidence:m,aiAssertions:{requested:t.aiAssertions===!0,applied:!1},checkedAt:new Date().toISOString()};if(!s&&g>0)throw new Error("base-url is required to run a QA check (pass --base-url or --dry-run).");let w=await br({workspaceFolder:e,suiteId:C.id,environment:t.environment,variables:t.variables,include:["perRequest","failedOnly"]}),E=new Map((w.failedRequests??[]).map(P=>[P.name??"",P])),F=new Map((w.results??[]).map(P=>[P.name??"",P])),N=0,j=0;for(let P of S.values()){let M=E.get(P.requestName),G=F.get(P.requestName);M?(P.passed=!1,P.statusGot=M.status,P.duration=M.duration,P.error=M.error,P.failures=(M.failedTests??[]).map(me=>me.message?`${me.name??"assertion"}: ${me.message}`:me.name??"assertion"),j++):(P.passed=!0,P.statusGot=G?.status??P.statusExpected,P.duration=G?.duration,N++)}let O,D=!1;if(t.aiAssertions===!0)if(!t.aiProvider)O="ai-assertions requested but no AI provider is available (set OPENAI_API_KEY / ANTHROPIC_API_KEY or configure a provider).";else{let P=[...S.values()].sort((G,me)=>+(G.passed===!1)-+(me.passed===!1)),M=P.slice(0,10);P.length>M.length&&(O=`AI assertion pass capped at 10 of ${P.length} endpoints.`);for(let G of M)try{let me=r.collection.getRequestDetail(p.id,G.requestId);if(!me)continue;let Ce=E.get(G.requestName),Ie=await _l(t.aiProvider,me,aS(Ce,G),t.aiMaxSuggestions??5,void 0);Ie.length>0&&(G.suggestions=Ie,D=!0)}catch{}}return{status:j===0?"pass":"fail",project:{path:t.projectPath,gitHash:i.gitHash,frameworks:d},drift:{status:a.status,reason:a.reason},discovered:u.length,reused:h,created:g,updatedUrls:v,suite:{id:C.id,name:C.name},results:{passed:N,failed:j,skipped:0},endpoints:[...S.values()],lowConfidence:m,aiAssertions:{requested:t.aiAssertions===!0,applied:D,...O?{note:O}:{}},checkedAt:new Date().toISOString()}}function aS(r,e){return r?{status:r.status,responseBody:typeof r.body=="string"?r.body:JSON.stringify(r.body??""),responseHeaders:r.headers,failedTests:r.failedTests}:{status:e.statusGot??e.statusExpected}}function cS(r){return r.source?.symbolName||`${r.method||"GET"} ${r.pathExpression}`}var Ou=k(()=>{"use strict";du();Oa();Sr();Dl()});function xr(r,e){let t=r[e];if(t===void 0)return;if(typeof t!="string")throw A(`"${e}" must be a string.`);let n=t.trim();return n.length>0?n:void 0}var Wm,Gm=k(()=>{"use strict";Ou();Fe();Ne();Wm=[{toolNames:[x.qaApi],async handle({args:r,services:e}){let t=xr(r,"projectPath")??e.workspaceFolder;if(!t)throw A('"projectPath" is required (or set services.workspaceFolder).');let n=xr(r,"collection");if(!n)throw A('"collection" is required.');let s=xr(r,"baseUrl")?.replace(/\/+$/,"")||void 0,i=r.dryRun===!0;if(!i&&!s)throw A('"baseUrl" is required unless dryRun is true.');if(r.variables!==void 0&&(typeof r.variables!="object"||r.variables===null||Array.isArray(r.variables)))throw A('"variables" must be an object.');let o=await Tu({collection:e.collection,testSuite:e.testSuite},e.workspaceFolder??t,{projectPath:t,collectionRef:n,baseUrl:s,environment:xr(r,"environment"),variables:r.variables,framework:xr(r,"framework"),dryRun:i,failOnDrift:r.failOnDrift===!0,storedGitHash:xr(r,"storedGitHash"),storedScannedAt:xr(r,"storedScannedAt"),aiAssertions:r.aiAssertions===!0,aiProvider:e.aiProvider});return{...o,hint:o.status==="fail"?"Fix the failing endpoints, then re-run qa_api (requests are reused, nothing is duplicated).":o.status==="drift"?"Project moved since the stored scan \u2014 review drift, then re-run without failOnDrift to regenerate.":"Use get_request for full detail on any endpoint, or analyze_test_failure for failures."}}}]});function uS(){let r=new Map;for(let e of lS)for(let t of e.toolNames)r.set(t,e);return r}var lS,$u,yT,Km=k(()=>{"use strict";Dl();zp();tm();rm();im();am();lm();dm();ym();bm();Cm();Gm();lS=[...cm,...nm,...vm,...om,...Vp,...um,...gm,...em,...Wm,...Rm,...sm,...Bp];$u=uS(),yT=new Set([...$u.keys()].map(r=>r))});function dS(r){return new Error(`Bad request: ${r}`)}async function Nu(r,e,t,n,s){let i=$u.get(r);if(!i)throw dS(`unknown tool: "${r}"`);let o=t.collection.getAllCollections(),a={tool:r,args:e,services:t,runStore:n,callbacks:s,collections:o};return i.handle(a)}var Fu,_u=k(()=>{"use strict";Km();Fe();Ne();Fu=new Set([x.createCollection,x.renameCollection,x.deleteCollection,x.duplicateCollection,x.createFolder,x.deleteFolder,x.createRequest,x.updateRequest,x.deleteRequest,x.reorderCollectionItems,x.createSuite,x.updateSuiteConfig,x.addSuiteNode,x.updateSuiteNode,x.removeSuiteNode,x.moveSuiteNode,x.duplicateSuite,x.deleteSuite,x.designApiFromIntent])});var Bi,Du=k(()=>{"use strict";Bi=class{store=new Map;newId(){return`run_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}create(e,t){this.prune();let n={id:this.newId(),status:"running",suiteName:e,startedAt:Date.now(),progress:{completed:0,total:t},summary:{passed:0,failed:0,total:0,allPassed:!1},failedRequests:[],allResults:[],reportPath:null};return this.store.set(n.id,n),n}get(e){return this.store.get(e)}require(e){if(typeof e!="string"||!e)throw new Error('"runId" is required');let t=this.store.get(e);if(!t)throw new Error(`Run "${e}" not found. It may have expired (1-hour TTL) or never existed.`);return t}prune(){let e=Date.now()-36e5;for(let[t,n]of this.store)n.startedAt<e&&this.store.delete(t)}values(){return this.store.values()}cancel(e){let t=this.store.get(e);return!t||t.status!=="running"?!1:(t.status="cancelled",t.completedAt=Date.now(),!0)}}});import{createHash as pS}from"crypto";function Qm(r){return pS("sha256").update(r,"utf8").digest("hex").slice(0,fS)}function gS(r){let e=r.replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/__+/g,"_").replace(/^_+|_+$/g,"").toLowerCase();return e?e.slice(0,mS):"id"}function qn(r){return`${gS(r)}_${Qm(r)}`}function yS(r,e){return r.length>0&&r.length<=e&&/^[a-zA-Z0-9_-]+$/.test(r)&&!r.includes("__")}function ds(r,e=hS){return yS(r,e)?r:qn(r)}function Mu(r,e,t){let n=`${r}request__${ds(e)}__${ds(t)}`;return n.length<=Za?n:`${r}request__${qn(e)}__${qn(t)}`}function ju(r,e){let t=`${r}collection__${ds(e,100)}`;return t.length<=Za?t:`${r}collection__${qn(e)}`}function Lu(r,e,t){let n=`${r}folder__${ds(e)}__${ds(t)}`;return n.length<=Za?n:`${r}folder__${qn(e)}__${qn(t)}`}function Hu(r,e){let t=`${r}suite__${ds(e,100)}`;return t.length<=Za?t:`${r}suite__${qn(e)}`}function Bu(r){for(let e of["request","collection","folder","suite"]){let t=`${e}__`;if(r.startsWith(t))return{kind:e,tokens:r.slice(t.length).split("__")}}throw new Error(`Unknown MCP tool name: ${r}`)}function ps(r,e){let t=r.includes("_")?r.slice(r.lastIndexOf("_")+1):r;for(let n of e)if(Qm(n)===t)return n;for(let n of e)if(qn(n)===r)return n;for(let n of e)if(n===r)return n}function Uu(r,e){let t=ps(r,e);if(t!==void 0)return t;try{let n=Buffer.from(r,"base64url").toString("utf8");if(e.includes(n))return n}catch{}}function Vu(r,e,t,n){let s=n?` in folder "${n}"`:"";return`Run the "${e}" request [${r}]${s} of the "${t}" collection.`}function zu(r,e){return`Run all ${e} requests in the "${r}" collection.`}function Ju(r,e,t){return`Run all ${t} requests in folder "${r}" of the "${e}" collection.`}function Wu(r,e,t){return`Run the "${r}" test suite (${e} requests, ${t} iteration(s) by default).`}var fS,mS,hS,Za,Ya=k(()=>{"use strict";fS=12,mS=16,hS=60,Za=126});import*as Zm from"fs";import*as Ym from"path";function Gu(r){let e=new Set,t=[];for(let n of r)e.has(n.name)||(e.add(n.name),t.push(n));return t}function Ku(r){return Buffer.from(String(r)).toString("base64url")}function Qu(r){if(!r)return 0;try{let e=parseInt(Buffer.from(r,"base64url").toString(),10);return Number.isFinite(e)&&e>=0?e:0}catch{return 0}}function Zu(r,e,t,n){let s=t.toolPrefix??"",i=t.toolMode??"auto",o=t.drilldownThreshold??100;if(i==="execution-only"){let u=Zo(s,r.map(d=>d.name),e.map(d=>d.name));return Gu(u.filter(d=>!vS.some(p=>d.name.endsWith(p))).map(d=>({name:d.name,description:d.description,inputSchema:d.inputSchema,...d.annotations&&{annotations:d.annotations}})))}let a=0;for(let u of r)a+=X(u).length;let c=i==="drilldown"||i==="auto"&&a>o;if(c&&i==="auto"&&n){let u=Ym.join(n,".http-forge","AGENTS.md");Zm.existsSync(u)&&(i="execution-only")}if(i==="flat"&&a>500&&console.warn(`[http-forge MCP] WARNING: toolMode is "flat" but ${a} requests would produce ${a}+ tools. This will likely degrade AI tool-selection quality and bloat the context window. Consider setting toolMode to "auto" or "drilldown" in http-forge.config.json.`),c)return Gu(Zo(s,r.map(u=>u.name),e.map(u=>u.name)).map(u=>({name:u.name,description:u.description,inputSchema:u.inputSchema,...u.annotations&&{annotations:u.annotations}})));let l=[];for(let u of r){let d=X(u);for(let{request:p,folderPath:m}of d)l.push({name:Mu(s,u.id,p.id),description:Vu(p.method,p.name,u.name,m),inputSchema:Wo});l.push({name:ju(s,u.id),description:zu(u.name,d.length),inputSchema:Go});for(let{folderPath:p,requestCount:m}of qe(u))m!==0&&l.push({name:Lu(s,u.id,p),description:Ju(p,u.name,m),inputSchema:Ko})}for(let u of e)l.push({name:Hu(s,u.id),description:Wu(u.name,u.nodes.filter(d=>d.type==="request").length,u.config.iterations),inputSchema:Qo});return Gu(l)}var vS,Yu=k(()=>{"use strict";tt();Ya();Fe();vS=["list_collections","list_folders","list_requests","search_requests","get_request","get_request_script","list_environments","get_environment","get_environment_variables","list_suites","get_suite","get_suite_node","list_suite_node_paths","create_collection","rename_collection","delete_collection","duplicate_collection","create_folder","delete_folder","create_request","update_request","delete_request","set_request_script","reorder_collection_items","create_suite","update_suite_config","add_suite_node","update_suite_node","remove_suite_node","move_suite_node","add_suite_requests","remove_suite_request","reorder_suite_requests","duplicate_suite","delete_suite","create_environment","delete_environment","create_request_from_endpoint","generate_test_suite","suggest_workflow","generate_workflow","check_drift","propose_update","qa_api","design_api_from_intent","review_suite"]});var nh={};nc(nh,{createMcpRuntime:()=>$S});import*as th from"fs";import{createServer as bS}from"http";import*as An from"path";async function qt(r){let e=process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS,t=process.env.HTTP_FORGE_GENERATE_REPORTS;process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS="true",process.env.HTTP_FORGE_GENERATE_REPORTS="true";try{return await r()}finally{e===void 0?delete process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS:process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS=e,t===void 0?delete process.env.HTTP_FORGE_GENERATE_REPORTS:process.env.HTTP_FORGE_GENERATE_REPORTS=t}}function fs(r){let e=[r.testSuite,r.collection,r.environmentConfig,r.config,r.console];for(let t of e)try{t?.dispose?.()}catch{}}async function wS(r,e){let t=td.get(r);if(t&&t.expiresAt>Date.now())return t.tools;let n=Xu.get(r);if(n)return n;let s=(async()=>{let i=e.config.getMcpConfig(),o=(l,u)=>!!l?.length&&(l.includes(u.id)||l.includes(u.name)),a=e.collection.getAllCollections().filter(l=>!o(i.excludedCollections,l)),c=(await e.testSuite.getAllSuites()).filter(l=>!o(i.excludedSuites,l));return Zu(a,c,i,r)})().then(i=>(td.set(r,{tools:i,expiresAt:Date.now()+xS}),i)).finally(()=>Xu.delete(r));return Xu.set(r,s),s}function RS(r,e){let t=r.config.getMcpConfig().toolPrefix??"";return t&&e.startsWith(t)?e.slice(t.length):e}function CS(r,e,t){return r.replace(/"uri"\s*:\s*"file:\/\/([^"]+)"/g,(n,s)=>`"uri":"http://${e}:${t}/report?path=${encodeURIComponent(s)}"`)}function Xm(r,e,t,n){wr(r,200,{jsonrpc:"2.0",id:e,error:{code:t,message:n}})}function kS(r){return r.config.getMcpConfig().toolPageSize??200}async function ES(r,e){switch(e.method){case"initialize":return{protocolVersion:"2024-11-05",capabilities:{tools:{},prompts:{}},serverInfo:{name:"http-forge",version:"1.0.0"},instructions:"You are assisting with HTTP API testing via HTTP Forge. When a run_suite, run_collection, or run_folder call completes with failures (summary.failed > 0 or allPassed === false), automatically analyze the 'failedRequests' in the response and provide: (1) root cause for each failure, (2) specific fix recommendations, (3) updated pm.test() assertion scripts where relevant. Do not wait for the user to ask \u2014 proactively diagnose and suggest fixes. For async runs (status: 'running'), poll with get_run_status until complete, then call get_run_summary. When get_run_summary returns a _nextStep field you MUST execute it immediately \u2014 the failedRequests array is already included inline so no extra tool call is needed. Analyze the failures and provide diagnosis without waiting for the user."};case"tools/list":{let t=await wS(r.workspaceFolder,r.container),n=e.params??{},s=typeof n.cursor=="string"?n.cursor:void 0,i=kS(r.container);if(i<=0||t.length<=i)return{tools:t};let o=Qu(s),a=t.slice(o,o+i),c=o+i,l={tools:a};return c<t.length&&(l.nextCursor=Ku(c)),l}case"tools/call":{let t=e.params??{},n=t.name,s=t.arguments;if(!n)throw new Error("Missing tool name");let i=await nd(r,n,s??{}),o=i,a=o?.summary;a&&((a.failed??0)>0||a.allPassed===!1)&&(o._nextStep=`${a.failed??"Some"} request(s) failed. Please analyze the 'failedRequests' above: identify the root cause of each failure, suggest specific fixes (URL, auth, body, environment variables), and provide updated pm.test() assertion scripts where the assertions are incorrect.`);let c=JSON.stringify(i,null,2),l=CS(c,r.host,r.port),u=l.match(/"uri"\s*:\s*"(http:\/\/[^"]+\/report\?[^"]+)"/),d=u?`
|
|
1789
1789
|
|
|
1790
|
-
[View HTML Report](${u[1]})`:"";return{content:[{type:"text",text:l+d}]}}case"prompts/list":return{prompts:Ia};case"prompts/get":{let t=e.params??{},n=t.name,s=t.arguments??{};if(!n)throw new Error("Missing prompt name");let i=pt(r.workspaceFolder);try{return await mu(n,s,i.collection,r.runStore,r.workspaceFolder)}finally{fs(i)}}default:throw new Error(`Method not found: ${e.method}`)}}function ES(r,e,t){let n=!r.container,s=r.container??pt(r.workspaceFolder),i;try{i=s.config.getMcpConfig().cors.allowedOrigins??["http://localhost","http://127.0.0.1"]}finally{n&&fs(s)}let o=e.headers.origin??"",a=i.includes(o)?o:i[0]??"http://localhost";t.setHeader("Access-Control-Allow-Origin",a),t.setHeader("Access-Control-Allow-Methods","POST, GET, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Mcp-Session-Id")}function qS(r,e,t){let s=new URL(e.url,`http://${r.host}:${r.port}`).searchParams.get("path");if(!s){t.statusCode=400,t.end("Missing path parameter");return}let i=An.resolve(s),o=r.container?.config.getResultsPath(),a=o?An.dirname(o):An.resolve(r.workspaceFolder,".http-forge",".cache");if(!i.startsWith(a+An.sep)||!i.endsWith(".html")){t.statusCode=403,t.end("Forbidden");return}th.readFile(i,"utf-8",(c,l)=>{if(c){t.statusCode=404,t.end("Report not found");return}t.statusCode=200,t.setHeader("content-type","text/html; charset=utf-8"),t.end(l)})}function ed(r,e,t,n){let s=r.create(e,t);return n().then(i=>{s.status!=="cancelled"&&(s.status="completed",s.completedAt=Date.now(),s.summary=i?.summary??s.summary,i?.failedRequests&&(s.failedRequests=i.failedRequests),i?.noAssertionExamples&&(s.noAssertionExamples=i.noAssertionExamples),s.reportPath=i?.report?.uri?.replace("file://","")??null,s.progress.completed=s.progress.total)}).catch(i=>{s.status!=="cancelled"&&(s.status="failed",s.completedAt=Date.now(),s.error=i.message)}),{runId:s.id,status:"running",total:t,message:"Run started. Use get_run_status to poll."}}function AS(r){let e=r.workspaceFolder;return{async runRequest(t,n,s){return qt(()=>Qa({workspaceFolder:e,collectionId:t.id,requestId:n,environment:s.environment,variables:s.variables,headers:s.headers,query:s.query,body:s.body,include:s.include}))},async runFolder(t,n,s){let i=X(t).filter(({folderPath:o})=>o===n||o.startsWith(`${n}/`)).length;return s.async===!0?ed(r.runStore,`${t.name} / ${Tt(n)}`,i,()=>qt(()=>Zt({workspaceFolder:e,collectionId:t.id,folderPath:n,recursive:s.recursive,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,include:s.include}))):qt(()=>Zt({workspaceFolder:e,collectionId:t.id,folderPath:n,recursive:s.recursive,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,include:s.include}))},async runCollection(t,n){let s=X(t).length;return n.async===!0?ed(r.runStore,t.name,s,()=>qt(()=>Zt({workspaceFolder:e,collectionId:t.id,environment:n.environment,variables:n.variables,iterations:n.iterations,stopOnError:n.stopOnError,delay:n.delay,include:n.include}))):qt(()=>Zt({workspaceFolder:e,collectionId:t.id,environment:n.environment,variables:n.variables,iterations:n.iterations,stopOnError:n.stopOnError,delay:n.delay,include:n.include}))},async runSuite(t,n,s){let i=pt(e),o=0;try{let a=await i.testSuite.getSuite(t);o=(a?.nodes.filter(l=>l.type==="request").length??0)*(s.iterations??a?.config?.iterations??1)}finally{fs(i)}return s.async===!0?ed(r.runStore,n,o,()=>qt(()=>br({workspaceFolder:e,suiteId:t,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,requestFilter:s.requestFilter,include:s.include}))):qt(()=>br({workspaceFolder:e,suiteId:t,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,requestFilter:s.requestFilter,include:s.include}))}}}async function nd(r,e,t={}){let n=r.workspaceFolder,s=wS(r.container,e);if(Object.values(x).includes(s)){let a=pt(n),c=yi();try{let l=await Nu(s,t,{collection:a.collection,testSuite:a.testSuite,environmentConfig:a.environmentConfig,workspaceFolder:n,...c?{aiProvider:c}:{}},r.runStore,AS(r));return PS.has(s)&&td.delete(n),l}finally{fs(a)}}let i=Bu(s),o=pt(n);try{let a=o.collection.getAllCollections(),c=a.map(m=>m.id),l=m=>{let f=ps(m,c),h=f?a.find(g=>g.id===f):void 0;if(!h)throw new Error(`Collection not found for tool: ${e}`);return h};if(i.kind==="request"){let[m,f]=i.tokens;if(!m||!f)throw new Error(`Malformed request tool: ${e}`);let h=l(m),g=X(h).map(y=>y.request.id),v=ps(f,g);if(!v)throw new Error(`Request not found in collection "${h.name}" for tool: ${e}`);return qt(()=>Qa({workspaceFolder:n,collectionId:h.id,requestId:v,environment:t.environment,variables:t.variables,headers:t.headers,query:t.query,body:t.body,include:t.include}))}if(i.kind==="collection"){let[m]=i.tokens;if(!m)throw new Error(`Malformed collection tool: ${e}`);let f=l(m);return qt(()=>Zt({workspaceFolder:n,collectionId:f.id,environment:t.environment,variables:t.variables,iterations:t.iterations,stopOnError:t.stopOnError,delay:t.delay,include:t.include}))}if(i.kind==="folder"){let[m,f]=i.tokens;if(!m||!f)throw new Error(`Malformed folder tool: ${e}`);let h=l(m),g=(o.collection.getAllCollections().find(S=>S.id===h.id),void 0),v=X(h).map(S=>S.folderPath).filter((S,b,C)=>S&&C.indexOf(S)===b),y=Uu(f,v);if(!y)throw new Error(`Folder not found in collection "${h.name}" for tool: ${e}`);return qt(()=>Zt({workspaceFolder:n,collectionId:h.id,folderPath:y,recursive:t.recursive,environment:t.environment,variables:t.variables,iterations:t.iterations,stopOnError:t.stopOnError,delay:t.delay,include:t.include}))}let[u]=i.tokens;if(!u)throw new Error(`Malformed suite tool: ${e}`);let d=await o.testSuite.getAllSuites(),p=ps(u,d.map(m=>m.id));if(!p)throw new Error(`Test suite not found for tool: ${e}`);return qt(()=>br({workspaceFolder:n,suiteId:p,environment:t.environment,variables:t.variables,iterations:t.iterations,stopOnError:t.stopOnError,delay:t.delay,requestFilter:t.requestFilter,include:t.include}))}finally{fs(o)}}function wr(r,e,t){r.statusCode=e,r.setHeader("content-type","application/json; charset=utf-8"),r.end(JSON.stringify(t))}function eh(r){return new Promise((e,t)=>{let n="";r.on("data",s=>{n+=s,n.length>1024*1024&&t(new Error("Request body too large (max 1MB)"))}),r.on("end",()=>{if(!n){e({});return}try{e(JSON.parse(n))}catch{t(new Error("Invalid JSON body"))}}),r.on("error",t)})}function IS(r){return vS(async(e,t)=>{try{if(ES(r,e,t),e.method==="OPTIONS"){t.statusCode=204,t.end();return}if(e.method==="GET"&&e.url==="/health"){wr(t,200,{status:"ok",port:r.port});return}if(e.method==="GET"&&e.url?.startsWith("/report?")){qS(r,e,t);return}if(e.method==="POST"&&(e.url==="/"||e.url==="/mcp")){let n;try{n=await eh(e)}catch{Xm(t,null,-32700,"Parse error");return}try{let s=await kS(r,n);wr(t,200,{jsonrpc:"2.0",id:n.id??null,result:s})}catch(s){Xm(t,n.id??null,-32603,s.message||"Internal error")}return}if(e.method==="POST"&&e.url==="/tools/execute"){let n=await eh(e);if(!n||typeof n.name!="string"||n.name.trim()===""){wr(t,400,{error:'Field "name" is required'});return}let s=await nd(r,n.name,n.args??{});wr(t,200,{result:s});return}wr(t,405,{error:"Method not allowed"})}catch(n){wr(t,500,{error:n.message})}})}function TS(r){if(typeof r.port=="number"&&Number.isFinite(r.port))return Math.min(65535,Math.max(1,Math.floor(r.port)));let t=new an(An.resolve(r.workspaceFolder)).getMcpConfig().port;return Math.min(65535,Math.max(1,Math.floor(t||3100)))}async function OS(r){let e=TS(r),t=r.host||"127.0.0.1",n=`${t}:${e}`,s={workspaceFolder:r.workspaceFolder,port:e,host:t,isRunning:!1,runStore:new Bi};return bS.set(n,s),{async start(){if(s.isRunning)return;s.container||(s.container=pt(s.workspaceFolder));let i=IS(s);await new Promise((o,a)=>{i.once("error",a),i.listen(s.port,s.host,()=>{i.off("error",a),o()})}),s.server=i,s.isRunning=!0},async stop(){if(s.container&&(fs(s.container),s.container=void 0),!s.server){s.isRunning=!1;return}await new Promise((i,o)=>{s.server.close(a=>{if(a){o(a);return}i()})}),s.server=void 0,s.isRunning=!1},isRunning(){return s.isRunning},getPort(){return s.port},async executeTool(i,o){return nd(s,i,o??{})}}}var bS,SS,td,Xu,PS,rh=k(()=>{"use strict";yo();Jo();Sr();tt();_u();Ta();Du();Yu();Ya();Fe();Ga();bS=new Map;SS=3e3,td=new Map,Xu=new Map;PS=Fu});var kr=class{constructor(e,t){this.fileSystem=e;this.parserRegistry=t}fileSystem;parserRegistry;directory;setDirectory(e){this.directory=e}async loadAll(){return this.directory?this.loadDirectory(this.directory):[]}async load(e,t={}){let n=await this.fileSystem.readFile(e);if(t.format){let i=this.parserRegistry.get(t.format);if(!i)throw new Error(`No parser registered for format: ${t.format}`);return i.parse(n,e)}let s=this.parserRegistry.detect(n);if(!s)throw new Error(`Could not detect collection format for: ${e}. Supported formats: ${this.parserRegistry.getFormats().join(", ")}`);return s.parser.parse(n,e)}async loadDirectory(e,t=["*.json","*.forge.json"]){let n=[],s=await this.fileSystem.glob(t,e);for(let i of s)try{let o=await this.load(i);n.push(o)}catch{}return n}async canLoad(e){try{if(!await this.fileSystem.exists(e))return!1;let t=await this.fileSystem.readFile(e);return this.parserRegistry.detect(t)!==null}catch{return!1}}getSupportedFormats(){return this.parserRegistry.getFormats()}};Qi();tn();function pc(r,e){return{id:r.id,name:r.name,description:r.description,variables:r.variables||{},auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(bd),source:{format:"folder",filePath:e,version:r.version}}}function bd(r){if(r.type==="folder")return{type:"folder",id:r.id,name:r.name,description:r.description,auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(bd)};let e=r;return{type:"request",id:e.id,name:e.name,description:e.description,requestType:e.requestType,method:e.method||"GET",url:e.url||"",headers:e.headers||[],query:e.query||[],params:e.params,body:e.body??void 0,auth:e.auth,settings:e.settings,scripts:e.scripts,websocket:e.websocket,...e.deprecated&&{deprecated:e.deprecated},...e.doc&&{doc:e.doc},...e.responseSchema&&{responseSchema:e.responseSchema},...e.bodySchema&&{bodySchema:e.bodySchema},...e.operationId&&{operationId:e.operationId},...e.summary&&{summary:e.summary},...e.tags&&e.tags.length>0&&{tags:e.tags},...e.examples&&e.examples.length>0&&{examples:e.examples},...e.responses&&Object.keys(e.responses).length>0&&{responses:e.responses},...e.security&&e.security.length>0&&{security:e.security}}}function Rh(r){return{id:r.id,name:r.name,description:r.description,version:r.source?.version,variables:r.variables,auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(fc)}}function fc(r){return r.type==="folder"?{type:"folder",id:r.id,name:r.name,description:r.description,auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(fc)}:{type:"request",id:r.id,name:r.name,description:r.description,requestType:r.requestType,method:r.method,url:r.url,headers:r.headers,query:r.query,params:r.params,body:r.body,auth:r.auth,settings:r.settings,scripts:r.scripts,websocket:r.websocket,...r.deprecated&&{deprecated:r.deprecated},...r.doc&&{doc:r.doc},...r.responseSchema&&{responseSchema:r.responseSchema},...r.bodySchema&&{bodySchema:r.bodySchema},...r.operationId&&{operationId:r.operationId},...r.summary&&{summary:r.summary},...r.tags&&{tags:r.tags},...r.examples&&{examples:r.examples},...r.responses&&{responses:r.responses},...r.security&&{security:r.security}}}var hs=class{store;constructor(e){this.store=new nn(e)}loadAll(){return this.store.loadAll().map(t=>pc(t,this.store.getCollectionPath(t.id)))}getSlugById(e){return this.store.getSlugById(e)}getIdBySlug(e){return this.store.getIdBySlug(e)}load(e){let t=this.store.load(e);if(t)return pc(t,this.store.getCollectionPath(t.id))}async create(e,t){let n=await this.store.create(e,t);return pc(n,this.store.getCollectionPath(n.id))}async save(e){return this.store.save(Rh(e))}async delete(e){return this.store.delete(e)}exists(e){return this.store.exists(e)}getCollectionPath(e){return this.store.getCollectionPath(e)}async updateCollectionMetadata(e,t){return this.store.updateCollectionMetadata(e,t)}async saveItem(e,t,n){return this.store.saveItem(e,fc(t),n)}async updateItem(e,t,n){let s={...n};return this.store.updateItem(e,t,s)}async deleteItem(e,t){return this.store.deleteItem(e,t)}async moveItem(e,t,n){return this.store.moveItem(e,t,n)}async reorderItems(e,t,n){return this.store.reorderItems(e,t,n)}async saveScripts(e,t,n){return this.store.saveScripts(e,t,n)}loadScripts(e,t){return this.store.loadScripts(e,t)}};var gs=class{parsers=new Map;register(e,t){this.parsers.set(e.toLowerCase(),t)}get(e){return this.parsers.get(e.toLowerCase())}has(e){return this.parsers.has(e.toLowerCase())}getFormats(){return Array.from(this.parsers.keys())}detect(e){for(let[t,n]of this.parsers)if(n.canParse(e))return{parser:n,format:t};return null}clear(){this.parsers.clear()}};$n();var ys=class{cookies=new Map;getCookieKey(e,t,n){return oe.cookieKey(e,t,n)}get(e,t){if(t){let i=this.getCookieKey(e,t),o=this.cookies.get(i);if(o&&!this.isExpired(o))return o}let n=this.getCookieKey(e,"*"),s=this.cookies.get(n);if(s&&!this.isExpired(s))return s;for(let i of this.cookies.values())if(i.name===e&&!this.isExpired(i))if(t&&i.domain){if(this.domainMatches(t,i.domain))return i}else return i}set(e){let t=this.getCookieKey(e.name,e.domain,e.path);this.cookies.set(t,e)}setFromResponse(e){for(let t of e){let n=this.getCookieKey(t.name,t.domain,t.path);this.cookies.set(n,t)}}has(e,t){return this.get(e,t)!==void 0}delete(e,t,n){let s=this.getCookieKey(e,t,n);return this.cookies.delete(s)}getAll(e){let t=[];for(let n of this.cookies.values())this.isExpired(n)||(e?(!n.domain||this.domainMatches(e,n.domain))&&t.push(n):t.push(n));return t}getCookieHeader(e){let t=this.getAll(e);return oe.formatCookieHeader(t)}clear(){this.cookies.clear()}clearDomain(e){let t=[];for(let[n,s]of this.cookies.entries())s.domain&&this.domainMatches(e,s.domain)&&t.push(n);for(let n of t)this.cookies.delete(n)}parseCookieHeaders(e,t){return oe.parseCookieHeaders(e,t)}isExpired(e){return oe.isExpired(e)}domainMatches(e,t){return oe.domainMatches(e,t)}get count(){return this.cookies.size}cleanExpiredCookies(){let e=[];for(let[t,n]of this.cookies.entries())this.isExpired(n)&&e.push(t);for(let t of e)this.cookies.delete(t)}};Xi();var $t=class r{config;selectedEnvironment;sessionGlobals={};sessionEnvironmentValues=new Map;constructor(e){this.config=e,this.selectedEnvironment=e.selectedEnvironment||Object.keys(e.environments)[0]||"default"}get(e){return this.getVariables()[e]}set(e,t){let n=this.sessionEnvironmentValues.get(this.selectedEnvironment);n||(n={},this.sessionEnvironmentValues.set(this.selectedEnvironment,n)),n[e]=t}getAll(){return this.getVariables()}getEnvironments(){return Object.keys(this.config.environments)}getActive(){return this.selectedEnvironment}setActive(e){if(!this.config.environments[e])throw new Error(`Environment not found: ${e}`);this.selectedEnvironment=e}getVariables(e){let t=e||this.selectedEnvironment,n=this.config.environments[t],s={...this.config.globalVariables||{},...this.sessionGlobals};if(n){if(n.inherits&&this.config.environments[n.inherits]){let o=this.getEnvironmentVariables(n.inherits);s={...s,...o}}s={...s,...n.variables};let i=this.sessionEnvironmentValues.get(t);i&&(s={...s,...i})}return s}getEnvironmentVariables(e){let t=this.config.environments[e];if(!t)return{};let n={};return t.inherits&&this.config.environments[t.inherits]&&(n={...this.getEnvironmentVariables(t.inherits)}),{...n,...t.variables}}getGlobals(){return{...this.config.globalVariables||{},...this.sessionGlobals}}setGlobal(e,t){this.sessionGlobals[e]=t}unsetGlobal(e){delete this.sessionGlobals[e]}clearGlobals(){this.sessionGlobals={}}resolve(e){let t=e||this.selectedEnvironment;return{name:t,merged:this.getVariables(t),globals:this.getGlobals()}}static fromVariables(e,t="default"){return new r({environments:{[t]:{name:t,variables:e}},selectedEnvironment:t})}};Er();Ar();var sn=class r{envStore;interpolator;urlBuilder;constructor(e,t){this.envStore=e,this.interpolator=t||new jn,this.urlBuilder=new yt}get(e){return this.envStore.get(e)}set(e,t){this.envStore.set(e,t)}has(e){return this.envStore.get(e)!==void 0}delete(e){this.envStore.set(e,"")}getAll(){return this.envStore.getAll()}getActiveEnvironment(){return this.envStore.getActive()}setActiveEnvironment(e){this.envStore.setActive(e)}getEnvironments(){let e=this.envStore;return typeof e.getEnvironments=="function"?e.getEnvironments():[]}getGlobals(){let e=this.envStore;return typeof e.getGlobals=="function"?e.getGlobals():{}}setGlobal(e,t){let n=this.envStore;typeof n.setGlobal=="function"&&n.setGlobal(e,t)}unsetGlobal(e){let t=this.envStore;typeof t.unsetGlobal=="function"&&t.unsetGlobal(e)}clearGlobals(){let e=this.envStore;typeof e.clearGlobals=="function"&&e.clearGlobals()}resolve(e){return this.interpolator.interpolate(e,this.getAll())}resolvePath(e,t={}){let n=this.interpolator.interpolate(e,this.getAll());return this.urlBuilder.buildUrl(n,t)}buildUrl(e,t={}){let n=this.interpolator.interpolate(e,this.getAll());return this.urlBuilder.buildUrl(n,t.params||{},t.query||{})}resolveObject(e){return this.interpolator.interpolateObject(e,this.getAll())}extractVariables(e){return this.interpolator.extractVariables(e)}extractPathParams(e){return this.urlBuilder.extractPathParams(e)}static create(e={}){let t=$t.fromVariables(e);return new r(t)}static fromResolver(e){return new r(e)}};Ar();Cs();ks();Er();Is();As();var Tr=class{constructor(e,t,n,s,i){this.httpClient=e;this.forgeEnv=t;this.cookieJar=n;this.preprocessor=s;if(i?.scriptExecutor)this.scriptExecutor=i.scriptExecutor;else{let o=i?.forgeRoot?[pe("path").join(i.forgeRoot,"modules")]:[],a=new Ft(new yt,new Nt,e);this.scriptExecutor=new _t(a,o,void 0,i?.scriptScope??"shared",i?.scriptTimeout??5e3)}}httpClient;forgeEnv;cookieJar;preprocessor;scriptExecutor;async execute(e,t,n={}){if(e.requestType==="websocket")throw new Error("WebSocket requests are not supported by the HTTP request executor");let s=Date.now(),i={...this.forgeEnv.getAll()},o={...this.forgeEnv.getGlobals()},a={...n.additionalVariables||{}},c={...i},l=this.buildHttpRequest(e,n.overrides),u=n.overrides?.body||e.body,d=this.findFolderPath(t,e.id),p=this.buildScriptChain(e,t,d),m={request:{url:l.url,method:l.method,headers:{...l.headers},body:u?typeof u=="string"?{type:"raw",content:u}:u:void 0},variables:a,collectionVariables:t.variables||{},globals:{...o},environmentVariables:c,environmentName:this.forgeEnv.getActiveEnvironment?.()||void 0,cookieJar:this.cookieJar,info:{eventName:"prerequest",requestName:e.name,requestId:e.id,collectionName:t?.name},onEnvironmentChange:n.onEnvironmentChange,onGlobalsChange:(v,y,S)=>{v==="set"&&y&&S!==void 0?this.forgeEnv.setGlobal(y,S):v==="unset"&&y?this.forgeEnv.unsetGlobal(y):v==="clear"&&this.forgeEnv.clearGlobals()}},f=this.scriptExecutor.createRequestSession(m),h,g;try{if(!n.skipPreRequest&&p.preRequest.length>0){let b=await f.executePreRequest(p.preRequest);if(h={success:b.success,error:b.error,modifiedVariables:b.modifiedVariables,modifiedEnvironment:b.modifiedEnvironmentVariables,modifiedGlobals:b.modifiedGlobals,modifiedCollectionVariables:b.modifiedCollectionVariables,consoleOutput:b.consoleOutput,modifiedRequest:b.modifiedRequest?{url:b.modifiedRequest.url,method:b.modifiedRequest.method,headers:b.modifiedRequest.headers,body:b.modifiedRequest.body?.content}:void 0},b.modifiedVariables&&(a={...a,...b.localVariables??b.modifiedVariables}),b.modifiedEnvironmentVariables&&(c={...c,...b.modifiedEnvironmentVariables}),b.modifiedRequest){let C=b.modifiedRequest;C.url&&(l.url=C.url),C.method&&(l.method=C.method),C.headers&&(l.headers={...l.headers,...C.headers}),C.body!==void 0&&(l.body=C.body?.content||C.body)}if(!b.success)throw new Error(`Pre-request script failed: ${b.error}`)}let v={...c,...a};l=this.interpolateRequest(l,v);let y=n.overrides?.body||e.body;if(this.preprocessor&&y&&typeof y!="string"&&y.type==="graphql"&&l.body!==void 0){let b=this.preprocessor.encodeBody({type:"graphql",content:l.body});b!=null&&(l.body=typeof b=="string"?b:JSON.stringify(b))}if(u&&typeof u=="object"&&u.type==="form-data"&&Array.isArray(l.body)){let b=this.buildMultipartFormData({type:"form-data",content:l.body});b&&(l.body=b)}let S=await this.httpClient.send(l);if(!n.skipPostResponse&&p.postResponse.length>0){let b=await f.executePostResponse(p.postResponse,{status:S.status,statusText:S.statusText,headers:S.headers,body:S.body,cookies:ao(S.headers,S.cookies,l.url),responseTime:S.time,responseSize:S.size,executedRequest:{url:l.url,method:l.method,headers:l.headers||{},body:l.body?typeof l.body=="string"?{type:"raw",content:l.body}:l.body:{type:"none",content:""},params:{},query:{}}});g={success:!0,assertions:b.testResults,consoleOutput:b.consoleOutput,modifiedEnvironment:b.modifiedEnvironmentVariables},b.modifiedEnvironmentVariables&&(c={...c,...b.modifiedEnvironmentVariables})}return{response:S,preRequestResult:h,postResponseResult:g,totalTime:Date.now()-s,finalRequest:l,variables:{environment:c,local:a}}}finally{f.dispose?.()}}async executeSimple(e,t={}){let n=e,s={...this.forgeEnv.getAll(),...t.variables||{}};return n=this.interpolateRequest(e,s),t.timeout&&(n={...n,timeout:t.timeout}),this.httpClient.send(n)}buildHttpRequest(e,t){let n=e.url;if(e.query&&e.query.length>0){let u=new URLSearchParams;for(let d of e.query)d.enabled!==!1&&u.append(d.key,d.value);n+=(n.includes("?")?"&":"?")+u.toString()}let s=t?.url||n,i=t?.method||e.method,o={};if(e.headers&&Array.isArray(e.headers))for(let u of e.headers)u.enabled!==!1&&(o[u.key]=u.value);let a={...o,...t?.headers||{}},c,l=t?.body||e.body;if(l)if(typeof l=="string")c=l;else if(this.preprocessor&&l.type)if(l.type==="graphql")c=typeof l.content=="string"?l.content:JSON.stringify(l.content);else if(l.type==="form-data")c=this.buildMultipartFormData(l);else{let u=this.preprocessor.encodeBody(l);c=u!=null?String(u):void 0}else l.content&&(c=typeof l.content=="string"?l.content:JSON.stringify(l.content));return this.preprocessor&&l&&l.type!=="form-data"&&this.preprocessor.setContentTypeHeader(a,l),{url:s,method:i,headers:a,body:c,timeout:t?.timeout||e.settings?.timeout,settings:{...e.settings,...t?.settings}}}interpolateRequest(e,t){let n=sn.create(t),s=e.body,i=s;return typeof s=="string"?i=n.resolve(s):s instanceof FormData||s instanceof URLSearchParams?i=s:s&&typeof s=="object"&&(i=n.resolve(s)),{...e,url:n.resolvePath(e.url),headers:n.resolveObject(e.headers),body:i}}buildMultipartFormData(e){if(!e||e.type!=="form-data"||!Array.isArray(e.content))return;let t=new FormData;for(let n of e.content)!n?.key||n.enabled===!1||t.append(n.key,n.value==null?"":String(n.value));return t}buildScriptChain(e,t,n=[]){let s=[],i=[];t.scripts?.preRequest&&s.push(t.scripts.preRequest),t.scripts?.postResponse&&i.push(t.scripts.postResponse);for(let o of n)o.scripts?.preRequest&&s.push(o.scripts.preRequest),o.scripts?.postResponse&&i.push(o.scripts.postResponse);return e.scripts?.preRequest&&s.push(e.scripts.preRequest),e.scripts?.postResponse&&i.push(e.scripts.postResponse),{preRequest:s,postResponse:i}}findFolderPath(e,t){let n=[],s=(i,o)=>{for(let a of i){if(a.type==="request"&&a.id===t)return n.push(...o),!0;if(a.type==="folder"){let c=[...o,a];if(s(a.items,c))return!0}}return!1};return s(e.items,[]),n}};function og(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}var Ts=class{entries=new Map;requestIndex=new Map;fullResponses=new Map;maxEntriesPerRequest;storeFullResponses;constructor(e={}){this.maxEntriesPerRequest=e.maxEntriesPerRequest??100,this.storeFullResponses=e.storeFullResponses??!0}getEntries(e,t){let n=this.requestIndex.get(e)||[],s=[];for(let i of n){let o=this.entries.get(i);o&&(!t||o.environment===t)&&s.push(o)}return s}getEntry(e){return this.entries.get(e)}getFullResponse(e){return this.fullResponses.get(e)}get count(){return this.entries.size}addEntry(e,t,n,s,i){let o=og(),a=Date.now(),c={id:o,timestamp:a,environment:s,method:t.method,ticket:i?.ticket,branch:i?.branch,note:i?.note,sentRequest:{url:t.url,method:t.method,headers:{...t.headers},body:t.body},response:{status:n.status,statusText:n.statusText,time:n.time}};this.entries.set(o,c);let l=this.requestIndex.get(e)||[];for(l.unshift(o);l.length>this.maxEntriesPerRequest;){let u=l.pop();u&&(this.entries.delete(u),this.fullResponses.delete(u))}if(this.requestIndex.set(e,l),this.storeFullResponses){let u={timestamp:a,status:n.status,statusText:n.statusText,headers:{...n.headers},cookies:n.cookies||[],body:n.body,time:n.time};this.fullResponses.set(o,u)}return c}deleteEntry(e){if(!this.entries.get(e))return!1;this.entries.delete(e),this.fullResponses.delete(e);for(let[n,s]of this.requestIndex.entries()){let i=s.indexOf(e);if(i!==-1){s.splice(i,1),s.length===0&&this.requestIndex.delete(n);break}}return!0}clearHistory(e){let t=this.requestIndex.get(e);if(t){for(let n of t)this.entries.delete(n),this.fullResponses.delete(n);this.requestIndex.delete(e)}}clearAll(){this.entries.clear(),this.requestIndex.clear(),this.fullResponses.clear()}};var Os=class{async send(e){let t=Date.now(),n=new AbortController,s=e.timeout??3e4,i=setTimeout(()=>n.abort(),s);try{let o={method:e.method,headers:e.headers,signal:n.signal};e.body!==void 0&&(typeof e.body=="string"||e.body instanceof FormData||e.body instanceof URLSearchParams?o.body=e.body:typeof e.body=="object"&&(o.body=JSON.stringify(e.body),!e.headers?.["Content-Type"]&&!e.headers?.["content-type"]&&(o.headers["Content-Type"]="application/json"))),e.settings?.followRedirects===!1&&(o.redirect="manual");let a=await fetch(e.url,o),c=Date.now(),l;try{l=await a.text()}catch{l=null}let u={};return a.headers.forEach((d,p)=>{let m=u[p];m!==void 0?u[p]=Array.isArray(m)?[...m,d]:[m,d]:u[p]=d}),{status:a.status,statusText:a.statusText,headers:u,cookies:[],body:l,time:c-t}}catch(o){throw o.name==="AbortError"?new Error(`Request timeout after ${s}ms`):o}finally{clearTimeout(i)}}};Cs();ks();Ns();fo();Er();var Vn=class{format="http-forge";canParse(e){try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&"id"in t&&"name"in t&&"items"in t&&Array.isArray(t.items)&&!t.info?.schema?.includes("postman")&&!t._type}catch{return!1}}parse(e,t){let n=JSON.parse(e);return{id:n.id,name:n.name,description:n.description,variables:n.variables||{},auth:n.auth,scripts:n.scripts?{preRequest:n.scripts.preRequest,postResponse:n.scripts.postResponse}:void 0,items:this.convertItems(n.items),source:{format:"http-forge",filePath:t,version:n.version}}}convertItems(e){return e.map(t=>t.type==="folder"?this.convertFolder(t):this.convertRequest(t))}convertFolder(e){return{type:"folder",id:e.id,name:e.name,description:e.description,auth:e.auth,scripts:e.scripts?{preRequest:e.scripts.preRequest,postResponse:e.scripts.postResponse}:void 0,items:e.items?this.convertItems(e.items):[]}}convertRequest(e){let t={};if(e.headers)for(let s of e.headers)s.enabled!==!1&&(t[s.key]=s.value);let n={};if(e.query)for(let s of e.query)s.enabled!==!1&&(n[s.key]=s.value);return{type:"request",id:e.id,name:e.name,description:e.description,method:e.method||"GET",url:e.url||"",headers:Object.entries(t).map(([s,i])=>({key:s,value:i,enabled:!0})),query:Object.entries(n).map(([s,i])=>({key:s,value:i,enabled:!0})),params:e.params,body:e.body,auth:e.auth,settings:e.settings,scripts:e.scripts?{preRequest:e.scripts.preRequest,postResponse:e.scripts.postResponse}:void 0}}};mo();import*as Xe from"fs/promises";import*as Or from"path";var _s=class{async readFile(e){return Xe.readFile(e,"utf-8")}async writeFile(e,t){let n=Or.dirname(e);await this.mkdir(n),await Xe.writeFile(e,t,"utf-8")}async exists(e){try{return await Xe.access(e),!0}catch{return!1}}async mkdir(e){await Xe.mkdir(e,{recursive:!0})}async glob(e,t){let n=t||process.cwd(),s=[];try{await this.walkDirectory(n,i=>{let o=Or.basename(i);for(let a of e)if(this.matchPattern(o,a)){s.push(i);break}})}catch{}return s}async readDir(e){return Xe.readdir(e)}async isDirectory(e){try{return(await Xe.stat(e)).isDirectory()}catch{return!1}}async walkDirectory(e,t){let n=await Xe.readdir(e,{withFileTypes:!0});for(let s of n){let i=Or.join(e,s.name);s.isDirectory()?await this.walkDirectory(i,t):s.isFile()&&t(i)}}matchPattern(e,t){let n=t.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${n}$`,"i").test(e)}};Is();var Ac=class r{httpClient;fileSystem;scriptExecutor;interpolator;cookieJar;interceptorChain;preprocessor;dataFileParser;requestHistory;parserRegistry;collectionLoader;environmentStore;forgeEnv;requestExecutor;options;constructor(e={}){if(this.options=e,this.interpolator=e.interpolator||new jn,this.fileSystem=e.fileSystem||new _s,this.preprocessor=e.preprocessor||new Un,this.dataFileParser=e.dataFileParser||new zn,this.cookieJar=e.cookieJar||new ys,e.enableHistory?this.requestHistory=e.requestHistory||new Ts({maxEntriesPerRequest:e.maxHistoryEntries??100}):this.requestHistory=null,this.interceptorChain=e.interceptorChain||this.createInterceptorChain(e),e.httpClient)this.httpClient=e.httpClient;else if(e.useNativeHttp!==!1){let i={...e.httpSettings,timeout:e.requestTimeout??e.httpSettings?.timeout};this.httpClient=new Bn(i)}else this.httpClient=new Os;let t=e.forgeRoot?[pe("path").join(e.forgeRoot,"modules")]:[],n=new Ft(new yt,this.interceptorChain,this.httpClient);if(this.scriptExecutor=e.scriptExecutor||new _t(n,t,void 0,e.scriptScope??"shared",e.scriptTimeout??5e3),this.parserRegistry=new gs,this.parserRegistry.register("http-forge",new Vn),(e.storageFormat??"folder")==="folder"&&e.forgeRoot){let i=pe("path").join(e.forgeRoot,"collections");this.collectionLoader=new hs(i)}else this.collectionLoader=new kr(this.fileSystem,this.parserRegistry);this.environmentStore=e.environmentConfig?new $t(e.environmentConfig):$t.fromVariables({}),this.forgeEnv=sn.fromResolver(this.environmentStore),this.requestExecutor=new Tr(this.httpClient,this.forgeEnv,this.cookieJar,this.preprocessor,{forgeRoot:e.forgeRoot,scriptExecutor:this.scriptExecutor})}createInterceptorChain(e){let t=new Nt;if(e.requestInterceptors)for(let n of e.requestInterceptors)t.addRequestInterceptor(n);if(e.responseInterceptors)for(let n of e.responseInterceptors)t.addResponseInterceptor(n);if(e.errorInterceptors)for(let n of e.errorInterceptors)t.addErrorInterceptor(n);return t}async loadCollection(e){if(this.collectionLoader instanceof kr)return this.collectionLoader.load(e);throw new Error("loadCollection(filePath) is not supported with folder storage format. Use loadAllCollections() instead.")}async loadAllCollections(){return this.collectionLoader.loadAll()}async execute(e,t,n){return this.requestExecutor.execute(e,t,n)}async executeSimple(e,t){return this.requestExecutor.executeSimple(e,t)}registerParser(e,t){this.parserRegistry.register(e,t)}setEnvironmentConfig(e){this.environmentStore=new $t(e),this.forgeEnv=sn.fromResolver(this.environmentStore),this.requestExecutor=new Tr(this.httpClient,this.forgeEnv,this.cookieJar,this.preprocessor,{forgeRoot:this.options.forgeRoot,scriptExecutor:this.scriptExecutor})}static create(e){return new r(e)}static fromForgeRoot(e="./http-forge",t={}){let n=pe("path"),s=n.join(e,"environments"),i,o=vs(s);if(Object.keys(o.environments).length>0||Object.keys(o.globalVariables).length>0){i={globalVariables:{...o.globalVariables,...o.localVariables},environments:{},selectedEnvironment:void 0};for(let[c,l]of Object.entries(o.environments)){let u=o.localCredentials[c]?.variables||{};i.environments[c]={name:c,variables:{...l.variables,...u}}}}else{let c=pe("fs"),l=n.join(s,"environments.json");if(c.existsSync(l))try{let u=c.readFileSync(l,"utf-8"),d=JSON.parse(u);if(i={globalVariables:d.globalVariables||{},environments:{},selectedEnvironment:d.selectedEnvironment},d.environments)for(let[p,m]of Object.entries(d.environments)){let f=m;i.environments[p]={name:f.name||p,variables:f.variables||{}}}}catch(u){console.warn(`[ForgeContainer] Failed to load environments from ${l}:`,u)}}return new r({...t,forgeRoot:e,storageFormat:t.storageFormat??"folder",environmentConfig:i})}};Rl();Cl();Oo();tt();_u();Ta();Du();Yu();Ya();Fe();Ka();async function $S(r){let{createMcpRuntime:e}=await Promise.resolve().then(()=>(rh(),nh));return e(r)}async function FS(r){let{runRequest:e}=await Promise.resolve().then(()=>(Sr(),Li));return e(r)}async function NS(r){let{runCollection:e}=await Promise.resolve().then(()=>(Sr(),Li));return e(r)}async function _S(r){let{runFolder:e}=await Promise.resolve().then(()=>(Sr(),Li));return e(r)}async function DS(r){let{runSuite:e}=await Promise.resolve().then(()=>(Sr(),Li));return e(r)}Ga();_c();$n();$a();Dc();Cs();ks();Ns();fo();Er();yc();wc();Is();Es();As();Lr();jr();Oc();Fc();Qi();cc();tn();Tc();jo();function MS(r){let e=r.replace(/\\\n/g," "),t=[],n="",s=0;for(;s<e.length;){let i=e[s];if(i==="\\"&&s+1<e.length)n+=e[++s],s++;else if(i==="'"){for(s++;s<e.length&&e[s]!=="'";)n+=e[s++];s++}else if(i==='"'){for(s++;s<e.length&&e[s]!=='"';)if(e[s]==="\\"&&s+1<e.length){let o=e[s+1];o==='"'||o==="\\"||o==="$"||o==="`"?(n+=o,s+=2):n+=e[s++]}else n+=e[s++];s++}else/\s/.test(i)?(n.length>0&&(t.push(n),n=""),s++):(n+=i,s++)}return n.length>0&&t.push(n),t}function jS(r){try{let e="__FV__",t=[],n=r.replace(/\{\{[^}]+\}\}/g,u=>(t.push(u),`${e}${t.length-1}`)),s=n.indexOf("?");if(s===-1)return{cleanUrl:r,params:[]};let i=n.slice(0,s),o=n.slice(s+1),a=u=>u.replace(new RegExp(`${e}(\\d+)`,"g"),(d,p)=>t[parseInt(p,10)]),c=a(i),l=o.split("&").filter(Boolean).map(u=>{let d=a(u),p=d.indexOf("=");return p===-1?{key:d,value:"",enabled:!0}:{key:decodeURIComponent(d.slice(0,p)),value:decodeURIComponent(d.slice(p+1)),enabled:!0}});return{cleanUrl:c,params:l}}catch{return{cleanUrl:r,params:[]}}}function LS(r){try{let e=new URL(r.replace(/\{\{[^}]+\}\}/g,"placeholder")),t=e.pathname.split("/").filter(Boolean),n=t[t.length-1];return n&&!/^\d+$/.test(n)&&!n.startsWith("{")?n.replace(/[-_]/g," ").replace(/\b\w/g,s=>s.toUpperCase()):t.length>1?t[t.length-2].replace(/[-_]/g," ").replace(/\b\w/g,s=>s.toUpperCase()):e.hostname.replace(/^www\./,"").split(".")[0]??"Request"}catch{return"Request"}}function HS(r,e,t){let n=[],s=new Set,i=(o,a)=>{s.has(a)||(s.add(a),n.push({key:o,value:a}))};for(let o of r){let a=o.key.toLowerCase();if(a==="authorization"){let c=o.value.match(/^(bearer|basic|token|digest)\s+(.+)$/i);c&&wt(c[2])?i(`${c[1].toUpperCase()}_TOKEN`,c[2]):wt(o.value)&&i("AUTH_TOKEN",o.value)}else Do.has(a)&&wt(o.value)&&i(Ut(o.key),o.value)}for(let o of e)Mo.has(o.key.toLowerCase())&&wt(o.value)&&i(Ut(o.key),o.value);try{let o=new URL(t.replace(/\{\{[^}]+\}\}/g,"placeholder"));if(!["localhost","127.0.0.1","0.0.0.0","::1"].includes(o.hostname)&&!fi(t)){let c=`${o.protocol}//${o.host}`;i("BASE_URL",c)}}catch{}return n}function BS(r){let e=MS(r.trim()),t=0;for(;t<e.length&&e[t].toLowerCase()==="curl";)t++;let n=e.slice(t),s="",i="",o=[],a=null,c=!1,l=!1,u=[],d=[],p=0;for(;p<n.length;){let y=n[p];if(y==="-X"||y==="--request")s=n[++p]??"";else if(y==="-H"||y==="--header"){let S=n[++p]??"",b=S.indexOf(":");b>0&&o.push({key:S.slice(0,b).trim(),value:S.slice(b+1).trim()})}else if(y==="-d"||y==="--data"||y==="--data-raw"||y==="--data-binary"||y==="--data-ascii")a=n[++p]??"";else if(y==="--json")a=n[++p]??"",c=!0;else if(y==="-u"||y==="--user"){let S=n[++p]??"",b=btoa(S);o.push({key:"Authorization",value:`Basic ${b}`})}else if(y==="-b"||y==="--cookie")o.push({key:"Cookie",value:n[++p]??""});else if(y==="--url")i=n[++p]??"";else if(y==="-G"||y==="--get")l=!0;else if(y==="-F"||y==="--form"){let S=n[++p]??"",b=S.indexOf("=");b>0&&u.push({key:S.slice(0,b),value:S.slice(b+1)})}else y==="--data-urlencode"?d.push(n[++p]??""):y==="-A"||y==="--user-agent"?o.push({key:"User-Agent",value:n[++p]??""}):y==="-e"||y==="--referer"||y==="--referrer"?o.push({key:"Referer",value:n[++p]??""}):y==="--compressed"||y==="-L"||y==="--location"||y==="-v"||y==="--verbose"||y==="-s"||y==="--silent"||y==="-i"||y==="--include"||y==="-k"||y==="--insecure"||y==="--http1.1"||y==="--http2"||y==="--http3"||(y==="-o"||y==="--output"||y==="--max-time"||y==="--connect-timeout"||y==="-m"||y==="--limit-rate"||y==="--proxy"||y==="-x"?p++:!y.startsWith("-")&&!i&&(i=y));p++}l?s="GET":s||(s=a!==null||u.length>0||d.length>0?"POST":"GET");let{cleanUrl:m,params:f}=jS(i),h=null;if(u.length>0)h={type:"raw",format:"text",content:u.map(S=>`${encodeURIComponent(S.key)}=${encodeURIComponent(S.value)}`).join("&")},o.some(S=>S.key.toLowerCase()==="content-type")||o.push({key:"Content-Type",value:"multipart/form-data"});else if(d.length>0)h={type:"raw",format:"text",content:d.join("&")},o.some(y=>y.key.toLowerCase()==="content-type")||o.push({key:"Content-Type",value:"application/x-www-form-urlencoded"});else if(a!==null){let y=a.trim(),S=c||y.startsWith("{")||y.startsWith("[");h={type:"raw",format:S?"json":"text",content:a},S&&!o.some(b=>b.key.toLowerCase()==="content-type")&&o.push({key:"Content-Type",value:"application/json"})}let g=o.map(y=>({...y,enabled:!0})),v=HS(o,f,m||i);return{name:LS(m||i),method:s.toUpperCase(),url:m||i,headers:g,queryParams:f,body:h,suggestedVars:v}}Xn();er();Jo();er();Xn();var Xa=10;async function US(r,e,t,n){let s=sh(r.items);if(s.length===0)return;let i=Math.ceil(s.length/Xa);for(let o=0;o<s.length;o+=Xa){let a=s.slice(o,o+Xa).map(u=>e.getRequestDetail(r.id,u.id)??u),c=Math.floor(o/Xa)+1;n?.(`Enhancing requests (batch ${c}/${i})\u2026`,1/i*100);let l=a.map(u=>({id:u.id,name:u.name,method:u.method??"GET",url:u.url??"",bodyContent:WS(u),responseSchema:u.responseSchema?JSON.stringify(u.responseSchema).slice(0,500):void 0,description:u.description?.slice(0,200),doc:u.doc?u.doc.slice(0,800):void 0,operationId:u.operationId,tags:u.tags?.slice(0,5)}));try{let u=await ot(()=>t.complete(VS(l,a))),d=zS(u);JS(a,d)}catch{}}await e.saveCollection(r)}function VS(r,e){return`You are an API testing expert. For each HTTP request below, return two improvements:
|
|
1790
|
+
[View HTML Report](${u[1]})`:"";return{content:[{type:"text",text:l+d}]}}case"prompts/list":return{prompts:Ia};case"prompts/get":{let t=e.params??{},n=t.name,s=t.arguments??{};if(!n)throw new Error("Missing prompt name");let i=pt(r.workspaceFolder);try{return await mu(n,s,i.collection,r.runStore,r.workspaceFolder)}finally{fs(i)}}default:throw new Error(`Method not found: ${e.method}`)}}function qS(r,e,t){let n=!r.container,s=r.container??pt(r.workspaceFolder),i;try{i=s.config.getMcpConfig().cors.allowedOrigins??["http://localhost","http://127.0.0.1"]}finally{n&&fs(s)}let o=e.headers.origin??"",a=i.includes(o)?o:i[0]??"http://localhost";t.setHeader("Access-Control-Allow-Origin",a),t.setHeader("Access-Control-Allow-Methods","POST, GET, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Mcp-Session-Id")}function AS(r,e,t){let s=new URL(e.url,`http://${r.host}:${r.port}`).searchParams.get("path");if(!s){t.statusCode=400,t.end("Missing path parameter");return}let i=An.resolve(s),o=r.container?.config.getResultsPath(),a=o?An.dirname(o):An.resolve(r.workspaceFolder,".http-forge",".cache");if(!i.startsWith(a+An.sep)||!i.endsWith(".html")){t.statusCode=403,t.end("Forbidden");return}th.readFile(i,"utf-8",(c,l)=>{if(c){t.statusCode=404,t.end("Report not found");return}t.statusCode=200,t.setHeader("content-type","text/html; charset=utf-8"),t.end(l)})}function ed(r,e,t,n){let s=r.create(e,t);return n().then(i=>{s.status!=="cancelled"&&(s.status="completed",s.completedAt=Date.now(),s.summary=i?.summary??s.summary,i?.failedRequests&&(s.failedRequests=i.failedRequests),i?.noAssertionExamples&&(s.noAssertionExamples=i.noAssertionExamples),s.reportPath=i?.report?.uri?.replace("file://","")??null,s.progress.completed=s.progress.total)}).catch(i=>{s.status!=="cancelled"&&(s.status="failed",s.completedAt=Date.now(),s.error=i.message)}),{runId:s.id,status:"running",total:t,message:"Run started. Use get_run_status to poll."}}function PS(r){let e=r.workspaceFolder;return{async runRequest(t,n,s){return qt(()=>Qa({workspaceFolder:e,collectionId:t.id,requestId:n,environment:s.environment,variables:s.variables,headers:s.headers,query:s.query,body:s.body,include:s.include}))},async runFolder(t,n,s){let i=X(t).filter(({folderPath:o})=>o===n||o.startsWith(`${n}/`)).length;return s.async===!0?ed(r.runStore,`${t.name} / ${Tt(n)}`,i,()=>qt(()=>Zt({workspaceFolder:e,collectionId:t.id,folderPath:n,recursive:s.recursive,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,include:s.include}))):qt(()=>Zt({workspaceFolder:e,collectionId:t.id,folderPath:n,recursive:s.recursive,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,include:s.include}))},async runCollection(t,n){let s=X(t).length;return n.async===!0?ed(r.runStore,t.name,s,()=>qt(()=>Zt({workspaceFolder:e,collectionId:t.id,environment:n.environment,variables:n.variables,iterations:n.iterations,stopOnError:n.stopOnError,delay:n.delay,include:n.include}))):qt(()=>Zt({workspaceFolder:e,collectionId:t.id,environment:n.environment,variables:n.variables,iterations:n.iterations,stopOnError:n.stopOnError,delay:n.delay,include:n.include}))},async runSuite(t,n,s){let i=pt(e),o=0;try{let a=await i.testSuite.getSuite(t);o=(a?.nodes.filter(l=>l.type==="request").length??0)*(s.iterations??a?.config?.iterations??1)}finally{fs(i)}return s.async===!0?ed(r.runStore,n,o,()=>qt(()=>br({workspaceFolder:e,suiteId:t,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,requestFilter:s.requestFilter,include:s.include}))):qt(()=>br({workspaceFolder:e,suiteId:t,environment:s.environment,variables:s.variables,iterations:s.iterations,stopOnError:s.stopOnError,delay:s.delay,requestFilter:s.requestFilter,include:s.include}))}}}async function nd(r,e,t={}){let n=r.workspaceFolder,s=RS(r.container,e);if(Object.values(x).includes(s)){let a=pt(n),c=yi();try{let l=await Nu(s,t,{collection:a.collection,testSuite:a.testSuite,environmentConfig:a.environmentConfig,workspaceFolder:n,...c?{aiProvider:c}:{}},r.runStore,PS(r));return IS.has(s)&&td.delete(n),l}finally{fs(a)}}let i=Bu(s),o=pt(n);try{let a=o.collection.getAllCollections(),c=a.map(m=>m.id),l=m=>{let f=ps(m,c),h=f?a.find(g=>g.id===f):void 0;if(!h)throw new Error(`Collection not found for tool: ${e}`);return h};if(i.kind==="request"){let[m,f]=i.tokens;if(!m||!f)throw new Error(`Malformed request tool: ${e}`);let h=l(m),g=X(h).map(y=>y.request.id),v=ps(f,g);if(!v)throw new Error(`Request not found in collection "${h.name}" for tool: ${e}`);return qt(()=>Qa({workspaceFolder:n,collectionId:h.id,requestId:v,environment:t.environment,variables:t.variables,headers:t.headers,query:t.query,body:t.body,include:t.include}))}if(i.kind==="collection"){let[m]=i.tokens;if(!m)throw new Error(`Malformed collection tool: ${e}`);let f=l(m);return qt(()=>Zt({workspaceFolder:n,collectionId:f.id,environment:t.environment,variables:t.variables,iterations:t.iterations,stopOnError:t.stopOnError,delay:t.delay,include:t.include}))}if(i.kind==="folder"){let[m,f]=i.tokens;if(!m||!f)throw new Error(`Malformed folder tool: ${e}`);let h=l(m),g=(o.collection.getAllCollections().find(S=>S.id===h.id),void 0),v=X(h).map(S=>S.folderPath).filter((S,b,C)=>S&&C.indexOf(S)===b),y=Uu(f,v);if(!y)throw new Error(`Folder not found in collection "${h.name}" for tool: ${e}`);return qt(()=>Zt({workspaceFolder:n,collectionId:h.id,folderPath:y,recursive:t.recursive,environment:t.environment,variables:t.variables,iterations:t.iterations,stopOnError:t.stopOnError,delay:t.delay,include:t.include}))}let[u]=i.tokens;if(!u)throw new Error(`Malformed suite tool: ${e}`);let d=await o.testSuite.getAllSuites(),p=ps(u,d.map(m=>m.id));if(!p)throw new Error(`Test suite not found for tool: ${e}`);return qt(()=>br({workspaceFolder:n,suiteId:p,environment:t.environment,variables:t.variables,iterations:t.iterations,stopOnError:t.stopOnError,delay:t.delay,requestFilter:t.requestFilter,include:t.include}))}finally{fs(o)}}function wr(r,e,t){r.statusCode=e,r.setHeader("content-type","application/json; charset=utf-8"),r.end(JSON.stringify(t))}function eh(r){return new Promise((e,t)=>{let n="";r.on("data",s=>{n+=s,n.length>1024*1024&&t(new Error("Request body too large (max 1MB)"))}),r.on("end",()=>{if(!n){e({});return}try{e(JSON.parse(n))}catch{t(new Error("Invalid JSON body"))}}),r.on("error",t)})}function TS(r){return bS(async(e,t)=>{try{if(qS(r,e,t),e.method==="OPTIONS"){t.statusCode=204,t.end();return}if(e.method==="GET"&&e.url==="/health"){wr(t,200,{status:"ok",port:r.port});return}if(e.method==="GET"&&e.url?.startsWith("/report?")){AS(r,e,t);return}if(e.method==="POST"&&(e.url==="/"||e.url==="/mcp")){let n;try{n=await eh(e)}catch{Xm(t,null,-32700,"Parse error");return}try{let s=await ES(r,n);wr(t,200,{jsonrpc:"2.0",id:n.id??null,result:s})}catch(s){Xm(t,n.id??null,-32603,s.message||"Internal error")}return}if(e.method==="POST"&&e.url==="/tools/execute"){let n=await eh(e);if(!n||typeof n.name!="string"||n.name.trim()===""){wr(t,400,{error:'Field "name" is required'});return}let s=await nd(r,n.name,n.args??{});wr(t,200,{result:s});return}wr(t,405,{error:"Method not allowed"})}catch(n){wr(t,500,{error:n.message})}})}function OS(r){if(typeof r.port=="number"&&Number.isFinite(r.port))return Math.min(65535,Math.max(1,Math.floor(r.port)));let t=new an(An.resolve(r.workspaceFolder)).getMcpConfig().port;return Math.min(65535,Math.max(1,Math.floor(t||3100)))}async function $S(r){let e=OS(r),t=r.host||"127.0.0.1",n=`${t}:${e}`,s={workspaceFolder:r.workspaceFolder,port:e,host:t,isRunning:!1,runStore:new Bi};return SS.set(n,s),{async start(){if(s.isRunning)return;s.container||(s.container=pt(s.workspaceFolder));let i=TS(s);await new Promise((o,a)=>{i.once("error",a),i.listen(s.port,s.host,()=>{i.off("error",a),o()})}),s.server=i,s.isRunning=!0},async stop(){if(s.container&&(fs(s.container),s.container=void 0),!s.server){s.isRunning=!1;return}await new Promise((i,o)=>{s.server.close(a=>{if(a){o(a);return}i()})}),s.server=void 0,s.isRunning=!1},isRunning(){return s.isRunning},getPort(){return s.port},async executeTool(i,o){return nd(s,i,o??{})}}}var SS,xS,td,Xu,IS,rh=k(()=>{"use strict";yo();Jo();Sr();tt();_u();Ta();Du();Yu();Ya();Fe();Ga();SS=new Map;xS=3e3,td=new Map,Xu=new Map;IS=Fu});var kr=class{constructor(e,t){this.fileSystem=e;this.parserRegistry=t}fileSystem;parserRegistry;directory;setDirectory(e){this.directory=e}async loadAll(){return this.directory?this.loadDirectory(this.directory):[]}async load(e,t={}){let n=await this.fileSystem.readFile(e);if(t.format){let i=this.parserRegistry.get(t.format);if(!i)throw new Error(`No parser registered for format: ${t.format}`);return i.parse(n,e)}let s=this.parserRegistry.detect(n);if(!s)throw new Error(`Could not detect collection format for: ${e}. Supported formats: ${this.parserRegistry.getFormats().join(", ")}`);return s.parser.parse(n,e)}async loadDirectory(e,t=["*.json","*.forge.json"]){let n=[],s=await this.fileSystem.glob(t,e);for(let i of s)try{let o=await this.load(i);n.push(o)}catch{}return n}async canLoad(e){try{if(!await this.fileSystem.exists(e))return!1;let t=await this.fileSystem.readFile(e);return this.parserRegistry.detect(t)!==null}catch{return!1}}getSupportedFormats(){return this.parserRegistry.getFormats()}};Qi();tn();function pc(r,e){return{id:r.id,name:r.name,description:r.description,variables:r.variables||{},auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(bd),source:{format:"folder",filePath:e,version:r.version}}}function bd(r){if(r.type==="folder")return{type:"folder",id:r.id,name:r.name,description:r.description,auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(bd)};let e=r;return{type:"request",id:e.id,name:e.name,description:e.description,requestType:e.requestType,method:e.method||"GET",url:e.url||"",headers:e.headers||[],query:e.query||[],params:e.params,body:e.body??void 0,auth:e.auth,settings:e.settings,scripts:e.scripts,websocket:e.websocket,...e.deprecated&&{deprecated:e.deprecated},...e.doc&&{doc:e.doc},...e.responseSchema&&{responseSchema:e.responseSchema},...e.bodySchema&&{bodySchema:e.bodySchema},...e.operationId&&{operationId:e.operationId},...e.summary&&{summary:e.summary},...e.tags&&e.tags.length>0&&{tags:e.tags},...e.examples&&e.examples.length>0&&{examples:e.examples},...e.responses&&Object.keys(e.responses).length>0&&{responses:e.responses},...e.security&&e.security.length>0&&{security:e.security}}}function Rh(r){return{id:r.id,name:r.name,description:r.description,version:r.source?.version,variables:r.variables,auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(fc)}}function fc(r){return r.type==="folder"?{type:"folder",id:r.id,name:r.name,description:r.description,auth:r.auth,scripts:r.scripts,items:(r.items||[]).map(fc)}:{type:"request",id:r.id,name:r.name,description:r.description,requestType:r.requestType,method:r.method,url:r.url,headers:r.headers,query:r.query,params:r.params,body:r.body,auth:r.auth,settings:r.settings,scripts:r.scripts,websocket:r.websocket,...r.deprecated&&{deprecated:r.deprecated},...r.doc&&{doc:r.doc},...r.responseSchema&&{responseSchema:r.responseSchema},...r.bodySchema&&{bodySchema:r.bodySchema},...r.operationId&&{operationId:r.operationId},...r.summary&&{summary:r.summary},...r.tags&&{tags:r.tags},...r.examples&&{examples:r.examples},...r.responses&&{responses:r.responses},...r.security&&{security:r.security}}}var hs=class{store;constructor(e){this.store=new nn(e)}loadAll(){return this.store.loadAll().map(t=>pc(t,this.store.getCollectionPath(t.id)))}getSlugById(e){return this.store.getSlugById(e)}getIdBySlug(e){return this.store.getIdBySlug(e)}load(e){let t=this.store.load(e);if(t)return pc(t,this.store.getCollectionPath(t.id))}async create(e,t){let n=await this.store.create(e,t);return pc(n,this.store.getCollectionPath(n.id))}async save(e){return this.store.save(Rh(e))}async delete(e){return this.store.delete(e)}exists(e){return this.store.exists(e)}getCollectionPath(e){return this.store.getCollectionPath(e)}async updateCollectionMetadata(e,t){return this.store.updateCollectionMetadata(e,t)}async saveItem(e,t,n){return this.store.saveItem(e,fc(t),n)}async updateItem(e,t,n){let s={...n};return this.store.updateItem(e,t,s)}async deleteItem(e,t){return this.store.deleteItem(e,t)}async moveItem(e,t,n){return this.store.moveItem(e,t,n)}async reorderItems(e,t,n){return this.store.reorderItems(e,t,n)}async saveScripts(e,t,n){return this.store.saveScripts(e,t,n)}loadScripts(e,t){return this.store.loadScripts(e,t)}};var gs=class{parsers=new Map;register(e,t){this.parsers.set(e.toLowerCase(),t)}get(e){return this.parsers.get(e.toLowerCase())}has(e){return this.parsers.has(e.toLowerCase())}getFormats(){return Array.from(this.parsers.keys())}detect(e){for(let[t,n]of this.parsers)if(n.canParse(e))return{parser:n,format:t};return null}clear(){this.parsers.clear()}};$n();var ys=class{cookies=new Map;getCookieKey(e,t,n){return oe.cookieKey(e,t,n)}get(e,t){if(t){let i=this.getCookieKey(e,t),o=this.cookies.get(i);if(o&&!this.isExpired(o))return o}let n=this.getCookieKey(e,"*"),s=this.cookies.get(n);if(s&&!this.isExpired(s))return s;for(let i of this.cookies.values())if(i.name===e&&!this.isExpired(i))if(t&&i.domain){if(this.domainMatches(t,i.domain))return i}else return i}set(e){let t=this.getCookieKey(e.name,e.domain,e.path);this.cookies.set(t,e)}setFromResponse(e){for(let t of e){let n=this.getCookieKey(t.name,t.domain,t.path);this.cookies.set(n,t)}}has(e,t){return this.get(e,t)!==void 0}delete(e,t,n){let s=this.getCookieKey(e,t,n);return this.cookies.delete(s)}getAll(e){let t=[];for(let n of this.cookies.values())this.isExpired(n)||(e?(!n.domain||this.domainMatches(e,n.domain))&&t.push(n):t.push(n));return t}getCookieHeader(e){let t=this.getAll(e);return oe.formatCookieHeader(t)}clear(){this.cookies.clear()}clearDomain(e){let t=[];for(let[n,s]of this.cookies.entries())s.domain&&this.domainMatches(e,s.domain)&&t.push(n);for(let n of t)this.cookies.delete(n)}parseCookieHeaders(e,t){return oe.parseCookieHeaders(e,t)}isExpired(e){return oe.isExpired(e)}domainMatches(e,t){return oe.domainMatches(e,t)}get count(){return this.cookies.size}cleanExpiredCookies(){let e=[];for(let[t,n]of this.cookies.entries())this.isExpired(n)&&e.push(t);for(let t of e)this.cookies.delete(t)}};Xi();var $t=class r{config;selectedEnvironment;sessionGlobals={};sessionEnvironmentValues=new Map;constructor(e){this.config=e,this.selectedEnvironment=e.selectedEnvironment||Object.keys(e.environments)[0]||"default"}get(e){return this.getVariables()[e]}set(e,t){let n=this.sessionEnvironmentValues.get(this.selectedEnvironment);n||(n={},this.sessionEnvironmentValues.set(this.selectedEnvironment,n)),n[e]=t}getAll(){return this.getVariables()}getEnvironments(){return Object.keys(this.config.environments)}getActive(){return this.selectedEnvironment}setActive(e){if(!this.config.environments[e])throw new Error(`Environment not found: ${e}`);this.selectedEnvironment=e}getVariables(e){let t=e||this.selectedEnvironment,n=this.config.environments[t],s={...this.config.globalVariables||{},...this.sessionGlobals};if(n){if(n.inherits&&this.config.environments[n.inherits]){let o=this.getEnvironmentVariables(n.inherits);s={...s,...o}}s={...s,...n.variables};let i=this.sessionEnvironmentValues.get(t);i&&(s={...s,...i})}return s}getEnvironmentVariables(e){let t=this.config.environments[e];if(!t)return{};let n={};return t.inherits&&this.config.environments[t.inherits]&&(n={...this.getEnvironmentVariables(t.inherits)}),{...n,...t.variables}}getGlobals(){return{...this.config.globalVariables||{},...this.sessionGlobals}}setGlobal(e,t){this.sessionGlobals[e]=t}unsetGlobal(e){delete this.sessionGlobals[e]}clearGlobals(){this.sessionGlobals={}}resolve(e){let t=e||this.selectedEnvironment;return{name:t,merged:this.getVariables(t),globals:this.getGlobals()}}static fromVariables(e,t="default"){return new r({environments:{[t]:{name:t,variables:e}},selectedEnvironment:t})}};Er();Ar();var sn=class r{envStore;interpolator;urlBuilder;constructor(e,t){this.envStore=e,this.interpolator=t||new jn,this.urlBuilder=new yt}get(e){return this.envStore.get(e)}set(e,t){this.envStore.set(e,t)}has(e){return this.envStore.get(e)!==void 0}delete(e){this.envStore.set(e,"")}getAll(){return this.envStore.getAll()}getActiveEnvironment(){return this.envStore.getActive()}setActiveEnvironment(e){this.envStore.setActive(e)}getEnvironments(){let e=this.envStore;return typeof e.getEnvironments=="function"?e.getEnvironments():[]}getGlobals(){let e=this.envStore;return typeof e.getGlobals=="function"?e.getGlobals():{}}setGlobal(e,t){let n=this.envStore;typeof n.setGlobal=="function"&&n.setGlobal(e,t)}unsetGlobal(e){let t=this.envStore;typeof t.unsetGlobal=="function"&&t.unsetGlobal(e)}clearGlobals(){let e=this.envStore;typeof e.clearGlobals=="function"&&e.clearGlobals()}resolve(e){return this.interpolator.interpolate(e,this.getAll())}resolvePath(e,t={}){let n=this.interpolator.interpolate(e,this.getAll());return this.urlBuilder.buildUrl(n,t)}buildUrl(e,t={}){let n=this.interpolator.interpolate(e,this.getAll());return this.urlBuilder.buildUrl(n,t.params||{},t.query||{})}resolveObject(e){return this.interpolator.interpolateObject(e,this.getAll())}extractVariables(e){return this.interpolator.extractVariables(e)}extractPathParams(e){return this.urlBuilder.extractPathParams(e)}static create(e={}){let t=$t.fromVariables(e);return new r(t)}static fromResolver(e){return new r(e)}};Ar();Cs();ks();Er();Is();As();var Tr=class{constructor(e,t,n,s,i){this.httpClient=e;this.forgeEnv=t;this.cookieJar=n;this.preprocessor=s;if(i?.scriptExecutor)this.scriptExecutor=i.scriptExecutor;else{let o=i?.forgeRoot?[pe("path").join(i.forgeRoot,"modules")]:[],a=new Ft(new yt,new Nt,e);this.scriptExecutor=new _t(a,o,void 0,i?.scriptScope??"shared",i?.scriptTimeout??5e3)}}httpClient;forgeEnv;cookieJar;preprocessor;scriptExecutor;async execute(e,t,n={}){if(e.requestType==="websocket")throw new Error("WebSocket requests are not supported by the HTTP request executor");let s=Date.now(),i={...this.forgeEnv.getAll()},o={...this.forgeEnv.getGlobals()},a={...n.additionalVariables||{}},c={...i},l=this.buildHttpRequest(e,n.overrides),u=n.overrides?.body||e.body,d=this.findFolderPath(t,e.id),p=this.buildScriptChain(e,t,d),m={request:{url:l.url,method:l.method,headers:{...l.headers},body:u?typeof u=="string"?{type:"raw",content:u}:u:void 0},variables:a,collectionVariables:t.variables||{},globals:{...o},environmentVariables:c,environmentName:this.forgeEnv.getActiveEnvironment?.()||void 0,cookieJar:this.cookieJar,info:{eventName:"prerequest",requestName:e.name,requestId:e.id,collectionName:t?.name},onEnvironmentChange:n.onEnvironmentChange,onGlobalsChange:(v,y,S)=>{v==="set"&&y&&S!==void 0?this.forgeEnv.setGlobal(y,S):v==="unset"&&y?this.forgeEnv.unsetGlobal(y):v==="clear"&&this.forgeEnv.clearGlobals()}},f=this.scriptExecutor.createRequestSession(m),h,g;try{if(!n.skipPreRequest&&p.preRequest.length>0){let b=await f.executePreRequest(p.preRequest);if(h={success:b.success,error:b.error,modifiedVariables:b.modifiedVariables,modifiedEnvironment:b.modifiedEnvironmentVariables,modifiedGlobals:b.modifiedGlobals,modifiedCollectionVariables:b.modifiedCollectionVariables,consoleOutput:b.consoleOutput,modifiedRequest:b.modifiedRequest?{url:b.modifiedRequest.url,method:b.modifiedRequest.method,headers:b.modifiedRequest.headers,body:b.modifiedRequest.body?.content}:void 0},b.modifiedVariables&&(a={...a,...b.localVariables??b.modifiedVariables}),b.modifiedEnvironmentVariables&&(c={...c,...b.modifiedEnvironmentVariables}),b.modifiedRequest){let C=b.modifiedRequest;C.url&&(l.url=C.url),C.method&&(l.method=C.method),C.headers&&(l.headers={...l.headers,...C.headers}),C.body!==void 0&&(l.body=C.body?.content||C.body)}if(!b.success)throw new Error(`Pre-request script failed: ${b.error}`)}let v={...c,...a};l=this.interpolateRequest(l,v);let y=n.overrides?.body||e.body;if(this.preprocessor&&y&&typeof y!="string"&&y.type==="graphql"&&l.body!==void 0){let b=this.preprocessor.encodeBody({type:"graphql",content:l.body});b!=null&&(l.body=typeof b=="string"?b:JSON.stringify(b))}if(u&&typeof u=="object"&&u.type==="form-data"&&Array.isArray(l.body)){let b=this.buildMultipartFormData({type:"form-data",content:l.body});b&&(l.body=b)}let S=await this.httpClient.send(l);if(!n.skipPostResponse&&p.postResponse.length>0){let b=await f.executePostResponse(p.postResponse,{status:S.status,statusText:S.statusText,headers:S.headers,body:S.body,cookies:ao(S.headers,S.cookies,l.url),responseTime:S.time,responseSize:S.size,executedRequest:{url:l.url,method:l.method,headers:l.headers||{},body:l.body?typeof l.body=="string"?{type:"raw",content:l.body}:l.body:{type:"none",content:""},params:{},query:{}}});g={success:!0,assertions:b.testResults,consoleOutput:b.consoleOutput,modifiedEnvironment:b.modifiedEnvironmentVariables},b.modifiedEnvironmentVariables&&(c={...c,...b.modifiedEnvironmentVariables})}return{response:S,preRequestResult:h,postResponseResult:g,totalTime:Date.now()-s,finalRequest:l,variables:{environment:c,local:a}}}finally{f.dispose?.()}}async executeSimple(e,t={}){let n=e,s={...this.forgeEnv.getAll(),...t.variables||{}};return n=this.interpolateRequest(e,s),t.timeout&&(n={...n,timeout:t.timeout}),this.httpClient.send(n)}buildHttpRequest(e,t){let n=e.url;if(e.query&&e.query.length>0){let u=new URLSearchParams;for(let d of e.query)d.enabled!==!1&&u.append(d.key,d.value);n+=(n.includes("?")?"&":"?")+u.toString()}let s=t?.url||n,i=t?.method||e.method,o={};if(e.headers&&Array.isArray(e.headers))for(let u of e.headers)u.enabled!==!1&&(o[u.key]=u.value);let a={...o,...t?.headers||{}},c,l=t?.body||e.body;if(l)if(typeof l=="string")c=l;else if(this.preprocessor&&l.type)if(l.type==="graphql")c=typeof l.content=="string"?l.content:JSON.stringify(l.content);else if(l.type==="form-data")c=this.buildMultipartFormData(l);else{let u=this.preprocessor.encodeBody(l);c=u!=null?String(u):void 0}else l.content&&(c=typeof l.content=="string"?l.content:JSON.stringify(l.content));return this.preprocessor&&l&&l.type!=="form-data"&&this.preprocessor.setContentTypeHeader(a,l),{url:s,method:i,headers:a,body:c,timeout:t?.timeout||e.settings?.timeout,settings:{...e.settings,...t?.settings}}}interpolateRequest(e,t){let n=sn.create(t),s=e.body,i=s;return typeof s=="string"?i=n.resolve(s):s instanceof FormData||s instanceof URLSearchParams?i=s:s&&typeof s=="object"&&(i=n.resolve(s)),{...e,url:n.resolvePath(e.url),headers:n.resolveObject(e.headers),body:i}}buildMultipartFormData(e){if(!e||e.type!=="form-data"||!Array.isArray(e.content))return;let t=new FormData;for(let n of e.content)!n?.key||n.enabled===!1||t.append(n.key,n.value==null?"":String(n.value));return t}buildScriptChain(e,t,n=[]){let s=[],i=[];t.scripts?.preRequest&&s.push(t.scripts.preRequest),t.scripts?.postResponse&&i.push(t.scripts.postResponse);for(let o of n)o.scripts?.preRequest&&s.push(o.scripts.preRequest),o.scripts?.postResponse&&i.push(o.scripts.postResponse);return e.scripts?.preRequest&&s.push(e.scripts.preRequest),e.scripts?.postResponse&&i.push(e.scripts.postResponse),{preRequest:s,postResponse:i}}findFolderPath(e,t){let n=[],s=(i,o)=>{for(let a of i){if(a.type==="request"&&a.id===t)return n.push(...o),!0;if(a.type==="folder"){let c=[...o,a];if(s(a.items,c))return!0}}return!1};return s(e.items,[]),n}};function og(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}var Ts=class{entries=new Map;requestIndex=new Map;fullResponses=new Map;maxEntriesPerRequest;storeFullResponses;constructor(e={}){this.maxEntriesPerRequest=e.maxEntriesPerRequest??100,this.storeFullResponses=e.storeFullResponses??!0}getEntries(e,t){let n=this.requestIndex.get(e)||[],s=[];for(let i of n){let o=this.entries.get(i);o&&(!t||o.environment===t)&&s.push(o)}return s}getEntry(e){return this.entries.get(e)}getFullResponse(e){return this.fullResponses.get(e)}get count(){return this.entries.size}addEntry(e,t,n,s,i){let o=og(),a=Date.now(),c={id:o,timestamp:a,environment:s,method:t.method,ticket:i?.ticket,branch:i?.branch,note:i?.note,sentRequest:{url:t.url,method:t.method,headers:{...t.headers},body:t.body},response:{status:n.status,statusText:n.statusText,time:n.time}};this.entries.set(o,c);let l=this.requestIndex.get(e)||[];for(l.unshift(o);l.length>this.maxEntriesPerRequest;){let u=l.pop();u&&(this.entries.delete(u),this.fullResponses.delete(u))}if(this.requestIndex.set(e,l),this.storeFullResponses){let u={timestamp:a,status:n.status,statusText:n.statusText,headers:{...n.headers},cookies:n.cookies||[],body:n.body,time:n.time};this.fullResponses.set(o,u)}return c}deleteEntry(e){if(!this.entries.get(e))return!1;this.entries.delete(e),this.fullResponses.delete(e);for(let[n,s]of this.requestIndex.entries()){let i=s.indexOf(e);if(i!==-1){s.splice(i,1),s.length===0&&this.requestIndex.delete(n);break}}return!0}clearHistory(e){let t=this.requestIndex.get(e);if(t){for(let n of t)this.entries.delete(n),this.fullResponses.delete(n);this.requestIndex.delete(e)}}clearAll(){this.entries.clear(),this.requestIndex.clear(),this.fullResponses.clear()}};var Os=class{async send(e){let t=Date.now(),n=new AbortController,s=e.timeout??3e4,i=setTimeout(()=>n.abort(),s);try{let o={method:e.method,headers:e.headers,signal:n.signal};e.body!==void 0&&(typeof e.body=="string"||e.body instanceof FormData||e.body instanceof URLSearchParams?o.body=e.body:typeof e.body=="object"&&(o.body=JSON.stringify(e.body),!e.headers?.["Content-Type"]&&!e.headers?.["content-type"]&&(o.headers["Content-Type"]="application/json"))),e.settings?.followRedirects===!1&&(o.redirect="manual");let a=await fetch(e.url,o),c=Date.now(),l;try{l=await a.text()}catch{l=null}let u={};return a.headers.forEach((d,p)=>{let m=u[p];m!==void 0?u[p]=Array.isArray(m)?[...m,d]:[m,d]:u[p]=d}),{status:a.status,statusText:a.statusText,headers:u,cookies:[],body:l,time:c-t}}catch(o){throw o.name==="AbortError"?new Error(`Request timeout after ${s}ms`):o}finally{clearTimeout(i)}}};Cs();ks();Ns();fo();Er();var Vn=class{format="http-forge";canParse(e){try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&"id"in t&&"name"in t&&"items"in t&&Array.isArray(t.items)&&!t.info?.schema?.includes("postman")&&!t._type}catch{return!1}}parse(e,t){let n=JSON.parse(e);return{id:n.id,name:n.name,description:n.description,variables:n.variables||{},auth:n.auth,scripts:n.scripts?{preRequest:n.scripts.preRequest,postResponse:n.scripts.postResponse}:void 0,items:this.convertItems(n.items),source:{format:"http-forge",filePath:t,version:n.version}}}convertItems(e){return e.map(t=>t.type==="folder"?this.convertFolder(t):this.convertRequest(t))}convertFolder(e){return{type:"folder",id:e.id,name:e.name,description:e.description,auth:e.auth,scripts:e.scripts?{preRequest:e.scripts.preRequest,postResponse:e.scripts.postResponse}:void 0,items:e.items?this.convertItems(e.items):[]}}convertRequest(e){let t={};if(e.headers)for(let s of e.headers)s.enabled!==!1&&(t[s.key]=s.value);let n={};if(e.query)for(let s of e.query)s.enabled!==!1&&(n[s.key]=s.value);return{type:"request",id:e.id,name:e.name,description:e.description,method:e.method||"GET",url:e.url||"",headers:Object.entries(t).map(([s,i])=>({key:s,value:i,enabled:!0})),query:Object.entries(n).map(([s,i])=>({key:s,value:i,enabled:!0})),params:e.params,body:e.body,auth:e.auth,settings:e.settings,scripts:e.scripts?{preRequest:e.scripts.preRequest,postResponse:e.scripts.postResponse}:void 0}}};mo();import*as Xe from"fs/promises";import*as Or from"path";var _s=class{async readFile(e){return Xe.readFile(e,"utf-8")}async writeFile(e,t){let n=Or.dirname(e);await this.mkdir(n),await Xe.writeFile(e,t,"utf-8")}async exists(e){try{return await Xe.access(e),!0}catch{return!1}}async mkdir(e){await Xe.mkdir(e,{recursive:!0})}async glob(e,t){let n=t||process.cwd(),s=[];try{await this.walkDirectory(n,i=>{let o=Or.basename(i);for(let a of e)if(this.matchPattern(o,a)){s.push(i);break}})}catch{}return s}async readDir(e){return Xe.readdir(e)}async isDirectory(e){try{return(await Xe.stat(e)).isDirectory()}catch{return!1}}async walkDirectory(e,t){let n=await Xe.readdir(e,{withFileTypes:!0});for(let s of n){let i=Or.join(e,s.name);s.isDirectory()?await this.walkDirectory(i,t):s.isFile()&&t(i)}}matchPattern(e,t){let n=t.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${n}$`,"i").test(e)}};Is();var Ac=class r{httpClient;fileSystem;scriptExecutor;interpolator;cookieJar;interceptorChain;preprocessor;dataFileParser;requestHistory;parserRegistry;collectionLoader;environmentStore;forgeEnv;requestExecutor;options;constructor(e={}){if(this.options=e,this.interpolator=e.interpolator||new jn,this.fileSystem=e.fileSystem||new _s,this.preprocessor=e.preprocessor||new Un,this.dataFileParser=e.dataFileParser||new zn,this.cookieJar=e.cookieJar||new ys,e.enableHistory?this.requestHistory=e.requestHistory||new Ts({maxEntriesPerRequest:e.maxHistoryEntries??100}):this.requestHistory=null,this.interceptorChain=e.interceptorChain||this.createInterceptorChain(e),e.httpClient)this.httpClient=e.httpClient;else if(e.useNativeHttp!==!1){let i={...e.httpSettings,timeout:e.requestTimeout??e.httpSettings?.timeout};this.httpClient=new Bn(i)}else this.httpClient=new Os;let t=e.forgeRoot?[pe("path").join(e.forgeRoot,"modules")]:[],n=new Ft(new yt,this.interceptorChain,this.httpClient);if(this.scriptExecutor=e.scriptExecutor||new _t(n,t,void 0,e.scriptScope??"shared",e.scriptTimeout??5e3),this.parserRegistry=new gs,this.parserRegistry.register("http-forge",new Vn),(e.storageFormat??"folder")==="folder"&&e.forgeRoot){let i=pe("path").join(e.forgeRoot,"collections");this.collectionLoader=new hs(i)}else this.collectionLoader=new kr(this.fileSystem,this.parserRegistry);this.environmentStore=e.environmentConfig?new $t(e.environmentConfig):$t.fromVariables({}),this.forgeEnv=sn.fromResolver(this.environmentStore),this.requestExecutor=new Tr(this.httpClient,this.forgeEnv,this.cookieJar,this.preprocessor,{forgeRoot:e.forgeRoot,scriptExecutor:this.scriptExecutor})}createInterceptorChain(e){let t=new Nt;if(e.requestInterceptors)for(let n of e.requestInterceptors)t.addRequestInterceptor(n);if(e.responseInterceptors)for(let n of e.responseInterceptors)t.addResponseInterceptor(n);if(e.errorInterceptors)for(let n of e.errorInterceptors)t.addErrorInterceptor(n);return t}async loadCollection(e){if(this.collectionLoader instanceof kr)return this.collectionLoader.load(e);throw new Error("loadCollection(filePath) is not supported with folder storage format. Use loadAllCollections() instead.")}async loadAllCollections(){return this.collectionLoader.loadAll()}async execute(e,t,n){return this.requestExecutor.execute(e,t,n)}async executeSimple(e,t){return this.requestExecutor.executeSimple(e,t)}registerParser(e,t){this.parserRegistry.register(e,t)}setEnvironmentConfig(e){this.environmentStore=new $t(e),this.forgeEnv=sn.fromResolver(this.environmentStore),this.requestExecutor=new Tr(this.httpClient,this.forgeEnv,this.cookieJar,this.preprocessor,{forgeRoot:this.options.forgeRoot,scriptExecutor:this.scriptExecutor})}static create(e){return new r(e)}static fromForgeRoot(e="./http-forge",t={}){let n=pe("path"),s=n.join(e,"environments"),i,o=vs(s);if(Object.keys(o.environments).length>0||Object.keys(o.globalVariables).length>0){i={globalVariables:{...o.globalVariables,...o.localVariables},environments:{},selectedEnvironment:void 0};for(let[c,l]of Object.entries(o.environments)){let u=o.localCredentials[c]?.variables||{};i.environments[c]={name:c,variables:{...l.variables,...u}}}}else{let c=pe("fs"),l=n.join(s,"environments.json");if(c.existsSync(l))try{let u=c.readFileSync(l,"utf-8"),d=JSON.parse(u);if(i={globalVariables:d.globalVariables||{},environments:{},selectedEnvironment:d.selectedEnvironment},d.environments)for(let[p,m]of Object.entries(d.environments)){let f=m;i.environments[p]={name:f.name||p,variables:f.variables||{}}}}catch(u){console.warn(`[ForgeContainer] Failed to load environments from ${l}:`,u)}}return new r({...t,forgeRoot:e,storageFormat:t.storageFormat??"folder",environmentConfig:i})}};Rl();Cl();Oo();tt();_u();Ta();Du();Yu();Ya();Fe();Ka();async function FS(r){let{createMcpRuntime:e}=await Promise.resolve().then(()=>(rh(),nh));return e(r)}async function NS(r){let{runRequest:e}=await Promise.resolve().then(()=>(Sr(),Li));return e(r)}async function _S(r){let{runCollection:e}=await Promise.resolve().then(()=>(Sr(),Li));return e(r)}async function DS(r){let{runFolder:e}=await Promise.resolve().then(()=>(Sr(),Li));return e(r)}async function MS(r){let{runSuite:e}=await Promise.resolve().then(()=>(Sr(),Li));return e(r)}Ga();_c();$n();$a();Dc();Cs();ks();Ns();fo();Er();yc();wc();Is();Es();As();Lr();jr();Oc();Fc();Qi();cc();tn();Tc();jo();function jS(r){let e=r.replace(/\\\n/g," "),t=[],n="",s=0;for(;s<e.length;){let i=e[s];if(i==="\\"&&s+1<e.length)n+=e[++s],s++;else if(i==="'"){for(s++;s<e.length&&e[s]!=="'";)n+=e[s++];s++}else if(i==='"'){for(s++;s<e.length&&e[s]!=='"';)if(e[s]==="\\"&&s+1<e.length){let o=e[s+1];o==='"'||o==="\\"||o==="$"||o==="`"?(n+=o,s+=2):n+=e[s++]}else n+=e[s++];s++}else/\s/.test(i)?(n.length>0&&(t.push(n),n=""),s++):(n+=i,s++)}return n.length>0&&t.push(n),t}function LS(r){try{let e="__FV__",t=[],n=r.replace(/\{\{[^}]+\}\}/g,u=>(t.push(u),`${e}${t.length-1}`)),s=n.indexOf("?");if(s===-1)return{cleanUrl:r,params:[]};let i=n.slice(0,s),o=n.slice(s+1),a=u=>u.replace(new RegExp(`${e}(\\d+)`,"g"),(d,p)=>t[parseInt(p,10)]),c=a(i),l=o.split("&").filter(Boolean).map(u=>{let d=a(u),p=d.indexOf("=");return p===-1?{key:d,value:"",enabled:!0}:{key:decodeURIComponent(d.slice(0,p)),value:decodeURIComponent(d.slice(p+1)),enabled:!0}});return{cleanUrl:c,params:l}}catch{return{cleanUrl:r,params:[]}}}function HS(r){try{let e=new URL(r.replace(/\{\{[^}]+\}\}/g,"placeholder")),t=e.pathname.split("/").filter(Boolean),n=t[t.length-1];return n&&!/^\d+$/.test(n)&&!n.startsWith("{")?n.replace(/[-_]/g," ").replace(/\b\w/g,s=>s.toUpperCase()):t.length>1?t[t.length-2].replace(/[-_]/g," ").replace(/\b\w/g,s=>s.toUpperCase()):e.hostname.replace(/^www\./,"").split(".")[0]??"Request"}catch{return"Request"}}function BS(r,e,t){let n=[],s=new Set,i=(o,a)=>{s.has(a)||(s.add(a),n.push({key:o,value:a}))};for(let o of r){let a=o.key.toLowerCase();if(a==="authorization"){let c=o.value.match(/^(bearer|basic|token|digest)\s+(.+)$/i);c&&wt(c[2])?i(`${c[1].toUpperCase()}_TOKEN`,c[2]):wt(o.value)&&i("AUTH_TOKEN",o.value)}else Do.has(a)&&wt(o.value)&&i(Ut(o.key),o.value)}for(let o of e)Mo.has(o.key.toLowerCase())&&wt(o.value)&&i(Ut(o.key),o.value);try{let o=new URL(t.replace(/\{\{[^}]+\}\}/g,"placeholder"));if(!["localhost","127.0.0.1","0.0.0.0","::1"].includes(o.hostname)&&!fi(t)){let c=`${o.protocol}//${o.host}`;i("BASE_URL",c)}}catch{}return n}function US(r){let e=jS(r.trim()),t=0;for(;t<e.length&&e[t].toLowerCase()==="curl";)t++;let n=e.slice(t),s="",i="",o=[],a=null,c=!1,l=!1,u=[],d=[],p=0;for(;p<n.length;){let y=n[p];if(y==="-X"||y==="--request")s=n[++p]??"";else if(y==="-H"||y==="--header"){let S=n[++p]??"",b=S.indexOf(":");b>0&&o.push({key:S.slice(0,b).trim(),value:S.slice(b+1).trim()})}else if(y==="-d"||y==="--data"||y==="--data-raw"||y==="--data-binary"||y==="--data-ascii")a=n[++p]??"";else if(y==="--json")a=n[++p]??"",c=!0;else if(y==="-u"||y==="--user"){let S=n[++p]??"",b=btoa(S);o.push({key:"Authorization",value:`Basic ${b}`})}else if(y==="-b"||y==="--cookie")o.push({key:"Cookie",value:n[++p]??""});else if(y==="--url")i=n[++p]??"";else if(y==="-G"||y==="--get")l=!0;else if(y==="-F"||y==="--form"){let S=n[++p]??"",b=S.indexOf("=");b>0&&u.push({key:S.slice(0,b),value:S.slice(b+1)})}else y==="--data-urlencode"?d.push(n[++p]??""):y==="-A"||y==="--user-agent"?o.push({key:"User-Agent",value:n[++p]??""}):y==="-e"||y==="--referer"||y==="--referrer"?o.push({key:"Referer",value:n[++p]??""}):y==="--compressed"||y==="-L"||y==="--location"||y==="-v"||y==="--verbose"||y==="-s"||y==="--silent"||y==="-i"||y==="--include"||y==="-k"||y==="--insecure"||y==="--http1.1"||y==="--http2"||y==="--http3"||(y==="-o"||y==="--output"||y==="--max-time"||y==="--connect-timeout"||y==="-m"||y==="--limit-rate"||y==="--proxy"||y==="-x"?p++:!y.startsWith("-")&&!i&&(i=y));p++}l?s="GET":s||(s=a!==null||u.length>0||d.length>0?"POST":"GET");let{cleanUrl:m,params:f}=LS(i),h=null;if(u.length>0)h={type:"raw",format:"text",content:u.map(S=>`${encodeURIComponent(S.key)}=${encodeURIComponent(S.value)}`).join("&")},o.some(S=>S.key.toLowerCase()==="content-type")||o.push({key:"Content-Type",value:"multipart/form-data"});else if(d.length>0)h={type:"raw",format:"text",content:d.join("&")},o.some(y=>y.key.toLowerCase()==="content-type")||o.push({key:"Content-Type",value:"application/x-www-form-urlencoded"});else if(a!==null){let y=a.trim(),S=c||y.startsWith("{")||y.startsWith("[");h={type:"raw",format:S?"json":"text",content:a},S&&!o.some(b=>b.key.toLowerCase()==="content-type")&&o.push({key:"Content-Type",value:"application/json"})}let g=o.map(y=>({...y,enabled:!0})),v=BS(o,f,m||i);return{name:HS(m||i),method:s.toUpperCase(),url:m||i,headers:g,queryParams:f,body:h,suggestedVars:v}}Xn();er();Jo();er();Xn();var Xa=10;async function VS(r,e,t,n){let s=sh(r.items);if(s.length===0)return;let i=Math.ceil(s.length/Xa);for(let o=0;o<s.length;o+=Xa){let a=s.slice(o,o+Xa).map(u=>e.getRequestDetail(r.id,u.id)??u),c=Math.floor(o/Xa)+1;n?.(`Enhancing requests (batch ${c}/${i})\u2026`,1/i*100);let l=a.map(u=>({id:u.id,name:u.name,method:u.method??"GET",url:u.url??"",bodyContent:GS(u),responseSchema:u.responseSchema?JSON.stringify(u.responseSchema).slice(0,500):void 0,description:u.description?.slice(0,200),doc:u.doc?u.doc.slice(0,800):void 0,operationId:u.operationId,tags:u.tags?.slice(0,5)}));try{let u=await ot(()=>t.complete(zS(l,a))),d=JS(u);WS(a,d)}catch{}}await e.saveCollection(r)}function zS(r,e){return`You are an API testing expert. For each HTTP request below, return two improvements:
|
|
1791
1791
|
1. "body" \u2014 a realistic, human-readable JSON request body string (not schema placeholders like "string" or 0). If the request has no body or is a GET/HEAD/DELETE, return null.
|
|
1792
1792
|
2. "testScript" \u2014 a JavaScript postResponse test using pm.test() syntax. Always include a status code check. Add response body assertions if a responseSchema is provided.
|
|
1793
1793
|
|
|
@@ -1803,7 +1803,7 @@ Return ONLY a valid JSON array matching this shape (no markdown fences, no extra
|
|
|
1803
1803
|
Rules:
|
|
1804
1804
|
- Keep "body" as a valid JSON string (escaped). Use realistic values, not placeholder strings.
|
|
1805
1805
|
- Keep "testScript" as valid JS. Use pm.test(), pm.response.to.have.status(), pm.expect().
|
|
1806
|
-
- One output object per input, same order, same id.`}function
|
|
1806
|
+
- One output object per input, same order, same id.`}function JS(r){let e=Ot(r);return Array.isArray(e)?e:[]}function WS(r,e){let t=new Map(e.map(n=>[n.id,n]));for(let n of r){let s=t.get(n.id);if(s){if(s.body&&n.body?.type==="raw")try{JSON.parse(s.body),n.body.content=s.body}catch{}s.testScript?.trim()&&(n.scripts||(n.scripts={}),n.scripts.postResponse||(n.scripts.postResponse=s.testScript.trim()))}}}function sh(r){let e=[];for(let t of r)t.type==="request"?e.push(t):t.type==="folder"&&t.items&&e.push(...sh(t.items));return e}function GS(r){if(r.body?.type==="raw"&&typeof r.body.content=="string")return r.body.content.slice(0,300)}tt();er();Xn();jo();async function KS(r,e,t){let n=X(r).map(l=>l.request);if(n.length===0)return[];let s=t?n.slice(0,30).map(l=>t.getRequestDetail(r.id,l.id)??l):n.slice(0,30),i=pi(s.map(l=>st(l))),o=`You are an API testing expert scanning an HTTP collection for hardcoded values.
|
|
1807
1807
|
Find all values that should be extracted to environment variables: base URLs, API keys/tokens, tenant or org IDs, user IDs, repeated hostnames.
|
|
1808
1808
|
Skip: HTTP methods, standard header names (Content-Type, Accept, Authorization key names), empty values, boolean literals, short numeric IDs.
|
|
1809
1809
|
|
|
@@ -1813,17 +1813,17 @@ Collection: "${r.name}"
|
|
|
1813
1813
|
${i}
|
|
1814
1814
|
|
|
1815
1815
|
Return ONLY a valid JSON array (no markdown fences):
|
|
1816
|
-
[{"value":"exact hardcoded string","suggestedName":"UPPER_SNAKE_CASE_NAME","reason":"one sentence","requestIds":["id1","id2"]}]`,a=await ot(()=>e.complete(o)),c=Ot(a);return Array.isArray(c)?c.filter(l=>l.value&&l.suggestedName).map(l=>({varName:Ut(l.suggestedName),value:l.value,reason:l.reason??"",occurrences:
|
|
1817
|
-
`)}Oa();Lc();Xi();Ar();Gs();Vc();bl();wl();Zc();Pc();function
|
|
1816
|
+
[{"value":"exact hardcoded string","suggestedName":"UPPER_SNAKE_CASE_NAME","reason":"one sentence","requestIds":["id1","id2"]}]`,a=await ot(()=>e.complete(o)),c=Ot(a);return Array.isArray(c)?c.filter(l=>l.value&&l.suggestedName).map(l=>({varName:Ut(l.suggestedName),value:l.value,reason:l.reason??"",occurrences:QS(n,l.value)})).filter(l=>l.occurrences.length>0).sort((l,u)=>u.occurrences.length-l.occurrences.length):[]}function QS(r,e){let t=[];for(let n of r){let s=n.name??n.url??n.id;n.url?.includes(e)&&t.push({requestId:n.id,requestName:s,field:"URL"});for(let i of n.headers??[])String(i.value??"").includes(e)&&t.push({requestId:n.id,requestName:s,field:`Header: ${i.key}`});for(let i of n.query??[])String(i.value??"").includes(e)&&t.push({requestId:n.id,requestName:s,field:`Query: ${i.key}`});n.body?.type==="raw"&&typeof n.body.content=="string"&&n.body.content.includes(e)&&t.push({requestId:n.id,requestName:s,field:"Body"})}return t}ql();Ou();function ZS(r){let e=[],t=r.status==="pass"?"PASS":r.status==="fail"?"FAIL":r.status==="drift"?"DRIFT":r.status==="dry-run"?"DRY-RUN":"INFRA ERROR";if(e.push(`QA check: ${t}`),e.push(` project: ${r.project.path}`),r.project.gitHash&&e.push(` git: ${r.project.gitHash.slice(0,12)}`),r.project.frameworks.length>0&&e.push(` frameworks: ${r.project.frameworks.join(", ")}`),e.push(` drift: ${r.drift.status}${r.drift.reason?` (${r.drift.reason})`:""}`),e.push(` discovered: ${r.discovered} reused: ${r.reused} created: ${r.created}`+(r.updatedUrls>0?` urls updated: ${r.updatedUrls}`:"")),r.suite&&e.push(` suite: ${r.suite.name} (${r.suite.id})`),e.push(` results: ${r.results.passed} passed, ${r.results.failed} failed`+(r.results.skipped>0?`, ${r.results.skipped} skipped`:"")),r.endpoints.length>0){e.push(""),e.push(" endpoints:");for(let s of r.endpoints){let i=r.status==="dry-run"?"\xB7":s.passed===!1?"\u2717":"\u2713",o=r.status==="dry-run"?`${s.reused?"reuse":"create"}`:`${s.statusGot??"?"}${s.duration?` (${s.duration})`:""}`,a=s.confidence==="low"?" [low-confidence]":"";e.push(` ${i} ${s.method} ${s.path} \u2192 ${o}${a}`),s.error&&e.push(` error: ${s.error}`);for(let c of s.failures??[])e.push(` failed: ${c}`)}}let n=r.endpoints.filter(s=>s.passed===!1);if(n.length>0){e.push(""),e.push(` failures: ${n.length}`);for(let s of n)e.push(` - [${s.method}] ${s.path}: expected ${s.statusExpected}, got ${s.statusGot??"no response"}`+(s.error?` (${s.error})`:""))}if(r.lowConfidence.length>0){e.push(""),e.push(" low-confidence discoveries (verify manually):");for(let s of r.lowConfidence)e.push(` - ${s}`)}return e.join(`
|
|
1817
|
+
`)}Oa();Lc();Xi();Ar();Gs();Vc();bl();wl();Zc();Pc();function YS(r,e,t){let n=r.slice(0,e),s=n.match(/([a-zA-Z_]\w*)$/),i=s?s[1]:"",o=ax(n);if(o.trimEnd().endsWith("@")||i&&o.trimEnd().endsWith("@"+i))return{contextType:"directive",fieldPath:[],prefix:i};if(cx(o))return{contextType:"variable_def",fieldPath:[],prefix:i};let a=o.match(/\.\.\.\s+on\s+(\w*)$/);if(a)return{contextType:"fragment_type",fieldPath:[],prefix:a[1]||""};let c=o.match(/\(\s*(?:[\w]+\s*:\s*(?:"[^"]*"|[^,)]+)\s*,\s*)*(\w+)\s*:\s*(\w*)$/);if(c&&ih(o)){let d=rd(o,t),p=d.length>0?d[d.length-1]:void 0,m=oh(o);return{contextType:"argument_value",fieldPath:d,parentType:p,prefix:c[2]||"",currentArg:c[1],currentField:m||void 0}}if(ih(o)){let d=rd(o,t),p=d.length>0?d[d.length-1]:void 0,m=oh(o);return{contextType:"argument",fieldPath:d,parentType:p,prefix:i,currentField:m||void 0}}if(sd(o,"{","}")===0)return{contextType:"root",fieldPath:[],prefix:i};let u=rd(o,t);return{contextType:"selection_set",fieldPath:u,parentType:u.length>0?u[u.length-1]:void 0,prefix:i}}function XS(r,e){switch(e.contextType){case"root":return ex(r,e.prefix);case"selection_set":return tx(r,e);case"argument":return nx(r,e);case"argument_value":return rx(r,e);case"directive":return sx(r,e.prefix);case"fragment_type":return ix(r,e.prefix);case"variable_def":return ox(r,e.prefix);default:return[]}}function ex(r,e){let t=[],n=[{label:"query",detail:"Query operation",insertText:`query \${1:OperationName} {
|
|
1818
1818
|
$0
|
|
1819
1819
|
}`},{label:"mutation",detail:"Mutation operation",insertText:`mutation \${1:OperationName} {
|
|
1820
1820
|
$0
|
|
1821
1821
|
}`},{label:"subscription",detail:"Subscription operation",insertText:`subscription \${1:OperationName} {
|
|
1822
1822
|
$0
|
|
1823
|
-
}`},{label:"fragment",detail:"Fragment definition",insertText:"fragment ${1:FragmentName} on ${2:TypeName} {\n $0\n}"}];for(let i of n)i.label==="mutation"&&!r.mutationType||i.label==="subscription"&&!r.subscriptionType||(!e||i.label.startsWith(e.toLowerCase()))&&t.push({label:i.label,kind:"keyword",detail:i.detail,insertText:i.insertText,sortOrder:0});let s=r.types.get(r.queryType);if(s)for(let i of s.fields)(!e||i.name.toLowerCase().startsWith(e.toLowerCase()))&&t.push(ah(i,1,r));return t}function
|
|
1823
|
+
}`},{label:"fragment",detail:"Fragment definition",insertText:"fragment ${1:FragmentName} on ${2:TypeName} {\n $0\n}"}];for(let i of n)i.label==="mutation"&&!r.mutationType||i.label==="subscription"&&!r.subscriptionType||(!e||i.label.startsWith(e.toLowerCase()))&&t.push({label:i.label,kind:"keyword",detail:i.detail,insertText:i.insertText,sortOrder:0});let s=r.types.get(r.queryType);if(s)for(let i of s.fields)(!e||i.name.toLowerCase().startsWith(e.toLowerCase()))&&t.push(ah(i,1,r));return t}function tx(r,e){let t=[],n=e.parentType;if(!n)return t;let s=r.types.get(n);if(!s)return t;if(s.kind==="OBJECT"||s.kind==="INTERFACE"){for(let i of s.fields)(!e.prefix||i.name.toLowerCase().startsWith(e.prefix.toLowerCase()))&&t.push(ah(i,0,r));(!e.prefix||"__typename".startsWith(e.prefix.toLowerCase()))&&t.push({label:"__typename",kind:"field",detail:"String!",description:"The name of the current object type",sortOrder:10})}if(s.kind==="UNION"||s.kind==="INTERFACE")for(let i of s.possibleTypes){let o=i.replace(/[!\[\]]/g,"");(!e.prefix||o.toLowerCase().startsWith(e.prefix.toLowerCase()))&&t.push({label:`... on ${o}`,kind:"snippet",detail:`Inline fragment on ${o}`,insertText:`... on ${o} {
|
|
1824
1824
|
$0
|
|
1825
|
-
}`,sortOrder:5})}return(!e.prefix||"...".startsWith(e.prefix))&&t.push({label:"...",kind:"snippet",detail:"Fragment spread",insertText:"...${1:FragmentName}",sortOrder:8}),t}function
|
|
1825
|
+
}`,sortOrder:5})}return(!e.prefix||"...".startsWith(e.prefix))&&t.push({label:"...",kind:"snippet",detail:"Fragment spread",insertText:"...${1:FragmentName}",sortOrder:8}),t}function nx(r,e){if(!e.currentField||!e.parentType)return[];let t=r.types.get(e.parentType);if(!t)return[];let n=t.fields.find(i=>i.name===e.currentField);if(!n)return[];let s=[];for(let i of n.args)(!e.prefix||i.name.toLowerCase().startsWith(e.prefix.toLowerCase()))&&s.push({label:i.name,kind:"argument",detail:i.type,description:i.description,insertText:`${i.name}: `,sortOrder:0});return s}function rx(r,e){if(!e.currentArg||!e.currentField||!e.parentType)return[];let t=[],n=r.types.get(e.parentType);if(!n)return t;let s=n.fields.find(c=>c.name===e.currentField);if(!s)return t;let i=s.args.find(c=>c.name===e.currentArg);if(!i)return t;let o=i.type.replace(/[!\[\]]/g,""),a=r.types.get(o);if(a&&a.kind==="ENUM")for(let c of a.enumValues)(!e.prefix||c.name.toLowerCase().startsWith(e.prefix.toLowerCase()))&&t.push({label:c.name,kind:"enum",detail:a.name,description:c.description,deprecated:c.isDeprecated,sortOrder:0});else if(o==="Boolean")for(let c of["true","false"])(!e.prefix||c.startsWith(e.prefix.toLowerCase()))&&t.push({label:c,kind:"keyword",detail:"Boolean",sortOrder:0});return t}function sx(r,e){let t=[];for(let n of r.directives)if(!e||n.name.toLowerCase().startsWith(e.toLowerCase())){let s=n.args.length>0?`(${n.args.map(i=>`${i.name}: ${i.type}`).join(", ")})`:"";t.push({label:`@${n.name}`,kind:"directive",detail:s||void 0,description:n.description,insertText:n.args.length>0?`@${n.name}($1)`:`@${n.name}`,sortOrder:0})}return t}function ix(r,e){let t=[];for(let[n,s]of r.types)(s.kind==="OBJECT"||s.kind==="INTERFACE"||s.kind==="UNION")&&(!e||n.toLowerCase().startsWith(e.toLowerCase()))&&t.push({label:n,kind:"type",detail:s.kind,description:s.description,sortOrder:0});return t}function ox(r,e){let t=[];for(let[n,s]of r.types)(s.kind==="SCALAR"||s.kind==="INPUT_OBJECT"||s.kind==="ENUM")&&(!e||n.toLowerCase().startsWith(e.toLowerCase()))&&t.push({label:n,kind:"type",detail:s.kind,description:s.description,sortOrder:0});return t}function ah(r,e,t){let n=r.type.replace(/[!\[\]]/g,""),s=!1;if(t){let o=t.types.get(n);s=!!o&&(o.kind==="OBJECT"||o.kind==="INTERFACE"||o.kind==="UNION")}else s=!new Set(["String","Int","Float","Boolean","ID"]).has(n);let i=r.name;if(r.args.length>0){let o=r.args.filter(a=>a.type.endsWith("!"));if(o.length>0){let a=o.map((c,l)=>`${c.name}: \${${l+1}}`).join(", ");i=`${r.name}(${a})`}}return s&&(i+=` {
|
|
1826
1826
|
$0
|
|
1827
|
-
}`),{label:r.name,kind:"field",detail:r.type,description:r.description,insertText:i,deprecated:r.isDeprecated,sortOrder:e}}function
|
|
1828
|
-
`).map(u=>u.trim()).filter(Boolean).map(
|
|
1829
|
-
`)}Nc();yo();Ru();$i();rs();_a();function ec(r,e){if(r.length===0)return 0;let t=Math.ceil(e/100*r.length)-1;return r[Math.max(0,t)]}function id(r,e){return{key:r,name:e,count:0,passed:0,failed:0,skipped:0,min:0,max:0,avg:0,p50:0,p90:0,p95:0,p99:0,durations:[]}}function ph(r){if(r.durations.length===0){r.min=0,r.max=0,r.avg=0,r.p50=0,r.p90=0,r.p95=0,r.p99=0;return}let e=[...r.durations].sort((n,s)=>n-s),t=r.durations.reduce((n,s)=>n+s,0);r.min=e[0],r.max=e[e.length-1],r.avg=Math.round(t/r.durations.length),r.p50=ec(e,50),r.p90=ec(e,90),r.p95=ec(e,95),r.p99=ec(e,99)}var od=class{summary;byRequest;overall;errors;startTime=0;constructor(){this.summary=this.createEmptySummary(),this.byRequest=new Map,this.overall=id("overall","Overall"),this.errors=new Map}createEmptySummary(){return{totalRequests:0,passed:0,failed:0,skipped:0,passRate:0,duration:0,isRunning:!1}}start(){this.startTime=Date.now(),this.summary.isRunning=!0}reset(){this.summary=this.createEmptySummary(),this.byRequest.clear(),this.overall=id("overall","Overall"),this.errors.clear(),this.startTime=0}complete(){this.summary.isRunning=!1,this.startTime>0&&(this.summary.duration=Date.now()-this.startTime)}addResult(e,t,n,s,i,o){this.summary.totalRequests++,i?this.summary.skipped++:s?this.summary.passed++:this.summary.failed++;let a=this.summary.passed+this.summary.failed;if(this.summary.passRate=a>0?Math.round(this.summary.passed/a*1e3)/10:0,this.startTime>0&&(this.summary.duration=Date.now()-this.startTime),i)return;this.byRequest.has(e)||this.byRequest.set(e,id(e,t));let c=this.byRequest.get(e);if(c.name=t,c.count++,s?c.passed++:c.failed++,c.durations.push(n),ph(c),this.overall.count++,s?this.overall.passed++:this.overall.failed++,this.overall.durations.push(n),ph(this.overall),o){let l=this.errors.get(o)||0;this.errors.set(o,l+1)}}getStatistics(){let e=[];return this.errors.forEach((t,n)=>{e.push({message:n,count:t})}),e.sort((t,n)=>n.count-t.count),{summary:{...this.summary},byRequest:new Map(this.byRequest),overall:{...this.overall},errors:e}}getSerializableStatistics(){let e=this.getStatistics();return{summary:e.summary,byRequest:Array.from(e.byRequest.values()),overall:e.overall,errors:e.errors}}};yl();tn();import*as At from"fs";import*as Rr from"path";var ad=class{constructor(e){this.collectionService=e}collectionService;suite;suiteDir;setSuite(e){this.suite={...e,nodes:Array.isArray(e.nodes)?e.nodes:[]}}setSuiteDir(e){this.suiteDir=e}getSuite(){return this.suite}loadSuiteRequest(e){if(!this.suiteDir)return;let t=Rr.join(this.suiteDir,e,"request.json");if(At.existsSync(t))try{let n=JSON.parse(At.readFileSync(t,"utf-8")),s=Rr.join(this.suiteDir,e,"scripts"),i=Gi(s);return i&&(n.scripts=i),n}catch(n){console.error(`[TestSuiteStore] Failed to load request from ${e}:`,n);return}}saveSuiteRequest(e,t){if(!this.suiteDir)return;let n=Rr.join(this.suiteDir,e);At.mkdirSync(n,{recursive:!0});let s=t.scripts,i={...t};delete i.scripts;let o=Rr.join(n,"request.json"),a=`${o}.tmp-${process.pid}-${Date.now()}`;if(At.writeFileSync(a,JSON.stringify(i,null,2),"utf-8"),At.renameSync(a,o),s){let c=Rr.join(n,"scripts");Ki(c,{preRequest:s.preRequest||void 0,postResponse:s.postResponse||void 0})}}hasEmbeddedRequest(e){return!this.suiteDir||!e?!1:At.existsSync(Rr.join(this.suiteDir,e,"request.json"))}resolveRequestEntry(e){let t=e.slug?this.loadSuiteRequest(e.slug):void 0,n=this.collectionService.getCollection(e.collectionId);if(t){let i,o=[],a=[],c;if(n){i=n.scripts;let l=this.findRequestInCollection(n,e.requestId);l&&(o=l.folderScriptsChain,a=l.folderAuthChain,c=l.folderPath)}return{request:t,suiteRequest:e,collectionScripts:i,collectionAuth:n?.auth,folderScriptsChain:o,folderAuthChain:a,resolvedFolderPath:c,resolvedCollectionName:n?.name}}if(!n){console.warn(`[TestSuiteStore] Collection not found: ${e.collectionId}`);return}let s=this.findRequestInCollection(n,e.requestId);if(!s){console.warn(`[TestSuiteStore] Request not found: ${e.requestId}`);return}return{request:s.request,suiteRequest:e,collectionScripts:n.scripts,collectionAuth:n.auth,folderScriptsChain:s.folderScriptsChain,folderAuthChain:s.folderAuthChain,resolvedFolderPath:s.folderPath,resolvedCollectionName:n.name}}findRequestInCollection(e,t,n=[]){let s=e.items||[];return this.searchItems(s,t,n)}searchItems(e,t,n,s=[],i=""){for(let o of e)if(o.type==="folder"){let a=o;if(!a.items)continue;let c=a.scripts?[...n,a.scripts]:n,l=a.auth?[...s,a.auth]:s,u=(a.name||"").replace(/\//g,"%2F"),d=i?`${i}/${u}`:u,p=this.searchItems(a.items||[],t,c,l,d);if(p)return p}else if(o.id===t)return{request:this.normalizeRequest(o),folderScriptsChain:n,folderAuthChain:s,folderPath:i}}normalizeRequest(e){let{type:t,...n}=e;return n}normalizeKeyValues(e){return e?Array.isArray(e)?e.map(t=>({key:t.key||"",value:t.value||"",enabled:t.enabled!==!1})):typeof e=="object"?Object.entries(e).map(([t,n])=>({key:t,value:String(n||""),enabled:!0})):[]:[]}getRequestWithContext(e,t){if(!this.suite)return;let n=this._getRequestNodes().find(s=>s.collectionId===e&&s.requestId===t);if(n)return this.resolveRequestEntry(n)}getRequestBySlug(e){if(!this.suite)return;let t=this._getRequestNodes().find(n=>n.slug===e);if(t)return this.resolveRequestEntry(t)}getAllSuiteRequests(){if(!this.suite)return[];let e=[];for(let t of this._getRequestNodes()){let n=this.resolveRequestEntry(t);n&&e.push(n)}return e}getResolvedRequests(){if(!this.suite)return[];let t=(this.suite.nodes||[]).filter(i=>i.type==="request"),n=t.map(i=>i.request?.slug||"").filter(Boolean),s=[];for(let i of t){let o=i.request;if(!o)continue;o.slug||(o.slug=gt(o.name||"request",n),n.push(o.slug));let a=this.resolveRequestEntry(o);if(a){let c=this.collectionService.getCollection(o.collectionId);s.push({id:`${o.collectionId}:${o.requestId}`,collectionId:o.collectionId,requestId:o.requestId,name:a.request.name||"Unknown",method:a.request.method||"GET",url:a.request.url||"",collectionName:c?.name||"Unknown Collection",folderPath:o.folderPath||"",enabled:i.enabled!==!1,hasEmbeddedRequest:this.hasEmbeddedRequest(o.slug),slug:o.slug,description:i.name!==a.request.name?i.name:o.description||void 0})}else console.warn(`[TestSuiteStore] getResolvedRequests: could not resolve request \u2014 collectionId=${o.collectionId} requestId=${o.requestId} slug=${o.slug}`)}return s}getSelectedRequests(e){let t=[];for(let n of e){let[s,i]=n.split(":"),o=this._getRequestNodes().find(a=>a.collectionId===s&&a.requestId===i);if(o){let a=this.resolveRequestEntry(o);a&&t.push(a)}}return t}addRequest(e,t){if(this.suite){if(this.suite.nodes||(this.suite.nodes=[]),this.suiteDir&&t)if(e.slug)e.slug=this.resolveUniqueSlug(e.slug);else{let n=this._getRequestNodes().map(s=>s.slug||"").filter(Boolean);e.slug=gt(e.name||t.name||"request",n)}this.suite.nodes.push({type:"request",name:e.description||e.name,request:e,enabled:e.enabled!==!1})}}resolveUniqueSlug(e){if(!this.suite)return e;let t=new Set(this._getRequestNodes().map(s=>s.slug).filter(Boolean));if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}removeRequest(e){this.suite?.nodes&&(this.suite.nodes=this.suite.nodes.filter(t=>!(t.type==="request"&&t.request?.requestId===e)))}reorderRequests(e){if(!this.suite?.nodes)return;let t=new Map;for(let i of this.suite.nodes)if(i.type==="request"&&i.request){let o=i.request;t.set(`${o.collectionId}:${o.requestId}`,i)}let n=this.suite.nodes.filter(i=>i.type!=="request"),s=[];for(let i of e){let o=t.get(i);o&&s.push(o)}this.suite.nodes=[...s,...n]}updateSuiteRequest(e,t){if(!this.suite||!this.suiteDir)return;this.saveSuiteRequest(e,t);let n=this.suite.nodes?.find(s=>s.type==="request"&&s.request?.slug===e);n?.request&&(n.request.name=t.name||n.request.name,n.request.method=t.method||n.request.method)}resyncFromCollection(e){if(!this.suite||!this.suiteDir)return;let t=this.suite.nodes?.find(o=>o.type==="request"&&o.request?.slug===e);if(!t?.request)return;let n=t.request,s=this.collectionService.getCollection(n.collectionId);if(!s)return;let i=this.findRequestInCollection(s,n.requestId);if(i)return this.saveSuiteRequest(e,i.request),t.request.name=i.request.name||n.name,t.request.method=i.request.method||n.method,i.request}_getRequestNodes(){return(this.suite?.nodes||[]).filter(e=>e.type==="request"&&e.request).map(e=>e.request)}};Ze();function cd(r,e={}){let n=(typeof r=="string"?JSON.parse(r):r)?.log;if(!n||!Array.isArray(n.entries))throw new Error("Invalid HAR: missing log.entries");let s=n.entries.filter(a=>a?.request),i=[];for(let a of s){let c=a.request;if(e.filterHost)try{if(new URL(c.url).hostname!==e.filterHost)continue}catch{continue}let l=a.response?.status;e.skipFailed&&typeof l=="number"&&l>=400||i.push(dx(a))}let o=gx(i,e.collectionName??"Imported from HAR");return{requests:i,collection:o}}function fh(r,e={}){return cd(r,e).collection}function dx(r){let e=r.request,t=e.method||"GET",n=e.url||"",s=hx(t,n),i=(e.headers??[]).filter(l=>typeof l.name=="string").map(l=>({key:l.name,value:String(l.value),enabled:!0})),o=(e.queryString??[]).map(l=>({key:l.name,value:String(l.value),enabled:!0})),a=(e.cookies??[]).map(l=>({key:l.name,value:String(l.value),enabled:!0})),c=px(e.postData,i);return{name:s,method:t,url:n,headers:i,query:o,cookies:a,body:c,responseStatus:r.response?.status,responseTimeMs:typeof r.time=="number"?r.time:void 0,responseContentType:r.response?.content?.mimeType}}function px(r,e){if(!r)return null;let t=typeof r.text=="string"?r.text:"",n=r.mimeType||mx(e);if(!t&&r.params?.length){let s=r.params.map(i=>({key:i.name,value:String(i.value??""),enabled:!0}));return{type:n.includes("json")?"raw":"x-www-form-urlencoded",...n.includes("json")?{format:"json"}:{},content:s}}if(n.includes("json"))return{type:"raw",format:"json",content:t};if(n.includes("xml"))return{type:"raw",format:"xml",content:t};if(n.includes("html"))return{type:"raw",format:"html",content:t};if(n.includes("form-urlencoded")||n.includes("multipart")){let s=fx(t);if(s.length>0)return{type:"x-www-form-urlencoded",content:s}}return{type:"raw",format:"text",content:t}}function fx(r){try{return[...new URLSearchParams(r).entries()].map(([t,n])=>({key:t,value:n,enabled:!0}))}catch{return[]}}function mx(r){return r.find(t=>t.key.toLowerCase()==="content-type")?.value?.split(";")[0].trim()??""}function hx(r,e){try{let t=new URL(e),n=t.pathname.split("/").filter(Boolean).pop();return n?`${r} ${decodeURIComponent(n)}`:`${r} ${t.hostname}`}catch{return`${r} ${e.slice(0,80)}`}}function gx(r,e){let t=new Map,n=[];for(let s of r){let i="unknown-host";try{i=new URL(s.url).hostname}catch{}let o=t.get(i);o||(o={type:"folder",id:le(`har-${i}`),name:i,items:[]},t.set(i,o),n.push(o)),o.items.push(yx(s))}return{id:le("har-collection"),name:e,items:n,source:{format:"har",filePath:""},meta:{requestCount:r.length}}}function yx(r){let e=r.headers.map(n=>({...n}));if(r.cookies.length>0){let n=e.find(s=>s.key.toLowerCase()==="cookie");if(n){let s=r.cookies.map(i=>`${i.key}=${i.value}`).join("; ");n.value=n.value?`${n.value}; ${s}`:s}else e.push({key:"Cookie",value:r.cookies.map(s=>`${s.key}=${s.value}`).join("; "),enabled:!0})}return{type:"request",id:le(`har-${r.method}-${r.url}`),name:r.name,method:r.method,url:r.url,headers:e,query:r.query.map(n=>({...n})),body:r.body??void 0,responseSchema:r.responseStatus?{responses:{[String(r.responseStatus)]:{description:`Observed response (${r.responseTimeMs??"unknown"} ms)`,contentType:r.responseContentType}}}:void 0}}jc();go();mo();cl();ll();ul();dl();pl();fl();ml();bs();ws();Ze();Iu();export{dd as AGENTS_MD_BACKUP_FILENAME,ud as AGENTS_MD_FILENAME,Xt as AGENTS_MD_VERSION,gi as AnthropicProvider,hi as ApiArchitectService,kn as ApiDiscoveryService,ni as AwsSecretResolver,ri as AzureKeyVaultResolver,pd as BODY_FILE_MAP,Fu as CACHE_BUSTING_TOOLS,Go as COLLECTION_INPUT_SCHEMA,Wn as CONFIG_FILES,kr as CollectionLoader,js as CollectionLoaderFactory,Dt as CollectionRequestExecutor,Ls as CollectionService,an as ConfigService,ys as CookieJar,Hs as CookieService,oe as CookieUtils,se as DEFAULT_CONFIG,ze as DEFAULT_REQUEST_SETTINGS,zn as DataFileParser,si as DopplerResolver,Vs as EnvironmentConfigService,$t as EnvironmentResolver,Br as ExampleGenerator,Si as ExpressComponentAnalyzer,bn as ExpressDiscoveryProvider,Ko as FOLDER_INPUT_SCHEMA,Cn as FastApiDiscoveryProvider,wi as FastifyComponentAnalyzer,Sn as FastifyDiscoveryProvider,Os as FetchHttpClient,hs as FolderCollectionLoader,nn as FolderCollectionStore,Ac as ForgeContainer,sn as ForgeEnv,Qr as FrameworkDetector,x as GENERIC_TOOL_NAMES,ii as GcpSecretResolver,Qs as GraphQLSchemaService,bu as HTTP_METHOD_MAP,dt as HTTP_METHOD_REVERSE,oi as HashiCorpVaultResolver,Hr as HistoryAnalyzer,cs as HtmlReportGenerator,Vn as HttpForgeParser,Ft as HttpRequestService,dr as InMemoryCookieJar,Nt as InterceptorChain,Qt as JUnitReportGenerator,_r as JsonCollectionLoader,Ci as LambdaComponentAnalyzer,wn as LambdaDiscoveryProvider,Ia as MCP_PROMPTS,Me as METADATA_FILES,Bi as McpRunStore,no as ModuleLoader,xn as NestDiscoveryProvider,_s as NodeFileSystem,Bn as NodeHttpClient,Jr as NodeSocketIoClient,ui as NodeWebSocketClient,Ds as OAuth2TokenManager,ai as OnePasswordResolver,zo as OpenAiProvider,un as OpenApiExporter,Lt as OpenApiImporter,gs as ParserRegistry,Bs as PersistentCookieJar,Wo as REQUEST_INPUT_SCHEMA,on as ROOT_DIRECTORIES,Ur as RefResolver,Tr as RequestExecutor,Ys as RequestHistoryService,Ts as RequestHistoryStore,Ks as RequestPreparer,Un as RequestPreprocessor,Ps as RequestScriptSession,gr as ResultStorageService,On as SCHEMA_FILES,Ve as SCRIPTS_DIR,Wi as SCRIPT_FILES,Qo as SUITE_INPUT_SCHEMA,dn as SchemaInferenceService,ln as SchemaInferrer,Vr as ScriptAnalyzer,_t as ScriptExecutor,ci as SecretResolverRegistry,Qn as ServiceContainer,$ as ServiceIdentifiers,Sl as SocketIoClientAdapter,Rn as SpringDiscoveryProvider,od as StatisticsService,li as TestSuiteService,ad as TestSuiteStore,yt as UrlBuilder,jn as VariableInterpolator,Mn as VariableResolver,bi as analyzeComponentChainMetadata,ia as analyzeHandlerMetadata,El as applyEnvSuggestionsToItems,Ng as applyExtractionPlan,xs as applyFilterChain,zt as applyMcpBodyTruncation,ka as applyRegenerated,pi as assembleBusinessContext,ac as buildAgentsMdContent,Il as buildArchitectPrompt,Ap as buildCollectionBusinessContext,zu as buildCollectionToolDescription,ju as buildCollectionToolName,cr as buildDescription,Fg as buildExtractionPlan,Ju as buildFolderToolDescription,Lu as buildFolderToolName,Zo as buildGenericTools,Zu as buildMcpToolList,mu as buildPromptResult,kl as buildRequestBusinessContext,Vu as buildRequestToolDescription,Mu as buildRequestToolName,pr as buildResultFileName,Pp as buildRunResultsContext,Wu as buildSuiteToolDescription,Hu as buildSuiteToolName,hd as cleanupOldBodyFiles,py as clearRegisteredKnowledgeSources,lt as collectSourceFiles,Bt as collectionKnowledgeSource,Al as collectionToEndpoints,hn as combineConfidence,lr as computeProjectFreshness,oo as concatenateScripts,hl as countRequests,Ip as createDefaultKnowledgeSources,yi as createEnvAiProvider,Pr as createExpectChain,$S as createMcpRuntime,gc as createModuleLoader,ro as createMomentShim,pt as createNodeContainer,io as createResponseObject,bc as createTestFunction,Qu as decodeCursor,Tt as decodeFolderPath,yn as dedupeDiscoveredApiParameters,en as deleteItemFromTree,Pu as deserializeTypedRecord,us as deserializeTypedValue,Lo as detectEnvSuggestions,Gf as detectIndexDrift,ur as detectProjectDrift,Ii as diffLines,nr as discoverWorkflows,Nu as dispatchGenericTool,Ku as encodeCursor,$e as encodeFolderName,Pi as endpointToCreateRequestOptions,or as endpointToName,ar as endpointToRequestParts,US as enhanceCollection,oc as ensureAgentsMdFile,qe as enumerateFolders,It as evaluateExpression,cg as exportCollectionToRestClient,Ot as extractJsonFromLlm,gn as extractPathParameters,Ee as findItemById,X as flattenRequests,Ir as formatConsoleOutput,di as gatherWorkspaceKnowledge,Gr as generateFlowFromEndpoints,le as generateId,uh as generateReleaseNotes,gt as generateSlug,fn as generateSuiteFromEndpoints,Ji as getAgentsMdPath,Sh as getAgentsMdStatus,YS as getCompletions,fy as getRegisteredKnowledgeSources,Mr as getSecretValues,Ep as getServiceContainer,fh as harToCollection,qs as hasChanged,_n as isExpression,Yi as isSystemEnvironmentFile,vs as loadEnvironmentsFromFolder,ta as loadHybridSeedEndpoints,zr as normalizeFolderInput,Sc as normalizeHeaders,BS as parseCurlCommand,Dn as parseFilterChain,cd as parseHar,Bu as parseMcpToolName,Mc as parsePostmanEnvironment,ZS as parseQueryContext,md as prepareBodyForSave,Ca as proposeSuiteUpdates,Hi as qaEndpointKey,ic as readAgentsMdVersion,fd as readBodyFromDir,gd as readSchemaFile,Gi as readScriptsFromDir,Kc as redactFullResponse,Qc as redactFullResultDetails,St as redactHeaders,Gc as redactHistoryEntry,xh as refreshAgentsMd,$o as registerCoreServices,dy as registerKnowledgeSource,Dp as renderArchitectDocs,QS as renderQaReportTable,dh as renderReleaseNotesMarkdown,st as requestKnowledgeSource,Oi as resolveCollectionRef,yu as resolveFolderRef,Uu as resolveFolderToken,Zp as resolveProjectName,cu as resolveRegenerated,vu as resolveRequestRef,Di as resolveResultGrouping,ps as resolveToken,Aa as reviewSuiteRun,NS as runCollection,_S as runFolder,Tu as runQaCheck,FS as runRequest,No as runResultsKnowledgeSource,DS as runSuite,GS as scanCollectionForEnvVarsWithAi,ts as schemaToExample,lc as searchForItemPath,uc as searchForItemPathById,Mi as serializeTypedValue,vd as sortItemsByOrder,tr as suiteIdFromName,au as threeWayDiff,Pa as toReviewRequestResults,_p as validateDesignedSpec,ot as withAiRetry,it as workspaceKnowledgeSource,Nr as writeEnvFile,ho as writeFolderItems,yd as writeSchemaFiles,Ms as writeScriptFile,Ki as writeScriptsToDir};
|
|
1827
|
+
}`),{label:r.name,kind:"field",detail:r.type,description:r.description,insertText:i,deprecated:r.isDeprecated,sortOrder:e}}function ax(r){return r.replace(/"""[\s\S]*?"""/g,'""').replace(/"(?:[^"\\]|\\.)*"/g,'""').replace(/#[^\n]*/g,"")}function sd(r,e,t){let n=0;for(let s of r)s===e?n++:s===t&&n--;return n}function ih(r){return sd(r,"(",")")>0}function cx(r){if(sd(r,"(",")")<=0)return!1;let t=r.indexOf("{"),n=t>=0?r.slice(0,t):r;return/\$\w+\s*:\s*\w*$/.test(n)}function oh(r){let e=0;for(let t=r.length-1;t>=0;t--)if(r[t]===")")e++;else if(r[t]==="("){if(e===0){let s=r.slice(0,t).trimEnd().match(/(\w+)$/);return s?s[1]:null}e--}return null}function rd(r,e){if(!e)return[];let t=[],n=e.queryType,s=r.match(/\b(query|mutation|subscription)\b/);s&&(s[1]==="mutation"&&e.mutationType?n=e.mutationType:s[1]==="subscription"&&e.subscriptionType&&(n=e.subscriptionType)),t.push(n);let i=lx(r),o=e.types.get(n);for(let a=0;a<i.length;a++){let c=i[a];if(c!=="{"){if(c==="}"){t.pop(),o=t.length>0?e.types.get(t[t.length-1]):void 0;continue}if(a+1<i.length&&(i[a+1]==="{"||i[a+1]==="(")){let l=a+1;if(i[l]==="("){let u=1;for(l++;l<i.length&&u>0;)i[l]==="("?u++:i[l]===")"&&u--,l++}if(l<i.length&&i[l]==="{"&&o){let u=o.fields.find(d=>d.name===c);if(u){let d=u.type.replace(/[!\[\]]/g,"");t.push(d),o=e.types.get(d)}}}}}return t}function lx(r){let e=[],t=/([a-zA-Z_]\w*|[{}(),:=@!$\[\].]|\.\.\.|"[^"]*"|\d+)/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]);return e}zc();sl();Yc();ol();So();al();Eo();Co();ko();Ol();Pl();Tl();Xr();ou();uu();lu();iu();Xo();jl();Jl();Wl();Yl();Kl();na();mn();ru();Ho();Ml();Vo();fu();import{execSync as ch}from"child_process";var ux=/^(feat|fix|perf|docs|refactor|test|build|chore)(?:\(([^)]*)\))?(!?):\s*(.+)$/i,lh=/BREAKING[- ]CHANGE:/i;function uh(r){let{projectRoot:e,from:t,to:n="HEAD"}=r,s=t?`${t}..${n}`:n,i=!0,o,a="";try{a=ch(`git log --no-merges --pretty=format:%h%x09%s ${s}`,{cwd:e,stdio:["ignore","pipe","ignore"],encoding:"utf-8",timeout:5e3,maxBuffer:4*1024*1024}),o=ch("git rev-parse HEAD",{cwd:e,stdio:["ignore","pipe","ignore"],encoding:"utf-8",timeout:3e3}).trim()}catch{i=!1}let c=a.split(`
|
|
1828
|
+
`).map(u=>u.trim()).filter(Boolean).map(dx).filter(u=>u!==null),l={};for(let u of c)l[u.type]=(l[u.type]??0)+1;return{from:t??null,to:n,toHash:o,entries:c,summary:l,gitAvailable:i}}function dx(r){let e=r.indexOf(" ");if(e<0)return null;let t=r.slice(0,e),n=r.slice(e+1),s=n.match(ux);if(!s)return{type:"other",subject:n,hash:t,breaking:lh.test(n)};let[,i,o,a,c]=s;return{type:i.toLowerCase(),scope:o||void 0,subject:c,hash:t,breaking:a==="!"||lh.test(c)}}function dh(r){if(!r.gitAvailable)return"Release notes unavailable: project is not a git work tree.";if(r.entries.length===0)return r.from?`No commits in ${r.from}..${r.to}.`:`No commits found up to ${r.to}.`;let e=["feat","fix","perf","refactor","docs","test","build","chore","other"],t=r.entries.filter(s=>s.breaking),n=[];t.length>0&&n.push("### \u26A0\uFE0F Breaking changes",...t.map(s=>`- **${s.subject}** \`${s.hash}\``));for(let s of e){let i=r.entries.filter(a=>a.type===s&&!a.breaking);if(i.length===0)continue;let o={feat:"### \u2728 Features",fix:"### \u{1F41B} Bug fixes",perf:"### \u26A1 Performance",refactor:"### \u{1F527} Refactors",docs:"### \u{1F4DA} Docs",test:"### \u2705 Tests",build:"### \u{1F4E6} Build",chore:"### \u{1F9F9} Chores",other:"### Other"};n.push(o[s]);for(let a of i){let c=a.scope?`**${a.scope}:** `:"";n.push(`- ${c}${a.subject} \`${a.hash}\``)}}return n.join(`
|
|
1829
|
+
`)}Nc();yo();Ru();$i();rs();_a();function ec(r,e){if(r.length===0)return 0;let t=Math.ceil(e/100*r.length)-1;return r[Math.max(0,t)]}function id(r,e){return{key:r,name:e,count:0,passed:0,failed:0,skipped:0,min:0,max:0,avg:0,p50:0,p90:0,p95:0,p99:0,durations:[]}}function ph(r){if(r.durations.length===0){r.min=0,r.max=0,r.avg=0,r.p50=0,r.p90=0,r.p95=0,r.p99=0;return}let e=[...r.durations].sort((n,s)=>n-s),t=r.durations.reduce((n,s)=>n+s,0);r.min=e[0],r.max=e[e.length-1],r.avg=Math.round(t/r.durations.length),r.p50=ec(e,50),r.p90=ec(e,90),r.p95=ec(e,95),r.p99=ec(e,99)}var od=class{summary;byRequest;overall;errors;startTime=0;constructor(){this.summary=this.createEmptySummary(),this.byRequest=new Map,this.overall=id("overall","Overall"),this.errors=new Map}createEmptySummary(){return{totalRequests:0,passed:0,failed:0,skipped:0,passRate:0,duration:0,isRunning:!1}}start(){this.startTime=Date.now(),this.summary.isRunning=!0}reset(){this.summary=this.createEmptySummary(),this.byRequest.clear(),this.overall=id("overall","Overall"),this.errors.clear(),this.startTime=0}complete(){this.summary.isRunning=!1,this.startTime>0&&(this.summary.duration=Date.now()-this.startTime)}addResult(e,t,n,s,i,o){this.summary.totalRequests++,i?this.summary.skipped++:s?this.summary.passed++:this.summary.failed++;let a=this.summary.passed+this.summary.failed;if(this.summary.passRate=a>0?Math.round(this.summary.passed/a*1e3)/10:0,this.startTime>0&&(this.summary.duration=Date.now()-this.startTime),i)return;this.byRequest.has(e)||this.byRequest.set(e,id(e,t));let c=this.byRequest.get(e);if(c.name=t,c.count++,s?c.passed++:c.failed++,c.durations.push(n),ph(c),this.overall.count++,s?this.overall.passed++:this.overall.failed++,this.overall.durations.push(n),ph(this.overall),o){let l=this.errors.get(o)||0;this.errors.set(o,l+1)}}getStatistics(){let e=[];return this.errors.forEach((t,n)=>{e.push({message:n,count:t})}),e.sort((t,n)=>n.count-t.count),{summary:{...this.summary},byRequest:new Map(this.byRequest),overall:{...this.overall},errors:e}}getSerializableStatistics(){let e=this.getStatistics();return{summary:e.summary,byRequest:Array.from(e.byRequest.values()),overall:e.overall,errors:e.errors}}};yl();tn();import*as At from"fs";import*as Rr from"path";var ad=class{constructor(e){this.collectionService=e}collectionService;suite;suiteDir;setSuite(e){this.suite={...e,nodes:Array.isArray(e.nodes)?e.nodes:[]}}setSuiteDir(e){this.suiteDir=e}getSuite(){return this.suite}loadSuiteRequest(e){if(!this.suiteDir)return;let t=Rr.join(this.suiteDir,e,"request.json");if(At.existsSync(t))try{let n=JSON.parse(At.readFileSync(t,"utf-8")),s=Rr.join(this.suiteDir,e,"scripts"),i=Gi(s);return i&&(n.scripts=i),n}catch(n){console.error(`[TestSuiteStore] Failed to load request from ${e}:`,n);return}}saveSuiteRequest(e,t){if(!this.suiteDir)return;let n=Rr.join(this.suiteDir,e);At.mkdirSync(n,{recursive:!0});let s=t.scripts,i={...t};delete i.scripts;let o=Rr.join(n,"request.json"),a=`${o}.tmp-${process.pid}-${Date.now()}`;if(At.writeFileSync(a,JSON.stringify(i,null,2),"utf-8"),At.renameSync(a,o),s){let c=Rr.join(n,"scripts");Ki(c,{preRequest:s.preRequest||void 0,postResponse:s.postResponse||void 0})}}hasEmbeddedRequest(e){return!this.suiteDir||!e?!1:At.existsSync(Rr.join(this.suiteDir,e,"request.json"))}resolveRequestEntry(e){let t=e.slug?this.loadSuiteRequest(e.slug):void 0,n=this.collectionService.getCollection(e.collectionId);if(t){let i,o=[],a=[],c;if(n){i=n.scripts;let l=this.findRequestInCollection(n,e.requestId);l&&(o=l.folderScriptsChain,a=l.folderAuthChain,c=l.folderPath);let u=this.collectionService.findRequest(n.id,e.requestId);u?.body!=null&&(t.body=u.body)}return{request:t,suiteRequest:e,collectionScripts:i,collectionAuth:n?.auth,folderScriptsChain:o,folderAuthChain:a,resolvedFolderPath:c,resolvedCollectionName:n?.name}}if(!n){console.warn(`[TestSuiteStore] Collection not found: ${e.collectionId}`);return}let s=this.findRequestInCollection(n,e.requestId);if(!s){console.warn(`[TestSuiteStore] Request not found: ${e.requestId}`);return}return{request:s.request,suiteRequest:e,collectionScripts:n.scripts,collectionAuth:n.auth,folderScriptsChain:s.folderScriptsChain,folderAuthChain:s.folderAuthChain,resolvedFolderPath:s.folderPath,resolvedCollectionName:n.name}}findRequestInCollection(e,t,n=[]){let s=e.items||[];return this.searchItems(s,t,n)}searchItems(e,t,n,s=[],i=""){for(let o of e)if(o.type==="folder"){let a=o;if(!a.items)continue;let c=a.scripts?[...n,a.scripts]:n,l=a.auth?[...s,a.auth]:s,u=(a.name||"").replace(/\//g,"%2F"),d=i?`${i}/${u}`:u,p=this.searchItems(a.items||[],t,c,l,d);if(p)return p}else if(o.id===t)return{request:this.normalizeRequest(o),folderScriptsChain:n,folderAuthChain:s,folderPath:i}}normalizeRequest(e){let{type:t,...n}=e;return n}normalizeKeyValues(e){return e?Array.isArray(e)?e.map(t=>({key:t.key||"",value:t.value||"",enabled:t.enabled!==!1})):typeof e=="object"?Object.entries(e).map(([t,n])=>({key:t,value:String(n||""),enabled:!0})):[]:[]}getRequestWithContext(e,t){if(!this.suite)return;let n=this._getRequestNodes().find(s=>s.collectionId===e&&s.requestId===t);if(n)return this.resolveRequestEntry(n)}getRequestBySlug(e){if(!this.suite)return;let t=this._getRequestNodes().find(n=>n.slug===e);if(t)return this.resolveRequestEntry(t)}getAllSuiteRequests(){if(!this.suite)return[];let e=[];for(let t of this._getRequestNodes()){let n=this.resolveRequestEntry(t);n&&e.push(n)}return e}getResolvedRequests(){if(!this.suite)return[];let t=(this.suite.nodes||[]).filter(i=>i.type==="request"),n=t.map(i=>i.request?.slug||"").filter(Boolean),s=[];for(let i of t){let o=i.request;if(!o)continue;o.slug||(o.slug=gt(o.name||"request",n),n.push(o.slug));let a=this.resolveRequestEntry(o);if(a){let c=this.collectionService.getCollection(o.collectionId);s.push({id:`${o.collectionId}:${o.requestId}`,collectionId:o.collectionId,requestId:o.requestId,name:a.request.name||"Unknown",method:a.request.method||"GET",url:a.request.url||"",collectionName:c?.name||"Unknown Collection",folderPath:o.folderPath||"",enabled:i.enabled!==!1,hasEmbeddedRequest:this.hasEmbeddedRequest(o.slug),slug:o.slug,description:i.name!==a.request.name?i.name:o.description||void 0})}else console.warn(`[TestSuiteStore] getResolvedRequests: could not resolve request \u2014 collectionId=${o.collectionId} requestId=${o.requestId} slug=${o.slug}`)}return s}getSelectedRequests(e){let t=[];for(let n of e){let[s,i]=n.split(":"),o=this._getRequestNodes().find(a=>a.collectionId===s&&a.requestId===i);if(o){let a=this.resolveRequestEntry(o);a&&t.push(a)}}return t}addRequest(e,t){if(this.suite){if(this.suite.nodes||(this.suite.nodes=[]),this.suiteDir&&t)if(e.slug)e.slug=this.resolveUniqueSlug(e.slug);else{let n=this._getRequestNodes().map(s=>s.slug||"").filter(Boolean);e.slug=gt(e.name||t.name||"request",n)}this.suite.nodes.push({type:"request",name:e.description||e.name,request:e,enabled:e.enabled!==!1})}}resolveUniqueSlug(e){if(!this.suite)return e;let t=new Set(this._getRequestNodes().map(s=>s.slug).filter(Boolean));if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}removeRequest(e){this.suite?.nodes&&(this.suite.nodes=this.suite.nodes.filter(t=>!(t.type==="request"&&t.request?.requestId===e)))}reorderRequests(e){if(!this.suite?.nodes)return;let t=new Map;for(let i of this.suite.nodes)if(i.type==="request"&&i.request){let o=i.request;t.set(`${o.collectionId}:${o.requestId}`,i)}let n=this.suite.nodes.filter(i=>i.type!=="request"),s=[];for(let i of e){let o=t.get(i);o&&s.push(o)}this.suite.nodes=[...s,...n]}updateSuiteRequest(e,t){if(!this.suite||!this.suiteDir)return;this.saveSuiteRequest(e,t);let n=this.suite.nodes?.find(s=>s.type==="request"&&s.request?.slug===e);n?.request&&(n.request.name=t.name||n.request.name,n.request.method=t.method||n.request.method)}resyncFromCollection(e){if(!this.suite||!this.suiteDir)return;let t=this.suite.nodes?.find(o=>o.type==="request"&&o.request?.slug===e);if(!t?.request)return;let n=t.request,s=this.collectionService.getCollection(n.collectionId);if(!s)return;let i=this.findRequestInCollection(s,n.requestId);if(i)return this.saveSuiteRequest(e,i.request),t.request.name=i.request.name||n.name,t.request.method=i.request.method||n.method,i.request}_getRequestNodes(){return(this.suite?.nodes||[]).filter(e=>e.type==="request"&&e.request).map(e=>e.request)}};Ze();function cd(r,e={}){let n=(typeof r=="string"?JSON.parse(r):r)?.log;if(!n||!Array.isArray(n.entries))throw new Error("Invalid HAR: missing log.entries");let s=n.entries.filter(a=>a?.request),i=[];for(let a of s){let c=a.request;if(e.filterHost)try{if(new URL(c.url).hostname!==e.filterHost)continue}catch{continue}let l=a.response?.status;e.skipFailed&&typeof l=="number"&&l>=400||i.push(px(a))}let o=yx(i,e.collectionName??"Imported from HAR");return{requests:i,collection:o}}function fh(r,e={}){return cd(r,e).collection}function px(r){let e=r.request,t=e.method||"GET",n=e.url||"",s=gx(t,n),i=(e.headers??[]).filter(l=>typeof l.name=="string").map(l=>({key:l.name,value:String(l.value),enabled:!0})),o=(e.queryString??[]).map(l=>({key:l.name,value:String(l.value),enabled:!0})),a=(e.cookies??[]).map(l=>({key:l.name,value:String(l.value),enabled:!0})),c=fx(e.postData,i);return{name:s,method:t,url:n,headers:i,query:o,cookies:a,body:c,responseStatus:r.response?.status,responseTimeMs:typeof r.time=="number"?r.time:void 0,responseContentType:r.response?.content?.mimeType}}function fx(r,e){if(!r)return null;let t=typeof r.text=="string"?r.text:"",n=r.mimeType||hx(e);if(!t&&r.params?.length){let s=r.params.map(i=>({key:i.name,value:String(i.value??""),enabled:!0}));return{type:n.includes("json")?"raw":"x-www-form-urlencoded",...n.includes("json")?{format:"json"}:{},content:s}}if(n.includes("json"))return{type:"raw",format:"json",content:t};if(n.includes("xml"))return{type:"raw",format:"xml",content:t};if(n.includes("html"))return{type:"raw",format:"html",content:t};if(n.includes("form-urlencoded")||n.includes("multipart")){let s=mx(t);if(s.length>0)return{type:"x-www-form-urlencoded",content:s}}return{type:"raw",format:"text",content:t}}function mx(r){try{return[...new URLSearchParams(r).entries()].map(([t,n])=>({key:t,value:n,enabled:!0}))}catch{return[]}}function hx(r){return r.find(t=>t.key.toLowerCase()==="content-type")?.value?.split(";")[0].trim()??""}function gx(r,e){try{let t=new URL(e),n=t.pathname.split("/").filter(Boolean).pop();return n?`${r} ${decodeURIComponent(n)}`:`${r} ${t.hostname}`}catch{return`${r} ${e.slice(0,80)}`}}function yx(r,e){let t=new Map,n=[];for(let s of r){let i="unknown-host";try{i=new URL(s.url).hostname}catch{}let o=t.get(i);o||(o={type:"folder",id:le(`har-${i}`),name:i,items:[]},t.set(i,o),n.push(o)),o.items.push(vx(s))}return{id:le("har-collection"),name:e,items:n,source:{format:"har",filePath:""},meta:{requestCount:r.length}}}function vx(r){let e=r.headers.map(n=>({...n}));if(r.cookies.length>0){let n=e.find(s=>s.key.toLowerCase()==="cookie");if(n){let s=r.cookies.map(i=>`${i.key}=${i.value}`).join("; ");n.value=n.value?`${n.value}; ${s}`:s}else e.push({key:"Cookie",value:r.cookies.map(s=>`${s.key}=${s.value}`).join("; "),enabled:!0})}return{type:"request",id:le(`har-${r.method}-${r.url}`),name:r.name,method:r.method,url:r.url,headers:e,query:r.query.map(n=>({...n})),body:r.body??void 0,responseSchema:r.responseStatus?{responses:{[String(r.responseStatus)]:{description:`Observed response (${r.responseTimeMs??"unknown"} ms)`,contentType:r.responseContentType}}}:void 0}}jc();go();mo();cl();ll();ul();dl();pl();fl();ml();bs();ws();Ze();Iu();export{dd as AGENTS_MD_BACKUP_FILENAME,ud as AGENTS_MD_FILENAME,Xt as AGENTS_MD_VERSION,gi as AnthropicProvider,hi as ApiArchitectService,kn as ApiDiscoveryService,ni as AwsSecretResolver,ri as AzureKeyVaultResolver,pd as BODY_FILE_MAP,Fu as CACHE_BUSTING_TOOLS,Go as COLLECTION_INPUT_SCHEMA,Wn as CONFIG_FILES,kr as CollectionLoader,js as CollectionLoaderFactory,Dt as CollectionRequestExecutor,Ls as CollectionService,an as ConfigService,ys as CookieJar,Hs as CookieService,oe as CookieUtils,se as DEFAULT_CONFIG,ze as DEFAULT_REQUEST_SETTINGS,zn as DataFileParser,si as DopplerResolver,Vs as EnvironmentConfigService,$t as EnvironmentResolver,Br as ExampleGenerator,Si as ExpressComponentAnalyzer,bn as ExpressDiscoveryProvider,Ko as FOLDER_INPUT_SCHEMA,Cn as FastApiDiscoveryProvider,wi as FastifyComponentAnalyzer,Sn as FastifyDiscoveryProvider,Os as FetchHttpClient,hs as FolderCollectionLoader,nn as FolderCollectionStore,Ac as ForgeContainer,sn as ForgeEnv,Qr as FrameworkDetector,x as GENERIC_TOOL_NAMES,ii as GcpSecretResolver,Qs as GraphQLSchemaService,bu as HTTP_METHOD_MAP,dt as HTTP_METHOD_REVERSE,oi as HashiCorpVaultResolver,Hr as HistoryAnalyzer,cs as HtmlReportGenerator,Vn as HttpForgeParser,Ft as HttpRequestService,dr as InMemoryCookieJar,Nt as InterceptorChain,Qt as JUnitReportGenerator,_r as JsonCollectionLoader,Ci as LambdaComponentAnalyzer,wn as LambdaDiscoveryProvider,Ia as MCP_PROMPTS,Me as METADATA_FILES,Bi as McpRunStore,no as ModuleLoader,xn as NestDiscoveryProvider,_s as NodeFileSystem,Bn as NodeHttpClient,Jr as NodeSocketIoClient,ui as NodeWebSocketClient,Ds as OAuth2TokenManager,ai as OnePasswordResolver,zo as OpenAiProvider,un as OpenApiExporter,Lt as OpenApiImporter,gs as ParserRegistry,Bs as PersistentCookieJar,Wo as REQUEST_INPUT_SCHEMA,on as ROOT_DIRECTORIES,Ur as RefResolver,Tr as RequestExecutor,Ys as RequestHistoryService,Ts as RequestHistoryStore,Ks as RequestPreparer,Un as RequestPreprocessor,Ps as RequestScriptSession,gr as ResultStorageService,On as SCHEMA_FILES,Ve as SCRIPTS_DIR,Wi as SCRIPT_FILES,Qo as SUITE_INPUT_SCHEMA,dn as SchemaInferenceService,ln as SchemaInferrer,Vr as ScriptAnalyzer,_t as ScriptExecutor,ci as SecretResolverRegistry,Qn as ServiceContainer,$ as ServiceIdentifiers,Sl as SocketIoClientAdapter,Rn as SpringDiscoveryProvider,od as StatisticsService,li as TestSuiteService,ad as TestSuiteStore,yt as UrlBuilder,jn as VariableInterpolator,Mn as VariableResolver,bi as analyzeComponentChainMetadata,ia as analyzeHandlerMetadata,El as applyEnvSuggestionsToItems,_g as applyExtractionPlan,xs as applyFilterChain,zt as applyMcpBodyTruncation,ka as applyRegenerated,pi as assembleBusinessContext,ac as buildAgentsMdContent,Il as buildArchitectPrompt,Ap as buildCollectionBusinessContext,zu as buildCollectionToolDescription,ju as buildCollectionToolName,cr as buildDescription,Ng as buildExtractionPlan,Ju as buildFolderToolDescription,Lu as buildFolderToolName,Zo as buildGenericTools,Zu as buildMcpToolList,mu as buildPromptResult,kl as buildRequestBusinessContext,Vu as buildRequestToolDescription,Mu as buildRequestToolName,pr as buildResultFileName,Pp as buildRunResultsContext,Wu as buildSuiteToolDescription,Hu as buildSuiteToolName,hd as cleanupOldBodyFiles,fy as clearRegisteredKnowledgeSources,lt as collectSourceFiles,Bt as collectionKnowledgeSource,Al as collectionToEndpoints,hn as combineConfidence,lr as computeProjectFreshness,oo as concatenateScripts,hl as countRequests,Ip as createDefaultKnowledgeSources,yi as createEnvAiProvider,Pr as createExpectChain,FS as createMcpRuntime,gc as createModuleLoader,ro as createMomentShim,pt as createNodeContainer,io as createResponseObject,bc as createTestFunction,Qu as decodeCursor,Tt as decodeFolderPath,yn as dedupeDiscoveredApiParameters,en as deleteItemFromTree,Pu as deserializeTypedRecord,us as deserializeTypedValue,Lo as detectEnvSuggestions,Gf as detectIndexDrift,ur as detectProjectDrift,Ii as diffLines,nr as discoverWorkflows,Nu as dispatchGenericTool,Ku as encodeCursor,$e as encodeFolderName,Pi as endpointToCreateRequestOptions,or as endpointToName,ar as endpointToRequestParts,VS as enhanceCollection,oc as ensureAgentsMdFile,qe as enumerateFolders,It as evaluateExpression,cg as exportCollectionToRestClient,Ot as extractJsonFromLlm,gn as extractPathParameters,Ee as findItemById,X as flattenRequests,Ir as formatConsoleOutput,di as gatherWorkspaceKnowledge,Gr as generateFlowFromEndpoints,le as generateId,uh as generateReleaseNotes,gt as generateSlug,fn as generateSuiteFromEndpoints,Ji as getAgentsMdPath,Sh as getAgentsMdStatus,XS as getCompletions,my as getRegisteredKnowledgeSources,Mr as getSecretValues,Ep as getServiceContainer,fh as harToCollection,qs as hasChanged,_n as isExpression,Yi as isSystemEnvironmentFile,vs as loadEnvironmentsFromFolder,ta as loadHybridSeedEndpoints,zr as normalizeFolderInput,Sc as normalizeHeaders,US as parseCurlCommand,Dn as parseFilterChain,cd as parseHar,Bu as parseMcpToolName,Mc as parsePostmanEnvironment,YS as parseQueryContext,md as prepareBodyForSave,Ca as proposeSuiteUpdates,Hi as qaEndpointKey,ic as readAgentsMdVersion,fd as readBodyFromDir,gd as readSchemaFile,Gi as readScriptsFromDir,Kc as redactFullResponse,Qc as redactFullResultDetails,St as redactHeaders,Gc as redactHistoryEntry,xh as refreshAgentsMd,$o as registerCoreServices,py as registerKnowledgeSource,Dp as renderArchitectDocs,ZS as renderQaReportTable,dh as renderReleaseNotesMarkdown,st as requestKnowledgeSource,Oi as resolveCollectionRef,yu as resolveFolderRef,Uu as resolveFolderToken,Zp as resolveProjectName,cu as resolveRegenerated,vu as resolveRequestRef,Di as resolveResultGrouping,ps as resolveToken,Aa as reviewSuiteRun,_S as runCollection,DS as runFolder,Tu as runQaCheck,NS as runRequest,No as runResultsKnowledgeSource,MS as runSuite,KS as scanCollectionForEnvVarsWithAi,ts as schemaToExample,lc as searchForItemPath,uc as searchForItemPathById,Mi as serializeTypedValue,vd as sortItemsByOrder,tr as suiteIdFromName,au as threeWayDiff,Pa as toReviewRequestResults,_p as validateDesignedSpec,ot as withAiRetry,it as workspaceKnowledgeSource,Nr as writeEnvFile,ho as writeFolderItems,yd as writeSchemaFiles,Ms as writeScriptFile,Ki as writeScriptsToDir};
|