@http-forge/core 0.6.39 → 0.6.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var rh=Object.create;var Xi=Object.defineProperty;var sh=Object.getOwnPropertyDescriptor;var ih=Object.getOwnPropertyNames;var oh=Object.getPrototypeOf,ah=Object.prototype.hasOwnProperty;var E=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var Ot=(r,e)=>{for(var t in e)Xi(r,t,{get:e[t],enumerable:!0})},ed=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ih(e))!ah.call(r,s)&&s!==t&&Xi(r,s,{get:()=>e[s],enumerable:!(n=sh(e,s))||n.enumerable});return r};var I=(r,e,t)=>(t=r!=null?rh(oh(r)):{},ed(e||!r||!r.__esModule?Xi(t,"default",{value:r,enumerable:!0}):t,r)),_n=r=>ed(Xi({},"__esModule",{value:!0}),r);function ve(r){return r.replace(/[^a-zA-Z0-9-_]/g,"_").replace(/\s+/g,"-").toLowerCase().substring(0,100)}function oe(r){let e=Date.now().toString(36)+(ch++).toString(36)+Math.random().toString(36).slice(2,7);return r?`${ve(r)}_${e}`:e}function td(){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)})}function eo(r,e){let t={},n={};for(let[s,i]of Object.entries(r)){let o=s.toLowerCase();n[o]=s,t[s]=i}for(let[s,i]of Object.entries(e)){let o=s.toLowerCase(),a=n[o];a&&delete t[a],n[o]=s,t[s]=i}return t}var ch,Ke=E(()=>{"use strict";ch=0});function Bs(r){return Pc.join(r,kc)}function to(r){let e=lh.exec(r);if(!e)return 0;let t=Number.parseInt(e[1]??"",10);return Number.isFinite(t)&&t>=0?t:0}function nd(r){let e=Bs(r);if(!De.existsSync(e))return{exists:!1,path:e,currentVersion:0,latestVersion:Bt,stale:!1};let t="";try{t=De.readFileSync(e,"utf-8")}catch{return{exists:!0,path:e,currentVersion:0,latestVersion:Bt,stale:!0}}let n=to(t);return{exists:!0,path:e,currentVersion:n,latestVersion:Bt,stale:n<Bt}}function rd(r){let e=Bs(r),t=ro();if(!De.existsSync(e))return De.mkdirSync(r,{recursive:!0}),De.writeFileSync(e,t,"utf-8"),{path:e,backupPath:null,previousVersion:0,version:Bt,created:!0};let n="";try{n=De.readFileSync(e,"utf-8")}catch{n=""}let s=to(n),i=Pc.join(r,Ic);return De.writeFileSync(i,n,"utf-8"),De.writeFileSync(e,t,"utf-8"),{path:e,backupPath:i,previousVersion:s,version:Bt,created:!1}}function no(r){let e=Bs(r);return De.existsSync(e)?!1:(De.mkdirSync(r,{recursive:!0}),De.writeFileSync(e,ro(),"utf-8"),!0)}function ro(){let r="https://raw.githubusercontent.com/hsl1230/http-forge/main/resources";return`<!-- http-forge-agents-md-version: ${Bt} -->
1
+ "use strict";var ah=Object.create;var to=Object.defineProperty;var ch=Object.getOwnPropertyDescriptor;var lh=Object.getOwnPropertyNames;var uh=Object.getPrototypeOf,dh=Object.prototype.hasOwnProperty;var E=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var Tt=(r,e)=>{for(var t in e)to(r,t,{get:e[t],enumerable:!0})},sd=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lh(e))!dh.call(r,s)&&s!==t&&to(r,s,{get:()=>e[s],enumerable:!(n=ch(e,s))||n.enumerable});return r};var I=(r,e,t)=>(t=r!=null?ah(uh(r)):{},sd(e||!r||!r.__esModule?to(t,"default",{value:r,enumerable:!0}):t,r)),jn=r=>sd(to({},"__esModule",{value:!0}),r);function Se(r){return r.replace(/[^a-zA-Z0-9-_]/g,"_").replace(/\s+/g,"-").toLowerCase().substring(0,100)}function ae(r){let e=Date.now().toString(36)+(ph++).toString(36)+Math.random().toString(36).slice(2,7);return r?`${Se(r)}_${e}`:e}function id(){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)})}function no(r,e){let t={},n={};for(let[s,i]of Object.entries(r)){let o=s.toLowerCase();n[o]=s,t[s]=i}for(let[s,i]of Object.entries(e)){let o=s.toLowerCase(),a=n[o];a&&delete t[a],n[o]=s,t[s]=i}return t}var ph,We=E(()=>{"use strict";ph=0});function Hn(r){return r._light===!0}function ro(r){r._light=!1}var Tc=E(()=>{"use strict"});function Vs(r){return Oc.join(r,$c)}function so(r){let e=fh.exec(r);if(!e)return 0;let t=Number.parseInt(e[1]??"",10);return Number.isFinite(t)&&t>=0?t:0}function od(r){let e=Vs(r);if(!je.existsSync(e))return{exists:!1,path:e,currentVersion:0,latestVersion:Ht,stale:!1};let t="";try{t=je.readFileSync(e,"utf-8")}catch{return{exists:!0,path:e,currentVersion:0,latestVersion:Ht,stale:!0}}let n=so(t);return{exists:!0,path:e,currentVersion:n,latestVersion:Ht,stale:n<Ht}}function ad(r){let e=Vs(r),t=oo();if(!je.existsSync(e))return je.mkdirSync(r,{recursive:!0}),je.writeFileSync(e,t,"utf-8"),{path:e,backupPath:null,previousVersion:0,version:Ht,created:!0};let n="";try{n=je.readFileSync(e,"utf-8")}catch{n=""}let s=so(n),i=Oc.join(r,Fc);return je.writeFileSync(i,n,"utf-8"),je.writeFileSync(e,t,"utf-8"),{path:e,backupPath:i,previousVersion:s,version:Ht,created:!1}}function io(r){let e=Vs(r);return je.existsSync(e)?!1:(je.mkdirSync(r,{recursive:!0}),je.writeFileSync(e,oo(),"utf-8"),!0)}function oo(){let r="https://raw.githubusercontent.com/hsl1230/http-forge/main/resources";return`<!-- http-forge-agents-md-version: ${Ht} -->
2
2
  # HTTP Forge \u2014 AI Agent Guide
3
3
 
4
4
  This folder is already the **HTTP Forge workspace root**. Do not create a second nested \`.http-forge/\` directory inside it.
@@ -249,19 +249,19 @@ suggest_assertions \u2192 generate pm.test() assertions for a request
249
249
  > For collection / suite / folder runs, pass \`include: ["report"]\` to generate an HTML report
250
250
  > (\`report.uri\`) \u2014 open it in a browser to inspect full response details without consuming tokens.
251
251
  > Single \`run_request\` calls do not generate a report unless \`include: ["report"]\` is also passed.
252
- `}var De,Pc,Bt,kc,Ic,lh,Tc=E(()=>{"use strict";De=I(require("fs")),Pc=I(require("path")),Bt=1,kc="AGENTS.md",Ic="AGENTS.md.bak",lh=/http-forge-agents-md-version:\s*(\d+)/});function Vs(r){if(!ae.existsSync(r))return;let e={},t=Qe.join(r,Us.preRequest);ae.existsSync(t)&&(e.preRequest=ae.readFileSync(t,"utf-8"));let n=Qe.join(r,Us.postResponse);return ae.existsSync(n)&&(e.postResponse=ae.readFileSync(n,"utf-8")),Object.keys(e).length>0?e:void 0}async function zs(r,e){await ae.promises.mkdir(r,{recursive:!0});let t=Qe.join(r,Us.preRequest);e.preRequest?await ae.promises.writeFile(t,e.preRequest,"utf-8"):ae.existsSync(t)&&await ae.promises.unlink(t);let n=Qe.join(r,Us.postResponse);e.postResponse?await ae.promises.writeFile(n,e.postResponse,"utf-8"):ae.existsSync(n)&&await ae.promises.unlink(n)}function $c(r){for(let[e,t]of Object.entries(Oc)){let n=Qe.join(r,e);if(ae.existsSync(n))try{let s=ae.readFileSync(n,"utf-8"),i;if(t.type==="graphql")try{i=JSON.parse(s)}catch{i=s}else i=s;return{type:t.type,format:t.format,content:i}}catch(s){console.error(`[FolderIO] Failed to load body from ${n}:`,s)}}}function Fc(r){if(!r||r.type==="none")return{bodyForMetadata:r};if(r.type==="raw"){let e=r.format||"json",n={json:"body.json",xml:"body.xml",text:"body.txt",html:"body.html",javascript:"body.js"}[e];if(n){let s=e==="json"?typeof r.content=="string"?r.content:JSON.stringify(r.content,null,2):String(r.content||"");return{bodyForMetadata:{type:r.type,format:r.format},externalBodyFile:{filename:n,content:s}}}}if(r.type==="graphql"){let e=typeof r.content=="string"?r.content:JSON.stringify(r.content,null,2);return{bodyForMetadata:{type:r.type},externalBodyFile:{filename:"body.graphql",content:e}}}return{bodyForMetadata:r}}async function Nc(r,e){for(let t of Object.keys(Oc))if(t!==e){let n=Qe.join(r,t);if(ae.existsSync(n))try{await ae.promises.unlink(n)}catch{}}}function Mc(r){if(ae.existsSync(r))try{let e=ae.readFileSync(r,"utf-8");return JSON.parse(e)}catch(e){console.error(`[FolderIO] Failed to load schema file ${r}:`,e);return}}async function _c(r,e,t){let n=Qe.join(r,Tr.responseSchema),s=Qe.join(r,Tr.bodySchema);e?await ae.promises.writeFile(n,JSON.stringify(e,null,2),"utf-8"):ae.existsSync(n)&&await ae.promises.unlink(n),t?await ae.promises.writeFile(s,JSON.stringify(t,null,2),"utf-8"):ae.existsSync(s)&&await ae.promises.unlink(s)}function xe(r,e){for(let t of r){if(t.id===e)return t;if(t.type==="folder"&&t.items){let n=xe(t.items,e);if(n)return n}}}function Ut(r,e){for(let t=0;t<r.length;t++){let n=r[t];if(n.id===e)return r.splice(t,1),!0;if(n.type==="folder"&&n.items&&Ut(n.items,e))return!0}return!1}function Dc(r,e){let t=new Map(r.map(s=>[s.id,s])),n=[];for(let s of e){let i=t.get(s);i&&(n.push(i),t.delete(s))}for(let s of t.values())n.push(s);return n}function so(r,e){let t;try{t=ae.readdirSync(r,{withFileTypes:!0})}catch{return}for(let n of t){if(!n.isDirectory()||n.name===Be)continue;if(n.name===e)return Qe.join(r,n.name);let s=so(Qe.join(r,n.name),e);if(s)return s}}function uh(r){for(let e of[Oe.request,Oe.folder]){let t=Qe.join(r,e);if(ae.existsSync(t))try{let n=ae.readFileSync(t,"utf-8");return JSON.parse(n).id}catch{return}}}function io(r,e){let t;try{t=ae.readdirSync(r,{withFileTypes:!0})}catch{return}for(let n of t){if(!n.isDirectory()||n.name===Be)continue;let s=Qe.join(r,n.name);if(uh(s)===e)return s;let i=io(s,e);if(i)return i}}function ct(r,e=[]){let t=r.toLowerCase().trim(),n=t.match(/^(get|post|put|patch|delete|head|options)[_\s-]/i),s=n?n[1]:"",i=t.match(/t(\d+)/gi)||[],o=0;for(let p of i){let m=parseInt(p.substring(1));m>o&&(o=m)}let a="";if(o>0)a=`t${o}`;else{let p=t.match(/[_\s-](\d+\.\d+)[_\s-]/);p&&(a=`v${p[1].replace(".","_")}`)}let c=t;n&&(c=c.substring(n[0].length)),c=c.replace(/[_\s-]?t\d+(?:\.\d+)?[_\s-]?/gi,"-"),c=c.replace(/[_\s-]?\d+\.\d+[_\s-]?/g,"-"),c=c.replace(/\([^)]+\)/g,""),c=c.replace(/:[a-z_][a-z0-9_]*/gi,""),c=c.replace(/\{[^}]+\}/g,""),c=c.replace(/\?$/g,"").replace(/[_/\\ ]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");let l=c.split("-").filter(p=>p.length>0),u=[];s&&u.push(s),u.push(...l),a&&u.push(a);let d=u.join("-");if(d||(d="item"),e.includes(d)){let p=2;for(;e.includes(`${d}-${p}`);)p++;d=`${d}-${p}`}return d}var ae,Qe,Us,Oe,Oc,Tr,Be,dn=E(()=>{"use strict";ae=I(require("fs")),Qe=I(require("path")),Us={preRequest:"pre-request.js",postResponse:"post-response.js"},Oe={collection:"collection.json",folder:"folder.json",request:"request.json"},Oc={"body.json":{type:"raw",format:"json"},"body.xml":{type:"raw",format:"xml"},"body.txt":{type:"raw",format:"text"},"body.html":{type:"raw",format:"html"},"body.js":{type:"raw",format:"javascript"},"body.graphql":{type:"graphql"}},Tr={responseSchema:"response.schema.json",bodySchema:"body.schema.json"},Be="scripts"});var G,W,jc,Vt,oo=E(()=>{"use strict";G=I(require("fs")),W=I(require("path"));Ke();Tc();dn();jc={collection:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/collection.schema.json",folder:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/folder.schema.json",request:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/request.schema.json"},Vt=class{collectionsDir;cache=new Map;slugToIdMap=new Map;idToSlugMap=new Map;constructor(e){this.collectionsDir=e}getSlugById(e){return this.idToSlugMap.get(e)}getIdBySlug(e){return this.slugToIdMap.get(e)}ensureDirectory(){G.existsSync(this.collectionsDir)||G.mkdirSync(this.collectionsDir,{recursive:!0}),this.ensureAgentsMd()}ensureAgentsMd(){let e=W.resolve(this.collectionsDir,"..","..");try{no(e)}catch{}}readJsonFileSafe(e,t){let n;try{n=G.readFileSync(e,"utf-8")}catch(s){console.error(`[FolderCollectionStore] Failed to read ${t} ${e}:`,s);return}if(n.trim().length!==0)try{return JSON.parse(n)}catch(s){if(s instanceof SyntaxError&&/Unexpected end of JSON input/.test(s.message))return;console.error(`[FolderCollectionStore] Failed to parse ${t} ${e}:`,s);return}}loadAll(){if(this.cache.clear(),this.slugToIdMap.clear(),this.idToSlugMap.clear(),!G.existsSync(this.collectionsDir))return[];let e=G.readdirSync(this.collectionsDir,{withFileTypes:!0}),t=[];for(let n of e)if(n.isDirectory())try{let s=this.loadCollectionFromFolder(n.name);s&&(this.cache.set(s.id,s),this.slugToIdMap.set(n.name,s.id),this.idToSlugMap.set(s.id,n.name),t.push(s))}catch(s){console.error(`[FolderCollectionStore] Failed to load ${n.name}:`,s)}return t}loadCollectionFromFolder(e){let t=W.join(this.collectionsDir,e),n=W.join(t,Oe.collection);if(!G.existsSync(n))return;let s=this.readJsonFileSafe(n,"collection");if(s)try{let i=this.loadScriptsFromDir(W.join(t,Be)),o=this.loadItemsFromDir(t,s.id,s.order);return{id:s.id,name:s.name,description:s.description,version:s.version,variables:s.variables,auth:s.auth,scripts:i,items:o}}catch(i){console.error(`[FolderCollectionStore] Failed to parse ${n}:`,i);return}}loadItemsFromDir(e,t,n){let s=[],i=new Map,o=G.readdirSync(e,{withFileTypes:!0});for(let a of o){if(!a.isDirectory()||a.name===Be)continue;let c=W.join(e,a.name);if(G.existsSync(W.join(c,Oe.folder))){let l=this.loadFolderFromDir(c,a.name);l&&i.set(a.name,l)}else if(G.existsSync(W.join(c,Oe.request))){let l=this.loadRequestFromDir(c,a.name);l&&i.set(a.name,l)}}if(n&&n.length>0){for(let a of n){let c=i.get(a);c&&(s.push(c),i.delete(a))}for(let a of i.values())s.push(a)}else for(let a of i.values())s.push(a);return s}loadFolderFromDir(e,t){let n=W.join(e,Oe.folder),s=this.readJsonFileSafe(n,"folder");if(s)try{let i=this.loadScriptsFromDir(W.join(e,Be)),o=this.loadItemsFromDir(e,s.id,s.order);return this.slugToIdMap.set(t,s.id),this.idToSlugMap.set(s.id,t),{id:s.id,type:"folder",name:s.name,description:s.description,auth:s.auth,scripts:i,items:o}}catch(i){console.error(`[FolderCollectionStore] Failed to load folder ${e}:`,i);return}}loadRequestFromDir(e,t){let n=W.join(e,Oe.request),s=this.readJsonFileSafe(n,"request");if(s)try{let i=this.loadScriptsFromDir(W.join(e,Be)),o=s.body,a=this.loadBodyFromDir(e);a&&(o=a);let c=this.loadSchemaFile(W.join(e,Tr.responseSchema)),l=this.loadSchemaFile(W.join(e,Tr.bodySchema)),u=W.join(e,"doc.md"),d=G.existsSync(u)?G.readFileSync(u,"utf-8"):void 0;return this.slugToIdMap.set(t,s.id),this.idToSlugMap.set(s.id,t),{id:s.id,type:"request",name:s.name,description:s.description,method:s.method,url:s.url,params:s.params,query:s.query,headers:s.headers,body:o,bodyContentType:s.bodyContentType,auth:s.auth,settings:s.settings,scripts:i,disabled:s.disabled,deprecated:s.deprecated,operationId:s.operationId,summary:s.summary,tags:s.tags,examples:s.examples,responses:s.responses,security:s.security,...d&&{doc:d},...c&&{responseSchema:c},...l&&{bodySchema:l}}}catch(i){console.error(`[FolderCollectionStore] Failed to load request ${e}:`,i);return}}loadScriptsFromDir(e){return Vs(e)}loadBodyFromDir(e){return $c(e)}loadSchemaFile(e){return Mc(e)}async saveSchemaFiles(e,t){return _c(e,t.responseSchema,t.bodySchema)}load(e){if(this.cache.has(e))return this.cache.get(e);let t=this.idToSlugMap.get(e);if(t){let n=this.loadCollectionFromFolder(t);return n&&this.cache.set(e,n),n}return this.loadAll(),this.cache.get(e)}async save(e){if(this.ensureDirectory(),!e.name)throw new Error("Collection name is required");e.id||(e.id=oe(e.name));let t=this.idToSlugMap.get(e.id);if(!t){let c=G.readdirSync(this.collectionsDir);t=ct(e.name,c),this.idToSlugMap.set(e.id,t),this.slugToIdMap.set(t,e.id)}let n=W.join(this.collectionsDir,t),s=!G.existsSync(n);await G.promises.mkdir(n,{recursive:!0});let i={id:e.id,name:e.name,description:e.description,version:e.version,variables:e.variables,auth:e.auth},[o]=await Promise.all([this.saveItemsToDir(n,e.items,s),e.scripts?this.saveScriptsToDir(W.join(n,Be),e.scripts):Promise.resolve()]);o.length>0&&(i.order=o);let a={$schema:jc.collection,...i};await G.promises.writeFile(W.join(n,Oe.collection),JSON.stringify(a,null,2),"utf-8"),this.cache.set(e.id,e)}async saveItemsToDir(e,t,n=!1){let s=[],i=[];for(let o of t){let a=this.idToSlugMap.get(o.id);a||(a=ct(o.name,s),this.idToSlugMap.set(o.id,a),this.slugToIdMap.set(a,o.id)),s.push(a),i.push({item:o,slug:a})}return await Promise.all(i.map(async({item:o,slug:a})=>{let c=W.join(e,a);await G.promises.mkdir(c,{recursive:!0}),o.type==="folder"?await this.saveFolderToDir(c,o,n):await this.saveRequestToDir(c,o,n)})),s}async saveFolderToDir(e,t,n=!1){let s={id:t.id,name:t.name,description:t.description,auth:t.auth},[i]=await Promise.all([t.items?this.saveItemsToDir(e,t.items,n):Promise.resolve([]),t.scripts?this.saveScriptsToDir(W.join(e,Be),t.scripts):Promise.resolve()]);i.length>0&&(s.order=i);let o={$schema:jc.folder,...s};await G.promises.writeFile(W.join(e,Oe.folder),JSON.stringify(o,null,2),"utf-8")}async saveRequestToDir(e,t,n=!1){let{bodyForMetadata:s,externalBodyFile:i}=this.prepareBodyForSave(t.body),o={id:t.id,name:t.name,method:t.method||"GET",url:t.url||"",description:t.description,params:t.params,query:t.query,headers:t.headers,body:s,bodyContentType:t.bodyContentType,auth:t.auth,settings:t.settings,...t.disabled!==void 0&&{disabled:t.disabled},...t.deprecated&&{deprecated:t.deprecated},...t.operationId&&{operationId:t.operationId},...t.summary&&{summary:t.summary},...t.tags&&t.tags.length>0&&{tags:t.tags},...t.examples&&t.examples.length>0&&{examples:t.examples},...t.responses&&Object.keys(t.responses).length>0&&{responses:t.responses},...t.security&&t.security.length>0&&{security:t.security}},a=[G.promises.writeFile(W.join(e,Oe.request),JSON.stringify({$schema:jc.request,...o},null,2),"utf-8")];i&&a.push(G.promises.writeFile(W.join(e,i.filename),i.content,"utf-8")),n||a.push(this.cleanupOldBodyFiles(e,i?.filename)),(!n||t.responseSchema||t.bodySchema)&&a.push(this.saveSchemaFiles(e,t)),t.doc&&a.push(G.promises.writeFile(W.join(e,"doc.md"),t.doc,"utf-8")),t.scripts&&a.push(this.saveScriptsToDir(W.join(e,Be),t.scripts)),await Promise.all(a)}prepareBodyForSave(e){return Fc(e)}async cleanupOldBodyFiles(e,t){return Nc(e,t)}async saveScriptsToDir(e,t){return zs(e,t)}async delete(e){let t=this.idToSlugMap.get(e);if(!t&&(this.loadAll(),t=this.idToSlugMap.get(e),!t))return!1;let n=W.join(this.collectionsDir,t);if(!G.existsSync(n))return!1;try{return await G.promises.rm(n,{recursive:!0,force:!0}),this.cache.delete(e),this.idToSlugMap.delete(e),this.slugToIdMap.delete(t),!0}catch(s){return console.error(`[FolderCollectionStore] Failed to delete collection ${e}:`,s),!1}}exists(e){let t=this.idToSlugMap.get(e);return t?G.existsSync(W.join(this.collectionsDir,t,Oe.collection)):!1}getCollectionPath(e){let t=this.idToSlugMap.get(e)||e;return W.join(this.collectionsDir,t)}getItemPath(e,t){return this.findItemPath(e,t)}async create(e,t){let n={id:t||oe(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=this.findItemPath(e,t);if(!i)throw new Error(`Item ${t} not found in collection ${e}`);await this.saveScriptsToDir(W.join(i,Be),n);let o=this.findItemById(s.items,t);o&&(o.scripts=n)}loadScripts(e,t){let n=this.findItemPath(e,t);if(n)return this.loadScriptsFromDir(W.join(n,Be))}async updateCollectionMetadata(e,t){let n=this.load(e);if(!n)throw new Error(`Collection ${e} not found`);let s=this.idToSlugMap.get(e);if(!s)throw new Error(`Collection slug not found for ${e}`);let i=W.join(this.collectionsDir,s),o=W.join(i,Oe.collection),a=G.readFileSync(o,"utf-8"),l={...JSON.parse(a),...t,id:e};await G.promises.writeFile(o,JSON.stringify(l,null,2),"utf-8"),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)}async saveItem(e,t,n){let s=this.load(e);if(!s)throw new Error(`Collection ${e} not found`);let i=this.idToSlugMap.get(e);if(!i)throw new Error(`Collection slug not found for ${e}`);let o;if(n){let u=this.findItemPath(e,n);if(!u)throw new Error(`Parent folder ${n} not found`);o=u}else o=W.join(this.collectionsDir,i);let a=this.idToSlugMap.get(t.id);if(!a){let u=G.readdirSync(o).filter(d=>G.statSync(W.join(o,d)).isDirectory()&&d!==Be);a=ct(t.name,u),this.idToSlugMap.set(t.id,a),this.slugToIdMap.set(a,t.id)}let c=W.join(o,a);await G.promises.mkdir(c,{recursive:!0}),t.type==="folder"?await this.saveFolderToDir(c,t):await this.saveRequestToDir(c,t);let l=this.findItemById(s.items,t.id);if(l)Object.assign(l,t);else if(n){let u=this.findItemById(s.items,n);u&&u.type==="folder"&&(u.items=u.items||[],u.items.push(t))}else s.items.push(t)}async deleteItem(e,t){let n=this.load(e);if(!n)return!1;let s=this.findItemPath(e,t);if(!s||!G.existsSync(s))return!1;try{await G.promises.rm(s,{recursive:!0,force:!0}),this.deleteItemFromTree(n.items,t);let i=this.idToSlugMap.get(t);return i&&(this.slugToIdMap.delete(i),this.idToSlugMap.delete(t)),!0}catch(i){return console.error(`[FolderCollectionStore] Failed to delete item ${t}:`,i),!1}}async updateItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=this.findItemPath(e,t);if(!i)return!1;let o=this.findItemById(s.items,t);if(!o)return!1;let{id:a,type:c,items:l,...u}=n;return Object.assign(o,u),o.type==="folder"?await this.saveFolderToDir(i,o):await this.saveRequestToDir(i,o),!0}async moveItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=this.idToSlugMap.get(e);if(!i)return!1;let o=this.findItemPath(e,t);if(!o||!G.existsSync(o))return!1;let a;if(n){let u=this.findItemPath(e,n);if(!u)return!1;a=u}else a=W.join(this.collectionsDir,i);let c=this.idToSlugMap.get(t);if(!c)return!1;let l=W.join(a,c);if(G.existsSync(l))return!1;try{await G.promises.rename(o,l);let u=this.findItemById(s.items,t);if(u){let d=u.type==="folder"?{...u,items:u.items?[...u.items]:[]}:{...u};if(this.deleteItemFromTree(s.items,t),n){let p=this.findItemById(s.items,n);p&&p.type==="folder"&&(p.items=p.items||[],p.items.push(d))}else s.items.push(d)}return!0}catch(u){return console.error(`[FolderCollectionStore] Failed to move item ${t}:`,u),!1}}async reorderItems(e,t,n){let s=this.load(e);if(!s)return!1;let i=this.idToSlugMap.get(e);if(!i)return!1;let o=[];for(let a of n){let c=this.idToSlugMap.get(a);c&&o.push(c)}try{if(t){let a=this.findItemPath(e,t);if(!a)return!1;let c=W.join(a,Oe.folder),l=G.readFileSync(c,"utf-8"),u=JSON.parse(l);u.order=o,await G.promises.writeFile(c,JSON.stringify(u,null,2),"utf-8");let d=this.findItemById(s.items,t);d&&d.type==="folder"&&d.items&&(d.items=this.sortItemsByOrder(d.items,n))}else{let a=W.join(this.collectionsDir,i,Oe.collection),c=G.readFileSync(a,"utf-8"),l=JSON.parse(c);l.order=o,await G.promises.writeFile(a,JSON.stringify(l,null,2),"utf-8"),s.items=this.sortItemsByOrder(s.items,n)}return!0}catch(a){return console.error("[FolderCollectionStore] Failed to reorder items:",a),!1}}sortItemsByOrder(e,t){return Dc(e,t)}findItemPath(e,t){let n=this.idToSlugMap.get(e);if(!n)return;let s=W.join(this.collectionsDir,n),i=io(s,t);if(i)return i;let o=this.load(e);if(o){let c=this.buildSlugPath(o.items,t);if(c)return W.join(s,...c)}let a=this.idToSlugMap.get(t);if(a)return so(s,a)}buildSlugPath(e,t){for(let n of e){let s=this.idToSlugMap.get(n.id);if(s){if(n.id===t)return[s];if(n.type==="folder"&&n.items){let i=this.buildSlugPath(n.items,t);if(i)return[s,...i]}}}}findItemById(e,t){return xe(e,t)}deleteItemFromTree(e,t){return Ut(e,t)}}});var ie,jn=E(()=>{"use strict";ie=class{static parseSetCookie(e,t){let n=e.split(";").map(u=>u.trim());if(n.length===0)return null;let[s,...i]=n,o=s.indexOf("=");if(o===-1)return null;let a=s.substring(0,o).trim(),c=s.substring(o+1).trim(),l={name:a,value:c,domain:t};for(let u of i){let d=u.indexOf("="),p=(d===-1?u:u.substring(0,d)).toLowerCase(),m=d===-1?"":u.substring(d+1);switch(p){case"domain":l.domain=m.startsWith(".")?m.substring(1):m;break;case"path":l.path=m;break;case"expires":l.expires=m;break;case"max-age":l.maxAge=parseInt(m,10);break;case"httponly":l.httpOnly=!0;break;case"secure":l.secure=!0;break;case"samesite":l.sameSite=m;break}}return l}static parseCookieHeaders(e,t){let n=[],s=e["set-cookie"]||e["Set-Cookie"];if(!s)return n;let i=Array.isArray(s)?s:[s];for(let o of i){let a=this.parseSetCookie(o,t);a&&n.push(a)}return n}static formatCookieHeader(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}static cookieKey(e,t,n){return`${t||"*"}|${n||"/"}|${e}`}static isExpired(e){return!!(e.expires&&new Date(e.expires).getTime()<Date.now()||e.maxAge!==void 0&&e.maxAge<=0)}static domainMatches(e,t){if(t==="*")return!0;let n=e.toLowerCase().split(".").reverse(),s=t.toLowerCase().split(".").reverse();if(s.length>n.length)return!1;for(let i=0;i<s.length;i++)if(s[i]!==n[i])return!1;return!0}static extractDomain(e){try{return new URL(e).hostname}catch{return""}}static extractPath(e){try{return new URL(e).pathname}catch{return"/"}}}});function Js(r){let e=r.toLowerCase();return e==="_global.json"||e==="_global.local.json"||e.endsWith(".local.json")}function Nr(r){if(!pn.existsSync(r))return ph();let e=ao(Ln.join(r,"_global.json"))||{},t=e.variables||{},n=e.defaultHeaders||{},s=pn.readdirSync(r).filter(l=>l.endsWith(".json")).filter(l=>!l.endsWith(".local.json")).filter(l=>!Js(l)),i={};for(let l of s){let u=ao(Ln.join(r,l))||{},d=Ln.basename(l,".json");i[d]={description:u.description,requiresConfirmation:u.requiresConfirmation,variables:u.variables||{},secretVariables:u.secretVariables}}let a=(ao(Ln.join(r,"_global.local.json"))||{}).variables||{},c={};for(let l of Object.keys(i)){let u=Ln.join(r,`${l}.local.json`);if(pn.existsSync(u)){let d=ao(u)||{};c[l]={variables:d.variables||{}}}}return{globalVariables:t,defaultHeaders:n,environments:i,localVariables:a,localCredentials:c}}function ph(){return{globalVariables:{},defaultHeaders:{},environments:{},localVariables:{},localCredentials:{}}}function ao(r){try{if(!pn.existsSync(r))return null;let e=pn.readFileSync(r,"utf-8");return JSON.parse(e)}catch(e){return console.error(`[environment-file-loader] Failed to load JSON from ${r}:`,e),null}}var pn,Ln,co=E(()=>{"use strict";pn=I(require("fs")),Ln=I(require("path"))});var lt,Mr=E(()=>{"use strict";lt=class{buildUrl(e,t={},n={}){let s=e;return s=this.replacePathParams(s,t),s=this.appendQueryParams(s,n),s}replacePathParams(e,t){let n="",s="",i=e,o="",a=e.indexOf("?");a!==-1&&(o=e.substring(a),i=e.substring(0,a));let c=i.match(/^(https?:\/\/)([^\/]*)(\/.*)?$/);c&&(n=c[1],s=c[2],i=c[3]||"/");let l=/:(\w+)(?:\([^)]*\))?(\?)?/g,u=i.replace(l,(d,p,m)=>{let f=t[p];return f!==void 0&&f!==""?encodeURIComponent(f):m?"":(console.warn(`[UrlBuilder] Missing required path parameter: ${p}`),d)});return u=u.replace(/([^:])\/+/g,"$1/"),`${n}${s}${u}${o}`}extractPathParams(e){let t=/:(\w+)(?:\([^)]*\))?(\?)?/g,n=[],s;for(;(s=t.exec(e))!==null;)n.push(s[1]);return[...new Set(n)]}appendQueryParams(e,t){let n=e,s={};if(e.includes("?")){let[c,l]=e.split("?");n=c,l&&new URLSearchParams(l).forEach((d,p)=>{s[p]=d})}let i={...s,...t},o=new URLSearchParams;for(let[c,l]of Object.entries(i))l!=null&&o.append(c,l);let a=o.toString();return a?`${n}?${a}`:n}}});function fh(r=0,e=999){return Math.floor(Math.random()*(e-r+1))+r}function mh(){return Date.now()}function id(){return(0,Bc.v4)()}function hh(){return(0,Bc.v4)()}function od(r=10){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let n=0;n<r;n++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function gh(){let r=od(8).toLowerCase(),e=["example.com","test.org","mail.dev","sample.net"];return`${r}@${e[Math.floor(Math.random()*e.length)]}`}function yh(){return Math.random()<.5}function vh(r=10){let e="0123456789abcdef",t="";for(let n=0;n<r;n++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function bh(){return Math.floor(Date.now()/1e3)}function Sh(){return new Date().toISOString()}function xh(){return new Date().toISOString().split("T")[0]}function wh(){return new Date().toISOString().split("T")[1].split(".")[0]}function Rh(){return new Date().toISOString()}function Ch(r=""){return Buffer.from(String(r)).toString("base64")}function Eh(r=""){return Buffer.from(String(r),"base64").toString("utf-8")}function Ah(r=""){return encodeURIComponent(String(r))}function qh(r=""){return decodeURIComponent(String(r))}function Hn(r,e){let t=Ph[r];return t?e&&e.length>0?t(...e):t():null}function _r(r,e){let t=/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,n=null,s;for(;(s=t.exec(r))!==null;){let i=s[0],o=s[1];if(!(i in e)){let a=Hn(o);a!==null&&(n||(n={...e}),n[i]=a)}}return n??e}var Bc,Ph,Uc=E(()=>{"use strict";Bc=require("uuid");Ph={randomInt:fh,timestamp:mh,guid:hh,uuid:id,randomUUID:id,randomString:od,randomHexadecimal:vh,randomEmail:gh,randomBoolean:yh,isoTimestamp:Rh,timestamp_s:bh,datetime:Sh,date:xh,time:wh,base64Encode:Ch,base64Decode:Eh,urlEncode:Ah,urlDecode:qh}});function fn(r){let e=r.trim();return!e||/^(\$?)[a-zA-Z_][a-zA-Z0-9_]*(\([^)]*\))?$/.test(e)||/(?<!\|)\|(?!\|)/.test(e)?!1:/[+\-*/%<>=!&|?:~^()[\]{}.,`]/.test(e)}function yt(r,e={}){try{let t={...e,Math,Date,JSON,Number,String,Boolean,Array,Object,parseInt,parseFloat,isNaN,isFinite,encodeURIComponent,decodeURIComponent,encodeURI,decodeURI,undefined:void 0,null:null,true:!0,false:!1,NaN:NaN,Infinity:1/0},n=lo.createContext(t);return lo.runInContext(r,n,{timeout:kh,displayErrors:!1})}catch{return}}var lo,kh,Gs=E(()=>{"use strict";lo=I(require("vm")),kh=100});function Ih(r){if(typeof r=="string"&&r.charCodeAt(0)===30)try{return JSON.parse(r.slice(1))}catch{return r}return r}function Dr(r){if(!r||!r.includes("|"))return null;let e=Th(r);if(e.length<2)return null;let t=e[0].trim(),n=[];for(let s=1;s<e.length;s++){let i=e[s].trim();if(!i)continue;let o=Oh(i);o&&n.push(o)}return n.length===0?null:{input:t,filters:n}}function Th(r){let e=[],t="",n=0,s=!1,i=!1;for(let o=0;o<r.length;o++){let a=r[o],c=o>0?r[o-1]:"",l=o<r.length-1?r[o+1]:"";if(c==="\\"){t+=a;continue}if(a==="'"&&!i)s=!s;else if(a==='"'&&!s)i=!i;else if(a==="("&&!s&&!i)n++;else if(a===")"&&!s&&!i)n--;else if(a==="|"&&n===0&&!s&&!i){if(l==="|"){t+="||",o++;continue}e.push(t),t="";continue}t+=a}return t&&e.push(t),e}function Oh(r){let e=r.indexOf("(");if(e===-1)return{name:r.trim(),args:[]};let t=r.substring(0,e).trim(),n=r.substring(e+1,r.lastIndexOf(")"));return{name:t,args:$h(n)}}function $h(r){if(!r||!r.trim())return[];let e=[],t="",n=!1,s=!1;for(let i=0;i<r.length;i++){let o=r[i];if((i>0?r[i-1]:"")==="\\"){t+=o;continue}if(o==="'"&&!s){n=!n,t+=o;continue}else if(o==='"'&&!n){s=!s,t+=o;continue}else if(o===","&&!n&&!s){e.push(t.trim()),t="";continue}t+=o}return t.trim()&&e.push(t.trim()),e}function ge(r,e){if(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))return r.slice(1,-1);let t=Number(r);if(!isNaN(t)&&r!=="")return t;if(r==="true")return!0;if(r==="false")return!1;if(e&&r in e){let n=Ih(e[r]),s=Number(n);return!isNaN(s)&&n!==""?s:n}return r}function jr(r,e,t={}){let n=r;for(let s of e)n=Fh(n,s.name,s.args,t);return n}function Fh(r,e,t,n){switch(e){case"upper":return String(r).toUpperCase();case"lower":return String(r).toLowerCase();case"trim":return String(r).trim();case"length":return Array.isArray(r)?r.length:String(r).length;case"substring":{let s=ge(t[0],n),i=t[1]!==void 0?ge(t[1],n):void 0;return String(r).substring(s<0?String(r).length+s:s,i!==void 0?i<0?String(r).length+i:i:void 0)}case"replace":{let s=t[0]!==void 0?String(ge(t[0],n)):"",i=t[1]!==void 0?String(ge(t[1],n)):"";return String(r).replace(new RegExp(Mh(s),"g"),i)}case"split":{let s=t[0]!==void 0?String(ge(t[0],n)):",";return String(r).split(s)}case"join":{let s=t[0]!==void 0?String(ge(t[0],n)):",";return Array.isArray(r)?r.join(s):String(r)}case"removeQuotes":return String(r).replace(/["']/g,"");case"removeSpaces":return String(r).replace(/\s/g,"");case"format":{let s=t[0]!==void 0?String(ge(t[0],n)):"{0}";s=s.replace("{0}",String(r));for(let i=1;i<t.length;i++){let o=ge(t[i],n);s=s.replace(`{${i}}`,String(o))}return s}case"add":{let s=ge(t[0],n);return Number(r)+s}case"subtract":{let s=ge(t[0],n);return Number(r)-s}case"multiply":{let s=ge(t[0],n);return Number(r)*s}case"abs":return Math.abs(Number(r));case"btoa":return Buffer.from(String(r)).toString("base64");case"atob":return Buffer.from(String(r),"base64").toString("utf-8");case"urlEncode":return encodeURIComponent(String(r));case"urlDecode":return decodeURIComponent(String(r));case"hash":{let s=String(t[0]!==void 0?ge(t[0],n):"md5").toLowerCase(),i=String(t[1]!==void 0?ge(t[1],n):"base64"),a={md5:"md5",sha1:"sha1",sha256:"sha256",sha512:"sha512"}[s]||"md5";return uo.createHash(a).update(String(r)).digest(i)}case"hmac":{let s=t[0]?String(ge(t[0],n)):"",i=String(t[1]!==void 0?ge(t[1],n):"sha256").toLowerCase(),o=String(t[2]!==void 0?ge(t[2],n):"base64"),c={md5:"md5",sha1:"sha1",sha256:"sha256",sha512:"sha512"}[i]||"sha256";return uo.createHmac(c,s).update(String(r)).digest(o)}case"first":return Array.isArray(r)?r[0]:r;case"last":return Array.isArray(r)?r[r.length-1]:r;case"at":{let s=ge(t[0],n);return Array.isArray(r)?r.at(s):r}case"slice":{let s=ge(t[0],n),i=t[1]!==void 0?ge(t[1],n):void 0;return Array.isArray(r)?r.slice(s,i):String(r).slice(s,i)}case"unique":return Array.isArray(r)?[...new Set(r)]:r;case"filter":return!Array.isArray(r)||!t[0]?r:Nh(r,t[0],n);case"map":{if(!Array.isArray(r))return r;let s=t.map(i=>String(ge(i,n)));return s.length===1?r.map(i=>Ws(i,s[0])):r.map(i=>{let o={};for(let a of s){let c=Ws(i,a);c!==void 0&&(o[a]=c)}return o})}case"prop":{let s=t[0]!==void 0?String(ge(t[0],n)):"";if(Array.isArray(r)){let i=r.map(o=>Ws(o,s)).filter(o=>o!==void 0);return i.length===1?i[0]:i.join(",")}return r&&typeof r=="object"?Ws(r,s):r}case"parseJSON":try{return JSON.parse(String(r))}catch{return r}case"stringify":try{return JSON.stringify(r)}catch{return String(r)}case"isEmail":return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(r));case"isUrl":try{return new URL(String(r)),!0}catch{return!1}case"setIfValue":return r||void 0;case"setNull":return r===null?null:r;default:return r}}function Nh(r,e,t){let n=e.match(/^([\w.]+)\s*(>=|<=|!=|\*=|\^=|\$=|>|<|=)\s*(.+)$/);if(!n)return r;let[,s,i,o]=n,a=ge(o,t);return r.filter(c=>{let l=Ws(c,s);if(l===void 0)return!1;switch(i){case">":return Number(l)>Number(a);case">=":return Number(l)>=Number(a);case"<":return Number(l)<Number(a);case"<=":return Number(l)<=Number(a);case"=":return String(l)===String(a);case"!=":return String(l)!==String(a);case"*=":return String(l).includes(String(a));case"^=":return String(l).startsWith(String(a));case"$=":return String(l).endsWith(String(a));default:return!0}})}function Ws(r,e){if(!(!r||typeof r!="object"))return e in r?r[e]:e.split(".").reduce((t,n)=>t?.[n],r)}function Mh(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var uo,po=E(()=>{"use strict";uo=I(require("crypto"))});function Ks(r,e){if(r)return r.split(",").map(t=>{let n=t.trim();if(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))return n.slice(1,-1);let s=Number(n);if(!isNaN(s)&&n!=="")return s;if(e&&n in e){let i=e[n],o=Number(i);return!isNaN(o)&&i!==""?o:i}return n})}var mn,hn,Lr=E(()=>{"use strict";Uc();Gs();po();mn=class r{allVariables;static MAX_RESOLUTION_DEPTH=20;constructor(e){this.allVariables={...e.globals,...e.collectionVariables,...e.environmentVariables,...e.variables}}resolveString(e,t=!1){return typeof e!="string"?e:this.resolveUntilStable(e,this.allVariables,t)}resolveStringWithExtra(e,t,n=!1){if(typeof e!="string")return e;let s={...this.allVariables,...t};return this.resolveUntilStable(e,s,n)}resolveUntilStable(e,t,n){let s=e;for(let i=0;i<r.MAX_RESOLUTION_DEPTH;i++){let o=this.resolveSinglePass(s,t,n);if(o===s)break;s=o}return s}resolveSinglePass(e,t,n){if(!n)return e.replace(/\{\{((?:[^}]|\}(?!\}))+)\}\}/g,(c,l)=>this.resolveTemplateContent(l.trim(),t,c));let s="",i=0,o=/\{\{((?:[^}]|\}(?!\}))+)\}\}/g,a;for(;(a=o.exec(e))!==null;){let c=a[1].trim(),l=this.resolveTemplateContent(c,t,a[0]);if(l!==a[0]){s+=e.slice(i,a.index);let u=this.getStringContext(e,a.index);s+=u?this.escapeForString(String(l),u):String(l)}else s+=e.slice(i,a.index+a[0].length);i=a.index+a[0].length}return s+=e.slice(i),s}resolveObject(e,t=!1){if(typeof e=="string")return this.resolveString(e,t);if(Array.isArray(e))return e.map(n=>this.resolveObject(n,t));if(e!==null&&typeof e=="object"){let n={};for(let[s,i]of Object.entries(e))n[s]=this.resolveObject(i,t);return n}return e}resolveObjectWithExtra(e,t,n=!1){if(typeof e=="string")return this.resolveStringWithExtra(e,t,n);if(Array.isArray(e))return e.map(s=>this.resolveObjectWithExtra(s,t,n));if(e!==null&&typeof e=="object"){let s={};for(let[i,o]of Object.entries(e))s[i]=this.resolveObjectWithExtra(o,t,n);return s}return e}resolveTemplateContent(e,t,n){let s=e.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(s){let a=Ks(s[2],t),c=Hn(s[1],a);return c!==null?String(c):n}let i=Dr(e);if(i){let a=this.resolveFilterInput(i.input,t);if(a!==void 0){let c=jr(a,i.filters,t);return c!==void 0?String(c):n}return n}let o=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(\[.+\]|\..+)$/);if(o){let a=o[1];if(t[a]!==void 0){let c=this.deserializeValue(t[a]),l=o[2],u=this.resolvePropertyAccess(c,l);if(u!==void 0)return typeof u=="object"?JSON.stringify(u):String(u)}}if(t[e]!==void 0){let a=t[e];if(typeof a=="string"&&a.charCodeAt(0)===30){let c=a.slice(1);return c==="undefined"?"":c}return String(a)}if(fn(e)){let a=this.deserializeVariables(t),c=_r(e,a),l=yt(e,c);if(l!==void 0)return String(l)}return n}resolveFilterInput(e,t){if(e==="@")return"";if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);let n=e.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(n){let i=Ks(n[2],t),o=Hn(n[1],i);return o!==null?o:void 0}let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(\[.+\]|\..+)$/);if(s){let i=s[1];if(t[i]!==void 0){let o=this.deserializeValue(t[i]),a=this.resolvePropertyAccess(o,s[2]);if(a!==void 0)return a}}if(t[e]!==void 0)return this.deserializeValue(t[e]);if(fn(e)){let i=this.deserializeVariables(t),o=_r(e,i),a=yt(e,o);if(a!==void 0)return a}}deserializeValue(e){if(typeof e=="string"&&e.charCodeAt(0)===30){let t=e.slice(1);if(t==="undefined")return;try{return JSON.parse(t)}catch{return e}}return e}deserializeVariables(e){let t={};for(let[n,s]of Object.entries(e))t[n]=this.deserializeValue(s);return t}resolvePropertyAccess(e,t){let n=e,s=/\[(\d+|"[^"]*"|'[^']*')\]|\.([a-zA-Z_][a-zA-Z0-9_]*)/g,i;for(;(i=s.exec(t))!==null;){if(n==null)return;if(i[1]!==void 0){let o=i[1];/^\d+$/.test(o)?n=n[Number(o)]:n=n[o.slice(1,-1)]}else i[2]!==void 0&&(n=n[i[2]])}return n}escapeForString(e,t){let n=e.replace(/\\/g,"\\\\");return t==='"'?n=n.replace(/"/g,'\\"'):n=n.replace(/'/g,"\\'"),n.replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}getStringContext(e,t){let n=null;for(let s=0;s<t;s++){let i=e[s];(s>0?e[s-1]:"")!=="\\"&&(i==='"'||i==="'")&&(n===null?n=i:n===i&&(n=null))}return n}},hn=class{interpolate(e,t){return!e||typeof e!="string"?e:new mn({globals:{},collectionVariables:{},environmentVariables:{},variables:t}).resolveString(e,!0)}extractVariables(e){if(!e||typeof e!="string")return[];let t=[],n,s=/\{\{((?:[^}]|\}(?!\}))+)\}\}/g;for(;(n=s.exec(e))!==null;){let i=n[1].trim();!i.startsWith("$")&&!i.includes("|")&&/^[a-zA-Z_]\w*$/.test(i)&&(t.includes(i)||t.push(i))}return t}interpolateObject(e,t){if(e==null)return e;if(typeof e=="string")return this.interpolate(e,t);if(Array.isArray(e))return e.map(n=>this.interpolateObject(n,t));if(typeof e=="object"){let n={};for(let[s,i]of Object.entries(e))n[s]=this.interpolateObject(i,t);return n}return e}}});var Ft,Qs=E(()=>{"use strict";Ft=class{constructor(e,t,n){this.urlBuilder=e;this.interceptors=t;this.httpClient=n}urlBuilder;interceptors;httpClient;async execute(e){let t={},n;try{n=await this.interceptors.executeRequestInterceptors(e,t)}catch(s){let i=await this.interceptors.executeErrorInterceptors(s,e,t);if(i)return i;throw s}try{let s=await this.httpClient.send(n);return await this.interceptors.executeResponseInterceptors(s,n,t)}catch(s){let i=await this.interceptors.executeErrorInterceptors(s,n,t);if(i)return i;throw s}}buildUrl(e,t={},n={}){return this.urlBuilder.buildUrl(e,t,n)}}});var Nt,Zs=E(()=>{"use strict";Nt=class{requestInterceptors=[];responseInterceptors=[];errorInterceptors=[];addRequestInterceptor(e){return this.requestInterceptors.push(e),this.sortByPriority(this.requestInterceptors),this}addResponseInterceptor(e){return this.responseInterceptors.push(e),this.sortByPriority(this.responseInterceptors),this}addErrorInterceptor(e){return this.errorInterceptors.push(e),this.sortByPriority(this.errorInterceptors),this}removeRequestInterceptor(e){let t=this.requestInterceptors.findIndex(n=>n.name===e);return t>=0?(this.requestInterceptors.splice(t,1),!0):!1}removeResponseInterceptor(e){let t=this.responseInterceptors.findIndex(n=>n.name===e);return t>=0?(this.responseInterceptors.splice(t,1),!0):!1}removeErrorInterceptor(e){let t=this.errorInterceptors.findIndex(n=>n.name===e);return t>=0?(this.errorInterceptors.splice(t,1),!0):!1}async executeRequestInterceptors(e,t){let n=e;for(let s of this.requestInterceptors)try{n=await s.intercept(n,t)}catch(i){throw console.error(`[InterceptorChain] Request interceptor '${s.name}' failed:`,i),i}return n}async executeResponseInterceptors(e,t,n){let s=e;for(let i of this.responseInterceptors)try{s=await i.intercept(s,t,n)}catch(o){throw console.error(`[InterceptorChain] Response interceptor '${i.name}' failed:`,o),o}return s}async executeErrorInterceptors(e,t,n){for(let s of this.errorInterceptors)try{let i=await s.handle(e,t,n);if(i)return i}catch(i){console.error(`[InterceptorChain] Error interceptor '${s.name}' failed:`,i)}}clear(){this.requestInterceptors=[],this.responseInterceptors=[],this.errorInterceptors=[]}getRegisteredInterceptors(){return{request:this.requestInterceptors.map(e=>e.name),response:this.responseInterceptors.map(e=>e.name),error:this.errorInterceptors.map(e=>e.name)}}sortByPriority(e){e.sort((t,n)=>(t.priority??100)-(n.priority??100))}}});function ad(r,e,t,n){let s=Buffer.concat([Buffer.from(r,"utf8"),n||Buffer.alloc(0)]),i=[],o=Buffer.alloc(0);for(;Buffer.concat(i).length<e+t;)o=$e.createHash("md5").update(Buffer.concat([o,s])).digest(),i.push(o);let a=Buffer.concat(i);return{key:a.subarray(0,e),iv:a.subarray(e,e+t)}}function Vc(r,e,t){let n=s=>r==="aes"?`aes-${s*8}-cbc`:r==="des"?"des-cbc":r==="des-ede3"?"des-ede3-cbc":r;return{encrypt(s,i,o){let a=s instanceof ne?s.toBuffer():Buffer.from(String(s),"utf8");if(typeof i=="string"){let c=$e.randomBytes(8),{key:l,iv:u}=ad(i,e,t,c),d=$e.createCipheriv(n(e),l,u),p=Buffer.concat([d.update(a),d.final()]),m=Buffer.concat([Buffer.from("Salted__"),c,p]);return{ciphertext:new ne(p),salt:new ne(c),toString:f=>f?f.stringify(new ne(m)):m.toString("base64")}}else{let c=i.toBuffer(),l=o?.iv&&o.iv instanceof ne?o.iv.toBuffer():Buffer.alloc(t),u=$e.createCipheriv(n(c.length),c,l);o?.padding===!1&&u.setAutoPadding(!1);let d=Buffer.concat([u.update(a),u.final()]);return{ciphertext:new ne(d),toString:p=>p?p.stringify(new ne(d)):d.toString("base64")}}},decrypt(s,i,o){if(typeof i=="string"){let a=typeof s=="string"?Buffer.from(s,"base64"):s.ciphertext.toBuffer(),c,l;a.subarray(0,8).toString()==="Salted__"?(l=a.subarray(8,16),c=a.subarray(16)):(l=Buffer.alloc(0),c=a);let{key:u,iv:d}=ad(i,e,t,l),p=$e.createDecipheriv(n(e),u,d);return new ne(Buffer.concat([p.update(c),p.final()]))}else{let a=i.toBuffer(),c=o?.iv&&o.iv instanceof ne?o.iv.toBuffer():Buffer.alloc(t),l=typeof s=="string"?Buffer.from(s,"base64"):s.ciphertext?s.ciphertext.toBuffer():Buffer.from(s),u=$e.createDecipheriv(n(a.length),a,c);return o?.padding===!1&&u.setAutoPadding(!1),new ne(Buffer.concat([u.update(l),u.final()]))}}}}function cd(){let r=t=>n=>{let s=n instanceof ne?n.toBuffer():Buffer.from(String(n),"utf8");return new ne($e.createHash(t).update(s).digest())},e=t=>(n,s)=>{let i=n instanceof ne?n.toBuffer():Buffer.from(String(n),"utf8"),o=s instanceof ne?s.toBuffer():Buffer.from(String(s),"utf8");return new ne($e.createHmac(t,o).update(i).digest())};return{MD5:r("md5"),SHA1:r("sha1"),SHA224:r("sha224"),SHA256:r("sha256"),SHA384:r("sha384"),SHA512:r("sha512"),SHA3:r("sha3-256"),RIPEMD160:r("ripemd160"),HmacMD5:e("md5"),HmacSHA1:e("sha1"),HmacSHA256:e("sha256"),HmacSHA512:e("sha512"),AES:Vc("aes",32,16),DES:Vc("des",8,8),TripleDES:Vc("des-ede3",24,8),PBKDF2(t,n,s){let i=t instanceof ne?t.toBuffer():Buffer.from(String(t),"utf8"),o=n instanceof ne?n.toBuffer():Buffer.from(String(n),"utf8"),a=(s?.keySize||4)*4,c=s?.iterations||1;return new ne($e.pbkdf2Sync(i,o,c,a,"sha1"))},enc:{Base64:{stringify:t=>(t instanceof ne?t.toBuffer():Buffer.from(String(t))).toString("base64"),parse:t=>ne.fromBase64(t)},Utf8:{stringify:t=>(t instanceof ne?t.toBuffer():Buffer.from(String(t))).toString("utf8"),parse:t=>ne.fromUtf8(t)},Hex:{stringify:t=>(t instanceof ne?t.toBuffer():Buffer.from(String(t))).toString("hex"),parse:t=>ne.fromHex(t)},Latin1:{stringify:t=>(t instanceof ne?t.toBuffer():Buffer.from(String(t))).toString("latin1"),parse:t=>new ne(Buffer.from(t,"latin1"))},Utf16:{stringify:t=>(t instanceof ne?t.toBuffer():Buffer.from(String(t))).toString("utf16le"),parse:t=>new ne(Buffer.from(t,"utf16le"))},Utf16BE:{stringify:t=>(t instanceof ne?t.toBuffer():Buffer.from(String(t))).swap16().toString("utf16le"),parse:t=>new ne(Buffer.from(t,"utf16le").swap16())}},lib:{WordArray:{create:t=>t?typeof t=="string"?new ne(Buffer.from(t,"utf8")):Buffer.isBuffer(t)?new ne(t):new ne(Buffer.from(String(t))):new ne(Buffer.alloc(0)),random:t=>new ne($e.randomBytes(t))}},pad:{Pkcs7:{_name:"pkcs7"},NoPadding:{_name:"nopadding"},ZeroPadding:{_name:"zeropadding"}},mode:{CBC:{_name:"cbc"},ECB:{_name:"ecb"}}}}var $e,ne,ld=E(()=>{"use strict";$e=I(require("crypto")),ne=class r{_buffer;constructor(e){this._buffer=typeof e=="string"?Buffer.from(e,"utf8"):e}toString(e){return e?e.stringify(this):this._buffer.toString("hex")}toBuffer(){return this._buffer}static fromHex(e){return new r(Buffer.from(e,"hex"))}static fromBase64(e){return new r(Buffer.from(e,"base64"))}static fromUtf8(e){return new r(Buffer.from(e,"utf8"))}}});function Xs(){return{format:(r,e)=>{let t=r?new Date(r):new Date;return e==="YYYY-MM-DD"?t.toISOString().split("T")[0]:t.toISOString()},unix:()=>Math.floor(Date.now()/1e3),utc:()=>{let r=new Date;return{format:()=>r.toISOString(),toISOString:()=>r.toISOString()}},__isShim:!0,__warning:"This is a lightweight shim. For full features, install moment.js via modules/package.json"}}function Dh(){return{get:(r,e,t)=>{let n=e.split("."),s=r;for(let i of n)if(s=s?.[i],s===void 0)return t;return s},set:(r,e,t)=>{let n=e.split("."),s=r;for(let i=0;i<n.length-1;i++)s[n[i]]||(s[n[i]]={}),s=s[n[i]];return s[n[n.length-1]]=t,r},cloneDeep:r=>JSON.parse(JSON.stringify(r)),keys:r=>Object.keys(r??{}),values:r=>Object.values(r??{}),entries:r=>Object.entries(r??{}),each(r,e){Array.isArray(r)?r.forEach((t,n)=>e(t,n,r)):r&&typeof r=="object"&&Object.entries(r).forEach(([t,n])=>e(n,t,r))},forEach(r,e){Array.isArray(r)?r.forEach((t,n)=>e(t,n,r)):r&&typeof r=="object"&&Object.entries(r).forEach(([t,n])=>e(n,t,r))},map:(r,e)=>(Array.isArray(r)?r:Object.values(r??{})).map(t=>e(t)),filter:(r,e)=>(Array.isArray(r)?r:Object.values(r??{})).filter(t=>e(t)),find:(r,e)=>(Array.isArray(r)?r:Object.values(r??{})).find(t=>e(t)),reduce:(r,e,t)=>(Array.isArray(r)?r:Object.values(r??{})).reduce((n,s)=>e(n,s),t),includes:(r,e)=>Array.isArray(r)?r.includes(e):Object.values(r??{}).includes(e),isObject:r=>r!==null&&typeof r=="object"&&!Array.isArray(r),isArray:r=>Array.isArray(r),isString:r=>typeof r=="string",isNumber:r=>typeof r=="number",isFunction:r=>typeof r=="function",isNil:r=>r==null,isEmpty:r=>r==null?!0:Array.isArray(r)||typeof r=="string"?r.length===0:typeof r=="object"?Object.keys(r).length===0:!1,assign:(r,...e)=>Object.assign(r,...e),merge:(r,...e)=>{let t={...r};for(let n of e)for(let[s,i]of Object.entries(n??{}))t[s]=i&&typeof i=="object"&&!Array.isArray(i)?{...t[s]??{},...i}:i;return t},omit:(r,e)=>{let t={...r};for(let n of e)delete t[n];return t},pick:(r,e)=>{let t={};for(let n of e)n in(r??{})&&(t[n]=r[n]);return t}}}function fo(r,e){return new Ys(r,e)}var _h,Bn,ud,vt,dd,Ys,zc=E(()=>{"use strict";_h=I(require("crypto")),Bn=I(require("fs")),ud=require("module"),vt=I(require("path")),dd=require("uuid");Ys=class{availableModules=new Set;customModulesRequire;globalSetupExports;options;modulesPath=null;moduleCache=new Map;resolveStack=new Set;builtinModules={uuid:()=>({v4:dd.v4}),crypto:()=>_h,path:()=>vt,querystring:()=>require("querystring"),lodash:()=>this.loadOptionalModule("lodash",()=>require("lodash"),Dh),moment:()=>this.loadOptionalModule("moment",()=>require("moment"),Xs),tv4:()=>this.loadOptionalModule("tv4",()=>require("tv4")),ajv:()=>this.loadOptionalModule("ajv",()=>require("ajv")),"crypto-js":()=>this.loadOptionalModule("crypto-js",()=>require("crypto-js"),()=>{throw new Error('crypto-js npm module is not installed. The built-in CryptoJS global is already available in scripts with AES/DES/TripleDES/hash/HMAC/PBKDF2 support. If you need the exact npm package, add "crypto-js" to your modules/package.json and run npm install.')})};constructor(e=[],t={}){this.options={allowCustomModules:!0,maxResolveDepth:10,...t,outputChannel:t.outputChannel||{appendLine:n=>{console.log(`[ModuleLoader] ${n}`)}}};for(let n of e){let s=vt.resolve(n);if(this.initializeModules(s)){this.modulesPath=s;break}}}loadOptionalModule(e,t,n){try{return t()}catch{if(this.customModulesRequire)try{return console.debug(`[ModuleLoader] ${e} not in core, trying user modules`),this.customModulesRequire(e)}catch{this.logModuleWarning(e,"user")}else this.logModuleWarning(e,"core");if(n)return console.warn(`[ModuleLoader] Using shim for ${e}. Some features may be limited.`),n();throw new Error(this.getModuleInstallInstructions(e))}}logModuleWarning(e,t){let s={moment:"Date/time manipulation",lodash:"Utility functions",tv4:"JSON Schema validation (v4)",ajv:"JSON Schema validation"}[e]||e;console.warn(`[ModuleLoader] ${s} functionality (${e}) is not available.
252
+ `}var je,Oc,Ht,$c,Fc,fh,Nc=E(()=>{"use strict";je=I(require("fs")),Oc=I(require("path")),Ht=1,$c="AGENTS.md",Fc="AGENTS.md.bak",fh=/http-forge-agents-md-version:\s*(\d+)/});function Js(r){if(!ce.existsSync(r))return;let e={},t=Ke.join(r,zs.preRequest);ce.existsSync(t)&&(e.preRequest=ce.readFileSync(t,"utf-8"));let n=Ke.join(r,zs.postResponse);return ce.existsSync(n)&&(e.postResponse=ce.readFileSync(n,"utf-8")),Object.keys(e).length>0?e:void 0}async function Gs(r,e){await ce.promises.mkdir(r,{recursive:!0});let t=Ke.join(r,zs.preRequest);e.preRequest?await ce.promises.writeFile(t,e.preRequest,"utf-8"):ce.existsSync(t)&&await ce.promises.unlink(t);let n=Ke.join(r,zs.postResponse);e.postResponse?await ce.promises.writeFile(n,e.postResponse,"utf-8"):ce.existsSync(n)&&await ce.promises.unlink(n)}function _c(r){for(let[e,t]of Object.entries(Mc)){let n=Ke.join(r,e);if(ce.existsSync(n))try{let s=ce.readFileSync(n,"utf-8"),i;if(t.type==="graphql")try{i=JSON.parse(s)}catch{i=s}else i=s;return{type:t.type,format:t.format,content:i}}catch(s){console.error(`[FolderIO] Failed to load body from ${n}:`,s)}}}function Dc(r){if(!r||r.type==="none")return{bodyForMetadata:r};if(r.type==="raw"){let e=r.format||"json",n={json:"body.json",xml:"body.xml",text:"body.txt",html:"body.html",javascript:"body.js"}[e];if(n){let s=e==="json"?typeof r.content=="string"?r.content:JSON.stringify(r.content,null,2):String(r.content||"");return{bodyForMetadata:{type:r.type,format:r.format},externalBodyFile:{filename:n,content:s}}}}if(r.type==="graphql"){let e=typeof r.content=="string"?r.content:JSON.stringify(r.content,null,2);return{bodyForMetadata:{type:r.type},externalBodyFile:{filename:"body.graphql",content:e}}}return{bodyForMetadata:r}}async function jc(r,e){for(let t of Object.keys(Mc))if(t!==e){let n=Ke.join(r,t);if(ce.existsSync(n))try{await ce.promises.unlink(n)}catch{}}}function Lc(r){if(ce.existsSync(r))try{let e=ce.readFileSync(r,"utf-8");return JSON.parse(e)}catch(e){console.error(`[FolderIO] Failed to load schema file ${r}:`,e);return}}async function Hc(r,e,t){let n=Ke.join(r,dn.responseSchema),s=Ke.join(r,dn.bodySchema);e?await ce.promises.writeFile(n,JSON.stringify(e,null,2),"utf-8"):ce.existsSync(n)&&await ce.promises.unlink(n),t?await ce.promises.writeFile(s,JSON.stringify(t,null,2),"utf-8"):ce.existsSync(s)&&await ce.promises.unlink(s)}function Re(r,e){for(let t of r){if(t.id===e)return t;if(t.type==="folder"&&t.items){let n=Re(t.items,e);if(n)return n}}}function Bt(r,e){for(let t=0;t<r.length;t++){let n=r[t];if(n.id===e)return r.splice(t,1),!0;if(n.type==="folder"&&n.items&&Bt(n.items,e))return!0}return!1}function Bc(r,e){let t=new Map(r.map(s=>[s.id,s])),n=[];for(let s of e){let i=t.get(s);i&&(n.push(i),t.delete(s))}for(let s of t.values())n.push(s);return n}function ao(r,e){let t;try{t=ce.readdirSync(r,{withFileTypes:!0})}catch{return}for(let n of t){if(!n.isDirectory()||n.name===Le)continue;if(n.name===e)return Ke.join(r,n.name);let s=ao(Ke.join(r,n.name),e);if(s)return s}}function mh(r){for(let e of[Ie.request,Ie.folder]){let t=Ke.join(r,e);if(ce.existsSync(t))try{let n=ce.readFileSync(t,"utf-8");return JSON.parse(n).id}catch{return}}}function co(r,e){let t;try{t=ce.readdirSync(r,{withFileTypes:!0})}catch{return}for(let n of t){if(!n.isDirectory()||n.name===Le)continue;let s=Ke.join(r,n.name);if(mh(s)===e)return s;let i=co(s,e);if(i)return i}}function at(r,e=[]){let t=r.toLowerCase().trim(),n=t.match(/^(get|post|put|patch|delete|head|options)[_\s-]/i),s=n?n[1]:"",i=t.match(/t(\d+)/gi)||[],o=0;for(let d of i){let m=parseInt(d.substring(1));m>o&&(o=m)}let a="";if(o>0)a=`t${o}`;else{let d=t.match(/[_\s-](\d+\.\d+)[_\s-]/);d&&(a=`v${d[1].replace(".","_")}`)}let c=t;n&&(c=c.substring(n[0].length)),c=c.replace(/[_\s-]?t\d+(?:\.\d+)?[_\s-]?/gi,"-"),c=c.replace(/[_\s-]?\d+\.\d+[_\s-]?/g,"-"),c=c.replace(/\([^)]+\)/g,""),c=c.replace(/:[a-z_][a-z0-9_]*/gi,""),c=c.replace(/\{[^}]+\}/g,""),c=c.replace(/\?$/g,"").replace(/[_/\\ ]+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");let l=c.split("-").filter(d=>d.length>0),u=[];s&&u.push(s),u.push(...l),a&&u.push(a);let p=u.join("-");if(p||(p="item"),e.includes(p)){let d=2;for(;e.includes(`${p}-${d}`);)d++;p=`${p}-${d}`}return p}var ce,Ke,zs,Ie,Mc,dn,Le,pn=E(()=>{"use strict";ce=I(require("fs")),Ke=I(require("path")),zs={preRequest:"pre-request.js",postResponse:"post-response.js"},Ie={collection:"collection.json",folder:"folder.json",request:"request.json"},Mc={"body.json":{type:"raw",format:"json"},"body.xml":{type:"raw",format:"xml"},"body.txt":{type:"raw",format:"text"},"body.html":{type:"raw",format:"html"},"body.js":{type:"raw",format:"javascript"},"body.graphql":{type:"graphql"}},dn={responseSchema:"response.schema.json",bodySchema:"body.schema.json"},Le="scripts"});var J,V,Uc,Ut,lo=E(()=>{"use strict";J=I(require("fs")),V=I(require("path"));We();Tc();Nc();pn();Uc={collection:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/collection.schema.json",folder:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/folder.schema.json",request:"https://raw.githubusercontent.com/hsl1230/http-forge/main/resources/request.schema.json"},Ut=class{collectionsDir;cache=new Map;slugToIdMap=new Map;idToSlugMap=new Map;lightLoad=!1;constructor(e){this.collectionsDir=e}getSlugById(e){return this.idToSlugMap.get(e)}getIdBySlug(e){return this.slugToIdMap.get(e)}ensureDirectory(){J.existsSync(this.collectionsDir)||J.mkdirSync(this.collectionsDir,{recursive:!0}),this.ensureAgentsMd()}ensureAgentsMd(){let e=V.resolve(this.collectionsDir,"..","..");try{io(e)}catch{}}readJsonFileSafe(e,t){let n;try{n=J.readFileSync(e,"utf-8")}catch(s){console.error(`[FolderCollectionStore] Failed to read ${t} ${e}:`,s);return}if(n.trim().length!==0)try{return JSON.parse(n)}catch(s){if(s instanceof SyntaxError&&/Unexpected end of JSON input/.test(s.message))return;console.error(`[FolderCollectionStore] Failed to parse ${t} ${e}:`,s);return}}loadAll(){if(this.cache.clear(),this.slugToIdMap.clear(),this.idToSlugMap.clear(),!J.existsSync(this.collectionsDir))return[];let e=J.readdirSync(this.collectionsDir,{withFileTypes:!0}),t=[];for(let n of e)if(n.isDirectory())try{let s=this.loadCollectionFromFolder(n.name);s&&(this.cache.set(s.id,s),this.slugToIdMap.set(n.name,s.id),this.idToSlugMap.set(s.id,n.name),t.push(s))}catch(s){console.error(`[FolderCollectionStore] Failed to load ${n.name}:`,s)}return t}loadCollectionFromFolder(e){let t=V.join(this.collectionsDir,e),n=V.join(t,Ie.collection);if(!J.existsSync(n))return;let s=this.readJsonFileSafe(n,"collection");if(s)try{let i=this.loadScriptsFromDir(V.join(t,Le)),o=this.loadItemsFromDir(t,s.id,s.order);return{id:s.id,name:s.name,description:s.description,version:s.version,variables:s.variables,auth:s.auth,scripts:i,items:o}}catch(i){console.error(`[FolderCollectionStore] Failed to parse ${n}:`,i);return}}loadItemsFromDir(e,t,n){let s=[],i=new Map,o=J.readdirSync(e,{withFileTypes:!0});for(let a of o){if(!a.isDirectory()||a.name===Le)continue;let c=V.join(e,a.name);if(J.existsSync(V.join(c,Ie.folder))){let l=this.loadFolderFromDir(c,a.name);l&&i.set(a.name,l)}else if(J.existsSync(V.join(c,Ie.request))){let l=this.loadRequestFromDir(c,a.name);l&&i.set(a.name,l)}}if(n&&n.length>0){for(let a of n){let c=i.get(a);c&&(s.push(c),i.delete(a))}for(let a of i.values())s.push(a)}else for(let a of i.values())s.push(a);return s}loadFolderFromDir(e,t){let n=V.join(e,Ie.folder),s=this.readJsonFileSafe(n,"folder");if(s)try{let i=this.loadScriptsFromDir(V.join(e,Le)),o=this.loadItemsFromDir(e,s.id,s.order);return this.slugToIdMap.set(t,s.id),this.idToSlugMap.set(s.id,t),{id:s.id,type:"folder",name:s.name,description:s.description,auth:s.auth,scripts:i,items:o}}catch(i){console.error(`[FolderCollectionStore] Failed to load folder ${e}:`,i);return}}loadRequestFromDirLight(e,t){let n=V.join(e,Ie.request),s=this.readJsonFileSafe(n,"request");if(s)try{return this.slugToIdMap.set(t,s.id),this.idToSlugMap.set(s.id,t),{id:s.id,type:"request",name:s.name,description:s.description,method:s.method,url:s.url,params:s.params,query:s.query,headers:s.headers,body:s.body,bodyContentType:s.bodyContentType,auth:s.auth,settings:s.settings,disabled:s.disabled,deprecated:s.deprecated,operationId:s.operationId,summary:s.summary,tags:s.tags,examples:s.examples,responses:s.responses,security:s.security,_light:!0}}catch(i){console.error(`[FolderCollectionStore] Failed to load request (light) ${e}:`,i);return}}loadRequestDetail(e,t){let n=this.findItemById(this.cache.get(e)?.items||[],t);if(n&&!Hn(n))return n;let s=this.findItemPath(e,t);if(!s||!J.existsSync(s))return n;let i=this.idToSlugMap.get(t)||V.basename(s),o=this.loadScriptsFromDir(V.join(s,Le)),a=this.loadBodyFromDir(s),c=this.loadSchemaFile(V.join(s,dn.responseSchema)),l=this.loadSchemaFile(V.join(s,dn.bodySchema)),u=V.join(s,"doc.md"),p=J.existsSync(u)?J.readFileSync(u,"utf-8"):void 0;return n?(a&&(n.body=a),o&&(n.scripts=o),c&&(n.responseSchema=c),l&&(n.bodySchema=l),p&&(n.doc=p),ro(n),n):this.loadRequestFromDir(s,i)}loadAllLight(){this.lightLoad=!0;try{return this.loadAll()}finally{this.lightLoad=!1}}loadRequestFromDir(e,t){if(this.lightLoad)return this.loadRequestFromDirLight(e,t);let n=V.join(e,Ie.request),s=this.readJsonFileSafe(n,"request");if(s)try{let i=this.loadScriptsFromDir(V.join(e,Le)),o=s.body,a=this.loadBodyFromDir(e);a&&(o=a);let c=this.loadSchemaFile(V.join(e,dn.responseSchema)),l=this.loadSchemaFile(V.join(e,dn.bodySchema)),u=V.join(e,"doc.md"),p=J.existsSync(u)?J.readFileSync(u,"utf-8"):void 0;return this.slugToIdMap.set(t,s.id),this.idToSlugMap.set(s.id,t),{id:s.id,type:"request",name:s.name,description:s.description,method:s.method,url:s.url,params:s.params,query:s.query,headers:s.headers,body:o,bodyContentType:s.bodyContentType,auth:s.auth,settings:s.settings,scripts:i,disabled:s.disabled,deprecated:s.deprecated,operationId:s.operationId,summary:s.summary,tags:s.tags,examples:s.examples,responses:s.responses,security:s.security,...p&&{doc:p},...c&&{responseSchema:c},...l&&{bodySchema:l}}}catch(i){console.error(`[FolderCollectionStore] Failed to load request ${e}:`,i);return}}loadScriptsFromDir(e){return Js(e)}loadBodyFromDir(e){return _c(e)}loadSchemaFile(e){return Lc(e)}async saveSchemaFiles(e,t){return Hc(e,t.responseSchema,t.bodySchema)}load(e){if(this.cache.has(e))return this.cache.get(e);let t=this.idToSlugMap.get(e);if(t){let n=this.loadCollectionFromFolder(t);return n&&this.cache.set(e,n),n}return this.loadAll(),this.cache.get(e)}async save(e){if(this.ensureDirectory(),!e.name)throw new Error("Collection name is required");this.hydrateLightItems(e.id,e.items),e.id||(e.id=ae(e.name));let t=this.idToSlugMap.get(e.id);if(!t){let c=J.readdirSync(this.collectionsDir);t=at(e.name,c),this.idToSlugMap.set(e.id,t),this.slugToIdMap.set(t,e.id)}let n=V.join(this.collectionsDir,t),s=!J.existsSync(n);await J.promises.mkdir(n,{recursive:!0});let i={id:e.id,name:e.name,description:e.description,version:e.version,variables:e.variables,auth:e.auth},[o]=await Promise.all([this.saveItemsToDir(n,e.items,s),e.scripts?this.saveScriptsToDir(V.join(n,Le),e.scripts):Promise.resolve()]);o.length>0&&(i.order=o);let a={$schema:Uc.collection,...i};await J.promises.writeFile(V.join(n,Ie.collection),JSON.stringify(a,null,2),"utf-8"),this.cache.set(e.id,e)}async saveItemsToDir(e,t,n=!1){let s=[],i=[];for(let o of t){let a=this.idToSlugMap.get(o.id);a||(a=at(o.name,s),this.idToSlugMap.set(o.id,a),this.slugToIdMap.set(a,o.id)),s.push(a),i.push({item:o,slug:a})}return await Promise.all(i.map(async({item:o,slug:a})=>{let c=V.join(e,a);await J.promises.mkdir(c,{recursive:!0}),o.type==="folder"?await this.saveFolderToDir(c,o,n):await this.saveRequestToDir(c,o,n)})),s}async saveFolderToDir(e,t,n=!1){let s={id:t.id,name:t.name,description:t.description,auth:t.auth},[i]=await Promise.all([t.items?this.saveItemsToDir(e,t.items,n):Promise.resolve([]),t.scripts?this.saveScriptsToDir(V.join(e,Le),t.scripts):Promise.resolve()]);i.length>0&&(s.order=i);let o={$schema:Uc.folder,...s};await J.promises.writeFile(V.join(e,Ie.folder),JSON.stringify(o,null,2),"utf-8")}async saveRequestToDir(e,t,n=!1){let{bodyForMetadata:s,externalBodyFile:i}=this.prepareBodyForSave(t.body),o={id:t.id,name:t.name,method:t.method||"GET",url:t.url||"",description:t.description,params:t.params,query:t.query,headers:t.headers,body:s,bodyContentType:t.bodyContentType,auth:t.auth,settings:t.settings,...t.disabled!==void 0&&{disabled:t.disabled},...t.deprecated&&{deprecated:t.deprecated},...t.operationId&&{operationId:t.operationId},...t.summary&&{summary:t.summary},...t.tags&&t.tags.length>0&&{tags:t.tags},...t.examples&&t.examples.length>0&&{examples:t.examples},...t.responses&&Object.keys(t.responses).length>0&&{responses:t.responses},...t.security&&t.security.length>0&&{security:t.security}},a=[J.promises.writeFile(V.join(e,Ie.request),JSON.stringify({$schema:Uc.request,...o},null,2),"utf-8")];i&&a.push(J.promises.writeFile(V.join(e,i.filename),i.content,"utf-8")),n||a.push(this.cleanupOldBodyFiles(e,i?.filename)),(!n||t.responseSchema||t.bodySchema)&&a.push(this.saveSchemaFiles(e,t)),t.doc&&a.push(J.promises.writeFile(V.join(e,"doc.md"),t.doc,"utf-8")),t.scripts&&a.push(this.saveScriptsToDir(V.join(e,Le),t.scripts)),await Promise.all(a)}prepareBodyForSave(e){return Dc(e)}async cleanupOldBodyFiles(e,t){return jc(e,t)}async saveScriptsToDir(e,t){return Gs(e,t)}async delete(e){let t=this.idToSlugMap.get(e);if(!t&&(this.loadAll(),t=this.idToSlugMap.get(e),!t))return!1;let n=V.join(this.collectionsDir,t);if(!J.existsSync(n))return!1;try{return await J.promises.rm(n,{recursive:!0,force:!0}),this.cache.delete(e),this.idToSlugMap.delete(e),this.slugToIdMap.delete(t),!0}catch(s){return console.error(`[FolderCollectionStore] Failed to delete collection ${e}:`,s),!1}}exists(e){let t=this.idToSlugMap.get(e);return t?J.existsSync(V.join(this.collectionsDir,t,Ie.collection)):!1}getCollectionPath(e){let t=this.idToSlugMap.get(e)||e;return V.join(this.collectionsDir,t)}getItemPath(e,t){return this.findItemPath(e,t)}async create(e,t){let n={id:t||ae(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=this.findItemPath(e,t);if(!i)throw new Error(`Item ${t} not found in collection ${e}`);await this.saveScriptsToDir(V.join(i,Le),n);let o=this.findItemById(s.items,t);o&&(o.scripts=n)}loadScripts(e,t){let n=this.findItemPath(e,t);if(n)return this.loadScriptsFromDir(V.join(n,Le))}hydrateLightItems(e,t){if(t)for(let n of t)n.type==="request"?Hn(n)&&this.loadRequestDetail(e,n.id):n.items&&this.hydrateLightItems(e,n.items)}resolveWritableRequest(e,t){if(t.type==="request"&&Hn(t)){let n=this.loadRequestDetail(e,t.id);if(n)return n}return t}async updateCollectionMetadata(e,t){let n=this.load(e);if(!n)throw new Error(`Collection ${e} not found`);let s=this.idToSlugMap.get(e);if(!s)throw new Error(`Collection slug not found for ${e}`);let i=V.join(this.collectionsDir,s),o=V.join(i,Ie.collection),a=J.readFileSync(o,"utf-8"),l={...JSON.parse(a),...t,id:e};await J.promises.writeFile(o,JSON.stringify(l,null,2),"utf-8"),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)}async saveItem(e,t,n){let s=this.load(e);if(!s)throw new Error(`Collection ${e} not found`);let i=this.idToSlugMap.get(e);if(!i)throw new Error(`Collection slug not found for ${e}`);let o;if(n){let u=this.findItemPath(e,n);if(!u)throw new Error(`Parent folder ${n} not found`);o=u}else o=V.join(this.collectionsDir,i);let a=this.idToSlugMap.get(t.id);if(!a){let u=J.readdirSync(o).filter(p=>J.statSync(V.join(o,p)).isDirectory()&&p!==Le);a=at(t.name,u),this.idToSlugMap.set(t.id,a),this.slugToIdMap.set(a,t.id)}let c=V.join(o,a);await J.promises.mkdir(c,{recursive:!0}),t=this.resolveWritableRequest(e,t),t.type==="folder"?await this.saveFolderToDir(c,t):await this.saveRequestToDir(c,t);let l=this.findItemById(s.items,t.id);if(l)Object.assign(l,t);else if(n){let u=this.findItemById(s.items,n);u&&u.type==="folder"&&(u.items=u.items||[],u.items.push(t))}else s.items.push(t)}async deleteItem(e,t){let n=this.load(e);if(!n)return!1;let s=this.findItemPath(e,t);if(!s||!J.existsSync(s))return!1;try{await J.promises.rm(s,{recursive:!0,force:!0}),this.deleteItemFromTree(n.items,t);let i=this.idToSlugMap.get(t);return i&&(this.slugToIdMap.delete(i),this.idToSlugMap.delete(t)),!0}catch(i){return console.error(`[FolderCollectionStore] Failed to delete item ${t}:`,i),!1}}async updateItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=this.findItemPath(e,t);if(!i)return!1;let o=this.findItemById(s.items,t);if(!o)return!1;o.type==="request"&&Hn(o)&&this.loadRequestDetail(e,t);let{id:a,type:c,items:l,...u}=n;return Object.assign(o,u),o.type==="folder"?await this.saveFolderToDir(i,o):await this.saveRequestToDir(i,o),!0}async moveItem(e,t,n){let s=this.load(e);if(!s)return!1;let i=this.idToSlugMap.get(e);if(!i)return!1;let o=this.findItemPath(e,t);if(!o||!J.existsSync(o))return!1;let a;if(n){let u=this.findItemPath(e,n);if(!u)return!1;a=u}else a=V.join(this.collectionsDir,i);let c=this.idToSlugMap.get(t);if(!c)return!1;let l=V.join(a,c);if(J.existsSync(l))return!1;try{await J.promises.rename(o,l);let u=this.findItemById(s.items,t);if(u){let p=u.type==="folder"?{...u,items:u.items?[...u.items]:[]}:{...u};if(this.deleteItemFromTree(s.items,t),n){let d=this.findItemById(s.items,n);d&&d.type==="folder"&&(d.items=d.items||[],d.items.push(p))}else s.items.push(p)}return!0}catch(u){return console.error(`[FolderCollectionStore] Failed to move item ${t}:`,u),!1}}async reorderItems(e,t,n){let s=this.load(e);if(!s)return!1;let i=this.idToSlugMap.get(e);if(!i)return!1;let o=[];for(let a of n){let c=this.idToSlugMap.get(a);c&&o.push(c)}try{if(t){let a=this.findItemPath(e,t);if(!a)return!1;let c=V.join(a,Ie.folder),l=J.readFileSync(c,"utf-8"),u=JSON.parse(l);u.order=o,await J.promises.writeFile(c,JSON.stringify(u,null,2),"utf-8");let p=this.findItemById(s.items,t);p&&p.type==="folder"&&p.items&&(p.items=this.sortItemsByOrder(p.items,n))}else{let a=V.join(this.collectionsDir,i,Ie.collection),c=J.readFileSync(a,"utf-8"),l=JSON.parse(c);l.order=o,await J.promises.writeFile(a,JSON.stringify(l,null,2),"utf-8"),s.items=this.sortItemsByOrder(s.items,n)}return!0}catch(a){return console.error("[FolderCollectionStore] Failed to reorder items:",a),!1}}sortItemsByOrder(e,t){return Bc(e,t)}findItemPath(e,t){let n=this.idToSlugMap.get(e);if(!n)return;let s=V.join(this.collectionsDir,n),i=co(s,t);if(i)return i;let o=this.load(e);if(o){let c=this.buildSlugPath(o.items,t);if(c)return V.join(s,...c)}let a=this.idToSlugMap.get(t);if(a)return ao(s,a)}buildSlugPath(e,t){for(let n of e){let s=this.idToSlugMap.get(n.id);if(s){if(n.id===t)return[s];if(n.type==="folder"&&n.items){let i=this.buildSlugPath(n.items,t);if(i)return[s,...i]}}}}findItemById(e,t){return Re(e,t)}deleteItemFromTree(e,t){return Bt(e,t)}}});var oe,Bn=E(()=>{"use strict";oe=class{static parseSetCookie(e,t){let n=e.split(";").map(u=>u.trim());if(n.length===0)return null;let[s,...i]=n,o=s.indexOf("=");if(o===-1)return null;let a=s.substring(0,o).trim(),c=s.substring(o+1).trim(),l={name:a,value:c,domain:t};for(let u of i){let p=u.indexOf("="),d=(p===-1?u:u.substring(0,p)).toLowerCase(),m=p===-1?"":u.substring(p+1);switch(d){case"domain":l.domain=m.startsWith(".")?m.substring(1):m;break;case"path":l.path=m;break;case"expires":l.expires=m;break;case"max-age":l.maxAge=parseInt(m,10);break;case"httponly":l.httpOnly=!0;break;case"secure":l.secure=!0;break;case"samesite":l.sameSite=m;break}}return l}static parseCookieHeaders(e,t){let n=[],s=e["set-cookie"]||e["Set-Cookie"];if(!s)return n;let i=Array.isArray(s)?s:[s];for(let o of i){let a=this.parseSetCookie(o,t);a&&n.push(a)}return n}static formatCookieHeader(e){return e.map(t=>`${t.name}=${t.value}`).join("; ")}static cookieKey(e,t,n){return`${t||"*"}|${n||"/"}|${e}`}static isExpired(e){return!!(e.expires&&new Date(e.expires).getTime()<Date.now()||e.maxAge!==void 0&&e.maxAge<=0)}static domainMatches(e,t){if(t==="*")return!0;let n=e.toLowerCase().split(".").reverse(),s=t.toLowerCase().split(".").reverse();if(s.length>n.length)return!1;for(let i=0;i<s.length;i++)if(s[i]!==n[i])return!1;return!0}static extractDomain(e){try{return new URL(e).hostname}catch{return""}}static extractPath(e){try{return new URL(e).pathname}catch{return"/"}}}});function Ws(r){let e=r.toLowerCase();return e==="_global.json"||e==="_global.local.json"||e.endsWith(".local.json")}function _r(r){if(!fn.existsSync(r))return gh();let e=uo(Un.join(r,"_global.json"))||{},t=e.variables||{},n=e.defaultHeaders||{},s=fn.readdirSync(r).filter(l=>l.endsWith(".json")).filter(l=>!l.endsWith(".local.json")).filter(l=>!Ws(l)),i={};for(let l of s){let u=uo(Un.join(r,l))||{},p=Un.basename(l,".json");i[p]={description:u.description,requiresConfirmation:u.requiresConfirmation,variables:u.variables||{},secretVariables:u.secretVariables}}let a=(uo(Un.join(r,"_global.local.json"))||{}).variables||{},c={};for(let l of Object.keys(i)){let u=Un.join(r,`${l}.local.json`);if(fn.existsSync(u)){let p=uo(u)||{};c[l]={variables:p.variables||{}}}}return{globalVariables:t,defaultHeaders:n,environments:i,localVariables:a,localCredentials:c}}function gh(){return{globalVariables:{},defaultHeaders:{},environments:{},localVariables:{},localCredentials:{}}}function uo(r){try{if(!fn.existsSync(r))return null;let e=fn.readFileSync(r,"utf-8");return JSON.parse(e)}catch(e){return console.error(`[environment-file-loader] Failed to load JSON from ${r}:`,e),null}}var fn,Un,po=E(()=>{"use strict";fn=I(require("fs")),Un=I(require("path"))});var ct,Dr=E(()=>{"use strict";ct=class{buildUrl(e,t={},n={}){let s=e;return s=this.replacePathParams(s,t),s=this.appendQueryParams(s,n),s}replacePathParams(e,t){let n="",s="",i=e,o="",a=e.indexOf("?");a!==-1&&(o=e.substring(a),i=e.substring(0,a));let c=i.match(/^(https?:\/\/)([^\/]*)(\/.*)?$/);c&&(n=c[1],s=c[2],i=c[3]||"/");let l=/:(\w+)(?:\([^)]*\))?(\?)?/g,u=i.replace(l,(p,d,m)=>{let f=t[d];return f!==void 0&&f!==""?encodeURIComponent(f):m?"":(console.warn(`[UrlBuilder] Missing required path parameter: ${d}`),p)});return u=u.replace(/([^:])\/+/g,"$1/"),`${n}${s}${u}${o}`}extractPathParams(e){let t=/:(\w+)(?:\([^)]*\))?(\?)?/g,n=[],s;for(;(s=t.exec(e))!==null;)n.push(s[1]);return[...new Set(n)]}appendQueryParams(e,t){let n=e,s={};if(e.includes("?")){let[c,l]=e.split("?");n=c,l&&new URLSearchParams(l).forEach((p,d)=>{s[d]=p})}let i={...s,...t},o=new URLSearchParams;for(let[c,l]of Object.entries(i))l!=null&&o.append(c,l);let a=o.toString();return a?`${n}?${a}`:n}}});function yh(r=0,e=999){return Math.floor(Math.random()*(e-r+1))+r}function vh(){return Date.now()}function ld(){return(0,Jc.v4)()}function bh(){return(0,Jc.v4)()}function ud(r=10){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let n=0;n<r;n++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function Sh(){let r=ud(8).toLowerCase(),e=["example.com","test.org","mail.dev","sample.net"];return`${r}@${e[Math.floor(Math.random()*e.length)]}`}function xh(){return Math.random()<.5}function wh(r=10){let e="0123456789abcdef",t="";for(let n=0;n<r;n++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}function Rh(){return Math.floor(Date.now()/1e3)}function Ch(){return new Date().toISOString()}function Eh(){return new Date().toISOString().split("T")[0]}function qh(){return new Date().toISOString().split("T")[1].split(".")[0]}function Ah(){return new Date().toISOString()}function Ph(r=""){return Buffer.from(String(r)).toString("base64")}function kh(r=""){return Buffer.from(String(r),"base64").toString("utf-8")}function Ih(r=""){return encodeURIComponent(String(r))}function Th(r=""){return decodeURIComponent(String(r))}function Vn(r,e){let t=Oh[r];return t?e&&e.length>0?t(...e):t():null}function jr(r,e){let t=/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,n=null,s;for(;(s=t.exec(r))!==null;){let i=s[0],o=s[1];if(!(i in e)){let a=Vn(o);a!==null&&(n||(n={...e}),n[i]=a)}}return n??e}var Jc,Oh,Gc=E(()=>{"use strict";Jc=require("uuid");Oh={randomInt:yh,timestamp:vh,guid:bh,uuid:ld,randomUUID:ld,randomString:ud,randomHexadecimal:wh,randomEmail:Sh,randomBoolean:xh,isoTimestamp:Ah,timestamp_s:Rh,datetime:Ch,date:Eh,time:qh,base64Encode:Ph,base64Decode:kh,urlEncode:Ih,urlDecode:Th}});function mn(r){let e=r.trim();return!e||/^(\$?)[a-zA-Z_][a-zA-Z0-9_]*(\([^)]*\))?$/.test(e)||/(?<!\|)\|(?!\|)/.test(e)?!1:/[+\-*/%<>=!&|?:~^()[\]{}.,`]/.test(e)}function gt(r,e={}){try{let t={...e,Math,Date,JSON,Number,String,Boolean,Array,Object,parseInt,parseFloat,isNaN,isFinite,encodeURIComponent,decodeURIComponent,encodeURI,decodeURI,undefined:void 0,null:null,true:!0,false:!1,NaN:NaN,Infinity:1/0},n=fo.createContext(t);return fo.runInContext(r,n,{timeout:$h,displayErrors:!1})}catch{return}}var fo,$h,Ks=E(()=>{"use strict";fo=I(require("vm")),$h=100});function Fh(r){if(typeof r=="string"&&r.charCodeAt(0)===30)try{return JSON.parse(r.slice(1))}catch{return r}return r}function Lr(r){if(!r||!r.includes("|"))return null;let e=Nh(r);if(e.length<2)return null;let t=e[0].trim(),n=[];for(let s=1;s<e.length;s++){let i=e[s].trim();if(!i)continue;let o=Mh(i);o&&n.push(o)}return n.length===0?null:{input:t,filters:n}}function Nh(r){let e=[],t="",n=0,s=!1,i=!1;for(let o=0;o<r.length;o++){let a=r[o],c=o>0?r[o-1]:"",l=o<r.length-1?r[o+1]:"";if(c==="\\"){t+=a;continue}if(a==="'"&&!i)s=!s;else if(a==='"'&&!s)i=!i;else if(a==="("&&!s&&!i)n++;else if(a===")"&&!s&&!i)n--;else if(a==="|"&&n===0&&!s&&!i){if(l==="|"){t+="||",o++;continue}e.push(t),t="";continue}t+=a}return t&&e.push(t),e}function Mh(r){let e=r.indexOf("(");if(e===-1)return{name:r.trim(),args:[]};let t=r.substring(0,e).trim(),n=r.substring(e+1,r.lastIndexOf(")"));return{name:t,args:_h(n)}}function _h(r){if(!r||!r.trim())return[];let e=[],t="",n=!1,s=!1;for(let i=0;i<r.length;i++){let o=r[i];if((i>0?r[i-1]:"")==="\\"){t+=o;continue}if(o==="'"&&!s){n=!n,t+=o;continue}else if(o==='"'&&!n){s=!s,t+=o;continue}else if(o===","&&!n&&!s){e.push(t.trim()),t="";continue}t+=o}return t.trim()&&e.push(t.trim()),e}function ve(r,e){if(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))return r.slice(1,-1);let t=Number(r);if(!isNaN(t)&&r!=="")return t;if(r==="true")return!0;if(r==="false")return!1;if(e&&r in e){let n=Fh(e[r]),s=Number(n);return!isNaN(s)&&n!==""?s:n}return r}function Hr(r,e,t={}){let n=r;for(let s of e)n=Dh(n,s.name,s.args,t);return n}function Dh(r,e,t,n){switch(e){case"upper":return String(r).toUpperCase();case"lower":return String(r).toLowerCase();case"trim":return String(r).trim();case"length":return Array.isArray(r)?r.length:String(r).length;case"substring":{let s=ve(t[0],n),i=t[1]!==void 0?ve(t[1],n):void 0;return String(r).substring(s<0?String(r).length+s:s,i!==void 0?i<0?String(r).length+i:i:void 0)}case"replace":{let s=t[0]!==void 0?String(ve(t[0],n)):"",i=t[1]!==void 0?String(ve(t[1],n)):"";return String(r).replace(new RegExp(Lh(s),"g"),i)}case"split":{let s=t[0]!==void 0?String(ve(t[0],n)):",";return String(r).split(s)}case"join":{let s=t[0]!==void 0?String(ve(t[0],n)):",";return Array.isArray(r)?r.join(s):String(r)}case"removeQuotes":return String(r).replace(/["']/g,"");case"removeSpaces":return String(r).replace(/\s/g,"");case"format":{let s=t[0]!==void 0?String(ve(t[0],n)):"{0}";s=s.replace("{0}",String(r));for(let i=1;i<t.length;i++){let o=ve(t[i],n);s=s.replace(`{${i}}`,String(o))}return s}case"add":{let s=ve(t[0],n);return Number(r)+s}case"subtract":{let s=ve(t[0],n);return Number(r)-s}case"multiply":{let s=ve(t[0],n);return Number(r)*s}case"abs":return Math.abs(Number(r));case"btoa":return Buffer.from(String(r)).toString("base64");case"atob":return Buffer.from(String(r),"base64").toString("utf-8");case"urlEncode":return encodeURIComponent(String(r));case"urlDecode":return decodeURIComponent(String(r));case"hash":{let s=String(t[0]!==void 0?ve(t[0],n):"md5").toLowerCase(),i=String(t[1]!==void 0?ve(t[1],n):"base64"),a={md5:"md5",sha1:"sha1",sha256:"sha256",sha512:"sha512"}[s]||"md5";return mo.createHash(a).update(String(r)).digest(i)}case"hmac":{let s=t[0]?String(ve(t[0],n)):"",i=String(t[1]!==void 0?ve(t[1],n):"sha256").toLowerCase(),o=String(t[2]!==void 0?ve(t[2],n):"base64"),c={md5:"md5",sha1:"sha1",sha256:"sha256",sha512:"sha512"}[i]||"sha256";return mo.createHmac(c,s).update(String(r)).digest(o)}case"first":return Array.isArray(r)?r[0]:r;case"last":return Array.isArray(r)?r[r.length-1]:r;case"at":{let s=ve(t[0],n);return Array.isArray(r)?r.at(s):r}case"slice":{let s=ve(t[0],n),i=t[1]!==void 0?ve(t[1],n):void 0;return Array.isArray(r)?r.slice(s,i):String(r).slice(s,i)}case"unique":return Array.isArray(r)?[...new Set(r)]:r;case"filter":return!Array.isArray(r)||!t[0]?r:jh(r,t[0],n);case"map":{if(!Array.isArray(r))return r;let s=t.map(i=>String(ve(i,n)));return s.length===1?r.map(i=>Qs(i,s[0])):r.map(i=>{let o={};for(let a of s){let c=Qs(i,a);c!==void 0&&(o[a]=c)}return o})}case"prop":{let s=t[0]!==void 0?String(ve(t[0],n)):"";if(Array.isArray(r)){let i=r.map(o=>Qs(o,s)).filter(o=>o!==void 0);return i.length===1?i[0]:i.join(",")}return r&&typeof r=="object"?Qs(r,s):r}case"parseJSON":try{return JSON.parse(String(r))}catch{return r}case"stringify":try{return JSON.stringify(r)}catch{return String(r)}case"isEmail":return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(r));case"isUrl":try{return new URL(String(r)),!0}catch{return!1}case"setIfValue":return r||void 0;case"setNull":return r===null?null:r;default:return r}}function jh(r,e,t){let n=e.match(/^([\w.]+)\s*(>=|<=|!=|\*=|\^=|\$=|>|<|=)\s*(.+)$/);if(!n)return r;let[,s,i,o]=n,a=ve(o,t);return r.filter(c=>{let l=Qs(c,s);if(l===void 0)return!1;switch(i){case">":return Number(l)>Number(a);case">=":return Number(l)>=Number(a);case"<":return Number(l)<Number(a);case"<=":return Number(l)<=Number(a);case"=":return String(l)===String(a);case"!=":return String(l)!==String(a);case"*=":return String(l).includes(String(a));case"^=":return String(l).startsWith(String(a));case"$=":return String(l).endsWith(String(a));default:return!0}})}function Qs(r,e){if(!(!r||typeof r!="object"))return e in r?r[e]:e.split(".").reduce((t,n)=>t?.[n],r)}function Lh(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var mo,ho=E(()=>{"use strict";mo=I(require("crypto"))});function Zs(r,e){if(r)return r.split(",").map(t=>{let n=t.trim();if(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))return n.slice(1,-1);let s=Number(n);if(!isNaN(s)&&n!=="")return s;if(e&&n in e){let i=e[n],o=Number(i);return!isNaN(o)&&i!==""?o:i}return n})}var hn,gn,Br=E(()=>{"use strict";Gc();Ks();ho();hn=class r{allVariables;static MAX_RESOLUTION_DEPTH=20;constructor(e){this.allVariables={...e.globals,...e.collectionVariables,...e.environmentVariables,...e.variables}}resolveString(e,t=!1){return typeof e!="string"?e:this.resolveUntilStable(e,this.allVariables,t)}resolveStringWithExtra(e,t,n=!1){if(typeof e!="string")return e;let s={...this.allVariables,...t};return this.resolveUntilStable(e,s,n)}resolveUntilStable(e,t,n){let s=e;for(let i=0;i<r.MAX_RESOLUTION_DEPTH;i++){let o=this.resolveSinglePass(s,t,n);if(o===s)break;s=o}return s}resolveSinglePass(e,t,n){if(!n)return e.replace(/\{\{((?:[^}]|\}(?!\}))+)\}\}/g,(c,l)=>this.resolveTemplateContent(l.trim(),t,c));let s="",i=0,o=/\{\{((?:[^}]|\}(?!\}))+)\}\}/g,a;for(;(a=o.exec(e))!==null;){let c=a[1].trim(),l=this.resolveTemplateContent(c,t,a[0]);if(l!==a[0]){s+=e.slice(i,a.index);let u=this.getStringContext(e,a.index);s+=u?this.escapeForString(String(l),u):String(l)}else s+=e.slice(i,a.index+a[0].length);i=a.index+a[0].length}return s+=e.slice(i),s}resolveObject(e,t=!1){if(typeof e=="string")return this.resolveString(e,t);if(Array.isArray(e))return e.map(n=>this.resolveObject(n,t));if(e!==null&&typeof e=="object"){let n={};for(let[s,i]of Object.entries(e))n[s]=this.resolveObject(i,t);return n}return e}resolveObjectWithExtra(e,t,n=!1){if(typeof e=="string")return this.resolveStringWithExtra(e,t,n);if(Array.isArray(e))return e.map(s=>this.resolveObjectWithExtra(s,t,n));if(e!==null&&typeof e=="object"){let s={};for(let[i,o]of Object.entries(e))s[i]=this.resolveObjectWithExtra(o,t,n);return s}return e}resolveTemplateContent(e,t,n){let s=e.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(s){let a=Zs(s[2],t),c=Vn(s[1],a);return c!==null?String(c):n}let i=Lr(e);if(i){let a=this.resolveFilterInput(i.input,t);if(a!==void 0){let c=Hr(a,i.filters,t);return c!==void 0?String(c):n}return n}let o=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(\[.+\]|\..+)$/);if(o){let a=o[1];if(t[a]!==void 0){let c=this.deserializeValue(t[a]),l=o[2],u=this.resolvePropertyAccess(c,l);if(u!==void 0)return typeof u=="object"?JSON.stringify(u):String(u)}}if(t[e]!==void 0){let a=t[e];if(typeof a=="string"&&a.charCodeAt(0)===30){let c=a.slice(1);return c==="undefined"?"":c}return String(a)}if(mn(e)){let a=this.deserializeVariables(t),c=jr(e,a),l=gt(e,c);if(l!==void 0)return String(l)}return n}resolveFilterInput(e,t){if(e==="@")return"";if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);let n=e.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(n){let i=Zs(n[2],t),o=Vn(n[1],i);return o!==null?o:void 0}let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(\[.+\]|\..+)$/);if(s){let i=s[1];if(t[i]!==void 0){let o=this.deserializeValue(t[i]),a=this.resolvePropertyAccess(o,s[2]);if(a!==void 0)return a}}if(t[e]!==void 0)return this.deserializeValue(t[e]);if(mn(e)){let i=this.deserializeVariables(t),o=jr(e,i),a=gt(e,o);if(a!==void 0)return a}}deserializeValue(e){if(typeof e=="string"&&e.charCodeAt(0)===30){let t=e.slice(1);if(t==="undefined")return;try{return JSON.parse(t)}catch{return e}}return e}deserializeVariables(e){let t={};for(let[n,s]of Object.entries(e))t[n]=this.deserializeValue(s);return t}resolvePropertyAccess(e,t){let n=e,s=/\[(\d+|"[^"]*"|'[^']*')\]|\.([a-zA-Z_][a-zA-Z0-9_]*)/g,i;for(;(i=s.exec(t))!==null;){if(n==null)return;if(i[1]!==void 0){let o=i[1];/^\d+$/.test(o)?n=n[Number(o)]:n=n[o.slice(1,-1)]}else i[2]!==void 0&&(n=n[i[2]])}return n}escapeForString(e,t){let n=e.replace(/\\/g,"\\\\");return t==='"'?n=n.replace(/"/g,'\\"'):n=n.replace(/'/g,"\\'"),n.replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}getStringContext(e,t){let n=null;for(let s=0;s<t;s++){let i=e[s];(s>0?e[s-1]:"")!=="\\"&&(i==='"'||i==="'")&&(n===null?n=i:n===i&&(n=null))}return n}},gn=class{interpolate(e,t){return!e||typeof e!="string"?e:new hn({globals:{},collectionVariables:{},environmentVariables:{},variables:t}).resolveString(e,!0)}extractVariables(e){if(!e||typeof e!="string")return[];let t=[],n,s=/\{\{((?:[^}]|\}(?!\}))+)\}\}/g;for(;(n=s.exec(e))!==null;){let i=n[1].trim();!i.startsWith("$")&&!i.includes("|")&&/^[a-zA-Z_]\w*$/.test(i)&&(t.includes(i)||t.push(i))}return t}interpolateObject(e,t){if(e==null)return e;if(typeof e=="string")return this.interpolate(e,t);if(Array.isArray(e))return e.map(n=>this.interpolateObject(n,t));if(typeof e=="object"){let n={};for(let[s,i]of Object.entries(e))n[s]=this.interpolateObject(i,t);return n}return e}}});var $t,Ys=E(()=>{"use strict";$t=class{constructor(e,t,n){this.urlBuilder=e;this.interceptors=t;this.httpClient=n}urlBuilder;interceptors;httpClient;async execute(e){let t={},n;try{n=await this.interceptors.executeRequestInterceptors(e,t)}catch(s){let i=await this.interceptors.executeErrorInterceptors(s,e,t);if(i)return i;throw s}try{let s=await this.httpClient.send(n);return await this.interceptors.executeResponseInterceptors(s,n,t)}catch(s){let i=await this.interceptors.executeErrorInterceptors(s,n,t);if(i)return i;throw s}}buildUrl(e,t={},n={}){return this.urlBuilder.buildUrl(e,t,n)}}});var Ft,Xs=E(()=>{"use strict";Ft=class{requestInterceptors=[];responseInterceptors=[];errorInterceptors=[];addRequestInterceptor(e){return this.requestInterceptors.push(e),this.sortByPriority(this.requestInterceptors),this}addResponseInterceptor(e){return this.responseInterceptors.push(e),this.sortByPriority(this.responseInterceptors),this}addErrorInterceptor(e){return this.errorInterceptors.push(e),this.sortByPriority(this.errorInterceptors),this}removeRequestInterceptor(e){let t=this.requestInterceptors.findIndex(n=>n.name===e);return t>=0?(this.requestInterceptors.splice(t,1),!0):!1}removeResponseInterceptor(e){let t=this.responseInterceptors.findIndex(n=>n.name===e);return t>=0?(this.responseInterceptors.splice(t,1),!0):!1}removeErrorInterceptor(e){let t=this.errorInterceptors.findIndex(n=>n.name===e);return t>=0?(this.errorInterceptors.splice(t,1),!0):!1}async executeRequestInterceptors(e,t){let n=e;for(let s of this.requestInterceptors)try{n=await s.intercept(n,t)}catch(i){throw console.error(`[InterceptorChain] Request interceptor '${s.name}' failed:`,i),i}return n}async executeResponseInterceptors(e,t,n){let s=e;for(let i of this.responseInterceptors)try{s=await i.intercept(s,t,n)}catch(o){throw console.error(`[InterceptorChain] Response interceptor '${i.name}' failed:`,o),o}return s}async executeErrorInterceptors(e,t,n){for(let s of this.errorInterceptors)try{let i=await s.handle(e,t,n);if(i)return i}catch(i){console.error(`[InterceptorChain] Error interceptor '${s.name}' failed:`,i)}}clear(){this.requestInterceptors=[],this.responseInterceptors=[],this.errorInterceptors=[]}getRegisteredInterceptors(){return{request:this.requestInterceptors.map(e=>e.name),response:this.responseInterceptors.map(e=>e.name),error:this.errorInterceptors.map(e=>e.name)}}sortByPriority(e){e.sort((t,n)=>(t.priority??100)-(n.priority??100))}}});function dd(r,e,t,n){let s=Buffer.concat([Buffer.from(r,"utf8"),n||Buffer.alloc(0)]),i=[],o=Buffer.alloc(0);for(;Buffer.concat(i).length<e+t;)o=Fe.createHash("md5").update(Buffer.concat([o,s])).digest(),i.push(o);let a=Buffer.concat(i);return{key:a.subarray(0,e),iv:a.subarray(e,e+t)}}function Wc(r,e,t){let n=s=>r==="aes"?`aes-${s*8}-cbc`:r==="des"?"des-cbc":r==="des-ede3"?"des-ede3-cbc":r;return{encrypt(s,i,o){let a=s instanceof re?s.toBuffer():Buffer.from(String(s),"utf8");if(typeof i=="string"){let c=Fe.randomBytes(8),{key:l,iv:u}=dd(i,e,t,c),p=Fe.createCipheriv(n(e),l,u),d=Buffer.concat([p.update(a),p.final()]),m=Buffer.concat([Buffer.from("Salted__"),c,d]);return{ciphertext:new re(d),salt:new re(c),toString:f=>f?f.stringify(new re(m)):m.toString("base64")}}else{let c=i.toBuffer(),l=o?.iv&&o.iv instanceof re?o.iv.toBuffer():Buffer.alloc(t),u=Fe.createCipheriv(n(c.length),c,l);o?.padding===!1&&u.setAutoPadding(!1);let p=Buffer.concat([u.update(a),u.final()]);return{ciphertext:new re(p),toString:d=>d?d.stringify(new re(p)):p.toString("base64")}}},decrypt(s,i,o){if(typeof i=="string"){let a=typeof s=="string"?Buffer.from(s,"base64"):s.ciphertext.toBuffer(),c,l;a.subarray(0,8).toString()==="Salted__"?(l=a.subarray(8,16),c=a.subarray(16)):(l=Buffer.alloc(0),c=a);let{key:u,iv:p}=dd(i,e,t,l),d=Fe.createDecipheriv(n(e),u,p);return new re(Buffer.concat([d.update(c),d.final()]))}else{let a=i.toBuffer(),c=o?.iv&&o.iv instanceof re?o.iv.toBuffer():Buffer.alloc(t),l=typeof s=="string"?Buffer.from(s,"base64"):s.ciphertext?s.ciphertext.toBuffer():Buffer.from(s),u=Fe.createDecipheriv(n(a.length),a,c);return o?.padding===!1&&u.setAutoPadding(!1),new re(Buffer.concat([u.update(l),u.final()]))}}}}function pd(){let r=t=>n=>{let s=n instanceof re?n.toBuffer():Buffer.from(String(n),"utf8");return new re(Fe.createHash(t).update(s).digest())},e=t=>(n,s)=>{let i=n instanceof re?n.toBuffer():Buffer.from(String(n),"utf8"),o=s instanceof re?s.toBuffer():Buffer.from(String(s),"utf8");return new re(Fe.createHmac(t,o).update(i).digest())};return{MD5:r("md5"),SHA1:r("sha1"),SHA224:r("sha224"),SHA256:r("sha256"),SHA384:r("sha384"),SHA512:r("sha512"),SHA3:r("sha3-256"),RIPEMD160:r("ripemd160"),HmacMD5:e("md5"),HmacSHA1:e("sha1"),HmacSHA256:e("sha256"),HmacSHA512:e("sha512"),AES:Wc("aes",32,16),DES:Wc("des",8,8),TripleDES:Wc("des-ede3",24,8),PBKDF2(t,n,s){let i=t instanceof re?t.toBuffer():Buffer.from(String(t),"utf8"),o=n instanceof re?n.toBuffer():Buffer.from(String(n),"utf8"),a=(s?.keySize||4)*4,c=s?.iterations||1;return new re(Fe.pbkdf2Sync(i,o,c,a,"sha1"))},enc:{Base64:{stringify:t=>(t instanceof re?t.toBuffer():Buffer.from(String(t))).toString("base64"),parse:t=>re.fromBase64(t)},Utf8:{stringify:t=>(t instanceof re?t.toBuffer():Buffer.from(String(t))).toString("utf8"),parse:t=>re.fromUtf8(t)},Hex:{stringify:t=>(t instanceof re?t.toBuffer():Buffer.from(String(t))).toString("hex"),parse:t=>re.fromHex(t)},Latin1:{stringify:t=>(t instanceof re?t.toBuffer():Buffer.from(String(t))).toString("latin1"),parse:t=>new re(Buffer.from(t,"latin1"))},Utf16:{stringify:t=>(t instanceof re?t.toBuffer():Buffer.from(String(t))).toString("utf16le"),parse:t=>new re(Buffer.from(t,"utf16le"))},Utf16BE:{stringify:t=>(t instanceof re?t.toBuffer():Buffer.from(String(t))).swap16().toString("utf16le"),parse:t=>new re(Buffer.from(t,"utf16le").swap16())}},lib:{WordArray:{create:t=>t?typeof t=="string"?new re(Buffer.from(t,"utf8")):Buffer.isBuffer(t)?new re(t):new re(Buffer.from(String(t))):new re(Buffer.alloc(0)),random:t=>new re(Fe.randomBytes(t))}},pad:{Pkcs7:{_name:"pkcs7"},NoPadding:{_name:"nopadding"},ZeroPadding:{_name:"zeropadding"}},mode:{CBC:{_name:"cbc"},ECB:{_name:"ecb"}}}}var Fe,re,fd=E(()=>{"use strict";Fe=I(require("crypto")),re=class r{_buffer;constructor(e){this._buffer=typeof e=="string"?Buffer.from(e,"utf8"):e}toString(e){return e?e.stringify(this):this._buffer.toString("hex")}toBuffer(){return this._buffer}static fromHex(e){return new r(Buffer.from(e,"hex"))}static fromBase64(e){return new r(Buffer.from(e,"base64"))}static fromUtf8(e){return new r(Buffer.from(e,"utf8"))}}});function ti(){return{format:(r,e)=>{let t=r?new Date(r):new Date;return e==="YYYY-MM-DD"?t.toISOString().split("T")[0]:t.toISOString()},unix:()=>Math.floor(Date.now()/1e3),utc:()=>{let r=new Date;return{format:()=>r.toISOString(),toISOString:()=>r.toISOString()}},__isShim:!0,__warning:"This is a lightweight shim. For full features, install moment.js via modules/package.json"}}function Bh(){return{get:(r,e,t)=>{let n=e.split("."),s=r;for(let i of n)if(s=s?.[i],s===void 0)return t;return s},set:(r,e,t)=>{let n=e.split("."),s=r;for(let i=0;i<n.length-1;i++)s[n[i]]||(s[n[i]]={}),s=s[n[i]];return s[n[n.length-1]]=t,r},cloneDeep:r=>JSON.parse(JSON.stringify(r)),keys:r=>Object.keys(r??{}),values:r=>Object.values(r??{}),entries:r=>Object.entries(r??{}),each(r,e){Array.isArray(r)?r.forEach((t,n)=>e(t,n,r)):r&&typeof r=="object"&&Object.entries(r).forEach(([t,n])=>e(n,t,r))},forEach(r,e){Array.isArray(r)?r.forEach((t,n)=>e(t,n,r)):r&&typeof r=="object"&&Object.entries(r).forEach(([t,n])=>e(n,t,r))},map:(r,e)=>(Array.isArray(r)?r:Object.values(r??{})).map(t=>e(t)),filter:(r,e)=>(Array.isArray(r)?r:Object.values(r??{})).filter(t=>e(t)),find:(r,e)=>(Array.isArray(r)?r:Object.values(r??{})).find(t=>e(t)),reduce:(r,e,t)=>(Array.isArray(r)?r:Object.values(r??{})).reduce((n,s)=>e(n,s),t),includes:(r,e)=>Array.isArray(r)?r.includes(e):Object.values(r??{}).includes(e),isObject:r=>r!==null&&typeof r=="object"&&!Array.isArray(r),isArray:r=>Array.isArray(r),isString:r=>typeof r=="string",isNumber:r=>typeof r=="number",isFunction:r=>typeof r=="function",isNil:r=>r==null,isEmpty:r=>r==null?!0:Array.isArray(r)||typeof r=="string"?r.length===0:typeof r=="object"?Object.keys(r).length===0:!1,assign:(r,...e)=>Object.assign(r,...e),merge:(r,...e)=>{let t={...r};for(let n of e)for(let[s,i]of Object.entries(n??{}))t[s]=i&&typeof i=="object"&&!Array.isArray(i)?{...t[s]??{},...i}:i;return t},omit:(r,e)=>{let t={...r};for(let n of e)delete t[n];return t},pick:(r,e)=>{let t={};for(let n of e)n in(r??{})&&(t[n]=r[n]);return t}}}function go(r,e){return new ei(r,e)}var Hh,zn,md,yt,hd,ei,Kc=E(()=>{"use strict";Hh=I(require("crypto")),zn=I(require("fs")),md=require("module"),yt=I(require("path")),hd=require("uuid");ei=class{availableModules=new Set;customModulesRequire;globalSetupExports;options;modulesPath=null;moduleCache=new Map;resolveStack=new Set;builtinModules={uuid:()=>({v4:hd.v4}),crypto:()=>Hh,path:()=>yt,querystring:()=>require("querystring"),lodash:()=>this.loadOptionalModule("lodash",()=>require("lodash"),Bh),moment:()=>this.loadOptionalModule("moment",()=>require("moment"),ti),tv4:()=>this.loadOptionalModule("tv4",()=>require("tv4")),ajv:()=>this.loadOptionalModule("ajv",()=>require("ajv")),"crypto-js":()=>this.loadOptionalModule("crypto-js",()=>require("crypto-js"),()=>{throw new Error('crypto-js npm module is not installed. The built-in CryptoJS global is already available in scripts with AES/DES/TripleDES/hash/HMAC/PBKDF2 support. If you need the exact npm package, add "crypto-js" to your modules/package.json and run npm install.')})};constructor(e=[],t={}){this.options={allowCustomModules:!0,maxResolveDepth:10,...t,outputChannel:t.outputChannel||{appendLine:n=>{console.log(`[ModuleLoader] ${n}`)}}};for(let n of e){let s=yt.resolve(n);if(this.initializeModules(s)){this.modulesPath=s;break}}}loadOptionalModule(e,t,n){try{return t()}catch{if(this.customModulesRequire)try{return console.debug(`[ModuleLoader] ${e} not in core, trying user modules`),this.customModulesRequire(e)}catch{this.logModuleWarning(e,"user")}else this.logModuleWarning(e,"core");if(n)return console.warn(`[ModuleLoader] Using shim for ${e}. Some features may be limited.`),n();throw new Error(this.getModuleInstallInstructions(e))}}logModuleWarning(e,t){let s={moment:"Date/time manipulation",lodash:"Utility functions",tv4:"JSON Schema validation (v4)",ajv:"JSON Schema validation"}[e]||e;console.warn(`[ModuleLoader] ${s} functionality (${e}) is not available.
253
253
  ${this.getModuleInstallInstructions(e)}`)}getModuleInstallInstructions(e){let n={moment:"^2.30.1",lodash:"^4.17.21",tv4:"^1.3.0",ajv:"^8.17.1"}[e]||"latest";return`To use ${e}, add it to http-forge/modules/package.json:
254
254
  {
255
255
  "dependencies": {
256
256
  "${e}": "${n}"
257
257
  }
258
258
  }
259
- Then run: cd http-forge/modules && npm install`}initializeModules(e){if(this.logDebug("Initializing module loader..."),!this.options.allowCustomModules)return this.logDebug("Custom modules disabled by configuration"),!0;try{let t=vt.resolve(e,"package.json");if(!Bn.existsSync(t))return this.logDebug(`No modules/package.json found at ${e}`),!1;let n=Bn.realpathSync(t);return this.customModulesRequire=(0,ud.createRequire)(n),this.loadAvailableModules(e),this.loadGlobalSetup(e),this.logDebug(`Module loader initialized with ${this.availableModules.size} workspace modules`),!0}catch(t){return console.error("Failed to initialize modules:",t),!1}}loadAvailableModules(e){try{let t=vt.join(e,"package.json"),n=Bn.readFileSync(t,"utf-8"),s=JSON.parse(n);if(typeof s!="object"||s===null)throw new Error("Invalid package.json: must be an object");let i=s.dependencies||{},o=s.devDependencies||{};if(typeof i!="object"||typeof o!="object")throw new Error("Invalid dependencies in package.json");Object.keys(i).forEach(a=>{typeof a=="string"&&a.trim()&&this.availableModules.add(a.trim())}),Object.keys(o).forEach(a=>{typeof a=="string"&&a.trim()&&this.availableModules.add(a.trim())}),this.logDebug(`Loaded ${this.availableModules.size} modules from package.json`)}catch(t){let n=`Failed to load workspace modules from package.json: ${t instanceof Error?t.message:t}`;this.logError(n)}}loadGlobalSetup(e){let t=vt.join(e,"global-setup.js");if(Bn.existsSync(t))try{this.customModulesRequire&&(this.globalSetupExports=this.customModulesRequire("./global-setup.js"))}catch(n){console.error("Failed to load global-setup.js:",n),this.globalSetupExports=void 0}}createRequireFunction(){return e=>{let t=Date.now();try{if(this.resolveStack.has(e))throw new Error(`Circular dependency detected: ${Array.from(this.resolveStack).join(" -> ")} -> ${e}`);if(this.resolveStack.size>=this.options.maxResolveDepth)throw new Error(`Maximum module resolve depth (${this.options.maxResolveDepth}) exceeded`);this.resolveStack.add(e);let n=this.moduleCache.get(e);if(n)return this.logDebug(`Module cache hit: ${e}`),n.module;if(this.builtinModules[e]){this.logDebug(`Loading built-in module: ${e}`);let o=this.builtinModules[e]();return this.cacheModule(e,o,"builtin",Date.now()-t),o}if(!this.modulesPath)throw new Error("Module loading is not initialized. No valid modules/ directory found. Create .http-forge/assets/modules/package.json first.");if(e.startsWith("./")||e.startsWith("../")){if(!this.customModulesRequire)throw new Error(`Cannot load local module '${e}': No modules/ folder found. Create .http-forge/assets/modules/package.json first.`);let o=vt.resolve(this.modulesPath,e),a=vt.normalize(o),c=vt.normalize(this.modulesPath);if(!a.startsWith(c))throw new Error(`Security violation: Attempt to load module outside modules directory: ${e}`);try{this.logDebug(`Loading relative module: ${e}`);let l=this.customModulesRequire(e);return this.cacheModule(e,l,"relative",Date.now()-t),l}catch(l){throw new Error(`Failed to load local module '${e}': ${l.message}`)}}if(this.availableModules.has(e)&&this.customModulesRequire)try{this.logDebug(`Loading workspace module: ${e}`);let o=this.customModulesRequire(e);return this.cacheModule(e,o,"workspace",Date.now()-t),o}catch(o){throw new Error(`Module '${e}' is in package.json but failed to load: ${o.message}`)}let s=this.getModuleSuggestions(e),i=`Module '${e}' is not available.`;throw s.length>0&&(i+=` Did you mean: ${s.join(", ")}?`),i+=`
260
- Add it to http-forge/modules/package.json and run npm install.`,new Error(i)}finally{this.resolveStack.delete(e)}}}getModuleSuggestions(e){let t=this.getAvailableModules(),n=[];for(let s of t)if(s.startsWith(e.substring(0,3))&&(n.push(s),n.length>=3))break;return n}cacheModule(e,t,n,s){this.moduleCache.set(e,{module:t,source:n,resolveTime:s}),s>100&&this.logDebug(`Slow module load: ${e} took ${s}ms`)}getGlobalSetupExports(){return this.globalSetupExports}hasCustomModules(){return this.customModulesRequire!==void 0}getAvailableModules(){return[...Object.keys(this.builtinModules),...Array.from(this.availableModules)].sort()}clearCache(){this.moduleCache.clear(),this.logDebug("Module cache cleared")}getCacheStats(){return{size:this.moduleCache.size,hits:0}}logDebug(e){this.options.outputChannel&&this.options.outputChannel.appendLine(`[ModuleLoader] ${e}`)}logError(e){this.options.outputChannel&&this.options.outputChannel.appendLine(`[ModuleLoader ERROR] ${e}`),console.error(`[ModuleLoader ERROR] ${e}`)}}});function pd(r){let e=new Set,t=new Set,n=(u,d)=>{try{u(...d)}catch(p){try{r(p)}catch{}}},s={setTimeout:(u,d,...p)=>{if(typeof u!="function")return setTimeout(()=>{},d);let m=setTimeout(()=>{e.delete(m),n(u,p)},d);return e.add(m),m},clearTimeout:u=>{u!=null&&(e.delete(u),clearTimeout(u))},setInterval:(u,d,...p)=>{if(typeof u!="function")return setInterval(()=>{},d);let m=setInterval(()=>{n(u,p)},d);return t.add(m),m},clearInterval:u=>{u!=null&&(t.delete(u),clearInterval(u))}},i=()=>e.size+t.size,o=()=>{for(let u of e)clearTimeout(u);for(let u of t)clearInterval(u);e.clear(),t.clear()},a=u=>new Promise(d=>setTimeout(d,u)),c=async u=>{let d=Date.now();for(await a(0);i()>0;){let p=Date.now()-d;if(p>=u)return o(),{timedOut:!0,elapsedMs:Date.now()-d};let m=u-p;await a(Math.min(15,m))}return await a(0),i()>0?l(d,u):{timedOut:!1,elapsedMs:Date.now()-d}},l=async(u,d)=>{for(;i()>0;){let p=Date.now()-u;if(p>=d)return o(),{timedOut:!0,elapsedMs:Date.now()-u};let m=d-p;await a(Math.min(15,m))}return{timedOut:!1,elapsedMs:Date.now()-u}};return{timers:s,pendingCount:i,clearAll:o,drain:c}}var fd=E(()=>{"use strict"});function Un(r,e,t="$"){let n=[];if(e===null||typeof e!="object")return n;let s=i=>i===null?"null":Array.isArray(i)?"array":Number.isInteger(i)?"integer":typeof i;if(e.type!==void 0){let i=Array.isArray(e.type)?e.type:[e.type],o=s(r);if(!i.some(c=>c===o||c==="number"&&o==="integer"))return n.push(`${t}: expected type ${i.join("|")} but got ${o}`),n}if(Array.isArray(e.enum)&&!e.enum.some(i=>JSON.stringify(i)===JSON.stringify(r))&&n.push(`${t}: value ${JSON.stringify(r)} is not in enum ${JSON.stringify(e.enum)}`),typeof r=="number"&&(typeof e.minimum=="number"&&r<e.minimum&&n.push(`${t}: ${r} is below minimum ${e.minimum}`),typeof e.maximum=="number"&&r>e.maximum&&n.push(`${t}: ${r} is above maximum ${e.maximum}`)),typeof r=="string"&&(typeof e.minLength=="number"&&r.length<e.minLength&&n.push(`${t}: string length ${r.length} is below minLength ${e.minLength}`),typeof e.maxLength=="number"&&r.length>e.maxLength&&n.push(`${t}: string length ${r.length} is above maxLength ${e.maxLength}`),typeof e.pattern=="string"&&!new RegExp(e.pattern).test(r)&&n.push(`${t}: string does not match pattern ${e.pattern}`)),s(r)==="object"){if(Array.isArray(e.required))for(let i of e.required)i in r||n.push(`${t}: missing required property "${i}"`);if(e.properties&&typeof e.properties=="object")for(let[i,o]of Object.entries(e.properties))i in r&&n.push(...Un(r[i],o,`${t}.${i}`));if(e.additionalProperties===!1&&e.properties){let i=new Set(Object.keys(e.properties));for(let o of Object.keys(r))i.has(o)||n.push(`${t}: additional property "${o}" is not allowed`)}}return Array.isArray(r)&&e.items&&typeof e.items=="object"&&r.forEach((i,o)=>{n.push(...Un(i,e.items,`${t}[${o}]`))}),n}var mo=E(()=>{"use strict"});function jh(r,e){if(r==null)return{exists:!1,value:void 0};if(!e)return{exists:!0,value:r};let n=e.replace(/\[(\d+)\]/g,".$1").replace(/\[("([^"]*)"|'([^']*)')\]/g,".$2").replace(/^\./,"").split(".").filter(Boolean),s=r;for(let i of n){if(s==null)return{exists:!1,value:void 0};let o=/^\d+$/.test(i)?Number(i):i;if(!(o in Object(s)))return{exists:!1,value:void 0};s=s[o]}return{exists:!0,value:s}}function Vn(r){return{_value:r,_negated:!1,_deep:!1,_nested:!1,_own:!1,_ordered:!1,_any:!1,_all:!1,_itself:!1,_lastDeltaAssertion:void 0,get to(){return this},get be(){return this},get been(){return this},get is(){return this},get that(){return this},get which(){return this},get and(){return this},get has(){return this},get have(){return this},get with(){return this},get at(){return this},get of(){return this},get same(){return this},get but(){return this},get does(){return this},get still(){return this},get also(){return this},get not(){return this._negated=!this._negated,this},get deep(){return this._deep=!0,this},get nested(){return this._nested=!0,this},get own(){return this._own=!0,this},get ordered(){return this._ordered=!0,this},get any(){return this._any=!0,this._all=!1,this},get all(){return this._all=!0,this._any=!1,this},get itself(){return this._itself=!0,this},_assert(t,n){if(!(this._negated?!t:t))throw new Error(n)},_readSubjectValue(t,n){if(n!==void 0){if(t==null)throw new Error(`Expected subject object for property "${n}"`);return t[n]}if(typeof t!="function")throw new Error("Expected subject to be a function when property is not provided");return t()},_resetModifiers(){this._nested=!1,this._own=!1,this._ordered=!1,this._any=!1,this._all=!1,this._itself=!1},get ok(){return this._assert(!!this._value,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be truthy`),this},get true(){return this._assert(this._value===!0,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be true`),this},get false(){return this._assert(this._value===!1,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be false`),this},get null(){return this._assert(this._value===null,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be null`),this},get undefined(){return this._assert(this._value===void 0,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be undefined`),this},get NaN(){return this._assert(Number.isNaN(this._value),`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be NaN`),this},get exist(){return this._assert(this._value!==null&&this._value!==void 0,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}exist`),this},get exists(){return this.exist},get empty(){let t=!1;return this._value===null||this._value===void 0?t=!0:typeof this._value=="string"||Array.isArray(this._value)?t=this._value.length===0:typeof this._value=="object"&&(t=Object.keys(this._value).length===0),this._assert(t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be empty`),this},get arguments(){let t=Object.prototype.toString.call(this._value)==="[object Arguments]";return this._assert(t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be arguments`),this},get Arguments(){return this.arguments},get extensible(){let t=typeof this._value=="object"&&this._value!==null?Object.isExtensible(this._value):!1;return this._assert(t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be extensible`),this},get sealed(){let t=typeof this._value=="object"&&this._value!==null?Object.isSealed(this._value):!0;return this._assert(t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be sealed`),this},get frozen(){let t=typeof this._value=="object"&&this._value!==null?Object.isFrozen(this._value):!0;return this._assert(t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be frozen`),this},get finite(){let t=typeof this._value=="number"&&Number.isFinite(this._value);return this._assert(t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be finite`),this},equal(t){return this._deep?(this._deep=!1,this.eql(t)):(this._assert(this._value===t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}equal ${JSON.stringify(t)}`),this)},eq(t){return this.equal(t)},equals(t){return this.equal(t)},eql(t){return this._assert(JSON.stringify(this._value)===JSON.stringify(t),`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}deeply equal ${JSON.stringify(t)}`),this},eqls(t){return this.eql(t)},include(t){let n=!1;return typeof this._value=="string"?n=this._value.includes(t):Array.isArray(this._value)?n=this._value.includes(t):typeof this._value=="object"&&this._value!==null&&(n=t in this._value),this._assert(n,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}include ${JSON.stringify(t)}`),this},includes(t){return this.include(t)},contain(t){return this.include(t)},contains(t){return this.include(t)},oneOf(t){return this._assert(Array.isArray(t)&&t.includes(this._value),`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be one of ${JSON.stringify(t)}`),this},property(t,n){let s=this._deep||this._nested,i=this._own;if(s&&i)throw new Error("Cannot combine own and nested/deep for property assertion");this._deep=!1;let o=s?jh(this._value,t):i?{exists:typeof this._value=="object"&&this._value!==null&&Object.prototype.hasOwnProperty.call(this._value,t),value:this._value?.[t]}:{exists:typeof this._value=="object"&&this._value!==null&&t in this._value,value:this._value?.[t]};return n!==void 0?this._assert(o.exists&&o.value===n,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}have property "${t}" with value ${JSON.stringify(n)}`):this._assert(o.exists,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}have property "${t}"`),this._resetModifiers(),this},ownPropertyDescriptor(t,n){let s=this._value===null||this._value===void 0?void 0:Object(this._value),i=s?Object.getOwnPropertyDescriptor(s,t):void 0,o=i!==void 0;return o&&n!==void 0&&(o=Object.entries(n).every(([a,c])=>i[a]===c)),this._assert(o,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}have own property descriptor "${t}"`),this},haveOwnPropertyDescriptor(t,n){return this.ownPropertyDescriptor(t,n)},keys(...t){let n=Array.isArray(t[0])?t[0]:t,s=Object.keys(this._value||{}),i=n.every(c=>s.includes(c)),o=n.some(c=>s.includes(c)),a=this._any&&!this._all;return this._assert(a?o:i,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}have keys ${JSON.stringify(n)}`),this._resetModifiers(),this},key(...t){return this.keys(...t)},members(t){let n=this._value,s=Array.isArray(n)&&Array.isArray(t)&&t.every(o=>n.some(a=>JSON.stringify(a)===JSON.stringify(o))),i=Array.isArray(n)&&Array.isArray(t)&&t.every((o,a)=>JSON.stringify(n[a])===JSON.stringify(o));return this._assert(this._ordered?i:s,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}have members ${JSON.stringify(t)}`),this._resetModifiers(),this},string(t){return this._assert(typeof this._value=="string"&&this._value.includes(t),`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}contain string "${t}"`),this},match(t){return this._assert(t.test(String(this._value)),`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}match ${t}`),this},matches(t){return this.match(t)},a(t){let n=Array.isArray(this._value)?"array":typeof this._value;return this._assert(n===t.toLowerCase(),`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be a(n) ${t} (got ${n})`),this},an(t){return this.a(t)},length(t){let n=Array.isArray(this._value)||typeof this._value=="string"?this._value.length:Object.keys(this._value||{}).length;return this._assert(n===t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}have length ${t}`),this},lengthOf(t){return this.length(t)},satisfy(t){return this._assert(!!t(this._value),`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}satisfy matcher`),this},satisfies(t){return this.satisfy(t)},jsonSchema(t){let n=this._value;if(typeof n=="string")try{n=JSON.parse(n)}catch{throw new Error("Expected value to be valid JSON before JSON schema validation")}let s=Un(n,t);return this._assert(s.length===0,`Expected value to ${this._negated?"not ":""}match JSON schema:
259
+ Then run: cd http-forge/modules && npm install`}initializeModules(e){if(this.logDebug("Initializing module loader..."),!this.options.allowCustomModules)return this.logDebug("Custom modules disabled by configuration"),!0;try{let t=yt.resolve(e,"package.json");if(!zn.existsSync(t))return this.logDebug(`No modules/package.json found at ${e}`),!1;let n=zn.realpathSync(t);return this.customModulesRequire=(0,md.createRequire)(n),this.loadAvailableModules(e),this.loadGlobalSetup(e),this.logDebug(`Module loader initialized with ${this.availableModules.size} workspace modules`),!0}catch(t){return console.error("Failed to initialize modules:",t),!1}}loadAvailableModules(e){try{let t=yt.join(e,"package.json"),n=zn.readFileSync(t,"utf-8"),s=JSON.parse(n);if(typeof s!="object"||s===null)throw new Error("Invalid package.json: must be an object");let i=s.dependencies||{},o=s.devDependencies||{};if(typeof i!="object"||typeof o!="object")throw new Error("Invalid dependencies in package.json");Object.keys(i).forEach(a=>{typeof a=="string"&&a.trim()&&this.availableModules.add(a.trim())}),Object.keys(o).forEach(a=>{typeof a=="string"&&a.trim()&&this.availableModules.add(a.trim())}),this.logDebug(`Loaded ${this.availableModules.size} modules from package.json`)}catch(t){let n=`Failed to load workspace modules from package.json: ${t instanceof Error?t.message:t}`;this.logError(n)}}loadGlobalSetup(e){let t=yt.join(e,"global-setup.js");if(zn.existsSync(t))try{this.customModulesRequire&&(this.globalSetupExports=this.customModulesRequire("./global-setup.js"))}catch(n){console.error("Failed to load global-setup.js:",n),this.globalSetupExports=void 0}}createRequireFunction(){return e=>{let t=Date.now();try{if(this.resolveStack.has(e))throw new Error(`Circular dependency detected: ${Array.from(this.resolveStack).join(" -> ")} -> ${e}`);if(this.resolveStack.size>=this.options.maxResolveDepth)throw new Error(`Maximum module resolve depth (${this.options.maxResolveDepth}) exceeded`);this.resolveStack.add(e);let n=this.moduleCache.get(e);if(n)return this.logDebug(`Module cache hit: ${e}`),n.module;if(this.builtinModules[e]){this.logDebug(`Loading built-in module: ${e}`);let o=this.builtinModules[e]();return this.cacheModule(e,o,"builtin",Date.now()-t),o}if(!this.modulesPath)throw new Error("Module loading is not initialized. No valid modules/ directory found. Create .http-forge/assets/modules/package.json first.");if(e.startsWith("./")||e.startsWith("../")){if(!this.customModulesRequire)throw new Error(`Cannot load local module '${e}': No modules/ folder found. Create .http-forge/assets/modules/package.json first.`);let o=yt.resolve(this.modulesPath,e),a=yt.normalize(o),c=yt.normalize(this.modulesPath);if(!a.startsWith(c))throw new Error(`Security violation: Attempt to load module outside modules directory: ${e}`);try{this.logDebug(`Loading relative module: ${e}`);let l=this.customModulesRequire(e);return this.cacheModule(e,l,"relative",Date.now()-t),l}catch(l){throw new Error(`Failed to load local module '${e}': ${l.message}`)}}if(this.availableModules.has(e)&&this.customModulesRequire)try{this.logDebug(`Loading workspace module: ${e}`);let o=this.customModulesRequire(e);return this.cacheModule(e,o,"workspace",Date.now()-t),o}catch(o){throw new Error(`Module '${e}' is in package.json but failed to load: ${o.message}`)}let s=this.getModuleSuggestions(e),i=`Module '${e}' is not available.`;throw s.length>0&&(i+=` Did you mean: ${s.join(", ")}?`),i+=`
260
+ Add it to http-forge/modules/package.json and run npm install.`,new Error(i)}finally{this.resolveStack.delete(e)}}}getModuleSuggestions(e){let t=this.getAvailableModules(),n=[];for(let s of t)if(s.startsWith(e.substring(0,3))&&(n.push(s),n.length>=3))break;return n}cacheModule(e,t,n,s){this.moduleCache.set(e,{module:t,source:n,resolveTime:s}),s>100&&this.logDebug(`Slow module load: ${e} took ${s}ms`)}getGlobalSetupExports(){return this.globalSetupExports}hasCustomModules(){return this.customModulesRequire!==void 0}getAvailableModules(){return[...Object.keys(this.builtinModules),...Array.from(this.availableModules)].sort()}clearCache(){this.moduleCache.clear(),this.logDebug("Module cache cleared")}getCacheStats(){return{size:this.moduleCache.size,hits:0}}logDebug(e){this.options.outputChannel&&this.options.outputChannel.appendLine(`[ModuleLoader] ${e}`)}logError(e){this.options.outputChannel&&this.options.outputChannel.appendLine(`[ModuleLoader ERROR] ${e}`),console.error(`[ModuleLoader ERROR] ${e}`)}}});function gd(r){let e=new Set,t=new Set,n=(u,p)=>{try{u(...p)}catch(d){try{r(d)}catch{}}},s={setTimeout:(u,p,...d)=>{if(typeof u!="function")return setTimeout(()=>{},p);let m=setTimeout(()=>{e.delete(m),n(u,d)},p);return e.add(m),m},clearTimeout:u=>{u!=null&&(e.delete(u),clearTimeout(u))},setInterval:(u,p,...d)=>{if(typeof u!="function")return setInterval(()=>{},p);let m=setInterval(()=>{n(u,d)},p);return t.add(m),m},clearInterval:u=>{u!=null&&(t.delete(u),clearInterval(u))}},i=()=>e.size+t.size,o=()=>{for(let u of e)clearTimeout(u);for(let u of t)clearInterval(u);e.clear(),t.clear()},a=u=>new Promise(p=>setTimeout(p,u)),c=async u=>{let p=Date.now();for(await a(0);i()>0;){let d=Date.now()-p;if(d>=u)return o(),{timedOut:!0,elapsedMs:Date.now()-p};let m=u-d;await a(Math.min(15,m))}return await a(0),i()>0?l(p,u):{timedOut:!1,elapsedMs:Date.now()-p}},l=async(u,p)=>{for(;i()>0;){let d=Date.now()-u;if(d>=p)return o(),{timedOut:!0,elapsedMs:Date.now()-u};let m=p-d;await a(Math.min(15,m))}return{timedOut:!1,elapsedMs:Date.now()-u}};return{timers:s,pendingCount:i,clearAll:o,drain:c}}var yd=E(()=>{"use strict"});function Jn(r,e,t="$"){let n=[];if(e===null||typeof e!="object")return n;let s=i=>i===null?"null":Array.isArray(i)?"array":Number.isInteger(i)?"integer":typeof i;if(e.type!==void 0){let i=Array.isArray(e.type)?e.type:[e.type],o=s(r);if(!i.some(c=>c===o||c==="number"&&o==="integer"))return n.push(`${t}: expected type ${i.join("|")} but got ${o}`),n}if(Array.isArray(e.enum)&&!e.enum.some(i=>JSON.stringify(i)===JSON.stringify(r))&&n.push(`${t}: value ${JSON.stringify(r)} is not in enum ${JSON.stringify(e.enum)}`),typeof r=="number"&&(typeof e.minimum=="number"&&r<e.minimum&&n.push(`${t}: ${r} is below minimum ${e.minimum}`),typeof e.maximum=="number"&&r>e.maximum&&n.push(`${t}: ${r} is above maximum ${e.maximum}`)),typeof r=="string"&&(typeof e.minLength=="number"&&r.length<e.minLength&&n.push(`${t}: string length ${r.length} is below minLength ${e.minLength}`),typeof e.maxLength=="number"&&r.length>e.maxLength&&n.push(`${t}: string length ${r.length} is above maxLength ${e.maxLength}`),typeof e.pattern=="string"&&!new RegExp(e.pattern).test(r)&&n.push(`${t}: string does not match pattern ${e.pattern}`)),s(r)==="object"){if(Array.isArray(e.required))for(let i of e.required)i in r||n.push(`${t}: missing required property "${i}"`);if(e.properties&&typeof e.properties=="object")for(let[i,o]of Object.entries(e.properties))i in r&&n.push(...Jn(r[i],o,`${t}.${i}`));if(e.additionalProperties===!1&&e.properties){let i=new Set(Object.keys(e.properties));for(let o of Object.keys(r))i.has(o)||n.push(`${t}: additional property "${o}" is not allowed`)}}return Array.isArray(r)&&e.items&&typeof e.items=="object"&&r.forEach((i,o)=>{n.push(...Jn(i,e.items,`${t}[${o}]`))}),n}var yo=E(()=>{"use strict"});function Uh(r,e){if(r==null)return{exists:!1,value:void 0};if(!e)return{exists:!0,value:r};let n=e.replace(/\[(\d+)\]/g,".$1").replace(/\[("([^"]*)"|'([^']*)')\]/g,".$2").replace(/^\./,"").split(".").filter(Boolean),s=r;for(let i of n){if(s==null)return{exists:!1,value:void 0};let o=/^\d+$/.test(i)?Number(i):i;if(!(o in Object(s)))return{exists:!1,value:void 0};s=s[o]}return{exists:!0,value:s}}function Gn(r){return{_value:r,_negated:!1,_deep:!1,_nested:!1,_own:!1,_ordered:!1,_any:!1,_all:!1,_itself:!1,_lastDeltaAssertion:void 0,get to(){return this},get be(){return this},get been(){return this},get is(){return this},get that(){return this},get which(){return this},get and(){return this},get has(){return this},get have(){return this},get with(){return this},get at(){return this},get of(){return this},get same(){return this},get but(){return this},get does(){return this},get still(){return this},get also(){return this},get not(){return this._negated=!this._negated,this},get deep(){return this._deep=!0,this},get nested(){return this._nested=!0,this},get own(){return this._own=!0,this},get ordered(){return this._ordered=!0,this},get any(){return this._any=!0,this._all=!1,this},get all(){return this._all=!0,this._any=!1,this},get itself(){return this._itself=!0,this},_assert(t,n){if(!(this._negated?!t:t))throw new Error(n)},_readSubjectValue(t,n){if(n!==void 0){if(t==null)throw new Error(`Expected subject object for property "${n}"`);return t[n]}if(typeof t!="function")throw new Error("Expected subject to be a function when property is not provided");return t()},_resetModifiers(){this._nested=!1,this._own=!1,this._ordered=!1,this._any=!1,this._all=!1,this._itself=!1},get ok(){return this._assert(!!this._value,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be truthy`),this},get true(){return this._assert(this._value===!0,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be true`),this},get false(){return this._assert(this._value===!1,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be false`),this},get null(){return this._assert(this._value===null,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be null`),this},get undefined(){return this._assert(this._value===void 0,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be undefined`),this},get NaN(){return this._assert(Number.isNaN(this._value),`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be NaN`),this},get exist(){return this._assert(this._value!==null&&this._value!==void 0,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}exist`),this},get exists(){return this.exist},get empty(){let t=!1;return this._value===null||this._value===void 0?t=!0:typeof this._value=="string"||Array.isArray(this._value)?t=this._value.length===0:typeof this._value=="object"&&(t=Object.keys(this._value).length===0),this._assert(t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be empty`),this},get arguments(){let t=Object.prototype.toString.call(this._value)==="[object Arguments]";return this._assert(t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be arguments`),this},get Arguments(){return this.arguments},get extensible(){let t=typeof this._value=="object"&&this._value!==null?Object.isExtensible(this._value):!1;return this._assert(t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be extensible`),this},get sealed(){let t=typeof this._value=="object"&&this._value!==null?Object.isSealed(this._value):!0;return this._assert(t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be sealed`),this},get frozen(){let t=typeof this._value=="object"&&this._value!==null?Object.isFrozen(this._value):!0;return this._assert(t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be frozen`),this},get finite(){let t=typeof this._value=="number"&&Number.isFinite(this._value);return this._assert(t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be finite`),this},equal(t){return this._deep?(this._deep=!1,this.eql(t)):(this._assert(this._value===t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}equal ${JSON.stringify(t)}`),this)},eq(t){return this.equal(t)},equals(t){return this.equal(t)},eql(t){return this._assert(JSON.stringify(this._value)===JSON.stringify(t),`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}deeply equal ${JSON.stringify(t)}`),this},eqls(t){return this.eql(t)},include(t){let n=!1;return typeof this._value=="string"?n=this._value.includes(t):Array.isArray(this._value)?n=this._value.includes(t):typeof this._value=="object"&&this._value!==null&&(n=t in this._value),this._assert(n,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}include ${JSON.stringify(t)}`),this},includes(t){return this.include(t)},contain(t){return this.include(t)},contains(t){return this.include(t)},oneOf(t){return this._assert(Array.isArray(t)&&t.includes(this._value),`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be one of ${JSON.stringify(t)}`),this},property(t,n){let s=this._deep||this._nested,i=this._own;if(s&&i)throw new Error("Cannot combine own and nested/deep for property assertion");this._deep=!1;let o=s?Uh(this._value,t):i?{exists:typeof this._value=="object"&&this._value!==null&&Object.prototype.hasOwnProperty.call(this._value,t),value:this._value?.[t]}:{exists:typeof this._value=="object"&&this._value!==null&&t in this._value,value:this._value?.[t]};return n!==void 0?this._assert(o.exists&&o.value===n,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}have property "${t}" with value ${JSON.stringify(n)}`):this._assert(o.exists,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}have property "${t}"`),this._resetModifiers(),this},ownPropertyDescriptor(t,n){let s=this._value===null||this._value===void 0?void 0:Object(this._value),i=s?Object.getOwnPropertyDescriptor(s,t):void 0,o=i!==void 0;return o&&n!==void 0&&(o=Object.entries(n).every(([a,c])=>i[a]===c)),this._assert(o,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}have own property descriptor "${t}"`),this},haveOwnPropertyDescriptor(t,n){return this.ownPropertyDescriptor(t,n)},keys(...t){let n=Array.isArray(t[0])?t[0]:t,s=Object.keys(this._value||{}),i=n.every(c=>s.includes(c)),o=n.some(c=>s.includes(c)),a=this._any&&!this._all;return this._assert(a?o:i,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}have keys ${JSON.stringify(n)}`),this._resetModifiers(),this},key(...t){return this.keys(...t)},members(t){let n=this._value,s=Array.isArray(n)&&Array.isArray(t)&&t.every(o=>n.some(a=>JSON.stringify(a)===JSON.stringify(o))),i=Array.isArray(n)&&Array.isArray(t)&&t.every((o,a)=>JSON.stringify(n[a])===JSON.stringify(o));return this._assert(this._ordered?i:s,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}have members ${JSON.stringify(t)}`),this._resetModifiers(),this},string(t){return this._assert(typeof this._value=="string"&&this._value.includes(t),`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}contain string "${t}"`),this},match(t){return this._assert(t.test(String(this._value)),`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}match ${t}`),this},matches(t){return this.match(t)},a(t){let n=Array.isArray(this._value)?"array":typeof this._value;return this._assert(n===t.toLowerCase(),`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be a(n) ${t} (got ${n})`),this},an(t){return this.a(t)},length(t){let n=Array.isArray(this._value)||typeof this._value=="string"?this._value.length:Object.keys(this._value||{}).length;return this._assert(n===t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}have length ${t}`),this},lengthOf(t){return this.length(t)},satisfy(t){return this._assert(!!t(this._value),`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}satisfy matcher`),this},satisfies(t){return this.satisfy(t)},jsonSchema(t){let n=this._value;if(typeof n=="string")try{n=JSON.parse(n)}catch{throw new Error("Expected value to be valid JSON before JSON schema validation")}let s=Jn(n,t);return this._assert(s.length===0,`Expected value to ${this._negated?"not ":""}match JSON schema:
261
261
  - ${s.join(`
262
- - `)}`),this},above(t){return this._assert(Number(this._value)>t,`Expected ${this._value} to ${this._negated?"not ":""}be above ${t}`),this},gt(t){return this.above(t)},greaterThan(t){return this.above(t)},least(t){return this._assert(Number(this._value)>=t,`Expected ${this._value} to ${this._negated?"not ":""}be at least ${t}`),this},gte(t){return this.least(t)},greaterThanOrEqual(t){return this.least(t)},below(t){return this._assert(Number(this._value)<t,`Expected ${this._value} to ${this._negated?"not ":""}be below ${t}`),this},lt(t){return this.below(t)},lessThan(t){return this.below(t)},most(t){return this._assert(Number(this._value)<=t,`Expected ${this._value} to ${this._negated?"not ":""}be at most ${t}`),this},lte(t){return this.most(t)},lessThanOrEqual(t){return this.most(t)},within(t,n){return this._assert(Number(this._value)>=t&&Number(this._value)<=n,`Expected ${this._value} to ${this._negated?"not ":""}be within ${t}..${n}`),this},closeTo(t,n){return this._assert(Math.abs(Number(this._value)-t)<=n,`Expected ${this._value} to ${this._negated?"not ":""}be within ${n} of ${t}`),this},approximately(t,n){return this.closeTo(t,n)},instanceOf(t){return this._assert(this._value instanceof t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be an instance of ${t?.name||"provided constructor"}`),this},instanceof(t){return this.instanceOf(t)},throw(t){if(typeof this._value!="function")throw new Error(`Expected ${JSON.stringify(this._value)} to be a function`);let n;try{this._value()}catch(o){n=o}let i=n!==void 0;if(i&&t!==void 0){let o=n?.message??String(n);typeof t=="string"?i=o.includes(t):t instanceof RegExp?i=t.test(o):typeof t=="function"&&(i=n instanceof t)}return this._assert(i,`Expected ${this._value} to ${this._negated?"not ":""}throw${t!==void 0?` ${t}`:""}`),this},throws(t){return this.throw(t)},Throw(t){return this.throw(t)},respondTo(t){let n=this._value,s=!1;return typeof n=="function"?s=this._itself?typeof n[t]=="function":typeof n.prototype?.[t]=="function":n!=null&&(s=typeof n[t]=="function"),this._assert(s,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}respond to "${t}"`),this._resetModifiers(),this},respondsTo(t){return this.respondTo(t)},change(t,n){if(typeof this._value!="function")throw new Error(`Expected ${JSON.stringify(this._value)} to be a function`);let s=this._readSubjectValue(t,n);this._value();let i=this._readSubjectValue(t,n),o=Number(s),a=Number(i),c=Number.isFinite(o)&&Number.isFinite(a)?Math.abs(a-o):Number.NaN;return this._lastDeltaAssertion={kind:"change",delta:c},this._assert(s!==i,`Expected ${this._value} to ${this._negated?"not ":""}change${n?` property "${n}"`:""}`),this},changes(t,n){return this.change(t,n)},increase(t,n){if(typeof this._value!="function")throw new Error(`Expected ${JSON.stringify(this._value)} to be a function`);let s=Number(this._readSubjectValue(t,n));this._value();let i=Number(this._readSubjectValue(t,n));return this._lastDeltaAssertion={kind:"increase",delta:i-s},this._assert(Number.isFinite(s)&&Number.isFinite(i)&&i>s,`Expected ${this._value} to ${this._negated?"not ":""}increase${n?` property "${n}"`:""}`),this},increases(t,n){return this.increase(t,n)},decrease(t,n){if(typeof this._value!="function")throw new Error(`Expected ${JSON.stringify(this._value)} to be a function`);let s=Number(this._readSubjectValue(t,n));this._value();let i=Number(this._readSubjectValue(t,n));return this._lastDeltaAssertion={kind:"decrease",delta:s-i},this._assert(Number.isFinite(s)&&Number.isFinite(i)&&i<s,`Expected ${this._value} to ${this._negated?"not ":""}decrease${n?` property "${n}"`:""}`),this},decreases(t,n){return this.decrease(t,n)},by(t){if(!this._lastDeltaAssertion)throw new Error("Expected .by() to follow .change(), .increase(), or .decrease()");let n=this._lastDeltaAssertion.delta;return this._assert(Number.isFinite(n)&&n===t,`Expected previous ${this._lastDeltaAssertion.kind} assertion to ${this._negated?"not ":""}change by ${t} (actual ${n})`),this}}}var md=E(()=>{"use strict";mo()});function hd(r){let e=null;try{e=new URL(r)}catch{}return{toString(){return r},valueOf(){return r},[Symbol.toPrimitive](n){return n==="number"?NaN:r},getHost(){return e?e.hostname:""},getPath(){return e?e.pathname:r},getPathWithQuery(){return e?e.pathname+e.search:r},getQueryString(){return e?e.search.startsWith("?")?e.search.slice(1):e.search:""},getRemote(){if(!e)return"";let n=e.port||(e.protocol==="https:"?"443":"80");return`${e.hostname}:${n}`},getOAuth1BaseUrl(){return e?`${e.protocol}//${e.host}${e.pathname}`:r},get protocol(){return e?.protocol?.replace(":","")||""},get host(){return e?e.hostname.split("."):[]},get port(){return e?.port||""},get path(){return e?e.pathname.split("/").filter(Boolean):[]},get hash(){return e?.hash?.replace("#","")||""},query:{toObject(){if(!e)return{};let n={};return e.searchParams.forEach((s,i)=>{n[i]=s}),n},has(n){return e?e.searchParams.has(n):!1},get(n){return e?e.searchParams.get(n):void 0},each(n){e&&e.searchParams.forEach((s,i)=>n({key:i,value:s}))}}}}function Lh(r){let e=r.httpOnly??!1,t=r.secure??!1,n=r.expires==null&&r.maxAge==null;return{name:r.name,value:r.value,domain:r.domain,path:r.path,expires:r.expires,maxAge:r.maxAge,httpOnly:e,secure:t,session:n,hostOnly:!1,sameSite:r.sameSite,valueOf(){return r.value},toString(){let s=[`${r.name}=${r.value}`];return r.expires&&s.push(`Expires=${r.expires}`),r.maxAge!=null&&s.push(`Max-Age=${r.maxAge}`),r.domain&&s.push(`Domain=${r.domain}`),r.path&&s.push(`Path=${r.path}`),t&&s.push("Secure"),e&&s.push("HttpOnly"),r.sameSite&&s.push(`SameSite=${r.sameSite}`),s.join("; ")}}}function Hh(r){let e=r.map(Lh),t=n=>e.find(s=>s.name===n);return e.get=n=>t(n)?.value,e.one=n=>t(n),e.has=n=>e.some(s=>s.name===n),e.toObject=()=>{let n={};for(let s of e)n[s.name]=s.value;return n},e.all=()=>[...e],e.each=n=>{for(let s of e)n(s)},e.count=()=>e.length,e.idx=n=>e[n],e}function Bh(r){let e={...r};return e.get=t=>{let n=t.toLowerCase();for(let[s,i]of Object.entries(r))if(s.toLowerCase()===n)return i},e.has=t=>{let n=t.toLowerCase();return Object.keys(r).some(s=>s.toLowerCase()===n)},e.toObject=()=>({...r}),e.each=t=>{for(let[n,s]of Object.entries(r))t({key:n,value:s})},e}function ei(r){let e=Bh(r.headers),t=Hh(r.cookies||[]);return{status:r.statusText,code:r.status,statusText:r.statusText,headers:e,body:r.body,cookies:t,responseTime:r.responseTime,responseSize:r.responseSize,reason(){return this.statusText},json(){if(typeof this.body=="object")return this.body;try{return JSON.parse(this.body)}catch{return null}},text(){return typeof this.body=="string"?this.body:JSON.stringify(this.body)},to:{have:{status(n){if(r.status!==n)throw new Error(`Expected status ${n} but got ${r.status}`)},header(n,s){let i=r.headers[n]||r.headers[n.toLowerCase()];if(!i)throw new Error(`Expected header "${n}" to exist`);if(s!==void 0&&i!==s)throw new Error(`Expected header "${n}" to be "${s}" but got "${i}"`)},body(n){let s=typeof r.body=="string"?r.body:JSON.stringify(r.body);if(n!==void 0&&s!==n)throw new Error(`Expected body to be "${n}" but got "${s}"`)},jsonBody(n){let s=typeof r.body=="object"?r.body:JSON.parse(r.body);if(n!==void 0&&JSON.stringify(s)!==JSON.stringify(n))throw new Error("Expected JSON body to match")},jsonSchema(n){let s=typeof r.body=="object"?r.body:JSON.parse(r.body),i=Un(s,n);if(i.length>0)throw new Error(`Expected response body to match JSON schema:
262
+ - `)}`),this},above(t){return this._assert(Number(this._value)>t,`Expected ${this._value} to ${this._negated?"not ":""}be above ${t}`),this},gt(t){return this.above(t)},greaterThan(t){return this.above(t)},least(t){return this._assert(Number(this._value)>=t,`Expected ${this._value} to ${this._negated?"not ":""}be at least ${t}`),this},gte(t){return this.least(t)},greaterThanOrEqual(t){return this.least(t)},below(t){return this._assert(Number(this._value)<t,`Expected ${this._value} to ${this._negated?"not ":""}be below ${t}`),this},lt(t){return this.below(t)},lessThan(t){return this.below(t)},most(t){return this._assert(Number(this._value)<=t,`Expected ${this._value} to ${this._negated?"not ":""}be at most ${t}`),this},lte(t){return this.most(t)},lessThanOrEqual(t){return this.most(t)},within(t,n){return this._assert(Number(this._value)>=t&&Number(this._value)<=n,`Expected ${this._value} to ${this._negated?"not ":""}be within ${t}..${n}`),this},closeTo(t,n){return this._assert(Math.abs(Number(this._value)-t)<=n,`Expected ${this._value} to ${this._negated?"not ":""}be within ${n} of ${t}`),this},approximately(t,n){return this.closeTo(t,n)},instanceOf(t){return this._assert(this._value instanceof t,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}be an instance of ${t?.name||"provided constructor"}`),this},instanceof(t){return this.instanceOf(t)},throw(t){if(typeof this._value!="function")throw new Error(`Expected ${JSON.stringify(this._value)} to be a function`);let n;try{this._value()}catch(o){n=o}let i=n!==void 0;if(i&&t!==void 0){let o=n?.message??String(n);typeof t=="string"?i=o.includes(t):t instanceof RegExp?i=t.test(o):typeof t=="function"&&(i=n instanceof t)}return this._assert(i,`Expected ${this._value} to ${this._negated?"not ":""}throw${t!==void 0?` ${t}`:""}`),this},throws(t){return this.throw(t)},Throw(t){return this.throw(t)},respondTo(t){let n=this._value,s=!1;return typeof n=="function"?s=this._itself?typeof n[t]=="function":typeof n.prototype?.[t]=="function":n!=null&&(s=typeof n[t]=="function"),this._assert(s,`Expected ${JSON.stringify(this._value)} to ${this._negated?"not ":""}respond to "${t}"`),this._resetModifiers(),this},respondsTo(t){return this.respondTo(t)},change(t,n){if(typeof this._value!="function")throw new Error(`Expected ${JSON.stringify(this._value)} to be a function`);let s=this._readSubjectValue(t,n);this._value();let i=this._readSubjectValue(t,n),o=Number(s),a=Number(i),c=Number.isFinite(o)&&Number.isFinite(a)?Math.abs(a-o):Number.NaN;return this._lastDeltaAssertion={kind:"change",delta:c},this._assert(s!==i,`Expected ${this._value} to ${this._negated?"not ":""}change${n?` property "${n}"`:""}`),this},changes(t,n){return this.change(t,n)},increase(t,n){if(typeof this._value!="function")throw new Error(`Expected ${JSON.stringify(this._value)} to be a function`);let s=Number(this._readSubjectValue(t,n));this._value();let i=Number(this._readSubjectValue(t,n));return this._lastDeltaAssertion={kind:"increase",delta:i-s},this._assert(Number.isFinite(s)&&Number.isFinite(i)&&i>s,`Expected ${this._value} to ${this._negated?"not ":""}increase${n?` property "${n}"`:""}`),this},increases(t,n){return this.increase(t,n)},decrease(t,n){if(typeof this._value!="function")throw new Error(`Expected ${JSON.stringify(this._value)} to be a function`);let s=Number(this._readSubjectValue(t,n));this._value();let i=Number(this._readSubjectValue(t,n));return this._lastDeltaAssertion={kind:"decrease",delta:s-i},this._assert(Number.isFinite(s)&&Number.isFinite(i)&&i<s,`Expected ${this._value} to ${this._negated?"not ":""}decrease${n?` property "${n}"`:""}`),this},decreases(t,n){return this.decrease(t,n)},by(t){if(!this._lastDeltaAssertion)throw new Error("Expected .by() to follow .change(), .increase(), or .decrease()");let n=this._lastDeltaAssertion.delta;return this._assert(Number.isFinite(n)&&n===t,`Expected previous ${this._lastDeltaAssertion.kind} assertion to ${this._negated?"not ":""}change by ${t} (actual ${n})`),this}}}var vd=E(()=>{"use strict";yo()});function bd(r){let e=null;try{e=new URL(r)}catch{}return{toString(){return r},valueOf(){return r},[Symbol.toPrimitive](n){return n==="number"?NaN:r},getHost(){return e?e.hostname:""},getPath(){return e?e.pathname:r},getPathWithQuery(){return e?e.pathname+e.search:r},getQueryString(){return e?e.search.startsWith("?")?e.search.slice(1):e.search:""},getRemote(){if(!e)return"";let n=e.port||(e.protocol==="https:"?"443":"80");return`${e.hostname}:${n}`},getOAuth1BaseUrl(){return e?`${e.protocol}//${e.host}${e.pathname}`:r},get protocol(){return e?.protocol?.replace(":","")||""},get host(){return e?e.hostname.split("."):[]},get port(){return e?.port||""},get path(){return e?e.pathname.split("/").filter(Boolean):[]},get hash(){return e?.hash?.replace("#","")||""},query:{toObject(){if(!e)return{};let n={};return e.searchParams.forEach((s,i)=>{n[i]=s}),n},has(n){return e?e.searchParams.has(n):!1},get(n){return e?e.searchParams.get(n):void 0},each(n){e&&e.searchParams.forEach((s,i)=>n({key:i,value:s}))}}}}function Vh(r){let e=r.httpOnly??!1,t=r.secure??!1,n=r.expires==null&&r.maxAge==null;return{name:r.name,value:r.value,domain:r.domain,path:r.path,expires:r.expires,maxAge:r.maxAge,httpOnly:e,secure:t,session:n,hostOnly:!1,sameSite:r.sameSite,valueOf(){return r.value},toString(){let s=[`${r.name}=${r.value}`];return r.expires&&s.push(`Expires=${r.expires}`),r.maxAge!=null&&s.push(`Max-Age=${r.maxAge}`),r.domain&&s.push(`Domain=${r.domain}`),r.path&&s.push(`Path=${r.path}`),t&&s.push("Secure"),e&&s.push("HttpOnly"),r.sameSite&&s.push(`SameSite=${r.sameSite}`),s.join("; ")}}}function zh(r){let e=r.map(Vh),t=n=>e.find(s=>s.name===n);return e.get=n=>t(n)?.value,e.one=n=>t(n),e.has=n=>e.some(s=>s.name===n),e.toObject=()=>{let n={};for(let s of e)n[s.name]=s.value;return n},e.all=()=>[...e],e.each=n=>{for(let s of e)n(s)},e.count=()=>e.length,e.idx=n=>e[n],e}function Jh(r){let e={...r};return e.get=t=>{let n=t.toLowerCase();for(let[s,i]of Object.entries(r))if(s.toLowerCase()===n)return i},e.has=t=>{let n=t.toLowerCase();return Object.keys(r).some(s=>s.toLowerCase()===n)},e.toObject=()=>({...r}),e.each=t=>{for(let[n,s]of Object.entries(r))t({key:n,value:s})},e}function ni(r){let e=Jh(r.headers),t=zh(r.cookies||[]);return{status:r.statusText,code:r.status,statusText:r.statusText,headers:e,body:r.body,cookies:t,responseTime:r.responseTime,responseSize:r.responseSize,reason(){return this.statusText},json(){if(typeof this.body=="object")return this.body;try{return JSON.parse(this.body)}catch{return null}},text(){return typeof this.body=="string"?this.body:JSON.stringify(this.body)},to:{have:{status(n){if(r.status!==n)throw new Error(`Expected status ${n} but got ${r.status}`)},header(n,s){let i=r.headers[n]||r.headers[n.toLowerCase()];if(!i)throw new Error(`Expected header "${n}" to exist`);if(s!==void 0&&i!==s)throw new Error(`Expected header "${n}" to be "${s}" but got "${i}"`)},body(n){let s=typeof r.body=="string"?r.body:JSON.stringify(r.body);if(n!==void 0&&s!==n)throw new Error(`Expected body to be "${n}" but got "${s}"`)},jsonBody(n){let s=typeof r.body=="object"?r.body:JSON.parse(r.body);if(n!==void 0&&JSON.stringify(s)!==JSON.stringify(n))throw new Error("Expected JSON body to match")},jsonSchema(n){let s=typeof r.body=="object"?r.body:JSON.parse(r.body),i=Jn(s,n);if(i.length>0)throw new Error(`Expected response body to match JSON schema:
263
263
  - ${i.join(`
264
- - `)}`)}},be:{get ok(){if(r.status<200||r.status>=300)throw new Error(`Expected response to be OK (2xx) but got ${r.status}`);return(()=>{})},get success(){if(r.status<200||r.status>=300)throw new Error(`Expected response to be successful (2xx) but got ${r.status}`);return(()=>{})},get error(){if(r.status<400)throw new Error(`Expected response to be error (4xx/5xx) but got ${r.status}`);return(()=>{})},get clientError(){if(r.status<400||r.status>=500)throw new Error(`Expected response to be client error (4xx) but got ${r.status}`);return(()=>{})},get serverError(){if(r.status<500||r.status>=600)throw new Error(`Expected response to be server error (5xx) but got ${r.status}`);return(()=>{})}}}}}var ti=E(()=>{"use strict";mo();md();mo()});function Jc(r,e){let t=o=>{if(!o)return"none";switch(o){case"raw":return"raw";case"form-data":return"formdata";case"x-www-form-urlencoded":return"urlencoded";case"binary":return"file";case"graphql":return"graphql";case"none":return"none";default:return"raw"}},n=o=>{if(!o)return"none";switch(o){case"raw":return"raw";case"formdata":return"form-data";case"urlencoded":return"x-www-form-urlencoded";case"file":return"binary";case"graphql":return"graphql";case"none":return"none";default:return"raw"}},s={...r.headers,add:o=>{o&&o.key&&(r.headers[o.key]=o.value||"")},get:o=>{for(let[a,c]of Object.entries(r.headers))if(a.toLowerCase()===o.toLowerCase())return c},has:o=>{for(let a of Object.keys(r.headers))if(a.toLowerCase()===o.toLowerCase())return!0;return!1},remove:o=>{for(let a of Object.keys(r.headers))if(a.toLowerCase()===o.toLowerCase()){delete r.headers[a];break}},update:o=>{if(o&&o.key){for(let a of Object.keys(r.headers))if(a.toLowerCase()===o.key.toLowerCase()){r.headers[a]=o.value||"";return}}},upsert:o=>{if(o&&o.key){for(let a of Object.keys(r.headers))if(a.toLowerCase()===o.key.toLowerCase()){r.headers[a]=o.value||"";return}r.headers[o.key]=o.value||""}},toObject:()=>{let o={};for(let[a,c]of Object.entries(r.headers))typeof c=="string"&&(o[a]=c);return o},each:o=>{for(let[a,c]of Object.entries(r.headers))typeof c=="string"&&o({key:a,value:c})}},i={get mode(){return t(r.body?.type)},set mode(o){let a=n(o);r.body?r.body.type=a:r.body={type:a,content:null}},get raw(){let o=r.body?.content;return typeof o=="string"?o:o&&typeof o=="object"?JSON.stringify(o):""},set raw(o){r.body?(r.body.type="raw",r.body.content=o):r.body={type:"raw",content:o}},get formdata(){return r.body?.type==="form-data"&&Array.isArray(r.body.content)?r.body.content:[]},get urlencoded(){return r.body?.type==="x-www-form-urlencoded"&&Array.isArray(r.body.content)?r.body.content:[]},get graphql(){return r.body?.type==="graphql"?r.body.content:null},get file(){return r.body?.type==="binary"?r.body.content:null}};return{get url(){return hd(r.url)},set url(o){r.url=typeof o=="string"?o:String(o)},get method(){return r.method},set method(o){r.method=o},headers:s,get body(){return i},set body(o){if(o==null)r.body=null;else if(typeof o=="string")r.body={type:"raw",content:o};else if(typeof o=="object")if(o.type||o.mode||o.content!==void 0){let a=o.mode?n(o.mode):o.type||"raw";r.body={type:a,format:o.format,content:o.content}}else r.body={type:"raw",content:o}},get params(){return r.params||{}},set params(o){r.params=o||{}},get query(){return r.query||{}},set query(o){r.query=o||{}},get auth(){return e.request?.auth||null},set auth(o){e.request&&(e.request.auth=o)},get certificate(){return e.request?.certificate||null},set certificate(o){e.request&&(e.request.certificate=o)},get description(){return e.request?.description||null},set description(o){e.request&&(e.request.description=o)},get name(){return e.request?.name||null},set name(o){e.request&&(e.request.name=o)},get id(){return e.request?.id||null},get disabled(){return e.request?.disabled||!1},set disabled(o){e.request&&(e.request.disabled=o)},get messages(){return e.request?.messages||[]},get methodPath(){return e.request?.methodPath||null},get metadata(){return e.request?.metadata||[]},getHeaders(o){let a={};for(let[c,l]of Object.entries(r.headers))typeof l=="string"&&(a[c]=l);return a},addQueryParams(o){if(typeof o=="string"){let a=new URLSearchParams(o);for(let[c,l]of a)r.query||(r.query={}),r.query[c]=l}else Array.isArray(o)&&(r.query||(r.query={}),o.forEach(a=>{a.key&&(r.query[a.key]=a.value||"")}))},removeQueryParams(o){r.query&&(typeof o=="string"?delete r.query[o]:Array.isArray(o)&&o.forEach(a=>{let c=typeof a=="string"?a:a.key;c&&delete r.query[c]}))},authorizeUsing(o,a){e.request&&(typeof o=="string"?(e.request.auth||(e.request.auth={}),e.request.auth.type=o,a&&(e.request.auth.parameters=a)):typeof o=="object"&&(e.request.auth=o))},clone(){return{url:r.url,method:r.method,headers:{...r.headers},body:r.body?{...r.body}:null,params:r.params?{...r.params}:{},query:r.query?{...r.query}:{},auth:e.request?.auth,certificate:e.request?.certificate,description:e.request?.description,name:e.request?.name,id:e.request?.id,disabled:e.request?.disabled,metadata:e.request?.metadata,messages:e.request?.messages,methodPath:e.request?.methodPath}},describe(o,a){e.request&&(e.request.description={content:o,type:a||"text/plain"})},setHeader(o,a){r.headers[o]=a},addHeader(o,a){typeof o=="object"&&o!==null?r.headers[o.key]=o.value:r.headers[o]=a},removeHeader(o){delete r.headers[o]},setBody(o,a,c){r.body={type:a||r.body?.type||"raw",format:c||r.body?.format,content:o}}}}var gd=E(()=>{"use strict";ti()});function ni(r,e=!1){let t=(typeof r=="string"?[r]:r).filter(s=>s&&s.trim());return t.length===0?"":e?`(async () => {
264
+ - `)}`)}},be:{get ok(){if(r.status<200||r.status>=300)throw new Error(`Expected response to be OK (2xx) but got ${r.status}`);return(()=>{})},get success(){if(r.status<200||r.status>=300)throw new Error(`Expected response to be successful (2xx) but got ${r.status}`);return(()=>{})},get error(){if(r.status<400)throw new Error(`Expected response to be error (4xx/5xx) but got ${r.status}`);return(()=>{})},get clientError(){if(r.status<400||r.status>=500)throw new Error(`Expected response to be client error (4xx) but got ${r.status}`);return(()=>{})},get serverError(){if(r.status<500||r.status>=600)throw new Error(`Expected response to be server error (5xx) but got ${r.status}`);return(()=>{})}}}}}var ri=E(()=>{"use strict";yo();vd();yo()});function Qc(r,e){let t=o=>{if(!o)return"none";switch(o){case"raw":return"raw";case"form-data":return"formdata";case"x-www-form-urlencoded":return"urlencoded";case"binary":return"file";case"graphql":return"graphql";case"none":return"none";default:return"raw"}},n=o=>{if(!o)return"none";switch(o){case"raw":return"raw";case"formdata":return"form-data";case"urlencoded":return"x-www-form-urlencoded";case"file":return"binary";case"graphql":return"graphql";case"none":return"none";default:return"raw"}},s={...r.headers,add:o=>{o&&o.key&&(r.headers[o.key]=o.value||"")},get:o=>{for(let[a,c]of Object.entries(r.headers))if(a.toLowerCase()===o.toLowerCase())return c},has:o=>{for(let a of Object.keys(r.headers))if(a.toLowerCase()===o.toLowerCase())return!0;return!1},remove:o=>{for(let a of Object.keys(r.headers))if(a.toLowerCase()===o.toLowerCase()){delete r.headers[a];break}},update:o=>{if(o&&o.key){for(let a of Object.keys(r.headers))if(a.toLowerCase()===o.key.toLowerCase()){r.headers[a]=o.value||"";return}}},upsert:o=>{if(o&&o.key){for(let a of Object.keys(r.headers))if(a.toLowerCase()===o.key.toLowerCase()){r.headers[a]=o.value||"";return}r.headers[o.key]=o.value||""}},toObject:()=>{let o={};for(let[a,c]of Object.entries(r.headers))typeof c=="string"&&(o[a]=c);return o},each:o=>{for(let[a,c]of Object.entries(r.headers))typeof c=="string"&&o({key:a,value:c})}},i={get mode(){return t(r.body?.type)},set mode(o){let a=n(o);r.body?r.body.type=a:r.body={type:a,content:null}},get raw(){let o=r.body?.content;return typeof o=="string"?o:o&&typeof o=="object"?JSON.stringify(o):""},set raw(o){r.body?(r.body.type="raw",r.body.content=o):r.body={type:"raw",content:o}},get formdata(){return r.body?.type==="form-data"&&Array.isArray(r.body.content)?r.body.content:[]},get urlencoded(){return r.body?.type==="x-www-form-urlencoded"&&Array.isArray(r.body.content)?r.body.content:[]},get graphql(){return r.body?.type==="graphql"?r.body.content:null},get file(){return r.body?.type==="binary"?r.body.content:null}};return{get url(){return bd(r.url)},set url(o){r.url=typeof o=="string"?o:String(o)},get method(){return r.method},set method(o){r.method=o},headers:s,get body(){return i},set body(o){if(o==null)r.body=null;else if(typeof o=="string")r.body={type:"raw",content:o};else if(typeof o=="object")if(o.type||o.mode||o.content!==void 0){let a=o.mode?n(o.mode):o.type||"raw";r.body={type:a,format:o.format,content:o.content}}else r.body={type:"raw",content:o}},get params(){return r.params||{}},set params(o){r.params=o||{}},get query(){return r.query||{}},set query(o){r.query=o||{}},get auth(){return e.request?.auth||null},set auth(o){e.request&&(e.request.auth=o)},get certificate(){return e.request?.certificate||null},set certificate(o){e.request&&(e.request.certificate=o)},get description(){return e.request?.description||null},set description(o){e.request&&(e.request.description=o)},get name(){return e.request?.name||null},set name(o){e.request&&(e.request.name=o)},get id(){return e.request?.id||null},get disabled(){return e.request?.disabled||!1},set disabled(o){e.request&&(e.request.disabled=o)},get messages(){return e.request?.messages||[]},get methodPath(){return e.request?.methodPath||null},get metadata(){return e.request?.metadata||[]},getHeaders(o){let a={};for(let[c,l]of Object.entries(r.headers))typeof l=="string"&&(a[c]=l);return a},addQueryParams(o){if(typeof o=="string"){let a=new URLSearchParams(o);for(let[c,l]of a)r.query||(r.query={}),r.query[c]=l}else Array.isArray(o)&&(r.query||(r.query={}),o.forEach(a=>{a.key&&(r.query[a.key]=a.value||"")}))},removeQueryParams(o){r.query&&(typeof o=="string"?delete r.query[o]:Array.isArray(o)&&o.forEach(a=>{let c=typeof a=="string"?a:a.key;c&&delete r.query[c]}))},authorizeUsing(o,a){e.request&&(typeof o=="string"?(e.request.auth||(e.request.auth={}),e.request.auth.type=o,a&&(e.request.auth.parameters=a)):typeof o=="object"&&(e.request.auth=o))},clone(){return{url:r.url,method:r.method,headers:{...r.headers},body:r.body?{...r.body}:null,params:r.params?{...r.params}:{},query:r.query?{...r.query}:{},auth:e.request?.auth,certificate:e.request?.certificate,description:e.request?.description,name:e.request?.name,id:e.request?.id,disabled:e.request?.disabled,metadata:e.request?.metadata,messages:e.request?.messages,methodPath:e.request?.methodPath}},describe(o,a){e.request&&(e.request.description={content:o,type:a||"text/plain"})},setHeader(o,a){r.headers[o]=a},addHeader(o,a){typeof o=="object"&&o!==null?r.headers[o.key]=o.value:r.headers[o]=a},removeHeader(o){delete r.headers[o]},setBody(o,a,c){r.body={type:a||r.body?.type||"raw",format:c||r.body?.format,content:o}}}}var Sd=E(()=>{"use strict";ri()});function si(r,e=!1){let t=(typeof r=="string"?[r]:r).filter(s=>s&&s.trim());return t.length===0?"":e?`(async () => {
265
265
  ${t.map((s,i)=>`await (async () => {
266
266
  /* --- script unit ${i+1} --- */
267
267
  ${s}
@@ -271,14 +271,14 @@ ${s}
271
271
 
272
272
  // --- Next Script ---
273
273
 
274
- `)}function Hr(r,e){return JSON.stringify(r)!==JSON.stringify(e)}function zn(r){return r.map(e=>{let t=e.args.map(n=>{if(typeof n=="object")try{return JSON.stringify(n,null,2)}catch{return String(n)}return String(n)}).join(" ");return`[${e.level}] ${t}`})}function ho(r){let e=[],t=(n,s)=>{try{let i=s();if(i&&typeof i.then=="function"){let o=i.then(()=>{r.push({name:n,passed:!0})},a=>{r.push({name:n,passed:!1,message:a.message||String(a)})});e.push(o)}else r.push({name:n,passed:!0})}catch(i){r.push({name:n,passed:!1,message:i.message})}};return t.skip=(n,s)=>{r.push({name:n,passed:!0,skipped:!0})},t.fail=n=>{r.push({name:n||"Failed test",passed:!1,message:n||"pm.test.fail()"})},t.index=()=>r.length,t._pendingTests=e,t}function go(r){let e={};for(let[t,n]of Object.entries(r))e[t]=Array.isArray(n)?n.join(", "):n;return e}function yo(r,e,t){let n;if(t)try{n=new URL(t).hostname}catch{n=void 0}let s=ie.parseCookieHeaders(r||{},n);return s.length>0?s:Array.isArray(e)&&e.length>0?e.filter(i=>i&&i.name).map(i=>({name:i.name,value:i.value,domain:i.domain??n,path:i.path,expires:i.expires,maxAge:i.maxAge,httpOnly:i.httpOnly,secure:i.secure,sameSite:i.sameSite})):[]}var ri=E(()=>{"use strict";jn()});var Gc,Br,Wc=E(()=>{"use strict";Gc=I(require("vm"));fd();gd();ti();ri();Br=class{constructor(e,t){this.deps=e;this.initialContext=t;this.timerRegistry=pd(n=>{let s=n instanceof Error?n.message:String(n);this.consoleMessages.push({level:"error",args:[`Uncaught error in async callback: ${s}`]})}),this.initializeSession()}deps;initialContext;vmContext=null;ctx=null;modifiedRequest=null;assertions=[];consoleMessages=[];_variables={};_collectionVariables={};_globals={};_environmentVariables={};_liveEnvironmentScope=null;_liveGlobalsScope=null;_liveCollectionScope=null;_nextRequest=void 0;_skipRequest=!1;_visualizerData=void 0;timerRegistry;initializeSession(){this.modifiedRequest={url:this.initialContext.request.url,method:this.initialContext.request.method,headers:{...this.initialContext.request.headers},body:this.initialContext.request.body?{...this.initialContext.request.body}:null,params:this.initialContext.request.params?{...this.initialContext.request.params}:{},query:this.initialContext.request.query?{...this.initialContext.request.query}:{}},this.assertions=[],this.ctx=this.createSharedContext(),this.consoleMessages=[];let e=this,t={log:(...n)=>{e.consoleMessages.push({level:"log",args:n})},info:(...n)=>{e.consoleMessages.push({level:"info",args:n})},warn:(...n)=>{e.consoleMessages.push({level:"warn",args:n})},error:(...n)=>{e.consoleMessages.push({level:"error",args:n})}};this.vmContext=this.deps.createVM(this.ctx,t,this.timerRegistry.timers)}createSharedContext(){let e=this.initialContext,t=this.modifiedRequest,n=this.deps.createCommonContext(e,"prerequest");this._variables={...e.variables},this._collectionVariables={...e.collectionVariables||{}},this._globals={...e.globals||{}},this._environmentVariables={...e.environmentVariables||{}},this._liveEnvironmentScope=n.environment,this._liveGlobalsScope=n.globals,this._liveCollectionScope=n.collectionVariables;let s;try{s=new URL(e.request.url).hostname}catch{}let i={get:a=>e.cookieJar?e.cookieJar.get(a,s)?.value:void 0,set:(a,c)=>{e.cookieJar&&e.cookieJar.set({name:a,value:c,domain:s})},has:a=>e.cookieJar?e.cookieJar.has(a,s):!1,list:()=>e.cookieJar?e.cookieJar.getAll(s).map(a=>({name:a.name,value:a.value})):[],toObject:()=>{if(!e.cookieJar)return{};let a=e.cookieJar.getAll(s),c={};for(let l of a)c[l.name]=l.value;return c},jar:()=>{let a=e.cookieJar,c=l=>{if(l==null)return;let u=typeof l=="string"?l:typeof l=="object"||typeof l=="number"||typeof l=="boolean"?String(l):void 0;if(!u)return;let d=u.trim();if(d)try{return new URL(d).hostname}catch{return d}};return{getAll(l,u){try{if(!a){u(null,[]);return}let d=c(l),p=a.getAll(d).map(m=>({name:m.name,value:m.value,domain:m.domain,path:m.path,httpOnly:m.httpOnly,secure:m.secure}));u(null,p)}catch(d){u(d,[])}},get(l,u,d){try{if(!a){d(null,void 0);return}let p=c(l),m=a.get(u,p);d(null,m?{name:m.name,value:m.value,domain:m.domain}:void 0)}catch(p){d(p,void 0)}},set(l,u,d,p){try{if(!a){(p||d)?.(null);return}let m=c(l);typeof u=="string"&&typeof d=="string"?(a.set({name:u,value:d,domain:m}),p?.(null)):typeof u=="object"&&(a.set({...u,domain:m}),d?.(null))}catch(m){(p||d)?.(m)}},unset(l,u,d){try{if(!a){d?.(null);return}let p=c(l);a.delete(u,p),d?.(null)}catch(p){d?.(p)}},clear(l,u){try{let d=typeof l=="function"?l:u;if(!a){d?.(null);return}let p=typeof l=="function"?void 0:c(l);p&&typeof a.clearDomain=="function"?a.clearDomain(p):a.clear(),d?.(null)}catch(d){(typeof l=="function"?l:u)?.(d)}}}},remove:a=>{e.cookieJar&&e.cookieJar.delete(a,s)},unset:a=>{e.cookieJar&&e.cookieJar.delete(a,s)},clear:()=>{e.cookieJar&&e.cookieJar.clear()}},o=this;return{request:Jc(t,e),response:null,test:ho(this.assertions),expect:Vn,cookies:i,execution:{setNextRequest(a){o._nextRequest=a},skipRequest(){o._skipRequest=!0},runRequest(a,c){let u=(async()=>{if(typeof n.sendRequest!="function")throw new Error("pm.execution.runRequest is not available \u2014 HTTP service not configured.");let d=typeof a=="string"?{url:a,method:"GET"}:a,p=await n.sendRequest(d),m=Array.isArray(p?.cookies)?p.cookies.filter(g=>g?.name):[],f=p?.body,h=0;if(typeof f=="string")h=Buffer.byteLength(f,"utf8");else if(Buffer.isBuffer(f))h=f.length;else if(f!=null)try{h=Buffer.byteLength(JSON.stringify(f),"utf8")}catch{}return ei({executedRequest:null,status:p?.status??0,statusText:p?.statusText??"",headers:p?.headers??{},body:f,cookies:m,responseTime:p?.time,responseSize:h})})();if(typeof c=="function"){u.then(d=>c(null,d),d=>c(d));return}return u},location:{current:n.info?.requestName||"",currentRequestName:n.info?.requestName||"",eventName:"prerequest",toString(){return n.info?.requestName||""}}},setNextRequest(a){o._nextRequest=a},visualizer:{set(a,c){o._visualizerData={template:a,data:c}},clear(){o._visualizerData=void 0}},...n,info:{...n.info||{},eventName:"prerequest",requestName:n.info?.requestName||void 0,requestId:n.info?.requestId||void 0,iteration:e.iteration||0,iterationCount:e.iterationCount||1}}}injectLegacyGlobals(e,t){let n=this.vmContext;if(!n)return;let s=this.initialContext,i=e==="test"&&t?.executedRequest?t.executedRequest:this.modifiedRequest,o={};for(let[m,f]of Object.entries(i?.headers||{}))typeof f=="string"&&(o[m]=f);let a=i?.body,c=a==null?null:typeof a=="object"&&"content"in a?a.content:a,l=s.request;if(n.request={id:l?.id??"",name:l?.name??"",description:l?.description??"",url:typeof i?.url=="string"?i.url:String(i?.url??""),method:i?.method??"GET",headers:o,data:c},n.environment=this._liveEnvironmentScope?.toObject?.()??{...this._environmentVariables},n.globals=this._liveGlobalsScope?.toObject?.()??{...this._globals},n.data={...s.iterationData||{}},typeof n.iteration!="number"&&(n.iteration=0),e!=="test"||!t)return;let u=t.body;n.responseBody=u==null?"":typeof u=="string"?u:JSON.stringify(u);let d=t.statusText||"";n.responseCode={code:t.status,name:d,detail:d},n.responseHeaders={...t.headers||{}},n.responseTime=t.responseTime??0,n.responseCookies=(t.cookies||[]).map(m=>({...m}));let p=this;n.tests=new Proxy({},{set(m,f,h){return p.assertions.push({name:String(f),passed:!!h,message:h?void 0:`"${String(f)}" was false`}),!0}})}async executePreRequest(e){let t=ni(e,this.deps.isolateScripts);if(!t||!t.trim())return{success:!0};try{this.consoleMessages.length=0,this.injectLegacyGlobals("prerequest");let n=this.ctx.variables.replaceIn(t),s=this.deps.scriptTimeoutMs??5e3,i=Gc.runInContext(n,this.vmContext,{timeout:s});this.deps.isolateScripts&&i&&typeof i.then=="function"&&await i,(await this.timerRegistry.drain(s)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${s}ms; pending async work was cancelled.`]});let a=zn(this.consoleMessages),c=this.initialContext.request.body,l=!this.bodiesEqual(this.modifiedRequest.body,c);return{success:!0,modifiedRequest:{url:this.modifiedRequest.url!==this.initialContext.request.url?this.modifiedRequest.url:void 0,headers:Hr(this.modifiedRequest.headers,this.initialContext.request.headers)?this.modifiedRequest.headers:void 0,body:l?this.modifiedRequest.body:void 0,params:Hr(this.modifiedRequest.params,this.initialContext.request.params||{})?this.modifiedRequest.params:void 0,query:Hr(this.modifiedRequest.query,this.initialContext.request.query||{})?this.modifiedRequest.query:void 0},modifiedVariables:this.ctx.variables.toObject(),localVariables:this.ctx.variables.toLocalObject?.()??{},modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,consoleOutput:a.length>0?a:void 0,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}catch(n){let s=[...zn(this.consoleMessages),`[error] Script execution failed: ${n.message}`];return{success:!1,error:n.message||"Pre-request script execution failed",consoleOutput:s,modifiedVariables:this.ctx?.variables?.toObject(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}}async executePostResponse(e,t){let n=ni(e,this.deps.isolateScripts);if(!n||!n.trim())return{testResults:[],consoleOutput:[]};try{this.consoleMessages.length=0,this.assertions.length=0,this.ctx.info.eventName="test",this.ctx.response=ei(t),this.ctx.request=Jc(t.executedRequest,this.initialContext),this.injectLegacyGlobals("test",t);let s=this.ctx.variables.replaceIn(n),i=this.deps.scriptTimeoutMs??5e3,o=Gc.runInContext(s,this.vmContext,{timeout:i});this.deps.isolateScripts&&o&&typeof o.then=="function"&&await o,this.ctx.test._pendingTests?.length>0&&(await Promise.all(this.ctx.test._pendingTests),this.ctx.test._pendingTests.length=0),(await this.timerRegistry.drain(i)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${i}ms; pending async work was cancelled.`]});let c=zn(this.consoleMessages);return{testResults:[...this.assertions],consoleOutput:c.length>0?c:void 0,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}catch(s){this.assertions.push({name:"Script Execution",passed:!1,message:s.message||"Script execution failed"});let i=[...zn(this.consoleMessages),`[error] Script execution failed: ${s.message}`];return{testResults:[...this.assertions],consoleOutput:i,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}}bodiesEqual(e,t){return e===t||!e&&!t?!0:!e||!t?!1:e.type===t.type&&e.format===t.format&&JSON.stringify(e.content)===JSON.stringify(t.content)}dispose(){this.timerRegistry.clearAll(),this.vmContext=null,this.ctx=null,this.assertions=[]}}});function vd(r){if(typeof r=="string"&&r.charCodeAt(0)===30)try{return JSON.parse(r.slice(1))}catch{return r}return r}function Uh(r,e){if(r==="@")return"";if(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))return r.slice(1,-1);let t=r.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(t){let n=Ks(t[2],e),s=Hn(t[1],n);return s!==null?s:void 0}if(e[r]!==void 0)return vd(e[r]);if(fn(r)){let n=_r(r,e),s=yt(r,n);if(s!==void 0)return s}}var yd,vo,bd=E(()=>{"use strict";Uc();Gs();po();Lr();yd="";vo=class{serializeValue(e){return typeof e=="string"?e:e===void 0?yd+"undefined":yd+JSON.stringify(e)}deserializeValue(e){if(e!==void 0){if(typeof e=="string"&&e.charCodeAt(0)===30){let t=e.slice(1);if(t==="undefined")return;try{return JSON.parse(t)}catch{}}return e}}createVariableScope(e){return{get:t=>this.deserializeValue(e[t]),set:(t,n)=>{e[t]=this.serializeValue(n)},has(t){return t in e},unset(t){delete e[t]},clear(){Object.keys(e).forEach(t=>delete e[t])},toObject(){return{...e}}}}createGlobalsScope(e,t){let n=(s,i,o)=>{t&&t(s,i,o)};return{get:s=>this.deserializeValue(e[s]),set:(s,i)=>{let o=this.serializeValue(i);e[s]=o,n("set",s,o)},has(s){return s in e},unset(s){delete e[s],n("unset",s)},clear(){Object.keys(e).forEach(s=>delete e[s]),n("clear")},toObject(){return{...e}}}}createMergedVariableScope(e,t,n,s,i={}){let o={get:a=>a in e?this.deserializeValue(e[a]):a in i?i[a]:a in t?this.deserializeValue(t[a]):a in n?this.deserializeValue(n[a]):this.deserializeValue(s[a]),set:(a,c)=>{e[a]=this.serializeValue(c)},has(a){return a in e||a in i||a in t||a in t||a in n||a in s},unset(a){delete e[a]},clear(){Object.keys(e).forEach(a=>delete e[a])},toObject(){return{...s,...n,...t,...i,...e}},toLocalObject(){return{...n,...t,...i,...e}},replaceIn(a){if(!a||typeof a!="string")return a;let c=o.toObject(),l=20,u=p=>p.replace(/\{\{([^}]+)\}\}/g,(m,f)=>{let h=f.trim(),g=h.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(g)try{let y=Ks(g[2],c),x=Hn(g[1],y);return x!==null?String(x):m}catch{return m}let v=Dr(h);if(v){let y=Uh(v.input,c);if(y!==void 0){let x=jr(y,v.filters,c);return x!==void 0?String(x):m}return m}if(o.has(h)){let y=o.get(h);return y===void 0?"":String(y)}if(fn(h)){let y={};for(let[R,C]of Object.entries(c))y[R]=vd(C);let x=_r(h,y),b=yt(h,x);if(b!==void 0)return String(b)}return m}),d=a;for(let p=0;p<l;p++){let m=u(d);if(m===d)break;d=m}return d}};return o}createEnvironmentScope(e,t,n,s){let i=(o,a,c)=>{n&&(s?n(o,a,c):n(a||"",o==="set"?c:void 0))};return{name:t||"",get:o=>this.deserializeValue(e[o]),set:(o,a)=>{let c=this.serializeValue(a);e[o]=c,i("set",o,c)},has(o){return o in e},unset(o){delete e[o],i("unset",o)},clear(){Object.keys(e).forEach(o=>delete e[o]),i("clear")},toObject(){return{...e}}}}}});var Vh,zh,Sd,Mt,si=E(()=>{"use strict";Vh=I(require("crypto")),zh=I(require("querystring")),Sd=I(require("vm"));ld();zc();Wc();ti();bd();Mt=class{constructor(e,t=[],n,s="shared",i=5e3){this.httpService=e;this.secretRegistry=n;this.scopeMode=s;this.scriptTimeoutMs=i;this.moduleLoader=fo(t)}httpService;secretRegistry;scopeMode;scriptTimeoutMs;moduleLoader;variableScopes=new vo;createRequestSession(e){return new Br({createVM:this.createVM.bind(this),createCommonContext:this.createCommonContext.bind(this),isolateScripts:this.scopeMode==="isolated",scriptTimeoutMs:this.scriptTimeoutMs},e)}createVM(e,t,n){let s=this.moduleLoader.getGlobalSetupExports(),i=this.moduleLoader.createRequireFunction();e.require=i,e.vault=this.createVault();let o={ctx:e,hf:e,pm:e,console:t,...s||{},global:s,setTimeout:n?.setTimeout??setTimeout,setInterval:n?.setInterval??setInterval,clearTimeout:n?.clearTimeout??clearTimeout,clearInterval:n?.clearInterval??clearInterval,URL,URLSearchParams,Buffer,atob:a=>Buffer.from(a,"base64").toString("binary"),btoa:a=>Buffer.from(a,"binary").toString("base64"),TextEncoder,TextDecoder,crypto:Vh,_:i("lodash"),require:i,moment:Xs(),querystring:zh,CryptoJS:cd(),tv4:(()=>{try{return i("tv4")}catch{return}})(),postman:{setNextRequest:a=>e.setNextRequest?.(a),setGlobalVariable:(a,c)=>e.globals?.set(a,c),getGlobalVariable:a=>e.globals?.get(a),clearGlobalVariable:a=>e.globals?.unset(a),setEnvironmentVariable:(a,c)=>e.environment?.set(a,c),getEnvironmentVariable:a=>e.environment?.get(a),clearEnvironmentVariable:a=>e.environment?.unset(a),getResponseHeader:a=>{let c=e.response?.headers?.get?.(a);return c===void 0?null:c},getResponseCookie:a=>{let c=e.response?.cookies;if(c&&typeof c[Symbol.iterator]=="function"){for(let l of c)if(l?.name&&l.name.toLowerCase()===a.toLowerCase())return{...l}}return null}},jsonStringify:(a,c,l)=>JSON.stringify(a,c,l),jsonParse:a=>JSON.parse(a),xml2Json:a=>{try{let c=this.moduleLoader.createRequireFunction()("xml2js"),l;return c.parseString(a,{explicitArray:!1},(u,d)=>{if(u)throw u;l=d}),l}catch{throw new Error("xml2Json() requires the xml2js module. Add it to your modules/package.json and run npm install.")}}};return Sd.createContext(o)}createCommonContext(e,t){let n={...e.variables},s={...e.collectionVariables||{}},i={...e.globals||{}},o={...e.environmentVariables||{}},a=e.iterationData||{},c=this.variableScopes.createMergedVariableScope(n,o,s,i,a),l=this.variableScopes.createGlobalsScope(i,e.onGlobalsChange),u=this.variableScopes.createVariableScope(s),d=this.variableScopes.createEnvironmentScope(o,e.environmentName,e.onEnvironmentChange,!0),p={...d,set:(h,g)=>{let v=this.variableScopes.serializeValue(g);d.set(h,v),n[h]=v},unset(h){d.unset(h),delete n[h]},clear(){let h=Object.keys(o);d.clear();for(let g of h)delete n[g]}},m={...l,set:(h,g)=>{let v=this.variableScopes.serializeValue(g);l.set(h,v),n[h]=v},unset(h){l.unset(h),delete n[h]},clear(){let h=Object.keys(i);l.clear();for(let g of h)delete n[g]}};return m.replaceIn=c.replaceIn,u.replaceIn=c.replaceIn,p.replaceIn=c.replaceIn,{globals:m,collectionVariables:u,variables:c,environment:p,iterationData:{get:h=>a[h],has:h=>h in a,toObject:()=>({...a}),toJSON:()=>JSON.stringify(a)},sendRequest:this.createSendRequest(),expect:Vn,info:e.info||{eventName:t,requestName:void 0,requestId:void 0}}}createVault(){let e=this.secretRegistry,t=()=>{throw new Error("pm.vault is read-only in HTTP Forge. Use environment variables or {{secret:provider/path}} tokens to manage secrets.")};return{async get(n){if(!e)throw new Error('pm.vault is not available \u2014 no secret providers are configured. Configure a provider under "secrets.providers" to use pm.vault.get().');let s=`secret:${n}`;return(await e.resolveSecretTokens(`{{${s}}}`))[s]},set:t,unset:t}}createSendRequest(){return this.httpService?(e,t)=>{let n=typeof e=="string"?{url:e,method:"GET"}:e,s=this.httpService.execute({url:n.url,method:n.method||"GET",headers:n.headers||{},body:n.body,...n});if(t){s.then(i=>t(null,i)).catch(i=>t(i,null));return}return s}:(e,t)=>{let n=new Error("sendRequest not available - HTTP service not configured");if(t){t(n,null);return}return Promise.reject(n)}}}});function Kc(r){return r?String(r).replace(/[\u201C\u201D\u201E\u201F\u2033\u2036]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032\u2035]/g,"'").replace(/[\x00-\x08\x0A-\x1F\x7F]/g,""):""}function bo(r){let e={};for(let[t,n]of Object.entries(r))e[t]=Kc(String(n));return e}var Qc=E(()=>{"use strict"});var xd,Yc,ii,Zc,xo,wd,zr,wo,So,gn,Ro=E(()=>{"use strict";xd=I(require("fs")),Yc=I(require("http")),ii=I(require("https")),Zc=I(require("net")),xo=I(require("path")),wd=I(require("tls")),zr=require("url"),wo=I(require("zlib"));Qc();So={timeout:3e4,followRedirects:!0,followOriginalMethod:!1,followAuthHeader:!1,maxRedirects:10,strictSSL:!0,decompress:!0,includeCookies:!1,tls:{},certificates:[]},gn=class{resolveDefaults;resolveProxy;version;basePath;constructor(e,t=process.cwd(),n){if(typeof e=="function")this.resolveDefaults=()=>({...So,...e()??{}});else{let s={...So,...e};this.resolveDefaults=()=>s}this.basePath=t,typeof n=="function"?this.resolveProxy=n:this.resolveProxy=()=>n;try{this.version=require("../../package.json").version||"0.0.0"}catch{this.version="0.0.0"}}get settings(){return this.resolveDefaults()}async send(e){let t=this.mergeSettings(e.settings);return await this.executeInternal(e,t,0)}mergeSettings(e){let t=this.settings;return{timeout:e?.timeout??t.timeout,followRedirects:e?.followRedirects??t.followRedirects,followOriginalMethod:e?.followOriginalMethod??t.followOriginalMethod,followAuthHeader:e?.followAuthHeader??t.followAuthHeader,maxRedirects:e?.maxRedirects??t.maxRedirects,strictSSL:e?.strictSSL??t.strictSSL,decompress:e?.decompress??t.decompress,includeCookies:e?.includeCookies??t.includeCookies,tls:e?.tls??t.tls??{},certificates:e?.certificates??t.certificates??[]}}async executeInternal(e,t,n,s){let i=Date.now(),o=new zr.URL(e.url),a=o.protocol==="https:",c=bo(e.headers||{});Object.keys(c).some(g=>g.toLowerCase()==="user-agent")||(c["User-Agent"]=`HttpForge/${this.version}`);let u={hostname:o.hostname,port:o.port||(a?443:80),path:o.pathname+o.search,method:e.method,headers:{...c},timeout:t.timeout||void 0},d;if(e.body!==void 0&&e.body!==null){typeof e.body=="string"||e.body instanceof Buffer?d=e.body:e.body instanceof URLSearchParams?d=e.body.toString():typeof e.body=="object"?d=JSON.stringify(e.body):d=String(e.body);let g=u.headers;!Object.keys(g).some(y=>y.toLowerCase()==="content-length")&&d!==void 0&&(g["Content-Length"]=Buffer.byteLength(d).toString())}t.decompress&&!c["accept-encoding"]&&!c["Accept-Encoding"]&&(u.headers["Accept-Encoding"]="gzip, deflate");let p=this.resolveProxy(),m=p&&p.enabled!==!1,f=o.hostname,h=o.port?parseInt(o.port,10):a?443:80;if(a){let g=this.resolveTlsSettings(o,t),v=u;v.rejectUnauthorized=t.strictSSL;let y={rejectUnauthorized:t.strictSSL},x=this.readOptionalFile(g.caPath,"CA certificate");x&&(y.ca=x);let b=this.readOptionalFile(g.certPath,"client certificate");b&&(y.cert=b);let R=this.readOptionalFile(g.keyPath,"client private key");R&&(y.key=R);let C=this.readOptionalFile(g.pfxPath,"client pfx");C&&(y.pfx=C),g.passphrase&&(y.passphrase=g.passphrase),g.servername&&(v.servername=g.servername),m&&(p.https||p.http)?v.agent=this.buildHttpsProxyAgent(p.https||p.http,f,h,y):v.agent=new ii.Agent(y)}else if(m&&p.http){let g=new zr.URL(p.http);u.hostname=g.hostname,u.port=g.port||80,u.path=o.toString(),u.agent=this.buildHttpProxyAgent(p.http,f,h)}if(m&&p.bypass?.length&&p.bypass.some(v=>this.hostMatchesBypass(f,v)))if(u.hostname=o.hostname,u.port=o.port||(a?443:80),u.path=o.pathname+o.search,!a)delete u.agent;else{let v=this.resolveTlsSettings(o,t),y={rejectUnauthorized:t.strictSSL},x=this.readOptionalFile(v.caPath,"CA certificate");x&&(y.ca=x),u.agent=new ii.Agent(y)}return new Promise((g,v)=>{if(s?.aborted){let b=new Error("Request cancelled");b.name="AbortError",v(b);return}let x=(a?ii:Yc).request(u,async b=>{let R=b.statusCode||0;if(t.followRedirects&&[301,302,303,307,308].includes(R)){if(n>=t.maxRedirects){v(new Error(`Maximum redirects (${t.maxRedirects}) exceeded`));return}let q=b.headers.location;if(!q){v(new Error("Redirect response missing Location header"));return}let _=new zr.URL(q,e.url).toString(),M=e.method;!t.followOriginalMethod&&[301,302,303].includes(R)&&(M="GET");let D={...e.headers};t.followAuthHeader||(delete D.authorization,delete D.Authorization);try{let V=await this.executeInternal({...e,url:_,method:M,headers:D,body:M==="GET"?void 0:e.body},t,n+1,s),O=Date.now();V.time=O-i,g(V)}catch(V){v(V)}return}let C=[];b.on("data",q=>C.push(q)),b.on("end",()=>{let q=Date.now(),_=Buffer.concat(C),M=b.headers["content-encoding"];if(t.decompress&&M)try{M==="gzip"?_=wo.gunzipSync(_):M==="deflate"&&(_=wo.inflateSync(_))}catch(H){console.warn("[NodeHttpClient] Decompression failed:",H)}let D=_.toString("utf-8"),V={};for(let[H,Z]of Object.entries(b.headers))(typeof Z=="string"||Array.isArray(Z))&&(V[H]=Z);let O=this.parseCookies(b.headers["set-cookie"],o.hostname);g({status:b.statusCode||0,statusText:b.statusMessage||"",headers:V,cookies:O,body:D,time:q-i,size:_.length})})});s&&s.addEventListener("abort",()=>{x.destroy();let b=new Error("Request cancelled");b.name="AbortError",v(b)}),x.on("error",b=>{v(b)}),x.on("timeout",()=>{x.destroy(),v(new Error("Request timeout"))}),d!==void 0&&x.write(d),x.end()})}buildHttpProxyAgent(e,t,n){let s=new zr.URL(e),i=s.hostname,o=parseInt(s.port||"8080",10),a=new Yc.Agent;return a.createConnection=(c,l)=>Zc.createConnection({host:i,port:o},l),a}buildHttpsProxyAgent(e,t,n,s){let i=new zr.URL(e),o=i.hostname,a=parseInt(i.port||"8080",10),c=i.username?"Basic "+Buffer.from(`${decodeURIComponent(i.username)}:${decodeURIComponent(i.password)}`).toString("base64"):void 0,l=new ii.Agent(s);return l.createConnection=(u,d)=>{let p=Zc.createConnection({host:o,port:a});p.once("connect",()=>{let m=[`CONNECT ${t}:${n} HTTP/1.1`,`Host: ${t}:${n}`];c&&m.push(`Proxy-Authorization: ${c}`),p.write(m.join(`\r
274
+ `)}function Ur(r,e){return JSON.stringify(r)!==JSON.stringify(e)}function Wn(r){return r.map(e=>{let t=e.args.map(n=>{if(typeof n=="object")try{return JSON.stringify(n,null,2)}catch{return String(n)}return String(n)}).join(" ");return`[${e.level}] ${t}`})}function vo(r){let e=[],t=(n,s)=>{try{let i=s();if(i&&typeof i.then=="function"){let o=i.then(()=>{r.push({name:n,passed:!0})},a=>{r.push({name:n,passed:!1,message:a.message||String(a)})});e.push(o)}else r.push({name:n,passed:!0})}catch(i){r.push({name:n,passed:!1,message:i.message})}};return t.skip=(n,s)=>{r.push({name:n,passed:!0,skipped:!0})},t.fail=n=>{r.push({name:n||"Failed test",passed:!1,message:n||"pm.test.fail()"})},t.index=()=>r.length,t._pendingTests=e,t}function bo(r){let e={};for(let[t,n]of Object.entries(r))e[t]=Array.isArray(n)?n.join(", "):n;return e}function So(r,e,t){let n;if(t)try{n=new URL(t).hostname}catch{n=void 0}let s=oe.parseCookieHeaders(r||{},n);return s.length>0?s:Array.isArray(e)&&e.length>0?e.filter(i=>i&&i.name).map(i=>({name:i.name,value:i.value,domain:i.domain??n,path:i.path,expires:i.expires,maxAge:i.maxAge,httpOnly:i.httpOnly,secure:i.secure,sameSite:i.sameSite})):[]}var ii=E(()=>{"use strict";Bn()});var Zc,Vr,Yc=E(()=>{"use strict";Zc=I(require("vm"));yd();Sd();ri();ii();Vr=class{constructor(e,t){this.deps=e;this.initialContext=t;this.timerRegistry=gd(n=>{let s=n instanceof Error?n.message:String(n);this.consoleMessages.push({level:"error",args:[`Uncaught error in async callback: ${s}`]})}),this.initializeSession()}deps;initialContext;vmContext=null;ctx=null;modifiedRequest=null;assertions=[];consoleMessages=[];_variables={};_collectionVariables={};_globals={};_environmentVariables={};_liveEnvironmentScope=null;_liveGlobalsScope=null;_liveCollectionScope=null;_nextRequest=void 0;_skipRequest=!1;_visualizerData=void 0;timerRegistry;initializeSession(){this.modifiedRequest={url:this.initialContext.request.url,method:this.initialContext.request.method,headers:{...this.initialContext.request.headers},body:this.initialContext.request.body?{...this.initialContext.request.body}:null,params:this.initialContext.request.params?{...this.initialContext.request.params}:{},query:this.initialContext.request.query?{...this.initialContext.request.query}:{}},this.assertions=[],this.ctx=this.createSharedContext(),this.consoleMessages=[];let e=this,t={log:(...n)=>{e.consoleMessages.push({level:"log",args:n})},info:(...n)=>{e.consoleMessages.push({level:"info",args:n})},warn:(...n)=>{e.consoleMessages.push({level:"warn",args:n})},error:(...n)=>{e.consoleMessages.push({level:"error",args:n})}};this.vmContext=this.deps.createVM(this.ctx,t,this.timerRegistry.timers)}createSharedContext(){let e=this.initialContext,t=this.modifiedRequest,n=this.deps.createCommonContext(e,"prerequest");this._variables={...e.variables},this._collectionVariables={...e.collectionVariables||{}},this._globals={...e.globals||{}},this._environmentVariables={...e.environmentVariables||{}},this._liveEnvironmentScope=n.environment,this._liveGlobalsScope=n.globals,this._liveCollectionScope=n.collectionVariables;let s;try{s=new URL(e.request.url).hostname}catch{}let i={get:a=>e.cookieJar?e.cookieJar.get(a,s)?.value:void 0,set:(a,c)=>{e.cookieJar&&e.cookieJar.set({name:a,value:c,domain:s})},has:a=>e.cookieJar?e.cookieJar.has(a,s):!1,list:()=>e.cookieJar?e.cookieJar.getAll(s).map(a=>({name:a.name,value:a.value})):[],toObject:()=>{if(!e.cookieJar)return{};let a=e.cookieJar.getAll(s),c={};for(let l of a)c[l.name]=l.value;return c},jar:()=>{let a=e.cookieJar,c=l=>{if(l==null)return;let u=typeof l=="string"?l:typeof l=="object"||typeof l=="number"||typeof l=="boolean"?String(l):void 0;if(!u)return;let p=u.trim();if(p)try{return new URL(p).hostname}catch{return p}};return{getAll(l,u){try{if(!a){u(null,[]);return}let p=c(l),d=a.getAll(p).map(m=>({name:m.name,value:m.value,domain:m.domain,path:m.path,httpOnly:m.httpOnly,secure:m.secure}));u(null,d)}catch(p){u(p,[])}},get(l,u,p){try{if(!a){p(null,void 0);return}let d=c(l),m=a.get(u,d);p(null,m?{name:m.name,value:m.value,domain:m.domain}:void 0)}catch(d){p(d,void 0)}},set(l,u,p,d){try{if(!a){(d||p)?.(null);return}let m=c(l);typeof u=="string"&&typeof p=="string"?(a.set({name:u,value:p,domain:m}),d?.(null)):typeof u=="object"&&(a.set({...u,domain:m}),p?.(null))}catch(m){(d||p)?.(m)}},unset(l,u,p){try{if(!a){p?.(null);return}let d=c(l);a.delete(u,d),p?.(null)}catch(d){p?.(d)}},clear(l,u){try{let p=typeof l=="function"?l:u;if(!a){p?.(null);return}let d=typeof l=="function"?void 0:c(l);d&&typeof a.clearDomain=="function"?a.clearDomain(d):a.clear(),p?.(null)}catch(p){(typeof l=="function"?l:u)?.(p)}}}},remove:a=>{e.cookieJar&&e.cookieJar.delete(a,s)},unset:a=>{e.cookieJar&&e.cookieJar.delete(a,s)},clear:()=>{e.cookieJar&&e.cookieJar.clear()}},o=this;return{request:Qc(t,e),response:null,test:vo(this.assertions),expect:Gn,cookies:i,execution:{setNextRequest(a){o._nextRequest=a},skipRequest(){o._skipRequest=!0},runRequest(a,c){let u=(async()=>{if(typeof n.sendRequest!="function")throw new Error("pm.execution.runRequest is not available \u2014 HTTP service not configured.");let p=typeof a=="string"?{url:a,method:"GET"}:a,d=await n.sendRequest(p),m=Array.isArray(d?.cookies)?d.cookies.filter(g=>g?.name):[],f=d?.body,h=0;if(typeof f=="string")h=Buffer.byteLength(f,"utf8");else if(Buffer.isBuffer(f))h=f.length;else if(f!=null)try{h=Buffer.byteLength(JSON.stringify(f),"utf8")}catch{}return ni({executedRequest:null,status:d?.status??0,statusText:d?.statusText??"",headers:d?.headers??{},body:f,cookies:m,responseTime:d?.time,responseSize:h})})();if(typeof c=="function"){u.then(p=>c(null,p),p=>c(p));return}return u},location:{current:n.info?.requestName||"",currentRequestName:n.info?.requestName||"",eventName:"prerequest",toString(){return n.info?.requestName||""}}},setNextRequest(a){o._nextRequest=a},visualizer:{set(a,c){o._visualizerData={template:a,data:c}},clear(){o._visualizerData=void 0}},...n,info:{...n.info||{},eventName:"prerequest",requestName:n.info?.requestName||void 0,requestId:n.info?.requestId||void 0,iteration:e.iteration||0,iterationCount:e.iterationCount||1}}}injectLegacyGlobals(e,t){let n=this.vmContext;if(!n)return;let s=this.initialContext,i=e==="test"&&t?.executedRequest?t.executedRequest:this.modifiedRequest,o={};for(let[m,f]of Object.entries(i?.headers||{}))typeof f=="string"&&(o[m]=f);let a=i?.body,c=a==null?null:typeof a=="object"&&"content"in a?a.content:a,l=s.request;if(n.request={id:l?.id??"",name:l?.name??"",description:l?.description??"",url:typeof i?.url=="string"?i.url:String(i?.url??""),method:i?.method??"GET",headers:o,data:c},n.environment=this._liveEnvironmentScope?.toObject?.()??{...this._environmentVariables},n.globals=this._liveGlobalsScope?.toObject?.()??{...this._globals},n.data={...s.iterationData||{}},typeof n.iteration!="number"&&(n.iteration=0),e!=="test"||!t)return;let u=t.body;n.responseBody=u==null?"":typeof u=="string"?u:JSON.stringify(u);let p=t.statusText||"";n.responseCode={code:t.status,name:p,detail:p},n.responseHeaders={...t.headers||{}},n.responseTime=t.responseTime??0,n.responseCookies=(t.cookies||[]).map(m=>({...m}));let d=this;n.tests=new Proxy({},{set(m,f,h){return d.assertions.push({name:String(f),passed:!!h,message:h?void 0:`"${String(f)}" was false`}),!0}})}async executePreRequest(e){let t=si(e,this.deps.isolateScripts);if(!t||!t.trim())return{success:!0};try{this.consoleMessages.length=0,this.injectLegacyGlobals("prerequest");let n=this.ctx.variables.replaceIn(t),s=this.deps.scriptTimeoutMs??5e3,i=Zc.runInContext(n,this.vmContext,{timeout:s});this.deps.isolateScripts&&i&&typeof i.then=="function"&&await i,(await this.timerRegistry.drain(s)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${s}ms; pending async work was cancelled.`]});let a=Wn(this.consoleMessages),c=this.initialContext.request.body,l=!this.bodiesEqual(this.modifiedRequest.body,c);return{success:!0,modifiedRequest:{url:this.modifiedRequest.url!==this.initialContext.request.url?this.modifiedRequest.url:void 0,headers:Ur(this.modifiedRequest.headers,this.initialContext.request.headers)?this.modifiedRequest.headers:void 0,body:l?this.modifiedRequest.body:void 0,params:Ur(this.modifiedRequest.params,this.initialContext.request.params||{})?this.modifiedRequest.params:void 0,query:Ur(this.modifiedRequest.query,this.initialContext.request.query||{})?this.modifiedRequest.query:void 0},modifiedVariables:this.ctx.variables.toObject(),localVariables:this.ctx.variables.toLocalObject?.()??{},modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,consoleOutput:a.length>0?a:void 0,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}catch(n){let s=[...Wn(this.consoleMessages),`[error] Script execution failed: ${n.message}`];return{success:!1,error:n.message||"Pre-request script execution failed",consoleOutput:s,modifiedVariables:this.ctx?.variables?.toObject(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,nextRequest:this._nextRequest,skipRequest:this._skipRequest||void 0}}}async executePostResponse(e,t){let n=si(e,this.deps.isolateScripts);if(!n||!n.trim())return{testResults:[],consoleOutput:[]};try{this.consoleMessages.length=0,this.assertions.length=0,this.ctx.info.eventName="test",this.ctx.response=ni(t),this.ctx.request=Qc(t.executedRequest,this.initialContext),this.injectLegacyGlobals("test",t);let s=this.ctx.variables.replaceIn(n),i=this.deps.scriptTimeoutMs??5e3,o=Zc.runInContext(s,this.vmContext,{timeout:i});this.deps.isolateScripts&&o&&typeof o.then=="function"&&await o,this.ctx.test._pendingTests?.length>0&&(await Promise.all(this.ctx.test._pendingTests),this.ctx.test._pendingTests.length=0),(await this.timerRegistry.drain(i)).timedOut&&this.consoleMessages.push({level:"warn",args:[`Script timed out after ${i}ms; pending async work was cancelled.`]});let c=Wn(this.consoleMessages);return{testResults:[...this.assertions],consoleOutput:c.length>0?c:void 0,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}catch(s){this.assertions.push({name:"Script Execution",passed:!1,message:s.message||"Script execution failed"});let i=[...Wn(this.consoleMessages),`[error] Script execution failed: ${s.message}`];return{testResults:[...this.assertions],consoleOutput:i,modifiedVariables:this.ctx?.variables?.toObject?.(),localVariables:this.ctx?.variables?.toLocalObject?.()??{},modifiedEnvironmentVariables:this._liveEnvironmentScope?.toObject()||this._environmentVariables,modifiedGlobals:this._liveGlobalsScope?.toObject()||this._globals,modifiedCollectionVariables:this._liveCollectionScope?.toObject()||this._collectionVariables,nextRequest:this._nextRequest,visualizerData:this._visualizerData}}}bodiesEqual(e,t){return e===t||!e&&!t?!0:!e||!t?!1:e.type===t.type&&e.format===t.format&&JSON.stringify(e.content)===JSON.stringify(t.content)}dispose(){this.timerRegistry.clearAll(),this.vmContext=null,this.ctx=null,this.assertions=[]}}});function wd(r){if(typeof r=="string"&&r.charCodeAt(0)===30)try{return JSON.parse(r.slice(1))}catch{return r}return r}function Gh(r,e){if(r==="@")return"";if(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))return r.slice(1,-1);let t=r.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(t){let n=Zs(t[2],e),s=Vn(t[1],n);return s!==null?s:void 0}if(e[r]!==void 0)return wd(e[r]);if(mn(r)){let n=jr(r,e),s=gt(r,n);if(s!==void 0)return s}}var xd,xo,Rd=E(()=>{"use strict";Gc();Ks();ho();Br();xd="";xo=class{serializeValue(e){return typeof e=="string"?e:e===void 0?xd+"undefined":xd+JSON.stringify(e)}deserializeValue(e){if(e!==void 0){if(typeof e=="string"&&e.charCodeAt(0)===30){let t=e.slice(1);if(t==="undefined")return;try{return JSON.parse(t)}catch{}}return e}}createVariableScope(e){return{get:t=>this.deserializeValue(e[t]),set:(t,n)=>{e[t]=this.serializeValue(n)},has(t){return t in e},unset(t){delete e[t]},clear(){Object.keys(e).forEach(t=>delete e[t])},toObject(){return{...e}}}}createGlobalsScope(e,t){let n=(s,i,o)=>{t&&t(s,i,o)};return{get:s=>this.deserializeValue(e[s]),set:(s,i)=>{let o=this.serializeValue(i);e[s]=o,n("set",s,o)},has(s){return s in e},unset(s){delete e[s],n("unset",s)},clear(){Object.keys(e).forEach(s=>delete e[s]),n("clear")},toObject(){return{...e}}}}createMergedVariableScope(e,t,n,s,i={}){let o={get:a=>a in e?this.deserializeValue(e[a]):a in i?i[a]:a in t?this.deserializeValue(t[a]):a in n?this.deserializeValue(n[a]):this.deserializeValue(s[a]),set:(a,c)=>{e[a]=this.serializeValue(c)},has(a){return a in e||a in i||a in t||a in t||a in n||a in s},unset(a){delete e[a]},clear(){Object.keys(e).forEach(a=>delete e[a])},toObject(){return{...s,...n,...t,...i,...e}},toLocalObject(){return{...n,...t,...i,...e}},replaceIn(a){if(!a||typeof a!="string")return a;let c=o.toObject(),l=20,u=d=>d.replace(/\{\{([^}]+)\}\}/g,(m,f)=>{let h=f.trim(),g=h.match(/^\$([a-zA-Z_][a-zA-Z0-9_]*)(?:\(([^)]*)\))?$/);if(g)try{let y=Zs(g[2],c),x=Vn(g[1],y);return x!==null?String(x):m}catch{return m}let v=Lr(h);if(v){let y=Gh(v.input,c);if(y!==void 0){let x=Hr(y,v.filters,c);return x!==void 0?String(x):m}return m}if(o.has(h)){let y=o.get(h);return y===void 0?"":String(y)}if(mn(h)){let y={};for(let[C,R]of Object.entries(c))y[C]=wd(R);let x=jr(h,y),b=gt(h,x);if(b!==void 0)return String(b)}return m}),p=a;for(let d=0;d<l;d++){let m=u(p);if(m===p)break;p=m}return p}};return o}createEnvironmentScope(e,t,n,s){let i=(o,a,c)=>{n&&(s?n(o,a,c):n(a||"",o==="set"?c:void 0))};return{name:t||"",get:o=>this.deserializeValue(e[o]),set:(o,a)=>{let c=this.serializeValue(a);e[o]=c,i("set",o,c)},has(o){return o in e},unset(o){delete e[o],i("unset",o)},clear(){Object.keys(e).forEach(o=>delete e[o]),i("clear")},toObject(){return{...e}}}}}});var Wh,Kh,Cd,Nt,oi=E(()=>{"use strict";Wh=I(require("crypto")),Kh=I(require("querystring")),Cd=I(require("vm"));fd();Kc();Yc();ri();Rd();Nt=class{constructor(e,t=[],n,s="shared",i=5e3){this.httpService=e;this.secretRegistry=n;this.scopeMode=s;this.scriptTimeoutMs=i;this.moduleLoader=go(t)}httpService;secretRegistry;scopeMode;scriptTimeoutMs;moduleLoader;variableScopes=new xo;createRequestSession(e){return new Vr({createVM:this.createVM.bind(this),createCommonContext:this.createCommonContext.bind(this),isolateScripts:this.scopeMode==="isolated",scriptTimeoutMs:this.scriptTimeoutMs},e)}createVM(e,t,n){let s=this.moduleLoader.getGlobalSetupExports(),i=this.moduleLoader.createRequireFunction();e.require=i,e.vault=this.createVault();let o={ctx:e,hf:e,pm:e,console:t,...s||{},global:s,setTimeout:n?.setTimeout??setTimeout,setInterval:n?.setInterval??setInterval,clearTimeout:n?.clearTimeout??clearTimeout,clearInterval:n?.clearInterval??clearInterval,URL,URLSearchParams,Buffer,atob:a=>Buffer.from(a,"base64").toString("binary"),btoa:a=>Buffer.from(a,"binary").toString("base64"),TextEncoder,TextDecoder,crypto:Wh,_:i("lodash"),require:i,moment:ti(),querystring:Kh,CryptoJS:pd(),tv4:(()=>{try{return i("tv4")}catch{return}})(),postman:{setNextRequest:a=>e.setNextRequest?.(a),setGlobalVariable:(a,c)=>e.globals?.set(a,c),getGlobalVariable:a=>e.globals?.get(a),clearGlobalVariable:a=>e.globals?.unset(a),setEnvironmentVariable:(a,c)=>e.environment?.set(a,c),getEnvironmentVariable:a=>e.environment?.get(a),clearEnvironmentVariable:a=>e.environment?.unset(a),getResponseHeader:a=>{let c=e.response?.headers?.get?.(a);return c===void 0?null:c},getResponseCookie:a=>{let c=e.response?.cookies;if(c&&typeof c[Symbol.iterator]=="function"){for(let l of c)if(l?.name&&l.name.toLowerCase()===a.toLowerCase())return{...l}}return null}},jsonStringify:(a,c,l)=>JSON.stringify(a,c,l),jsonParse:a=>JSON.parse(a),xml2Json:a=>{try{let c=this.moduleLoader.createRequireFunction()("xml2js"),l;return c.parseString(a,{explicitArray:!1},(u,p)=>{if(u)throw u;l=p}),l}catch{throw new Error("xml2Json() requires the xml2js module. Add it to your modules/package.json and run npm install.")}}};return Cd.createContext(o)}createCommonContext(e,t){let n={...e.variables},s={...e.collectionVariables||{}},i={...e.globals||{}},o={...e.environmentVariables||{}},a=e.iterationData||{},c=this.variableScopes.createMergedVariableScope(n,o,s,i,a),l=this.variableScopes.createGlobalsScope(i,e.onGlobalsChange),u=this.variableScopes.createVariableScope(s),p=this.variableScopes.createEnvironmentScope(o,e.environmentName,e.onEnvironmentChange,!0),d={...p,set:(h,g)=>{let v=this.variableScopes.serializeValue(g);p.set(h,v),n[h]=v},unset(h){p.unset(h),delete n[h]},clear(){let h=Object.keys(o);p.clear();for(let g of h)delete n[g]}},m={...l,set:(h,g)=>{let v=this.variableScopes.serializeValue(g);l.set(h,v),n[h]=v},unset(h){l.unset(h),delete n[h]},clear(){let h=Object.keys(i);l.clear();for(let g of h)delete n[g]}};return m.replaceIn=c.replaceIn,u.replaceIn=c.replaceIn,d.replaceIn=c.replaceIn,{globals:m,collectionVariables:u,variables:c,environment:d,iterationData:{get:h=>a[h],has:h=>h in a,toObject:()=>({...a}),toJSON:()=>JSON.stringify(a)},sendRequest:this.createSendRequest(),expect:Gn,info:e.info||{eventName:t,requestName:void 0,requestId:void 0}}}createVault(){let e=this.secretRegistry,t=()=>{throw new Error("pm.vault is read-only in HTTP Forge. Use environment variables or {{secret:provider/path}} tokens to manage secrets.")};return{async get(n){if(!e)throw new Error('pm.vault is not available \u2014 no secret providers are configured. Configure a provider under "secrets.providers" to use pm.vault.get().');let s=`secret:${n}`;return(await e.resolveSecretTokens(`{{${s}}}`))[s]},set:t,unset:t}}createSendRequest(){return this.httpService?(e,t)=>{let n=typeof e=="string"?{url:e,method:"GET"}:e,s=this.httpService.execute({url:n.url,method:n.method||"GET",headers:n.headers||{},body:n.body,...n});if(t){s.then(i=>t(null,i)).catch(i=>t(i,null));return}return s}:(e,t)=>{let n=new Error("sendRequest not available - HTTP service not configured");if(t){t(n,null);return}return Promise.reject(n)}}}});function Xc(r){return r?String(r).replace(/[\u201C\u201D\u201E\u201F\u2033\u2036]/g,'"').replace(/[\u2018\u2019\u201A\u201B\u2032\u2035]/g,"'").replace(/[\x00-\x08\x0A-\x1F\x7F]/g,""):""}function wo(r){let e={};for(let[t,n]of Object.entries(r))e[t]=Xc(String(n));return e}var el=E(()=>{"use strict"});var Ed,nl,ai,tl,Co,qd,Gr,Eo,Ro,yn,qo=E(()=>{"use strict";Ed=I(require("fs")),nl=I(require("http")),ai=I(require("https")),tl=I(require("net")),Co=I(require("path")),qd=I(require("tls")),Gr=require("url"),Eo=I(require("zlib"));el();Ro={timeout:3e4,followRedirects:!0,followOriginalMethod:!1,followAuthHeader:!1,maxRedirects:10,strictSSL:!0,decompress:!0,includeCookies:!1,tls:{},certificates:[]},yn=class{resolveDefaults;resolveProxy;version;basePath;constructor(e,t=process.cwd(),n){if(typeof e=="function")this.resolveDefaults=()=>({...Ro,...e()??{}});else{let s={...Ro,...e};this.resolveDefaults=()=>s}this.basePath=t,typeof n=="function"?this.resolveProxy=n:this.resolveProxy=()=>n;try{this.version=require("../../package.json").version||"0.0.0"}catch{this.version="0.0.0"}}get settings(){return this.resolveDefaults()}async send(e){let t=this.mergeSettings(e.settings);return await this.executeInternal(e,t,0)}mergeSettings(e){let t=this.settings;return{timeout:e?.timeout??t.timeout,followRedirects:e?.followRedirects??t.followRedirects,followOriginalMethod:e?.followOriginalMethod??t.followOriginalMethod,followAuthHeader:e?.followAuthHeader??t.followAuthHeader,maxRedirects:e?.maxRedirects??t.maxRedirects,strictSSL:e?.strictSSL??t.strictSSL,decompress:e?.decompress??t.decompress,includeCookies:e?.includeCookies??t.includeCookies,tls:e?.tls??t.tls??{},certificates:e?.certificates??t.certificates??[]}}async executeInternal(e,t,n,s){let i=Date.now(),o=new Gr.URL(e.url),a=o.protocol==="https:",c=wo(e.headers||{});Object.keys(c).some(g=>g.toLowerCase()==="user-agent")||(c["User-Agent"]=`HttpForge/${this.version}`);let u={hostname:o.hostname,port:o.port||(a?443:80),path:o.pathname+o.search,method:e.method,headers:{...c},timeout:t.timeout||void 0},p;if(e.body!==void 0&&e.body!==null){typeof e.body=="string"||e.body instanceof Buffer?p=e.body:e.body instanceof URLSearchParams?p=e.body.toString():typeof e.body=="object"?p=JSON.stringify(e.body):p=String(e.body);let g=u.headers;!Object.keys(g).some(y=>y.toLowerCase()==="content-length")&&p!==void 0&&(g["Content-Length"]=Buffer.byteLength(p).toString())}t.decompress&&!c["accept-encoding"]&&!c["Accept-Encoding"]&&(u.headers["Accept-Encoding"]="gzip, deflate");let d=this.resolveProxy(),m=d&&d.enabled!==!1,f=o.hostname,h=o.port?parseInt(o.port,10):a?443:80;if(a){let g=this.resolveTlsSettings(o,t),v=u;v.rejectUnauthorized=t.strictSSL;let y={rejectUnauthorized:t.strictSSL},x=this.readOptionalFile(g.caPath,"CA certificate");x&&(y.ca=x);let b=this.readOptionalFile(g.certPath,"client certificate");b&&(y.cert=b);let C=this.readOptionalFile(g.keyPath,"client private key");C&&(y.key=C);let R=this.readOptionalFile(g.pfxPath,"client pfx");R&&(y.pfx=R),g.passphrase&&(y.passphrase=g.passphrase),g.servername&&(v.servername=g.servername),m&&(d.https||d.http)?v.agent=this.buildHttpsProxyAgent(d.https||d.http,f,h,y):v.agent=new ai.Agent(y)}else if(m&&d.http){let g=new Gr.URL(d.http);u.hostname=g.hostname,u.port=g.port||80,u.path=o.toString(),u.agent=this.buildHttpProxyAgent(d.http,f,h)}if(m&&d.bypass?.length&&d.bypass.some(v=>this.hostMatchesBypass(f,v)))if(u.hostname=o.hostname,u.port=o.port||(a?443:80),u.path=o.pathname+o.search,!a)delete u.agent;else{let v=this.resolveTlsSettings(o,t),y={rejectUnauthorized:t.strictSSL},x=this.readOptionalFile(v.caPath,"CA certificate");x&&(y.ca=x),u.agent=new ai.Agent(y)}return new Promise((g,v)=>{if(s?.aborted){let b=new Error("Request cancelled");b.name="AbortError",v(b);return}let x=(a?ai:nl).request(u,async b=>{let C=b.statusCode||0;if(t.followRedirects&&[301,302,303,307,308].includes(C)){if(n>=t.maxRedirects){v(new Error(`Maximum redirects (${t.maxRedirects}) exceeded`));return}let q=b.headers.location;if(!q){v(new Error("Redirect response missing Location header"));return}let N=new Gr.URL(q,e.url).toString(),M=e.method;!t.followOriginalMethod&&[301,302,303].includes(C)&&(M="GET");let _={...e.headers};t.followAuthHeader||(delete _.authorization,delete _.Authorization);try{let H=await this.executeInternal({...e,url:N,method:M,headers:_,body:M==="GET"?void 0:e.body},t,n+1,s),O=Date.now();H.time=O-i,g(H)}catch(H){v(H)}return}let R=[];b.on("data",q=>R.push(q)),b.on("end",()=>{let q=Date.now(),N=Buffer.concat(R),M=b.headers["content-encoding"];if(t.decompress&&M)try{M==="gzip"?N=Eo.gunzipSync(N):M==="deflate"&&(N=Eo.inflateSync(N))}catch(L){console.warn("[NodeHttpClient] Decompression failed:",L)}let _=N.toString("utf-8"),H={};for(let[L,Z]of Object.entries(b.headers))(typeof Z=="string"||Array.isArray(Z))&&(H[L]=Z);let O=this.parseCookies(b.headers["set-cookie"],o.hostname);g({status:b.statusCode||0,statusText:b.statusMessage||"",headers:H,cookies:O,body:_,time:q-i,size:N.length})})});s&&s.addEventListener("abort",()=>{x.destroy();let b=new Error("Request cancelled");b.name="AbortError",v(b)}),x.on("error",b=>{v(b)}),x.on("timeout",()=>{x.destroy(),v(new Error("Request timeout"))}),p!==void 0&&x.write(p),x.end()})}buildHttpProxyAgent(e,t,n){let s=new Gr.URL(e),i=s.hostname,o=parseInt(s.port||"8080",10),a=new nl.Agent;return a.createConnection=(c,l)=>tl.createConnection({host:i,port:o},l),a}buildHttpsProxyAgent(e,t,n,s){let i=new Gr.URL(e),o=i.hostname,a=parseInt(i.port||"8080",10),c=i.username?"Basic "+Buffer.from(`${decodeURIComponent(i.username)}:${decodeURIComponent(i.password)}`).toString("base64"):void 0,l=new ai.Agent(s);return l.createConnection=(u,p)=>{let d=tl.createConnection({host:o,port:a});d.once("connect",()=>{let m=[`CONNECT ${t}:${n} HTTP/1.1`,`Host: ${t}:${n}`];c&&m.push(`Proxy-Authorization: ${c}`),d.write(m.join(`\r
275
275
  `)+`\r
276
276
  \r
277
- `);let f="";p.once("data",h=>{if(f+=h.toString(),!f.includes("200")){d(new Error(`Proxy CONNECT failed: ${f.split(`\r
278
- `)[0]}`)),p.destroy();return}let g=wd.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=xo.isAbsolute(e)?e:xo.resolve(this.basePath,e);try{return xd.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 Xc,yn,Co=E(()=>{"use strict";Qc();Xc={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"},yn=class{sanitizeHeaderValue(e){return Kc(e)}sanitizeHeaders(e){return bo(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=Xc["x-www-form-urlencoded"];break;case"raw":i=t.format?Xc[t.format]:"text/plain",i||(i="text/plain");break;case"graphql":i=Xc.graphql;break;case"binary":i="application/octet-stream";break}i&&(e["Content-Type"]=i)}}});var bn,Eo=E(()=>{"use strict";bn=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}}});var Wr,Gh,Kr,el=E(()=>{"use strict";Wr=I(require("crypto")),Gh=3e4,Kr=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 C=e.pkceMethod||"S256";u=C==="S256"?this.generateCodeChallengeS256(l):l,d=C}let p=e.state||Wr.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[C,q]of Object.entries(e.extraParams))f.searchParams.set(C,this.resolve(q,t));this.pendingAuthCallback&&(this.pendingAuthCallback.reject(new Error("OAuth2 authorization superseded by a new request")),this.pendingAuthCallback=null);let h=new Promise((C,q)=>{this.pendingAuthCallback={resolve:C,reject:q,state:p}});await this.browserService.openExternal(f.toString());let g;try{g=await Promise.race([h,new Promise((C,q)=>setTimeout(()=>{this.pendingAuthCallback=null,q(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 x=await this.httpService.execute({method:"POST",url:s,headers:y,body:v.toString()}),b=this.parseTokenResponse(x.body,e),R=this.buildCacheKeyString(e);return this.tokenCache.set(R,b),b.refreshToken&&await this.storeRefreshToken(R,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||Wr.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-Gh:!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 Wr.randomBytes(32).toString("base64url")}generateCodeChallengeS256(e){return Wr.createHash("sha256").update(e).digest("base64url")}async storeRefreshToken(e,t){try{await this.secretStore.store(`oauth2_refresh_${e}`,t)}catch{}}}});function Wn(r,e={}){let t=[];Object.entries(e).forEach(([n,s])=>{t.push(`${n}=${s}`)}),t.length&&Gn.writeFileSync(r,t.join(`
279
- `),"utf-8")}function Zr(r,e,t){t&&(t.preRequest&&t.preRequest.trim()&&Gn.writeFileSync(Qr.join(r,`${e}.pre.js`),t.preRequest,"utf-8"),t.postResponse&&t.postResponse.trim()&&Gn.writeFileSync(Qr.join(r,`${e}.post.js`),t.postResponse,"utf-8"))}async function Rd(r,e,t,n,s){await r.exportCollectionAsRestClientFolder(t,n),e.exportEnvironmentsToFolder(n,s)}function oi(r,e,t){r.forEach(n=>{if(n.type==="folder"){let s=Qr.join(e,ve(n.name));Gn.mkdirSync(s,{recursive:!0}),Zr(s,ve(n.name),n.scripts),oi(n.items||[],s,t)}else if(n.type==="request"){let s=n,i=ve(s.name)+".http",o=Qr.join(e,i),a=Wh(s,t);Gn.writeFileSync(o,a,"utf-8"),Zr(e,ve(s.name),s.scripts)}})}function Wh(r,e){let t=[];t.push(`### ${e.name} / ${r.name}`),t.push(`# collection env: ${ve(e.name)}.env`),t.push(`# request scripts: ${ve(r.name)}.pre.js and .post.js`);let n=Kh(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(`
280
- `)}function Kh(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 Gn,Qr,qo=E(()=>{"use strict";Gn=I(require("fs")),Qr=I(require("path"));Ke()});var Fe,tl,Kn,nl=E(()=>{"use strict";Fe=I(require("fs")),tl=I(require("path"));Ke();dn();Kn=class{collectionsDir;cache=new Map;constructor(e){this.collectionsDir=e}ensureDirectory(){Fe.existsSync(this.collectionsDir)||Fe.mkdirSync(this.collectionsDir,{recursive:!0})}loadAll(){if(this.cache.clear(),!Fe.existsSync(this.collectionsDir))return[];let e=Fe.readdirSync(this.collectionsDir),t=[];for(let n of e)if(n.endsWith(".json"))try{let s=tl.join(this.collectionsDir,n),i=Fe.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(Fe.existsSync(t))try{let n=Fe.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=oe(e.name));let t=this.getCollectionPath(e.id),n=JSON.stringify(e,null,2);await Fe.promises.writeFile(t,n,"utf-8"),this.cache.set(e.id,e)}async delete(e){let t=this.getCollectionPath(e);if(!Fe.existsSync(t))return!1;try{return await Fe.promises.unlink(t),this.cache.delete(e),!0}catch(n){return console.error(`[JsonCollectionLoader] Failed to delete collection ${e}:`,n),!1}}exists(e){return Fe.existsSync(this.getCollectionPath(e))}getCollectionPath(e){return tl.join(this.collectionsDir,`${e}.json`)}getItemPath(e,t){}async create(e,t){let n={id:t||oe(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=xe(s.items,t);i&&(i.scripts=n,await this.save(s))}loadScripts(e,t){let n=this.load(e);return n?xe(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=xe(s.items,t.id);if(i)Object.assign(i,t);else if(n){let o=xe(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=Ut(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=xe(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=xe(s.items,t);if(!i)return!1;let o={...i};if(!Ut(s.items,t))return!1;if(n){let a=xe(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=xe(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=xe(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 Yr,rl=E(()=>{"use strict";oo();nl();Yr=class{static create(e){let t=e.getStorageConfig(),n=e.getCollectionsPath();return t.format==="folder"?new Vt(n):new Kn(n)}static createForFormat(e,t){return e==="folder"?new Vt(t):new Kn(t)}}});function Cd(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 Qh(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=>Ed(e)),event:sl(r.scripts),variable:r.variables?Object.entries(r.variables).map(([e,t])=>({key:e,value:t})):[]}}function Ed(r){if(r.type==="folder")return{name:r.name,item:r.items?r.items.map(Ed):[],event:sl(r.scripts)};if(r.type==="request"){let e=r;return{name:e.name,request:{method:e.method,header:(e.headers||[]).map(Zh),url:Yh(e),body:Xh(e),auth:eg(e.auth),description:e.description},event:sl(e.scripts),protocolProfileBehavior:tg(e.settings)}}}function Zh(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 Yh(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 Xh(r){if(!r.body)return;let e=r.body;if(typeof e=="string"){let i=Cd(e);return{mode:"raw",raw:e,options:{raw:{language:i}}}}if(e.type==="raw"){let i=e.format||Cd(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 eg(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 tg(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 sl(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 pe,bt,Xr,il=E(()=>{"use strict";Ke();qo();rl();dn();pe=I(require("fs")),bt=I(require("path"));Xr=class{constructor(e,t){this.configService=e;this.fileWatcherFactory=t;this.collectionsDir=e.getCollectionsPath(),this.loader=Yr.create(e),this.loadCollections(),this.setupFileWatcher()}configService;fileWatcherFactory;collectionsDir;collections=new Map;fileWatcher;loader;debounceTimer=null;selfWritePending=!1;localCollectionValues=new Map;onCollectionsChanged;ensureCollectionsDir(){pe.existsSync(this.collectionsDir)||pe.mkdirSync(this.collectionsDir,{recursive:!0})}loadCollections(){this.collections.clear();let e=this.loader.loadAll();for(let t of e)this.collections.set(t.id,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=oe(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 this.findItemRecursive(n.items,t)}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=oe(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:oe(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=oe(t),i=this.loader.getCollectionPath(e),o=bt.join(this.collectionsDir,s);if(!pe.existsSync(i))throw new Error(`Collection directory not found: ${i}`);this.copyDirRecursive(i,o);let a=bt.join(o,"collection.json");if(pe.existsSync(a)){let l=JSON.parse(pe.readFileSync(a,"utf-8"));l.id=s,l.name=t,pe.writeFileSync(a,JSON.stringify(l,null,2))}else pe.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:oe(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&&Ut(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=xe(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||!pe.existsSync(i))throw new Error(`Folder not found on disk: ${t}`);let o=bt.dirname(i),a=oe(n),c=bt.join(o,a);this.selfWritePending=!0,this.copyDirRecursive(i,c);let l=bt.join(c,"folder.json");if(pe.existsSync(l)){let p=JSON.parse(pe.readFileSync(l,"utf-8"));p.id=a,p.name=n,pe.writeFileSync(l,JSON.stringify(p,null,2))}else pe.writeFileSync(l,JSON.stringify({id:a,name:n,type:"folder"},null,2));this.loadCollections();let u=this.collections.get(e),d=u?xe(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||oe(e.name),type:"request",name:e.name,method:e.method||"GET",url:e.url,params:e.params,query:e.query,headers:e.headers,body:e.body,auth:e.auth,settings:e.settings,scripts:e.scripts,deprecated:e.deprecated,description:e.description,doc:e.doc,responseSchema:e.responseSchema,bodySchema:e.bodySchema,operationId:e.operationId,summary:e.summary,tags:e.tags,examples:e.examples,responses:e.responses,security:e.security};await this.loader.saveItem(e.collectionId,n,e.parentId);let 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=xe(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.collections.get(e);if(!s)return;let i=xe(s.items,t);if(!i||i.type!=="request")return;let o=i;return n==="pre-request"?o.scripts?.preRequest:o.scripts?.postResponse}async setRequestScript(e,t,n,s){let i=this.collections.get(e);if(!i)return!1;let o=xe(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){pe.existsSync(t)||pe.mkdirSync(t,{recursive:!0});for(let n of pe.readdirSync(e,{withFileTypes:!0})){let s=bt.join(e,n.name),i=bt.join(t,n.name);n.isDirectory()?this.copyDirRecursive(s,i):pe.copyFileSync(s,i)}}async importCollection(e){let t=pe.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||oe(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"),x=p.apikey?.find(b=>b.key==="in");return{type:"apikey",apikey:{key:v?.value||"",value:y?.value||"",in:x?.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(`
281
- `):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 C of f.header)!C.key||C.disabled||(C.key.toLowerCase()==="content-type"?g=C.value?.split(";")[0]?.trim():v[C.key]={description:String(C.value??""),schema:{type:"string"}});let y=f.body;if(typeof f.body=="string"&&f.body)try{y=JSON.parse(f.body)}catch{}let x=f.originalRequest,b;if(x){let C=typeof x.url=="string"?x.url:x.url?.raw??"";b=`${x.method||""} ${C}`.trim()||void 0}let R=f.name?f.name.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toLowerCase()||`example_${h}`:`example_${h}`;if(m.responses[h]){let C=m.responses[h];C.examples=C.examples??{},C.examples[R]={summary:b,value:y}}else m.responses[h]={description:f.name,contentType:g,examples:{[R]:{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:oe(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:oe(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:oe(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=Qh(n),i=JSON.stringify(s,null,2);pe.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,ve(n.name));pe.mkdirSync(s,{recursive:!0});let i=n.variables||{};Wn(bt.join(s,`${ve(n.name)}.env`),i),Zr(s,ve(n.name),n.scripts),oi(n.items,s,n)}dispose(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.fileWatcher?.dispose()}}});var re,Sn,Jt,ol=E(()=>{"use strict";re={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"}}}},Sn={preferred:".http-forge/http-forge.config.json",legacy:"http-forge.config.json"},Jt={collections:"collections",environments:"environments",flows:"flows",suites:"suites"}});var ee,j,Gt,Po=E(()=>{"use strict";ee=I(require("fs")),j=I(require("path"));ol();Gt=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=j.dirname(this.configPath),this.config=this.loadConfig(),this.setupFileWatcher()}workspacePath;fileWatcherFactory;notifications;config;configPath;configDir;fileWatchers=[];normalizeWorkspacePath(e){let t=j.resolve(e),n=j.basename(t),s=o=>ee.existsSync(j.join(o,"assets","collections"))||ee.existsSync(j.join(o,"collections"))||ee.existsSync(j.join(o,"environments"))||ee.existsSync(j.join(o,"http-forge.config.json"))?!0:ee.existsSync(j.join(o,".http-forge","http-forge.config.json"))?!1:ee.existsSync(j.join(o,"assets")),i=o=>!!(ee.existsSync(j.join(o,"collections"))||ee.existsSync(j.join(o,"environments"))||ee.existsSync(j.join(o,"suites")));if(n===".http-forge")return s(t)?t:j.dirname(t);if(n==="assets"){if(!i(t))return t;let o=j.dirname(t);return j.basename(o)===".http-forge"?j.dirname(o):o}return t}resolveConfigPath(){let e=j.join(this.workspacePath,Sn.legacy),t=j.join(this.workspacePath,Sn.preferred);return ee.existsSync(e)?e:ee.existsSync(t)||ee.existsSync(j.join(this.workspacePath,".http-forge"))?t:this.hasFolderCollectionsAtRoot(j.join(this.workspacePath,"assets"))||ee.existsSync(j.join(this.workspacePath,"assets"))||this.hasFolderCollectionsAtRoot(this.workspacePath)?e:t}loadConfig(){if(this.configPath=this.resolveConfigPath(),this.configDir=j.dirname(this.configPath),!ee.existsSync(this.configPath))return{...re};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 ${j.relative(this.workspacePath,this.configPath)}. Using default configuration.`),{...re}}}mergeWithDefaults(e){return{version:e.version??re.version,storage:{...re.storage,...e.storage},request:{...re.request,...e.request},scripts:{...re.scripts,...e.scripts},runner:{...re.runner,...e.runner,report:{...re.runner.report,...e.runner?.report}},environments:{...re.environments,...e.environments},restClientExport:{...re.restClientExport,...e.restClientExport},proxy:e.proxy!==void 0?e.proxy:re.proxy,discovery:{...re.discovery,...e.discovery},mcp:{...re.mcp,...e.mcp,cors:{...re.mcp.cors,...e.mcp?.cors}},secrets:{...re.secrets,...e.secrets,providers:{...re.secrets?.providers,...e.secrets?.providers}}}}setupFileWatcher(){if(!this.fileWatcherFactory)return;let e=()=>{this.reload()};for(let t of[Sn.preferred,Sn.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??re.runner.report,n=["all","failed","none"];return{...e,report:{maxBodyChars:Math.max(1e3,Math.floor(t.maxBodyChars??re.runner.report.maxBodyChars)),embedBodies:n.includes(t.embedBodies)?t.embedBodies:re.runner.report.embedBodies}}}getEnvironmentsConfig(){return this.config.environments}getRestClientExportPath(){let e=this.config.restClientExport?.path||"collections-rest-client";return j.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??re.discovery;return{customSeedLoaderModulePath:e.customSeedLoaderModulePath,frameworks:e.frameworks??re.discovery.frameworks,contextProperties:e.contextProperties??re.discovery.contextProperties,skipComponentAnalysis:e.skipComponentAnalysis??re.discovery.skipComponentAnalysis}}getMcpConfig(){let e=this.config.mcp??re.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(j.isAbsolute(e))return e;let t=e.startsWith("./")?e.slice(2):e,n=this.configExists()?this.configDir:this.workspacePath,s=t;if(j.basename(n)===".http-forge")(s===".http-forge"||s.startsWith(".http-forge/"))&&(s=s.slice(12));else if(n===this.workspacePath&&s.startsWith(".http-forge/")){let i=ee.existsSync(j.join(this.workspacePath,"assets")),o=ee.existsSync(j.join(this.workspacePath,".http-forge"));i&&!o&&(s=s.slice(12))}return s?j.join(n,...s.split("/").filter(i=>i!==""&&i!==".")):n}hasFolderCollectionsAtRoot(e){let t=j.join(e,Jt.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=j.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=[j.join(this.workspacePath,".http-forge","assets"),j.join(this.workspacePath,"assets"),j.join(this.workspacePath,"http-forge-assets"),this.workspacePath].find(i=>this.hasFolderCollectionsAtRoot(i));if(n)return n;let s=j.join(this.workspacePath,"assets");return this.hasFolderCollectionsAtRoot(s)?s:e}getRootPath(){return this.resolveStorageRootPath()}getCollectionsPath(){return j.join(this.getRootPath(),Jt.collections)}getEnvironmentsPath(){return j.join(this.getRootPath(),Jt.environments)}getFlowsPath(){return j.join(this.getRootPath(),Jt.flows)}getHistoryPath(){let e=this.resolvePath(this.config.storage.history);return this.configExists()||this.hasAnyEntries(e)?e:[j.join(this.workspacePath,".http-forge",".cache","histories"),j.join(this.workspacePath,".cache","histories"),j.join(this.workspacePath,".http-forge-cache","histories"),j.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:[j.join(this.workspacePath,".http-forge",".cache","results"),j.join(this.workspacePath,".cache","results"),j.join(this.workspacePath,".http-forge-cache","results"),j.join(this.getRootPath(),".cache","results")].find(s=>this.hasAnyEntries(s))||e}getSuitesPath(){return j.join(this.getRootPath(),Jt.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=j.dirname(this.configPath),this.config=this.loadConfig(),this.onConfigReloaded?.()}configExists(){return ee.existsSync(this.configPath)||ee.existsSync(this.resolveConfigPath())}getDefaultConfigForCurrentLocation(){if(j.basename(this.configDir)===".http-forge")return{...re,storage:{...re.storage,root:"./assets",history:"./.cache/histories",results:"./.cache/results"},scripts:{...re.scripts,modulePaths:["./assets/src","./assets/lib"]}};let e=ee.existsSync(j.join(this.workspacePath,"assets")),t=ee.existsSync(j.join(this.workspacePath,".http-forge"));return e&&!t?{...re,storage:{...re.storage,root:"./assets",history:"./.cache/histories",results:"./.cache/results"},scripts:{...re.scripts,modulePaths:["./assets/src","./assets/lib"]}}:{...re}}async createDefaultConfig(){this.configPath=this.resolveConfigPath(),this.configDir=j.dirname(this.configPath),await ee.promises.mkdir(j.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(j.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(j.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(j.join(e,"default-headers.json"),JSON.stringify(s,null,2),"utf-8")}dispose(){for(let e of this.fileWatchers)e.dispose();this.fileWatchers=[]}}});var ng,es,al=E(()=>{"use strict";jn();ng="httpForge.cookies",es=class{constructor(e,t=ng){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 ie.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 ie.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 ie.parseCookieHeaders(e,t)}isExpired(e){return ie.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 ie.domainMatches(e,t)}get count(){return this.cookies.size}}});var ts,cl=E(()=>{"use strict";jn();ts=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=>!(ie.isExpired(i)||i.domain&&!ie.domainMatches(t,i.domain)||!i.domain||i.path&&!n.startsWith(i.path)));if(s.length!==0)return ie.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 ko(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 ll=E(()=>{"use strict"});var ke,Ye,ai,ns,ul=E(()=>{"use strict";ke=I(require("fs")),Ye=I(require("path"));Ke();ll();qo();co();Lr();ai={SELECTED_ENVIRONMENT:"httpForge.selectedEnvironment",ENV_OVERRIDES_PREFIX:"httpForge.envOverrides."},ns=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=Ye.join(a,"_global.json"),this.localConfigPath=Ye.join(a,"_global.local.json"),this.historiesPath=n.getHistoryPath(),this.selectedEnvironment=t?.get(ai.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||!ke.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(!ke.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(ai.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`${ai.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=eo(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=Ye.join(e,"globals.env");Wn(o,i)}n.forEach(o=>{let a=s?.environments?.[o];if(!a)return;let c={...a.variables||{}};t&&(c={...i,...c});let l=Ye.join(e,`${ve(o)}.env`);Wn(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 Ye.join(this.environmentsPath,`${e}.json`)}localConfigExists(){return ke.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=ke.readFileSync(e,"utf-8"),n=ko(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 Ye.join(this.environmentsPath,`${e}.local.json`)}loadFolderConfigs(){let e=Nr(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){ke.existsSync(this.environmentsPath)||ke.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=ke.readdirSync(this.environmentsPath).filter(i=>i.endsWith(".json")).filter(i=>!Js(i)),s=new Set(Object.keys(e.environments||{}));for(let i of n){let o=Ye.basename(i,".json");if(!s.has(o))try{ke.unlinkSync(Ye.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(Ye.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(ai.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(ai.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=Ye.dirname(e);ke.existsSync(n)||ke.mkdirSync(n,{recursive:!0}),ke.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}catch(n){throw console.error(`Failed to save JSON to ${e}:`,n),n}}}});var _t,ci=E(()=>{"use strict";ri();_t=class r{constructor(e,t,n,s,i,o,a,c,l,u,d,p,m){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}httpService;scriptExecutor;envConfigService;requestPreparer;environment;cookieJar;collectionScripts;folderScriptsChain;onConsoleOutput;collectionName;collectionAuth;iteration;iterationCount;async execute(e,t,n){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 H={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:{url:e.url||"",method:e.method||"GET",headers:{},body:H,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,x={};for(let O in g)Object.prototype.hasOwnProperty.call(g,O)&&(x[O.toUpperCase()]=g[O]);if(!x.COOKIE&&m.settings?.includeCookies!==!1&&this.cookieJar){let H=this.cookieJar.getCookieHeader(h);H&&(x.COOKIE=H)}let b={method:y,url:h,headers:x,body:v.content,signal:n,settings:m.settings?{...m.settings}:void 0},R=await this.httpService.execute(b);this.cookieJar&&R.headers&&await this.cookieJar.setCookiesFromResponse(h,R.headers);let C=Date.now()-s,q=[],_={},M;if(o.length>0){let O=0;if(R.body)if(typeof R.body=="string")O=Buffer.byteLength(R.body,"utf8");else if(Buffer.isBuffer(R.body))O=R.body.length;else try{O=Buffer.byteLength(JSON.stringify(R.body),"utf8")}catch{O=0}let H=yo(R.headers,R.cookies,d.url),Z={executedRequest:d,status:R.status,statusText:R.statusText,headers:go(R.headers||{}),body:R.body,cookies:H,responseTime:R.time,responseSize:O},X=await u.executePostResponse(o,Z);q=X.testResults,_=X.modifiedEnvironmentVariables||{},M=X.visualizerData,(X.localVariables??X.modifiedVariables)&&(p=X.localVariables??X.modifiedVariables),X.nextRequest!==void 0&&(f=X.nextRequest),X.consoleOutput&&X.consoleOutput.length>0&&this.onConsoleOutput?.(X.consoleOutput,{requestName:e.name||"",phase:"post-response"})}let D=q.length===0||q.every(O=>O.passed),V=q.length>0?D:R.status>=200&&R.status<=302;return{requestId:e.id,name:e.name,executedRequest:{...d,headers:x},response:{status:R.status,statusText:R.statusText,headers:R.headers||{},body:R.body,time:R.time||C,cookies:R.cookies||[]},duration:C,timestamp:Date.now(),passed:V,assertions:q,modifiedVariables:p,modifiedEnvironmentVariables:_,nextRequest:f,visualizerData:M}}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:{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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");return`<!doctype html>
277
+ `);let f="";d.once("data",h=>{if(f+=h.toString(),!f.includes("200")){p(new Error(`Proxy CONNECT failed: ${f.split(`\r
278
+ `)[0]}`)),d.destroy();return}let g=qd.connect({...s,socket:d,servername:t});g.once("error",v=>p(v)),g.once("secureConnect",()=>p(null,g))})}),d.once("error",m=>p(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=Co.isAbsolute(e)?e:Co.resolve(this.basePath,e);try{return Ed.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[p,d]=u.split("=");switch(p.toLowerCase().trim()){case"domain":l.domain=d?.trim();break;case"path":l.path=d?.trim();break;case"expires":l.expires=d?.trim();break;case"httponly":l.httpOnly=!0;break;case"secure":l.secure=!0;break}}return l}):[]}}});var rl,vn,Ao=E(()=>{"use strict";el();rl={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"},vn=class{sanitizeHeaderValue(e){return Xc(e)}sanitizeHeaders(e){return wo(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=rl["x-www-form-urlencoded"];break;case"raw":i=t.format?rl[t.format]:"text/plain",i||(i="text/plain");break;case"graphql":i=rl.graphql;break;case"binary":i="application/octet-stream";break}i&&(e["Content-Type"]=i)}}});var Sn,Po=E(()=>{"use strict";Sn=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}}});var Qr,Zh,Zr,sl=E(()=>{"use strict";Qr=I(require("crypto")),Zh=3e4,Zr=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 p=this.buildCacheKeyString(e);return this.tokenCache.set(p,u),u.refreshToken&&await this.storeRefreshToken(p,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,p;if(c){l=this.generateCodeVerifier();let R=e.pkceMethod||"S256";u=R==="S256"?this.generateCodeChallengeS256(l):l,p=R}let d=e.state||Qr.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",d),u&&(f.searchParams.set("code_challenge",u),f.searchParams.set("code_challenge_method",p)),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[R,q]of Object.entries(e.extraParams))f.searchParams.set(R,this.resolve(q,t));this.pendingAuthCallback&&(this.pendingAuthCallback.reject(new Error("OAuth2 authorization superseded by a new request")),this.pendingAuthCallback=null);let h=new Promise((R,q)=>{this.pendingAuthCallback={resolve:R,reject:q,state:d}});await this.browserService.openExternal(f.toString());let g;try{g=await Promise.race([h,new Promise((R,q)=>setTimeout(()=>{this.pendingAuthCallback=null,q(new Error("OAuth2 authorization timed out after 2 minutes"))},12e4))])}finally{this.pendingAuthCallback=null}if(g.state&&g.state!==d)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 x=await this.httpService.execute({method:"POST",url:s,headers:y,body:v.toString()}),b=this.parseTokenResponse(x.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||Qr.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 p={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}},d=this.buildCacheKeyString(e);return this.tokenCache.set(d,p),p}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 p=this.resolve(e.username||"",t),d=this.resolve(e.password||"",t);if(!p)throw new Error("OAuth2 password grant requires username");c.append("username",p),c.append("password",d)}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[p,d]of Object.entries(e.extraParams))c.append(p,this.resolve(d,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-Zh:!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 Qr.randomBytes(32).toString("base64url")}generateCodeChallengeS256(e){return Qr.createHash("sha256").update(e).digest("base64url")}async storeRefreshToken(e,t){try{await this.secretStore.store(`oauth2_refresh_${e}`,t)}catch{}}}});function Zn(r,e={}){let t=[];Object.entries(e).forEach(([n,s])=>{t.push(`${n}=${s}`)}),t.length&&Qn.writeFileSync(r,t.join(`
279
+ `),"utf-8")}function Xr(r,e,t){t&&(t.preRequest&&t.preRequest.trim()&&Qn.writeFileSync(Yr.join(r,`${e}.pre.js`),t.preRequest,"utf-8"),t.postResponse&&t.postResponse.trim()&&Qn.writeFileSync(Yr.join(r,`${e}.post.js`),t.postResponse,"utf-8"))}async function Ad(r,e,t,n,s){await r.exportCollectionAsRestClientFolder(t,n),e.exportEnvironmentsToFolder(n,s)}function ci(r,e,t){r.forEach(n=>{if(n.type==="folder"){let s=Yr.join(e,Se(n.name));Qn.mkdirSync(s,{recursive:!0}),Xr(s,Se(n.name),n.scripts),ci(n.items||[],s,t)}else if(n.type==="request"){let s=n,i=Se(s.name)+".http",o=Yr.join(e,i),a=Yh(s,t);Qn.writeFileSync(o,a,"utf-8"),Xr(e,Se(s.name),s.scripts)}})}function Yh(r,e){let t=[];t.push(`### ${e.name} / ${r.name}`),t.push(`# collection env: ${Se(e.name)}.env`),t.push(`# request scripts: ${Se(r.name)}.pre.js and .post.js`);let n=Xh(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(`
280
+ `)}function Xh(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 Qn,Yr,Io=E(()=>{"use strict";Qn=I(require("fs")),Yr=I(require("path"));We()});var Ne,il,Yn,ol=E(()=>{"use strict";Ne=I(require("fs")),il=I(require("path"));We();pn();Yn=class{collectionsDir;cache=new Map;constructor(e){this.collectionsDir=e}ensureDirectory(){Ne.existsSync(this.collectionsDir)||Ne.mkdirSync(this.collectionsDir,{recursive:!0})}loadAll(){if(this.cache.clear(),!Ne.existsSync(this.collectionsDir))return[];let e=Ne.readdirSync(this.collectionsDir),t=[];for(let n of e)if(n.endsWith(".json"))try{let s=il.join(this.collectionsDir,n),i=Ne.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(Ne.existsSync(t))try{let n=Ne.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=ae(e.name));let t=this.getCollectionPath(e.id),n=JSON.stringify(e,null,2);await Ne.promises.writeFile(t,n,"utf-8"),this.cache.set(e.id,e)}async delete(e){let t=this.getCollectionPath(e);if(!Ne.existsSync(t))return!1;try{return await Ne.promises.unlink(t),this.cache.delete(e),!0}catch(n){return console.error(`[JsonCollectionLoader] Failed to delete collection ${e}:`,n),!1}}exists(e){return Ne.existsSync(this.getCollectionPath(e))}getCollectionPath(e){return il.join(this.collectionsDir,`${e}.json`)}getItemPath(e,t){}async create(e,t){let n={id:t||ae(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=Re(s.items,t);i&&(i.scripts=n,await this.save(s))}loadScripts(e,t){let n=this.load(e);return n?Re(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=Re(s.items,t.id);if(i)Object.assign(i,t);else if(n){let o=Re(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=Bt(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=Re(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=Re(s.items,t);if(!i)return!1;let o={...i};if(!Bt(s.items,t))return!1;if(n){let a=Re(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=Re(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=Re(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 es,al=E(()=>{"use strict";lo();ol();es=class{static create(e){let t=e.getStorageConfig(),n=e.getCollectionsPath();return t.format==="folder"?new Ut(n):new Yn(n)}static createForFormat(e,t){return e==="folder"?new Ut(t):new Yn(t)}}});function Pd(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 eg(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=>kd(e)),event:cl(r.scripts),variable:r.variables?Object.entries(r.variables).map(([e,t])=>({key:e,value:t})):[]}}function kd(r){if(r.type==="folder")return{name:r.name,item:r.items?r.items.map(kd):[],event:cl(r.scripts)};if(r.type==="request"){let e=r;return{name:e.name,request:{method:e.method,header:(e.headers||[]).map(tg),url:ng(e),body:rg(e),auth:sg(e.auth),description:e.description},event:cl(e.scripts),protocolProfileBehavior:ig(e.settings)}}}function tg(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 ng(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(p=>{let[d,...m]=p.split("=");return{key:d,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 rg(r){if(!r.body)return;let e=r.body;if(typeof e=="string"){let i=Pd(e);return{mode:"raw",raw:e,options:{raw:{language:i}}}}if(e.type==="raw"){let i=e.format||Pd(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 sg(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 ig(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 cl(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 me,vt,ts,ll=E(()=>{"use strict";We();Io();al();Tc();pn();me=I(require("fs")),vt=I(require("path"));ts=class{constructor(e,t){this.configService=e;this.fileWatcherFactory=t;this.collectionsDir=e.getCollectionsPath(),this.loader=es.create(e),this.loadCollections(),this.setupFileWatcher()}configService;fileWatcherFactory;collectionsDir;collections=new Map;fileWatcher;loader;debounceTimer=null;selfWritePending=!1;localCollectionValues=new Map;onCollectionsChanged;ensureCollectionsDir(){me.existsSync(this.collectionsDir)||me.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=ae(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(Hn(s)){let i=this.loader.loadRequestDetail?.(e,t);if(ro(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=ae(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:ae(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=ae(t),i=this.loader.getCollectionPath(e),o=vt.join(this.collectionsDir,s);if(!me.existsSync(i))throw new Error(`Collection directory not found: ${i}`);this.copyDirRecursive(i,o);let a=vt.join(o,"collection.json");if(me.existsSync(a)){let l=JSON.parse(me.readFileSync(a,"utf-8"));l.id=s,l.name=t,me.writeFileSync(a,JSON.stringify(l,null,2))}else me.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:ae(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&&Bt(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=Re(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||!me.existsSync(i))throw new Error(`Folder not found on disk: ${t}`);let o=vt.dirname(i),a=ae(n),c=vt.join(o,a);this.selfWritePending=!0,this.copyDirRecursive(i,c);let l=vt.join(c,"folder.json");if(me.existsSync(l)){let d=JSON.parse(me.readFileSync(l,"utf-8"));d.id=a,d.name=n,me.writeFileSync(l,JSON.stringify(d,null,2))}else me.writeFileSync(l,JSON.stringify({id:a,name:n,type:"folder"},null,2));this.loadCollections();let u=this.collections.get(e),p=u?Re(u.items,a):void 0;return p||{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||ae(e.name),type:"request",name:e.name,method:e.method||"GET",url:e.url,params:e.params,query:e.query,headers:e.headers,body:e.body,auth:e.auth,settings:e.settings,scripts:e.scripts,deprecated:e.deprecated,description:e.description,doc:e.doc,responseSchema:e.responseSchema,bodySchema:e.bodySchema,operationId:e.operationId,summary:e.summary,tags:e.tags,examples:e.examples,responses:e.responses,security:e.security};await this.loader.saveItem(e.collectionId,n,e.parentId);let 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=Re(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=Re(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){me.existsSync(t)||me.mkdirSync(t,{recursive:!0});for(let n of me.readdirSync(e,{withFileTypes:!0})){let s=vt.join(e,n.name),i=vt.join(t,n.name);n.isDirectory()?this.copyDirRecursive(s,i):me.copyFileSync(s,i)}}async importCollection(e){let t=me.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||ae(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=d=>{if(!d)return;switch(d.type?.toLowerCase()){case"bearer":return{type:"bearer",bearerToken:d.bearer?.find(b=>b.key==="token")?.value||""};case"basic":let h=d.basic?.find(b=>b.key==="username"),g=d.basic?.find(b=>b.key==="password");return{type:"basic",basicAuth:{username:h?.value||"",password:g?.value||""}};case"apikey":let v=d.apikey?.find(b=>b.key==="key"),y=d.apikey?.find(b=>b.key==="value"),x=d.apikey?.find(b=>b.key==="in");return{type:"apikey",apikey:{key:v?.value||"",value:y?.value||"",in:x?.value||"header"}};case"noauth":return{type:"none"};default:return}},n=d=>{if(!Array.isArray(d)||d.length===0)return;let m={};for(let f of d){let h=f.script?.exec;if(!h)continue;let g=Array.isArray(h)?h.join(`
281
+ `):h;f.listen==="prerequest"?m.preRequest=g:f.listen==="test"&&(m.postResponse=g)}return m.preRequest||m.postResponse?m:void 0},s=d=>{if(!d||typeof d!="object")return;let m={};return d.followRedirects===!1&&(m.followRedirects=!1),d.followOriginalHttpMethod===!0&&(m.followOriginalMethod=!0),d.followAuthorizationHeader===!1&&(m.followAuthHeader=!1),d.maxRedirects!==void 0&&(m.maxRedirects=d.maxRedirects),d.requestTimeout!==void 0&&(m.timeout=d.requestTimeout),Object.keys(m).length>0?m:void 0},i=d=>{if(!d||typeof d=="string")return;let m=d.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=d=>{if(typeof d=="string")return d;if(!d)return"";let m=new Set;if(Array.isArray(d.variable))for(let h of d.variable)h.key&&m.add(h.key);if(m.size===0&&d.raw)return d.raw;let f="";if(d.protocol&&(f+=d.protocol+"://"),d.host&&(f+=Array.isArray(d.host)?d.host.join("."):d.host),d.port&&(f+=":"+d.port),d.path){let g=(Array.isArray(d.path)?d.path:[d.path]).map(v=>{let y=v.startsWith(":")?v.substring(1):v;return m.has(y)?":"+y:(v.startsWith(":"),v)});f+="/"+g.join("/")}return!f&&d.raw?d.raw:f},a=d=>{if(!Array.isArray(d)||d.length===0)return;let m={responses:{}};for(let f of d){let h=String(f.code||200),g,v={};if(Array.isArray(f.header))for(let R of f.header)!R.key||R.disabled||(R.key.toLowerCase()==="content-type"?g=R.value?.split(";")[0]?.trim():v[R.key]={description:String(R.value??""),schema:{type:"string"}});let y=f.body;if(typeof f.body=="string"&&f.body)try{y=JSON.parse(f.body)}catch{}let x=f.originalRequest,b;if(x){let R=typeof x.url=="string"?x.url:x.url?.raw??"";b=`${x.method||""} ${R}`.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 R=m.responses[h];R.examples=R.examples??{},R.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=d=>!(!d||typeof d!="object"||d.item===void 0&&d.request===void 0&&(d.listen!==void 0||d.script!==void 0)),l=d=>d.filter(c).map(m=>{if(m.item)return{id:ae(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:ae(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||[]),p={id:ae(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(d=>d&&d.key).map(d=>[d.key,String(d.value??"")])):typeof e.variable=="object"&&e.variable!==null?Object.fromEntries(Object.entries(e.variable).map(([d,m])=>[d,String(m??"")])):void 0,items:u};return await this.saveCollection(p),p}async exportCollection(e,t){let n=this.collections.get(e);if(!n)throw new Error("Collection not found");let s=eg(n),i=JSON.stringify(s,null,2);me.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=vt.join(t,Se(n.name));me.mkdirSync(s,{recursive:!0});let i=n.variables||{};Zn(vt.join(s,`${Se(n.name)}.env`),i),Xr(s,Se(n.name),n.scripts),ci(n.items,s,n)}dispose(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.fileWatcher?.dispose()}}});var se,xn,zt,ul=E(()=>{"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"}}}},xn={preferred:".http-forge/http-forge.config.json",legacy:"http-forge.config.json"},zt={collections:"collections",environments:"environments",flows:"flows",suites:"suites"}});var te,D,Jt,To=E(()=>{"use strict";te=I(require("fs")),D=I(require("path"));ul();Jt=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=D.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=te.existsSync(D.join(this.workspacePath,"assets")),n=te.existsSync(D.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=D.resolve(e),n=D.basename(t),s=a=>te.existsSync(D.join(a,"assets","collections"))||te.existsSync(D.join(a,"collections"))||te.existsSync(D.join(a,"environments"))||te.existsSync(D.join(a,"http-forge.config.json"))?!0:te.existsSync(D.join(a,".http-forge","http-forge.config.json"))?!1:te.existsSync(D.join(a,"assets")),i=a=>!!(te.existsSync(D.join(a,"collections"))||te.existsSync(D.join(a,"environments"))||te.existsSync(D.join(a,"suites"))),o;if(n===".http-forge")o=s(t)?t:D.dirname(t);else if(n==="assets")if(!i(t))o=t;else{let a=D.dirname(t);D.basename(a)===".http-forge"?o=D.dirname(a):o=a}else o=t;return this._cachedWorkspaceNormalization={input:e,result:o},o}resolveConfigPath(){let e=D.join(this.workspacePath,xn.legacy),t=D.join(this.workspacePath,xn.preferred);return te.existsSync(e)?e:te.existsSync(t)||te.existsSync(D.join(this.workspacePath,".http-forge"))?t:this.hasFolderCollectionsAtRoot(D.join(this.workspacePath,"assets"))||te.existsSync(D.join(this.workspacePath,"assets"))||this.hasFolderCollectionsAtRoot(this.workspacePath)?e:t}loadConfig(){if(this.configPath=this.resolveConfigPath(),this.configDir=D.dirname(this.configPath),!te.existsSync(this.configPath))return{...se};try{let e=te.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 ${D.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[xn.preferred,xn.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 D.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(D.isAbsolute(e))return e;let t=e.startsWith("./")?e.slice(2):e,n=this.configExists()?this.configDir:this.workspacePath,s=t;return D.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?D.join(n,...s.split("/").filter(i=>i!==""&&i!==".")):n}hasFolderCollectionsAtRoot(e){let t=D.join(e,zt.collections);if(!te.existsSync(t))return!1;let n;try{n=te.readdirSync(t,{withFileTypes:!0})}catch{return!1}return n.some(s=>{if(!s.isDirectory())return!1;let i=D.join(t,s.name,"collection.json");return te.existsSync(i)})}hasAnyEntries(e){if(!te.existsSync(e))return!1;try{return te.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=[D.join(this.workspacePath,".http-forge","assets"),D.join(this.workspacePath,"assets"),D.join(this.workspacePath,"http-forge-assets"),this.workspacePath].find(i=>this.hasFolderCollectionsAtRoot(i));if(n)return n;let s=D.join(this.workspacePath,"assets");return this.hasFolderCollectionsAtRoot(s)?s:e}getRootPath(){return this.resolveStorageRootPath()}getCollectionsPath(){return D.join(this.getRootPath(),zt.collections)}getEnvironmentsPath(){return D.join(this.getRootPath(),zt.environments)}getFlowsPath(){return D.join(this.getRootPath(),zt.flows)}getHistoryPath(){let e=this.resolvePath(this.config.storage.history);return this.configExists()||this.hasAnyEntries(e)?e:[D.join(this.workspacePath,".http-forge",".cache","histories"),D.join(this.workspacePath,".cache","histories"),D.join(this.workspacePath,".http-forge-cache","histories"),D.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:[D.join(this.workspacePath,".http-forge",".cache","results"),D.join(this.workspacePath,".cache","results"),D.join(this.workspacePath,".http-forge-cache","results"),D.join(this.getRootPath(),".cache","results")].find(s=>this.hasAnyEntries(s))||e}getSuitesPath(){return D.join(this.getRootPath(),zt.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=D.dirname(this.configPath),this.config=this.loadConfig(),this.onConfigReloaded?.()}configExists(){return te.existsSync(this.configPath)||te.existsSync(this.resolveConfigPath())}getDefaultConfigForCurrentLocation(){if(D.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=te.existsSync(D.join(this.workspacePath,"assets")),t=te.existsSync(D.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=D.dirname(this.configPath),await te.promises.mkdir(D.dirname(this.configPath),{recursive:!0});let e=this.getDefaultConfigForCurrentLocation(),t=JSON.stringify(e,null,2);await te.promises.writeFile(this.configPath,t,"utf-8");let n=[this.getCollectionsPath(),this.getEnvironmentsPath(),this.getFlowsPath(),this.getSuitesPath()];for(let i of n)te.existsSync(i)||await te.promises.mkdir(i,{recursive:!0});let s=[this.getHistoryPath(),this.getResultsPath()];for(let i of s)te.existsSync(i)||await te.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 te.promises.writeFile(D.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 te.promises.writeFile(D.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 te.promises.writeFile(D.join(e,"default-headers.json"),JSON.stringify(s,null,2),"utf-8")}dispose(){for(let e of this.fileWatchers)e.dispose();this.fileWatchers=[]}}});var og,ns,dl=E(()=>{"use strict";Bn();og="httpForge.cookies",ns=class{constructor(e,t=og){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 rs,pl=E(()=>{"use strict";Bn();rs=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 Oo(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 fl=E(()=>{"use strict"});var Te,Ze,li,ss,ml=E(()=>{"use strict";Te=I(require("fs")),Ze=I(require("path"));We();fl();Io();po();Br();li={SELECTED_ENVIRONMENT:"httpForge.selectedEnvironment",ENV_OVERRIDES_PREFIX:"httpForge.envOverrides."},ss=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=Ze.join(a,"_global.json"),this.localConfigPath=Ze.join(a,"_global.local.json"),this.historiesPath=n.getHistoryPath(),this.selectedEnvironment=t?.get(li.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||!Te.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(!Te.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(li.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`${li.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=no(n.defaultHeaders||{},l),p=this.localEnvironmentValues.get(t)||{},d=this.secretValuesCache.get(t)||{},m={...i.variables||{},...c,...p,...d};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=Ze.join(e,"globals.env");Zn(o,i)}n.forEach(o=>{let a=s?.environments?.[o];if(!a)return;let c={...a.variables||{}};t&&(c={...i,...c});let l=Ze.join(e,`${Se(o)}.env`);Zn(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 Ze.join(this.environmentsPath,`${e}.json`)}localConfigExists(){return Te.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=Te.readFileSync(e,"utf-8"),n=Oo(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 Ze.join(this.environmentsPath,`${e}.local.json`)}loadFolderConfigs(){let e=_r(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 hn({globals:i,collectionVariables:{},environmentVariables:s,variables:{...o,...t||{}}})}saveFolderSharedConfig(e){Te.existsSync(this.environmentsPath)||Te.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=Te.readdirSync(this.environmentsPath).filter(i=>i.endsWith(".json")).filter(i=>!Ws(i)),s=new Set(Object.keys(e.environments||{}));for(let i of n){let o=Ze.basename(i,".json");if(!s.has(o))try{Te.unlinkSync(Ze.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(Ze.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 hn({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(li.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(li.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=Ze.dirname(e);Te.existsSync(n)||Te.mkdirSync(n,{recursive:!0}),Te.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}catch(n){throw console.error(`Failed to save JSON to ${e}:`,n),n}}}});var Mt,ui=E(()=>{"use strict";ii();Mt=class r{constructor(e,t,n,s,i,o,a,c,l,u,p,d,m){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=p;this.iteration=d;this.iterationCount=m}httpService;scriptExecutor;envConfigService;requestPreparer;environment;cookieJar;collectionScripts;folderScriptsChain;onConsoleOutput;collectionName;collectionAuth;iteration;iterationCount;async execute(e,t,n){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(d,m,f)=>{d==="set"&&m&&f!==void 0?this.envConfigService.setEnvironmentVariable(m,f,this.environment):d==="unset"&&m?this.envConfigService.deleteEnvironmentVariable(m,this.environment):d==="clear"&&this.envConfigService.clearEnvironmentVariables(this.environment)},onGlobalsChange:(d,m,f)=>{d==="set"&&m&&f!==void 0?this.envConfigService.setGlobalVariable(m,f):d==="unset"&&m?this.envConfigService.deleteGlobalVariable(m):d==="clear"&&this.envConfigService.clearGlobalVariables()}},u=this.scriptExecutor.createRequestSession(l),p=null;try{let d={...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 L={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:{url:e.url||"",method:e.method||"GET",headers:{},body:L,params:{},query:{}},response:{status:0,statusText:"Skipped",headers:{},body:null,time:0,cookies:[]},duration:Date.now()-s,timestamp:Date.now(),passed:!0,assertions:[],modifiedVariables:d,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)&&(d=O.localVariables??O.modifiedVariables))}p=await this.requestPreparer.prepareRequest(m,this.environment,a,d);let{url:h,headers:g,body:v,method:y}=p,x={};for(let O in g)Object.prototype.hasOwnProperty.call(g,O)&&(x[O.toUpperCase()]=g[O]);if(!x.COOKIE&&m.settings?.includeCookies!==!1&&this.cookieJar){let L=this.cookieJar.getCookieHeader(h);L&&(x.COOKIE=L)}let b={method:y,url:h,headers:x,body:v.content,signal:n,settings:m.settings?{...m.settings}:void 0},C=await this.httpService.execute(b);this.cookieJar&&C.headers&&await this.cookieJar.setCookiesFromResponse(h,C.headers);let R=Date.now()-s,q=[],N={},M;if(o.length>0){let O=0;if(C.body)if(typeof C.body=="string")O=Buffer.byteLength(C.body,"utf8");else if(Buffer.isBuffer(C.body))O=C.body.length;else try{O=Buffer.byteLength(JSON.stringify(C.body),"utf8")}catch{O=0}let L=So(C.headers,C.cookies,p.url),Z={executedRequest:p,status:C.status,statusText:C.statusText,headers:bo(C.headers||{}),body:C.body,cookies:L,responseTime:C.time,responseSize:O},X=await u.executePostResponse(o,Z);q=X.testResults,N=X.modifiedEnvironmentVariables||{},M=X.visualizerData,(X.localVariables??X.modifiedVariables)&&(d=X.localVariables??X.modifiedVariables),X.nextRequest!==void 0&&(f=X.nextRequest),X.consoleOutput&&X.consoleOutput.length>0&&this.onConsoleOutput?.(X.consoleOutput,{requestName:e.name||"",phase:"post-response"})}let _=q.length===0||q.every(O=>O.passed),H=q.length>0?_:C.status>=200&&C.status<=302;return{requestId:e.id,name:e.name,executedRequest:{...p,headers:x},response:{status:C.status,statusText:C.statusText,headers:C.headers||{},body:C.body,time:C.time||R,cookies:C.cookies||[]},duration:R,timestamp:Date.now(),passed:H,assertions:q,modifiedVariables:d,modifiedEnvironmentVariables:N,nextRequest:f,visualizerData:M}}catch(d){return this.handleError(e,p,d,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,p,d;u==="html"||u==="both"?(p=r.formatErrorAsHtml(c,l),d={"content-type":"text/html; charset=utf-8"}):(p=c,d={});let m={type:"none",content:null};return{requestId:e.id,name:e.name,executedRequest:{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:d,cookies:[],body:p,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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");return`<!doctype html>
282
282
  <html>
283
283
  <body style="font-family:system-ui,Segoe UI,Roboto,-apple-system,Helvetica,Arial,sans-serif;padding:12px;color:#c7254e;">
284
284
  <h2 style="margin-top:0;color:#a94442">Request Error</h2>
@@ -287,7 +287,7 @@ ${s}
287
287
  ${n(t)}
288
288
  </pre>`:""}
289
289
  </body>
290
- </html>`}}});var rs,dl=E(()=>{"use strict";Ke();rs=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){if(this.secretRegistry?.hasProviders){let y=await this.secretRegistry.resolveSecretTokens(e);Object.keys(y).length>0&&(s={...y,...s??{}})}let i=s&&Object.keys(s).length>0,o=i?this.envConfigService.resolveVariablesInObjectWithExtra(e.params||{},s,t):this.envConfigService.resolveVariablesInObject(e.params||{},t),a=i?this.envConfigService.resolveVariablesInObjectWithExtra(e.query||{},s,t):this.envConfigService.resolveVariablesInObject(e.query||{},t),c=eo(n?.headers||{},e.headers||{}),l=i?this.envConfigService.resolveVariablesInObjectWithExtra(c,s,t):this.envConfigService.resolveVariablesInObject(c,t);if(l=this.preprocessor.sanitizeHeaders(l),!Object.keys(l).some(y=>y.toLowerCase()==="user-agent")){let y=this.appInfo?.version||"0.0.0",x=this.appInfo?.name||"HttpForge";l["User-Agent"]=`${x}/${y}`}if(e.auth?.type==="bearer"&&e.auth.bearerToken){let y=i?this.envConfigService.resolveVariablesWithExtra(e.auth.bearerToken,s,t):this.envConfigService.resolveVariables(e.auth.bearerToken,t);l.Authorization=`Bearer ${y}`}if(e.auth?.type==="basic"&&e.auth.basicAuth){let y=i?this.envConfigService.resolveVariablesWithExtra(e.auth.basicAuth.username||"",s,t):this.envConfigService.resolveVariables(e.auth.basicAuth.username||"",t),x=i?this.envConfigService.resolveVariablesWithExtra(e.auth.basicAuth.password||"",s,t):this.envConfigService.resolveVariables(e.auth.basicAuth.password||"",t),b=Buffer.from(`${y}:${x}`).toString("base64");l.Authorization=`Basic ${b}`}e.auth?.type==="apikey"&&e.auth.apikey&&this.applyApiKey(e.auth.apikey,l,a,t,s),e.auth?.type==="oauth2"&&e.auth.oauth2&&await this.applyOAuth2(e.auth.oauth2,l,t);let d=null;if(e.body&&e.body.type!=="none"){let y=s&&Object.keys(s).length>0?this.envConfigService.resolveVariablesInObjectWithExtra(e.body.content,s,t):this.envConfigService.resolveVariablesInObject(e.body.content,t);if((e.body.format==="json"||e.body.type==="graphql")&&typeof y=="string")try{y=JSON.parse(y)}catch{e.body.format==="json"&&console.warn("[RequestPreparer] Failed to parse JSON body after variable resolution, keeping as string")}let x={type:e.body.type,format:e.body.format,content:y};e.body.type==="form-data"?d=this.buildMultipartFormData(x.content):d=this.preprocessor.encodeBody(x)}e.body?.type!=="form-data"&&this.preprocessor.setContentTypeHeader(l,e.body,e.bodyContentType);let p=e.method||"GET",m=e.url||"",f=s&&Object.keys(s).length>0?this.envConfigService.resolveVariablesWithExtra(m,s,t):this.envConfigService.resolveVariables(m,t),h=this.httpService.buildUrl(f,o,a),g=this.extractQueryFromUrl(h),v={type:e.body?.type||"none",format:e.body?.format,content:d};return{url:h,method:p,headers:l,body:v,params:o,query:g}}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){if(e.accessToken){let i=this.envConfigService.resolveVariables(e.accessToken,n),o=e.tokenPrefix||"Bearer";t.Authorization=`${o} ${i}`;return}if(!this.tokenManager)throw new Error("OAuth2 authentication requires IOAuth2TokenManager. Ensure the service is properly registered.");let s=await this.tokenManager.getToken(e,n);t.Authorization=`${s.tokenType} ${s.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 rg,ss,pl=E(()=>{"use strict";rg=`
290
+ </html>`}}});var is,hl=E(()=>{"use strict";We();is=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){if(this.secretRegistry?.hasProviders){let y=await this.secretRegistry.resolveSecretTokens(e);Object.keys(y).length>0&&(s={...y,...s??{}})}let i=s&&Object.keys(s).length>0,o=i?this.envConfigService.resolveVariablesInObjectWithExtra(e.params||{},s,t):this.envConfigService.resolveVariablesInObject(e.params||{},t),a=i?this.envConfigService.resolveVariablesInObjectWithExtra(e.query||{},s,t):this.envConfigService.resolveVariablesInObject(e.query||{},t),c=no(n?.headers||{},e.headers||{}),l=i?this.envConfigService.resolveVariablesInObjectWithExtra(c,s,t):this.envConfigService.resolveVariablesInObject(c,t);if(l=this.preprocessor.sanitizeHeaders(l),!Object.keys(l).some(y=>y.toLowerCase()==="user-agent")){let y=this.appInfo?.version||"0.0.0",x=this.appInfo?.name||"HttpForge";l["User-Agent"]=`${x}/${y}`}if(e.auth?.type==="bearer"&&e.auth.bearerToken){let y=i?this.envConfigService.resolveVariablesWithExtra(e.auth.bearerToken,s,t):this.envConfigService.resolveVariables(e.auth.bearerToken,t);l.Authorization=`Bearer ${y}`}if(e.auth?.type==="basic"&&e.auth.basicAuth){let y=i?this.envConfigService.resolveVariablesWithExtra(e.auth.basicAuth.username||"",s,t):this.envConfigService.resolveVariables(e.auth.basicAuth.username||"",t),x=i?this.envConfigService.resolveVariablesWithExtra(e.auth.basicAuth.password||"",s,t):this.envConfigService.resolveVariables(e.auth.basicAuth.password||"",t),b=Buffer.from(`${y}:${x}`).toString("base64");l.Authorization=`Basic ${b}`}e.auth?.type==="apikey"&&e.auth.apikey&&this.applyApiKey(e.auth.apikey,l,a,t,s),e.auth?.type==="oauth2"&&e.auth.oauth2&&await this.applyOAuth2(e.auth.oauth2,l,t);let p=null;if(e.body&&e.body.type!=="none"){let y=s&&Object.keys(s).length>0?this.envConfigService.resolveVariablesInObjectWithExtra(e.body.content,s,t):this.envConfigService.resolveVariablesInObject(e.body.content,t);if((e.body.format==="json"||e.body.type==="graphql")&&typeof y=="string")try{y=JSON.parse(y)}catch{e.body.format==="json"&&console.warn("[RequestPreparer] Failed to parse JSON body after variable resolution, keeping as string")}let x={type:e.body.type,format:e.body.format,content:y};e.body.type==="form-data"?p=this.buildMultipartFormData(x.content):p=this.preprocessor.encodeBody(x)}e.body?.type!=="form-data"&&this.preprocessor.setContentTypeHeader(l,e.body,e.bodyContentType);let d=e.method||"GET",m=e.url||"",f=s&&Object.keys(s).length>0?this.envConfigService.resolveVariablesWithExtra(m,s,t):this.envConfigService.resolveVariables(m,t),h=this.httpService.buildUrl(f,o,a),g=this.extractQueryFromUrl(h),v={type:e.body?.type||"none",format:e.body?.format,content:p};return{url:h,method:d,headers:l,body:v,params:o,query:g}}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){if(e.accessToken){let i=this.envConfigService.resolveVariables(e.accessToken,n),o=e.tokenPrefix||"Bearer";t.Authorization=`${o} ${i}`;return}if(!this.tokenManager)throw new Error("OAuth2 authentication requires IOAuth2TokenManager. Ensure the service is properly registered.");let s=await this.tokenManager.getToken(e,n);t.Authorization=`${s.tokenType} ${s.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 ag,os,gl=E(()=>{"use strict";ag=`
291
291
  query IntrospectionQuery {
292
292
  __schema {
293
293
  queryType { name }
@@ -315,26 +315,26 @@ fragment TypeRef on __Type {
315
315
  kind name
316
316
  ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } } }
317
317
  }
318
- `.trim(),ss=class{constructor(e){this.httpClient=e}httpClient;schemaCache=new Map;async fetchSchema(e,t){let n={method:"POST",url:e,headers:{"Content-Type":"application/json",Accept:"application/json",...t||{}},body:JSON.stringify({query:rg,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(`
319
- `),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 ut(r){let e={};for(let[t,n]of Object.entries(r))qd.test(t)?e[t]=Array.isArray(n)?n.map(()=>wn):wn:e[t]=n;return e}function ml(r=[]){return r.map(e=>e&&typeof e=="object"&&e.name&&Wt.test(e.name)?{...e,value:wn}:e)}function fl(r){try{let e=new URL(r),t=!1;for(let[n]of e.searchParams)Wt.test(n)&&(e.searchParams.set(n,wn),t=!0);return t?e.toString():r}catch{return r}}function li(r){if(r==null)return r;if(Array.isArray(r))return r.map(t=>li(t));if(typeof r!="object")return r;let e={};for(let[t,n]of Object.entries(r)){let s=Wt.test(t);n===null||typeof n!="object"?e[t]=s?wn:n:s&&Array.isArray(n)?e[t]=n.map(i=>i===null||typeof i!="object"?wn:li(i)):e[t]=li(n)}return e}function sg(r){try{let e=new URLSearchParams(r),t=!1;for(let[n]of e)Wt.test(n)&&(e.set(n,wn),t=!0);return t?e.toString():r}catch{return r}}function Pd(r){if(r==null)return r;if(typeof r=="object"&&!Buffer.isBuffer(r))return li(r);if(typeof r=="string"){let e=r.trim();if(e.startsWith("{")||e.startsWith("["))try{let t=JSON.parse(e),n=li(t);return JSON.stringify(n)}catch{}if(e.includes("=")&&!e.includes(`
320
- `))return sg(e)}return r}function To(r){return{...r,sentRequest:{...r.sentRequest,url:fl(r.sentRequest.url),headers:ut(r.sentRequest.headers),body:r.sentRequest.body!=null?Pd(r.sentRequest.body):r.sentRequest.body}}}function Oo(r){return{...r,headers:ut(r.headers),cookies:r.cookies.map(e=>e&&typeof e=="object"&&e.name&&Wt.test(e.name)?{...e,value:wn}:e)}}function $o(r){return{...r,url:fl(r.url),request:{...r.request,url:fl(r.request.url),headers:ut(r.request.headers),query:ut(r.request.query),params:ut(r.request.params),body:r.request.body!=null?Pd(r.request.body):r.request.body},response:{headers:ut(r.response.headers),body:r.response.body,time:r.response.time,size:r.response.size,cookies:r.response.cookies?ml(r.response.cookies):r.response.cookies}}}function xn(r){return typeof r=="string"&&ig.test(r)}function Qn(r){return r.replace(/\./g,"_").replace(/[^a-zA-Z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toLowerCase()}function kd(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)Wt.test(i)&&o&&!xn(o)&&e.push({location:"url",field:i,value:o,variableName:n(Qn(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)qd.test(i)&&o&&!xn(o)&&e.push({location:"header",field:i,value:o,variableName:n(Qn(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)Wt.test(i)&&o&&!xn(o)&&e.push({location:"query",field:i,value:o,variableName:n(Qn(i))})}if(r.auth){let s=r.auth;if(s.bearerToken&&!xn(s.bearerToken)&&e.push({location:"auth",field:"bearerToken",value:s.bearerToken,variableName:n("bearer_token")}),s.basicAuth&&s.basicAuth.password&&!xn(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&&!xn(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&&Io(s,e,t,"")}return e}function Io(r,e,t,n){if(r!=null){if(typeof r=="string"){let s=r.trim();if(s.startsWith("{")||s.startsWith("[")){try{Io(JSON.parse(s),e,t,n)}catch{}return}if(s.includes("=")&&!s.includes(`
321
- `)){try{let i=new URLSearchParams(s);for(let[o,a]of i)if(Wt.test(o)&&a&&!xn(a)){let c=Qn(o),l=2;for(;t.has(c);)c=`${Qn(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)=>Io(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(Wt.test(s)&&i&&typeof i=="string"&&!xn(i)){let a=Qn(s),c=2;for(;t.has(a);)a=`${Qn(s)}_${c++}`;t.add(a),e.push({location:"body",field:s,path:o,value:i,variableName:a})}else typeof i=="object"&&i!==null&&Io(i,e,t,o)}}}function Id(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(`([?&])${ag(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":og(t,n.field,n.path,n.value,s);break}}return t}function og(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);Ad(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(`
322
- `)){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&&Ad(o,e,t||e,n,s)}}function Ad(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 ag(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var wn,qd,Wt,ig,is=E(()=>{"use strict";wn="***",qd=/^(authorization|proxy-authorization|www-authenticate)$|(token|cookie|secret|credential|api[_\-]?key|bearer|session[_\-]?id)/i,Wt=/(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;ig=/\{\{[^}]+\}\}/});var Y,Ue,os,hl=E(()=>{"use strict";Y=I(require("fs")),Ue=I(require("path"));Ke();is();os=class{historyPath;sharedHistoryPath;constructor(e,t){this.historyPath=e,this.sharedHistoryPath=t}getEnvironmentHistoryPath(e){return Ue.join(this.historyPath,ve(e))}getCollectionHistoryPath(e,t){return Ue.join(this.getEnvironmentHistoryPath(e),t)}getRequestPath(e,t,n){return Ue.join(this.getCollectionHistoryPath(e,t),ve(n))}getSharedEnvironmentHistoryPath(e){return Ue.join(this.sharedHistoryPath,ve(e))}getSharedCollectionHistoryPath(e,t){return Ue.join(this.getSharedEnvironmentHistoryPath(e),t)}getSharedRequestPath(e,t,n){return Ue.join(this.getSharedCollectionHistoryPath(e,t),ve(n))}getHistoryFilePath(e,t,n){return Ue.join(this.getRequestPath(e,t,n),"transactions.json")}getSharedHistoryFilePath(e,t,n){return Ue.join(this.getSharedRequestPath(e,t,n),"transactions.json")}getResponseFilePath(e,t,n,s){return Ue.join(this.getRequestPath(e,t,n),`${s}.json`)}getSharedResponseFilePath(e,t,n,s){return Ue.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=To({...i,method:s,id:td(),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=Ue.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(Ue.join(s,o));Y.rmdirSync(s)}}saveFullResponse(e,t,n,s,i){let o=this.getRequestPath(e,t,n),a=this.getResponseFilePath(e,t,n,s);try{Y.existsSync(o)||Y.mkdirSync(o,{recursive:!0});let c=Oo(i);Y.writeFileSync(a,JSON.stringify(c,null,2),"utf-8")}catch(c){throw console.error(`Failed to save full response for ${s}:`,c),c}}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 Zn,gl=E(()=>{"use strict";Zn=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 $d(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 Td(r){return/^-?\d+$/.test(r)?"integer":/^-?\d+\.\d+$/.test(r)?"number":r==="true"||r==="false"?"boolean":"string"}function Fo(r,e){if(r==="integer"&&e==="number"||r==="number"&&e==="integer")return"number"}function Fd(r){return r.replace(/\{\{(\w+)\}\}/g,"<$1>")}function yl(r,e){let t=Fd(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 vl(r){if(typeof r=="string")return Fd(r);if(Array.isArray(r))return r.map(e=>vl(e));if(r!==null&&typeof r=="object"){let e={};for(let[t,n]of Object.entries(r))e[t]=vl(n);return e}return r}function ui(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 vl(e)}function bl(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 Sl(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 Od(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=yl(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 Nd(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:Td(n)},s.example=yl(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||Td(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=yl(i.value,s.schema.type||"string")}e.push(s)}if(r.query)for(let t of r.query){if(!t.key)continue;let n=Od(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||cg.has(n.key.toLowerCase()))continue;let s=Od(n,"header");e.push(s)}}return e}function Md(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 _d(r){return r.replace(/^\[DEPRECATED\]\s*/i,"")}function xl(r){return/^\[DEPRECATED\]/i.test(r)}function di(r){let e={};for(let t of r.split(/\s+/))t&&(e[t]="");return e}var cg,pi=E(()=>{"use strict";cg=new Set(["content-type","authorization","accept","cookie","host","content-length"])});var ug,dg,pg,fg,mg,hg,gg,Kt,No=E(()=>{"use strict";pi();ug=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,dg=/^\d{4}-\d{2}-\d{2}$/,pg=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,fg=/^https?:\/\/[^\s]+$/,mg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,hg=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,gg=/^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/,Kt=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=Fo(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(ug.test(e))return"date-time";if(dg.test(e))return"date";if(pg.test(e))return"email";if(mg.test(e))return"uuid";if(fg.test(e))return"uri";if(hg.test(e))return"ipv4";if(gg.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 Mo,Dd=E(()=>{"use strict";pi();Mo=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||_d(e.name),e.description&&(u.description=e.description),(e.deprecated||xl(e.name))&&(u.deprecated=!0,xl(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=Nd(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=Md(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=ui(n);d!==void 0&&s.content[u]&&(s.content[u].example=d)}return s}i=e.bodySchema.contentType||bl(n),o=e.bodySchema.schema,a=ui(n),e.bodySchema.encoding&&(c=e.bodySchema.encoding)}else switch(i=bl(n),n.type){case"raw":{if(n.format==="json"&&n.content){let u=ui(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=Sl(n);break}case"x-www-form-urlencoded":{o=Sl(n);break}case"binary":{o={type:"string",format:"binary"};break}case"graphql":{o={type:"object",properties:{query:{type:"string"},variables:{type:"object"}}},a=ui(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?di(t.scope):{}};break;case"authorization_code":n.authorizationCode={authorizationUrl:t.authUrl||"",tokenUrl:t.tokenUrl||"",scopes:t.scope?di(t.scope):{}};break;case"password":n.password={tokenUrl:t.tokenUrl||"",scopes:t.scope?di(t.scope):{}};break;case"implicit":n.implicit={authorizationUrl:t.authUrl||"",scopes:t.scope?di(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 _o,jd=E(()=>{"use strict";pi();_o=class{mergeOperation(e,t,n){if(t.summary&&t.summary!==e.summary&&(e.description=(e.description||e.summary||"")+`
318
+ `.trim(),os=class{constructor(e){this.httpClient=e}httpClient;schemaCache=new Map;async fetchSchema(e,t){let n={method:"POST",url:e,headers:{"Content-Type":"application/json",Accept:"application/json",...t||{}},body:JSON.stringify({query:ag,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(`
319
+ `),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 lt(r){let e={};for(let[t,n]of Object.entries(r))Td.test(t)?e[t]=Array.isArray(n)?n.map(()=>Rn):Rn:e[t]=n;return e}function vl(r=[]){return r.map(e=>e&&typeof e=="object"&&e.name&&Gt.test(e.name)?{...e,value:Rn}:e)}function yl(r){try{let e=new URL(r),t=!1;for(let[n]of e.searchParams)Gt.test(n)&&(e.searchParams.set(n,Rn),t=!0);return t?e.toString():r}catch{return r}}function di(r){if(r==null)return r;if(Array.isArray(r))return r.map(t=>di(t));if(typeof r!="object")return r;let e={};for(let[t,n]of Object.entries(r)){let s=Gt.test(t);n===null||typeof n!="object"?e[t]=s?Rn:n:s&&Array.isArray(n)?e[t]=n.map(i=>i===null||typeof i!="object"?Rn:di(i)):e[t]=di(n)}return e}function cg(r){try{let e=new URLSearchParams(r),t=!1;for(let[n]of e)Gt.test(n)&&(e.set(n,Rn),t=!0);return t?e.toString():r}catch{return r}}function Od(r){if(r==null)return r;if(typeof r=="object"&&!Buffer.isBuffer(r))return di(r);if(typeof r=="string"){let e=r.trim();if(e.startsWith("{")||e.startsWith("["))try{let t=JSON.parse(e),n=di(t);return JSON.stringify(n)}catch{}if(e.includes("=")&&!e.includes(`
320
+ `))return cg(e)}return r}function Fo(r){return{...r,sentRequest:{...r.sentRequest,url:yl(r.sentRequest.url),headers:lt(r.sentRequest.headers),body:r.sentRequest.body!=null?Od(r.sentRequest.body):r.sentRequest.body}}}function No(r){return{...r,headers:lt(r.headers),cookies:r.cookies.map(e=>e&&typeof e=="object"&&e.name&&Gt.test(e.name)?{...e,value:Rn}:e)}}function Mo(r){return{...r,url:yl(r.url),request:{...r.request,url:yl(r.request.url),headers:lt(r.request.headers),query:lt(r.request.query),params:lt(r.request.params),body:r.request.body!=null?Od(r.request.body):r.request.body},response:{headers:lt(r.response.headers),body:r.response.body,time:r.response.time,size:r.response.size,cookies:r.response.cookies?vl(r.response.cookies):r.response.cookies}}}function wn(r){return typeof r=="string"&&lg.test(r)}function Xn(r){return r.replace(/\./g,"_").replace(/[^a-zA-Z0-9_]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toLowerCase()}function $d(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)Gt.test(i)&&o&&!wn(o)&&e.push({location:"url",field:i,value:o,variableName:n(Xn(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)Td.test(i)&&o&&!wn(o)&&e.push({location:"header",field:i,value:o,variableName:n(Xn(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)Gt.test(i)&&o&&!wn(o)&&e.push({location:"query",field:i,value:o,variableName:n(Xn(i))})}if(r.auth){let s=r.auth;if(s.bearerToken&&!wn(s.bearerToken)&&e.push({location:"auth",field:"bearerToken",value:s.bearerToken,variableName:n("bearer_token")}),s.basicAuth&&s.basicAuth.password&&!wn(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&&!wn(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&&$o(s,e,t,"")}return e}function $o(r,e,t,n){if(r!=null){if(typeof r=="string"){let s=r.trim();if(s.startsWith("{")||s.startsWith("[")){try{$o(JSON.parse(s),e,t,n)}catch{}return}if(s.includes("=")&&!s.includes(`
321
+ `)){try{let i=new URLSearchParams(s);for(let[o,a]of i)if(Gt.test(o)&&a&&!wn(a)){let c=Xn(o),l=2;for(;t.has(c);)c=`${Xn(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)=>$o(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(Gt.test(s)&&i&&typeof i=="string"&&!wn(i)){let a=Xn(s),c=2;for(;t.has(a);)a=`${Xn(s)}_${c++}`;t.add(a),e.push({location:"body",field:s,path:o,value:i,variableName:a})}else typeof i=="object"&&i!==null&&$o(i,e,t,o)}}}function Fd(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(`([?&])${dg(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":ug(t,n.field,n.path,n.value,s);break}}return t}function ug(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);Id(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(`
322
+ `)){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&&Id(o,e,t||e,n,s)}}function Id(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 Rn,Td,Gt,lg,as=E(()=>{"use strict";Rn="***",Td=/^(authorization|proxy-authorization|www-authenticate)$|(token|cookie|secret|credential|api[_\-]?key|bearer|session[_\-]?id)/i,Gt=/(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;lg=/\{\{[^}]+\}\}/});var Y,Be,cs,bl=E(()=>{"use strict";Y=I(require("fs")),Be=I(require("path"));We();as();cs=class{historyPath;sharedHistoryPath;constructor(e,t){this.historyPath=e,this.sharedHistoryPath=t}getEnvironmentHistoryPath(e){return Be.join(this.historyPath,Se(e))}getCollectionHistoryPath(e,t){return Be.join(this.getEnvironmentHistoryPath(e),t)}getRequestPath(e,t,n){return Be.join(this.getCollectionHistoryPath(e,t),Se(n))}getSharedEnvironmentHistoryPath(e){return Be.join(this.sharedHistoryPath,Se(e))}getSharedCollectionHistoryPath(e,t){return Be.join(this.getSharedEnvironmentHistoryPath(e),t)}getSharedRequestPath(e,t,n){return Be.join(this.getSharedCollectionHistoryPath(e,t),Se(n))}getHistoryFilePath(e,t,n){return Be.join(this.getRequestPath(e,t,n),"transactions.json")}getSharedHistoryFilePath(e,t,n){return Be.join(this.getSharedRequestPath(e,t,n),"transactions.json")}getResponseFilePath(e,t,n,s){return Be.join(this.getRequestPath(e,t,n),`${s}.json`)}getSharedResponseFilePath(e,t,n,s){return Be.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=Fo({...i,method:s,id:id(),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 p=this.getResponseFilePath(e,t,n,s),d=this.getSharedResponseFilePath(e,t,n,s);if(Y.existsSync(p)){let m=Be.dirname(d);Y.existsSync(m)||Y.mkdirSync(m,{recursive:!0});try{Y.renameSync(p,d)}catch{try{Y.copyFileSync(p,d)}catch(h){return console.error(`Failed to copy full response from ${p} to ${d}:`,h),!0}try{Y.unlinkSync(p)}catch(h){console.warn(`Failed to remove original full response after copy: ${p}`,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(Be.join(s,o));Y.rmdirSync(s)}}saveFullResponse(e,t,n,s,i){let o=this.getRequestPath(e,t,n),a=this.getResponseFilePath(e,t,n,s);try{Y.existsSync(o)||Y.mkdirSync(o,{recursive:!0});let c=No(i);Y.writeFileSync(a,JSON.stringify(c,null,2),"utf-8")}catch(c){throw console.error(`Failed to save full response for ${s}:`,c),c}}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 er,Sl=E(()=>{"use strict";er=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 d of l){let m=this.historyService.loadFullResponse(s,e,t,d.id);if(m||(m=this.historyService.loadSharedFullResponse(s,e,t,d.id)),m){let f=m.status;u.has(f)||u.set(f,[]),u.get(f).push(m)}}let p={};for(let[d,m]of u){let f=this.buildResponseDefinition(m);p[String(d)]=f}return{responses:p}}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 _d(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 Nd(r){return/^-?\d+$/.test(r)?"integer":/^-?\d+\.\d+$/.test(r)?"number":r==="true"||r==="false"?"boolean":"string"}function _o(r,e){if(r==="integer"&&e==="number"||r==="number"&&e==="integer")return"number"}function Dd(r){return r.replace(/\{\{(\w+)\}\}/g,"<$1>")}function xl(r,e){let t=Dd(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 wl(r){if(typeof r=="string")return Dd(r);if(Array.isArray(r))return r.map(e=>wl(e));if(r!==null&&typeof r=="object"){let e={};for(let[t,n]of Object.entries(r))e[t]=wl(n);return e}return r}function pi(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 wl(e)}function Rl(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 Cl(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 Md(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=xl(r.value,t.schema.type||"string")),t}function fg(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 jd(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:Nd(n)},s.example=xl(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||Nd(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=xl(i.value,s.schema.type||"string")}e.push(s)}if(r.query)for(let t of r.query){if(!t.key)continue;let n=Md(t,"query");e.push(n)}if(r.headers){let t=r.headers.find(n=>n.key.toLowerCase()==="cookie");if(t){let n=fg(t.value);e.push(...n)}for(let n of r.headers){if(!n.key||pg.has(n.key.toLowerCase()))continue;let s=Md(n,"header");e.push(s)}}return e}function Ld(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 Hd(r){return r.replace(/^\[DEPRECATED\]\s*/i,"")}function El(r){return/^\[DEPRECATED\]/i.test(r)}function fi(r){let e={};for(let t of r.split(/\s+/))t&&(e[t]="");return e}var pg,mi=E(()=>{"use strict";pg=new Set(["content-type","authorization","accept","cookie","host","content-length"])});var mg,hg,gg,yg,vg,bg,Sg,Wt,Do=E(()=>{"use strict";mi();mg=/^\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}$/,gg=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,yg=/^https?:\/\/[^\s]+$/,vg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,bg=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Sg=/^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/,Wt=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=_o(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(mg.test(e))return"date-time";if(hg.test(e))return"date";if(gg.test(e))return"email";if(vg.test(e))return"uuid";if(yg.test(e))return"uri";if(bg.test(e))return"ipv4";if(Sg.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 p of a)i[p]&&o[p]?s.properties[p]=this.mergeSchemas(i[p],o[p]):i[p]?s.properties[p]={...i[p]}:s.properties[p]={...o[p]};let c=new Set(e.required||Object.keys(i)),l=new Set(t.required||Object.keys(o)),u=[...a].filter(p=>c.has(p)&&l.has(p));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 jo,Bd=E(()=>{"use strict";mi();jo=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||Hd(e.name),e.description&&(u.description=e.description),(e.deprecated||El(e.name))&&(u.deprecated=!0,El(e.name)&&(u.summary=e.name.replace(/^\[DEPRECATED\]\s*/i,"")));let p=e.tags;if(p&&p.length>0){u.tags=p;for(let g of p)o.add(g)}else a&&(u.tags=[a]);let d=jd(e);d.length>0&&(u.parameters=d);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=Ld(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[p,d]of Object.entries(e.bodySchema.content)){let m={};d.schema&&(m.schema=d.schema),d.examples&&(m.examples=d.examples),d.encoding&&(m.encoding=d.encoding),s.content[p]=m}let u=e.bodySchema.contentType||Object.keys(e.bodySchema.content)[0];if(u&&n.content){let p=pi(n);p!==void 0&&s.content[u]&&(s.content[u].example=p)}return s}i=e.bodySchema.contentType||Rl(n),o=e.bodySchema.schema,a=pi(n),e.bodySchema.encoding&&(c=e.bodySchema.encoding)}else switch(i=Rl(n),n.type){case"raw":{if(n.format==="json"&&n.content){let u=pi(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=Cl(n);break}case"x-www-form-urlencoded":{o=Cl(n);break}case"binary":{o={type:"string",format:"binary"};break}case"graphql":{o={type:"object",properties:{query:{type:"string"},variables:{type:"object"}}},a=pi(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?fi(t.scope):{}};break;case"authorization_code":n.authorizationCode={authorizationUrl:t.authUrl||"",tokenUrl:t.tokenUrl||"",scopes:t.scope?fi(t.scope):{}};break;case"password":n.password={tokenUrl:t.tokenUrl||"",scopes:t.scope?fi(t.scope):{}};break;case"implicit":n.implicit={authorizationUrl:t.authUrl||"",scopes:t.scope?fi(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 Lo,Ud=E(()=>{"use strict";mi();Lo=class{mergeOperation(e,t,n){if(t.summary&&t.summary!==e.summary&&(e.description=(e.description||e.summary||"")+`
323
323
 
324
- 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=Fo(e.type,t.type);n&&(e.type=n)}}}});var Ld,Do,Hd=E(()=>{"use strict";Ld=I(require("yaml")),Do=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"?Ld.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 Qt,jo=E(()=>{"use strict";No();Dd();jd();Hd();pi();Qt=class{constructor(e,t,n){this.collectionService=e;this.envConfigService=t;this.inferenceService=n;let s=new Kt;this.merger=new _o,this.operationBuilder=new Mo(s),this.specWriter=new Do}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}=$d(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 Yn,wl=E(()=>{"use strict";Yn=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]]}}});var Lo,Xn,Rl=E(()=>{"use strict";Lo=I(require("@apidevtools/json-schema-ref-parser")),Xn=class{async resolve(e){try{return await Lo.default.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 Lo.default.bundle(e)}catch(t){return console.error("[RefResolver] Failed to bundle $ref pointers:",t),e}}async resolveFile(e){try{return await Lo.default.dereference(e,{dereference:{circular:"ignore"}})}catch(t){throw console.error(`[RefResolver] Failed to resolve file ${e}:`,t),t}}}});var Bd,Ud,yg,Dt,Ho=E(()=>{"use strict";Bd=I(require("fs")),Ud=I(require("yaml"));Ke();wl();Rl();yg=["application/json","text/plain","text/html","multipart/form-data","application/x-www-form-urlencoded"],Dt=class{constructor(e,t){this.collectionService=e;this.envConfigService=t;this.exampleGenerator=new Yn,this.refResolver=new Xn}collectionService;envConfigService;exampleGenerator;refResolver;async import(e,t){let n=await Bd.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):Ud.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:oe(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:oe(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:oe(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=oe(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 yg)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 Zt,Bo=E(()=>{"use strict";Zt=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 Vd,Uo,zd,Jd,Gd,Wd,Kd,er,Cl=E(()=>{"use strict";Vd=/(?:jsonData|responseJson|data|json|body|response\.json\(\))\.([a-zA-Z_][\w.\[\]]*)/g,Uo="(?:pm|hf|ctx)",zd=new RegExp(`${Uo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.be\\.(?:a|an)\\(['"](\\w+)['"]\\)`,"g"),Jd=new RegExp(`${Uo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.(?:equal|eql)\\((.+?)\\)`,"g"),Gd=/(?:to\.have\.status|response\.code.*?equal)\((\d+)\)/g,Wd=new RegExp(`${Uo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.be\\.(true|false)`,"g"),Kd=new RegExp(`${Uo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.have\\.(?:lengthOf|length\\.above|length\\.below)`,"g"),er=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(Vd.source,Vd.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(zd.source,zd.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(Jd.source,Jd.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(Wd.source,Wd.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(Kd.source,Kd.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(Gd.source,Gd.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 Qd={};Ot(Qd,{AwsSecretResolver:()=>fi});var fi,El=E(()=>{"use strict";fi=class{providerName="aws";region;moduleRequire;constructor(e,t){this.region=e.region??process.env.AWS_DEFAULT_REGION??process.env.AWS_REGION,this.moduleRequire=t??(n=>require(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{let{SecretsManagerClient:i,GetSecretValueCommand:o}=this.moduleRequire("@aws-sdk/client-secrets-manager"),c=await new i(this.region?{region:this.region}:{}).send(new o({SecretId:n})),l=c.SecretString??(c.SecretBinary?Buffer.from(c.SecretBinary).toString("utf-8"):void 0);if(l===void 0)return;if(s)try{let u=JSON.parse(l);return u[s]!==void 0?String(u[s]):void 0}catch{return}return l}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 Zd={};Ot(Zd,{AzureKeyVaultResolver:()=>mi});var mi,Al=E(()=>{"use strict";mi=class{providerName="azure";vaultUrl;moduleRequire;constructor(e,t){let n=(e.vaultUrl||process.env.AZURE_KEYVAULT_URL)??"";this.vaultUrl=n.replace(/\/$/,""),this.moduleRequire=t??(s=>require(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{let{SecretClient:i}=this.moduleRequire("@azure/keyvault-secrets"),{DefaultAzureCredential:o}=this.moduleRequire("@azure/identity"),a=new o;return(await new i(this.vaultUrl,a).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}}}});var Yd={};Ot(Yd,{HashiCorpVaultResolver:()=>hi});var hi,ql=E(()=>{"use strict";hi=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/${this.mountPath}/data/${n}`,a={"X-Vault-Token":i};this.namespace&&(a["X-Vault-Namespace"]=this.namespace);let c;try{c=await fetch(o,{headers:a})}catch(p){throw new Error(`[HTTP Forge] Vault request failed: ${p?.message??p}`)}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}}});var tp={};Ot(tp,{OnePasswordResolver:()=>gi});var Xd,ep,vg,gi,Pl=E(()=>{"use strict";Xd=require("child_process"),ep=require("util"),vg=(0,ep.promisify)(Xd.execFile),gi=class{providerName="1password";defaultVault;constructor(e){this.defaultVault=e.vault}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;if(!s)return null;try{let{createClient:i}=require("@1password/sdk"),o=await i({auth:s,integrationName:"HTTP Forge",integrationVersion:"1.0.0"}),a=`op://${e}/${t}/${n}`;return await o.secrets.resolve(a)}catch(i){if(i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND")return null;throw new Error(`[HTTP Forge] 1Password SDK error for "${e}/${t}/${n}": ${i?.message??i}`)}}async resolveViaCli(e,t,n){try{let{stdout:s}=await vg("op",["item","get",t,"--vault",e,"--field",n,"--format","json"],{env:{...process.env},timeout:1e4}),i=JSON.parse(s.trim());return typeof i=="string"?i:i&&typeof i.value=="string"?i.value:void 0}catch(s){if(s?.code==="ENOENT")throw new Error("[HTTP Forge] 1Password resolver requires either the @1password/sdk npm package or the `op` CLI to be installed.\n Service Account: set OP_SERVICE_ACCOUNT_TOKEN and install @1password/sdk\n CLI: install 1Password CLI and run `op signin`");if(s?.stderr?.includes("not found")||s?.code===1)return;throw new Error(`[HTTP Forge] 1Password CLI error: ${s?.message??s}`)}}}});var np={};Ot(np,{GcpSecretResolver:()=>yi});var yi,kl=E(()=>{"use strict";yi=class{providerName="gcp";projectId;moduleRequire;constructor(e,t){this.projectId=e.projectId??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCLOUD_PROJECT??process.env.GCP_PROJECT,this.moduleRequire=t??(n=>require(n))}async resolve(e){let t=e.split("/"),n=t[0],s=t[1]==="versions"&&t[2]?t[2]:"latest";if(!this.projectId)throw new Error("[HTTP Forge] GCP secret resolver: no projectId configured and GOOGLE_CLOUD_PROJECT env var is not set.");try{let{SecretManagerServiceClient:i}=this.moduleRequire("@google-cloud/secret-manager"),o=new i,a=`projects/${this.projectId}/secrets/${n}/versions/${s}`,[c]=await o.accessSecretVersion({name:a}),l=c.payload?.data;return l?Buffer.isBuffer(l)?l.toString("utf-8"):Buffer.from(l).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}}}});var sp={};Ot(sp,{DopplerResolver:()=>vi});var rp,vi,Il=E(()=>{"use strict";rp=I(require("https")),vi=class{providerName="doppler";token;constructor(e){this.token=e.serviceToken??process.env.DOPPLER_TOKEN}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=rp.request(s,{method:"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}},c=>{let l=[];c.on("data",u=>l.push(u)),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.end()})}}});var Vo,ip,op,as,Tl=E(()=>{"use strict";Vo=I(require("fs")),ip=require("module"),op=I(require("path")),as=class{resolvers=new Map;moduleRequire;constructor(e){if(this.moduleRequire=this.buildModuleRequire(e),!e)return;let t;try{t=e.getConfig().secrets}catch{return}if(!(!t?.providers||typeof t.providers!="object"))for(let[n,s]of Object.entries(t.providers))try{let i=this.createResolver(s);i&&this.resolvers.set(n,i)}catch{}}async resolveSecretTokens(e,t){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)return;let l=a.slice(0,c),u=a.slice(c+1),d=this.resolvers.get(l);if(d)try{let p=await d.resolve(u);p!==void 0&&n.set(o,p)}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.resolvers.size>0}collectTokens(e,t){if(typeof e=="string"){let n=/\{\{(secret:[^}]+)\}\}/g,s;for(;(s=n.exec(e))!==null;)t.add(s[1])}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))}createResolver(e){switch(e.provider){case"aws":{let{AwsSecretResolver:t}=(El(),_n(Qd));return new t(e,this.moduleRequire)}case"azure":{let{AzureKeyVaultResolver:t}=(Al(),_n(Zd));return new t(e,this.moduleRequire)}case"vault":{let{HashiCorpVaultResolver:t}=(ql(),_n(Yd));return new t(e)}case"1password":{let{OnePasswordResolver:t}=(Pl(),_n(tp));return new t(e)}case"gcp":{let{GcpSecretResolver:t}=(kl(),_n(np));return new t(e,this.moduleRequire)}case"doppler":{let{DopplerResolver:t}=(Il(),_n(sp));return new t(e)}default:return}}buildModuleRequire(e){let t=s=>require(s);if(!e)return t;let n=[];try{n=e.getModulePaths()??[]}catch{return t}for(let s of n)try{let i=op.resolve(s,"package.json");if(Vo.existsSync(i)){let o=Vo.realpathSync(i),a=(0,ip.createRequire)(o);return c=>{try{return a(c)}catch{return t(c)}}}}catch{}return t}}});function Ee(r){return r.replace(/\//g,"%2F")}function bg(r){return r.replace(/%2F/gi,"/")}function St(r){return r?r.split("/").map(bg).join(" / "):""}function tr(r){return r.includes(" / ")?r.split(" / ").map(e=>Ee(e.trim())).join("/"):Ee(r)}function Q(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=Ee(i.name),a=t?`${t}/${o}`:o;n.push(...Q(r,i.items??[],a))}return n}function Re(r,e=r.items,t=""){let n=[];for(let s of e)if(s.type==="folder"){let i=s,o=Ee(i.name),a=t?`${t}/${o}`:o;n.push({folderId:i.id,folderPath:a,requestCount:zo(i.items??[])}),n.push(...Re(r,i.items??[],a))}return n}function zo(r){let e=0;for(let t of r)t.type==="request"?e++:e+=zo(t.items??[]);return e}var Xe=E(()=>{"use strict"});var Yt,Ol=E(()=>{"use strict";Yt={iterations:1,delayBetweenRequests:0,stopOnError:!1,readFromSharedSession:!1,writeToSharedSession:!1}});var le,xt,cs,$l=E(()=>{"use strict";le=I(require("fs")),xt=I(require("path"));Xe();Ke();Ol();cs=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(){le.existsSync(this.suitesDir)||le.mkdirSync(this.suitesDir,{recursive:!0})}setupFileWatcher(){try{this.fileWatcher=le.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(),!le.existsSync(this.suitesDir))return;let e=le.readdirSync(this.suitesDir);for(let t of e)if(t.endsWith(".suite.json"))try{let n=xt.join(this.suitesDir,t),s=le.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??{...Yt},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:oe(e),name:e,nodes:[],config:{...Yt},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 le.existsSync(o)&&this.copyDirRecursive(o,a),await this.saveSuiteToDisk(i),this.suites.set(i.id,i),i}copyDirRecursive(e,t){le.existsSync(t)||le.mkdirSync(t,{recursive:!0});for(let n of le.readdirSync(e,{withFileTypes:!0})){let s=xt.join(e,n.name),i=xt.join(t,n.name);n.isDirectory()?this.copyDirRecursive(s,i):le.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 le.existsSync(s)&&le.unlinkSync(s),le.existsSync(i)&&le.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:{...Yt},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} / ${St(o)}`,nodes:c,config:{...Yt},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:{...Yt},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:oe(t),name:t,isTemporary:!1,createdAt:n,updatedAt:n},o=xt.join(this.suitesDir,i.id);return le.existsSync(s)&&(le.existsSync(o)&&le.rmSync(o,{recursive:!0,force:!0}),le.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}/${Ee(o.name)}`:Ee(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}/${Ee(o.name)}`:Ee(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??{...Yt},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);le.writeFileSync(s,o,"utf-8"),le.renameSync(s,n)}}});var $,Jo=E(()=>{"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"),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")}});function bi(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 Gt(t,n,s)),r.registerSingleton($.Console,()=>u??Sg),r.registerSingleton($.EnvironmentConfig,p=>new ns(t,i,p.resolve($.Config),n,a,e.persistOverrides??!0)),r.registerSingleton($.Cookie,()=>new es(o)),r.registerSingleton($.Collection,p=>new Xr(p.resolve($.Config),n)),r.registerSingleton($.TestSuite,p=>new cs(p.resolve($.Collection),p.resolve($.Config))),r.registerSingleton($.HttpClient,p=>{let m=p.resolve($.Config),f=p.resolve($.EnvironmentConfig);return new gn(()=>f.getResolvedConfig().request,t,()=>f.getResolvedConfig()?.proxy??null)}),r.registerSingleton($.UrlBuilder,()=>new lt),r.registerSingleton($.InterceptorChain,()=>new Nt),r.registerSingleton($.HttpRequest,p=>new Ft(p.resolve($.UrlBuilder),p.resolve($.InterceptorChain),p.resolve($.HttpClient))),r.registerSingleton($.RequestPreprocessor,()=>new yn),r.registerSingleton($.RequestHistory,p=>{let m=p.resolve($.EnvironmentConfig);return new os(m.getHistoriesPath(),ap.join(m.getRootPath(),"shared-histories"))}),a&&c&&r.registerSingleton($.OAuth2TokenManager,p=>new Kr(a,c,p.resolve($.EnvironmentConfig),p.resolve($.HttpRequest))),r.registerSingleton($.GraphQLSchemaService,p=>new ss(p.resolve($.HttpClient))),r.registerSingleton($.SecretResolverRegistry,p=>new as(p.resolve($.Config)));let d=l??{name:"HttpForge",version:"0.0.0"};r.registerSingleton($.RequestPreparer,p=>new rs(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 Mt(p.resolve($.HttpRequest),m.getModulePaths(),p.resolve($.SecretResolverRegistry),m.getScriptScope(),m.getScriptTimeout())}),r.registerSingleton($.DataFileParser,()=>new bn),r.registerSingleton($.CollectionRequestExecutor,p=>new _t(p.resolve($.HttpRequest),p.resolve($.ScriptExecutor),p.resolve($.EnvironmentConfig),p.resolve($.RequestPreparer),"")),r.registerSingleton($.PersistentCookieJar,p=>new ts(p.resolve($.Cookie))),r.registerSingleton($.SchemaInferrer,()=>new Kt),r.registerSingleton($.HistoryAnalyzer,p=>new Zn(p.resolve($.RequestHistory),p.resolve($.SchemaInferrer))),r.registerSingleton($.ScriptAnalyzer,()=>new er),r.registerSingleton($.SchemaInferenceService,p=>new Zt(p.resolve($.HistoryAnalyzer),p.resolve($.ScriptAnalyzer),p.resolve($.SchemaInferrer))),r.registerSingleton($.OpenApiExporter,p=>new Qt(p.resolve($.Collection),p.resolve($.EnvironmentConfig),p.resolve($.SchemaInferenceService))),r.registerSingleton($.OpenApiImporter,p=>new Dt(p.resolve($.Collection),p.resolve($.EnvironmentConfig)))}var ap,Sg,Fl=E(()=>{"use strict";ap=I(require("path"));el();il();Po();al();cl();ul();ci();dl();pl();hl();Qs();Zs();Ro();Co();Mr();gl();jo();Ho();Bo();No();Cl();Eo();si();Tl();$l();Jo();Sg={log:()=>{},trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},logBatch:()=>{},logRawLines:()=>{},show:()=>{},clear:()=>{},dispose:()=>{}}});function Nl(){return Rn.instance}var Rn,Ml=E(()=>{"use strict";Jo();Rn=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 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)}}});function jt(r){return{kind:"collection",snapshot:()=>({kind:"collection",heading:"Collection",body:_l(r),generatedAt:Date.now()}),freshness:()=>r.items.length>0?"fresh":"stale"}}function et(r,e){return{kind:"collection",snapshot:()=>({kind:"collection",heading:"Request",body:Wo(r,e),generatedAt:Date.now()}),freshness:()=>Wo(r,e)?"fresh":"stale"}}function tt(r){return{kind:"workspace-knowledge",snapshot:()=>({kind:"workspace-knowledge",heading:"Business Knowledge",body:us(r),generatedAt:Date.now()}),freshness:()=>us(r)?"fresh":"stale"}}function Si(r,e){return{kind:"run-results",snapshot:()=>({kind:"run-results",heading:"Test Results",body:Dl(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 lp(r){Ko.push(r)}function up(){Ko.length=0}function dp(){return Ko.slice()}function Wo(r,e){let t=[],n=e&&e!=="(root)"?`${e} / ${r.name}`:r.name;return r.description?.trim()&&t.push(`Description: ${nr(r.description,400)}`),r.doc?.trim()&&t.push(`Docs (doc.md): ${nr(r.doc,xg)}`),r.operationId&&t.push(`OpenAPI operationId: ${r.operationId}`),r.summary?.trim()&&t.push(`OpenAPI summary: ${nr(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: ${nr(JSON.stringify(r.responseSchema),400)}`),r.bodySchema&&t.push(`Request body schema: ${nr(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}
324
+ 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=_o(e.type,t.type);n&&(e.type=n)}}}});var Vd,Ho,zd=E(()=>{"use strict";Vd=I(require("yaml")),Ho=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"?Vd.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 p of Object.values(u.content))p.schema&&this.trackSchema(p.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 Kt,Bo=E(()=>{"use strict";Do();Bd();Ud();zd();mi();Kt=class{constructor(e,t,n){this.collectionService=e;this.envConfigService=t;this.inferenceService=n;let s=new Wt;this.merger=new Lo,this.operationBuilder=new jo(s),this.specWriter=new Ho}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:p}=c;i.set(l,u),s.security=[p]}}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,p=o||u.name;s.add(p),u.items&&await this.processItems(u.items,t,n,s,i,p,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}=_d(e.url);u&&i.add(u);let p=(e.method||"GET").toLowerCase();t.paths[l]||(t.paths[l]={});let d=await this.operationBuilder.buildOperation(e,p,l,t,n,s,o,a,c),m=t.paths[l][p];m?this.merger.mergeOperation(m,d,e.name):t.paths[l][p]=d}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 tr,ql=E(()=>{"use strict";tr=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]]}}});var Uo,nr,Al=E(()=>{"use strict";Uo=I(require("@apidevtools/json-schema-ref-parser")),nr=class{async resolve(e){try{return await Uo.default.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 Uo.default.bundle(e)}catch(t){return console.error("[RefResolver] Failed to bundle $ref pointers:",t),e}}async resolveFile(e){try{return await Uo.default.dereference(e,{dereference:{circular:"ignore"}})}catch(t){throw console.error(`[RefResolver] Failed to resolve file ${e}:`,t),t}}}});var Jd,Gd,xg,_t,Vo=E(()=>{"use strict";Jd=I(require("fs")),Gd=I(require("yaml"));We();ql();Al();xg=["application/json","text/plain","text/html","multipart/form-data","application/x-www-form-urlencoded"],_t=class{constructor(e,t){this.collectionService=e;this.envConfigService=t;this.exampleGenerator=new tr,this.refResolver=new nr}collectionService;envConfigService;exampleGenerator;refResolver;async import(e,t){let n=await Jd.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):Gd.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:ae(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 p={type:"folder",id:ae(u.name),name:u.name,description:u.description,items:[]};c.set(u.name,p),a.items.push(p)}if(n.paths)for(let[u,p]of Object.entries(n.paths))for(let d of["get","post","put","patch","delete","head","options","trace"]){let m=p[d];if(!m)continue;let f=this.processOperation(d,u,m,p,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:ae(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=ae(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 p={type:"request",id:a,name:l,method:e.toUpperCase(),url:c,description:n.description||"",deprecated:u};n.operationId&&(p.operationId=n.operationId),n.summary&&(p.summary=n.summary),n.tags?.length&&(p.tags=[...n.tags]);let d=[...s.parameters||[],...n.parameters||[]];if(this.processParameters(p,d,o),n.requestBody&&this.processRequestBody(p,n.requestBody,o),n.responses&&(p.responseSchema=this.processResponses(n.responses,o)),n.security!==void 0&&i.components?.securitySchemes){if(Array.isArray(n.security)&&n.security.length===0)p.auth={type:"none"};else if(n.security&&n.security.length>0){let m=this.mapSecurityToAuth(n.security[0],i.components.securitySchemes);m&&(p.auth=m)}}return p}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,p=c.schema||{},d=c.example!==void 0?String(c.example):this.generateExampleForParam(p,n),m=c.deprecated===!0;switch(u){case"path":{if(c.description||p.type||p.format||p.enum||m||p.pattern||p.minimum!==void 0||p.maximum!==void 0||p.minLength!==void 0||p.maxLength!==void 0||p.multipleOf!==void 0||p.minItems!==void 0||p.maxItems!==void 0||p.uniqueItems||p.nullable||p.oneOf){let h={value:d};p.oneOf?(h.oneOf=p.oneOf,this.applyOneOfHints(h,p.oneOf)):(p.type&&(h.type=p.type),p.format&&(h.format=p.format),p.enum&&(h.enum=p.enum.map(String)),p.pattern&&(h.pattern=p.pattern),p.minimum!==void 0&&(h.minimum=p.minimum),p.maximum!==void 0&&(h.maximum=p.maximum),p.exclusiveMinimum!==void 0&&(h.exclusiveMinimum=p.exclusiveMinimum),p.exclusiveMaximum!==void 0&&(h.exclusiveMaximum=p.exclusiveMaximum),p.multipleOf!==void 0&&(h.multipleOf=p.multipleOf),p.minLength!==void 0&&(h.minLength=p.minLength),p.maxLength!==void 0&&(h.maxLength=p.maxLength),p.minItems!==void 0&&(h.minItems=p.minItems),p.maxItems!==void 0&&(h.maxItems=p.maxItems),p.uniqueItems&&(h.uniqueItems=!0),p.nullable&&(h.nullable=!0)),c.description&&(h.description=c.description),m&&(h.deprecated=!0),o[l]=h}else o[l]=d;break}case"query":{let f={key:l,value:d};this.applySchemaConstraints(f,p,c,m),i.push(f);break}case"header":{let f={key:l,value:d};this.applySchemaConstraints(f,p,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 xg)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],p=a.content[u];c.contentType=u,p.schema&&(c.schema=p.schema),p.examples&&(c.examples=p.examples),p.schema&&Object.assign(s,this.extractUsedComponents(p.schema,t))}else{c.content={};for(let u of l){let p=a.content[u],d={};p.schema&&(d.schema=p.schema),p.examples&&(d.examples=p.examples),c.content[u]=d,p.schema&&Object.assign(s,this.extractUsedComponents(p.schema,t))}}}if(a.headers){c.headers={};for(let[l,u]of Object.entries(a.headers)){let p=u;c.headers[l]={...p.description&&{description:p.description},schema:p.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 Qt,zo=E(()=>{"use strict";Qt=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 Wd,Jo,Kd,Qd,Zd,Yd,Xd,rr,Pl=E(()=>{"use strict";Wd=/(?:jsonData|responseJson|data|json|body|response\.json\(\))\.([a-zA-Z_][\w.\[\]]*)/g,Jo="(?:pm|hf|ctx)",Kd=new RegExp(`${Jo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.be\\.(?:a|an)\\(['"](\\w+)['"]\\)`,"g"),Qd=new RegExp(`${Jo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.(?:equal|eql)\\((.+?)\\)`,"g"),Zd=/(?:to\.have\.status|response\.code.*?equal)\((\d+)\)/g,Yd=new RegExp(`${Jo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.be\\.(true|false)`,"g"),Xd=new RegExp(`${Jo}\\.expect\\(.*?\\.([a-zA-Z_][\\w.]*)\\)\\.to\\.have\\.(?:lengthOf|length\\.above|length\\.below)`,"g"),rr=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(Wd.source,Wd.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(Kd.source,Kd.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(Qd.source,Qd.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(Yd.source,Yd.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(Xd.source,Xd.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(Zd.source,Zd.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 ep={};Tt(ep,{AwsSecretResolver:()=>hi});var hi,kl=E(()=>{"use strict";hi=class{providerName="aws";region;moduleRequire;constructor(e,t){this.region=e.region??process.env.AWS_DEFAULT_REGION??process.env.AWS_REGION,this.moduleRequire=t??(n=>require(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{let{SecretsManagerClient:i,GetSecretValueCommand:o}=this.moduleRequire("@aws-sdk/client-secrets-manager"),c=await new i(this.region?{region:this.region}:{}).send(new o({SecretId:n})),l=c.SecretString??(c.SecretBinary?Buffer.from(c.SecretBinary).toString("utf-8"):void 0);if(l===void 0)return;if(s)try{let u=JSON.parse(l);return u[s]!==void 0?String(u[s]):void 0}catch{return}return l}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 tp={};Tt(tp,{AzureKeyVaultResolver:()=>gi});var gi,Il=E(()=>{"use strict";gi=class{providerName="azure";vaultUrl;moduleRequire;constructor(e,t){let n=(e.vaultUrl||process.env.AZURE_KEYVAULT_URL)??"";this.vaultUrl=n.replace(/\/$/,""),this.moduleRequire=t??(s=>require(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{let{SecretClient:i}=this.moduleRequire("@azure/keyvault-secrets"),{DefaultAzureCredential:o}=this.moduleRequire("@azure/identity"),a=new o;return(await new i(this.vaultUrl,a).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}}}});var np={};Tt(np,{HashiCorpVaultResolver:()=>yi});var yi,Tl=E(()=>{"use strict";yi=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/${this.mountPath}/data/${n}`,a={"X-Vault-Token":i};this.namespace&&(a["X-Vault-Namespace"]=this.namespace);let c;try{c=await fetch(o,{headers:a})}catch(d){throw new Error(`[HTTP Forge] Vault request failed: ${d?.message??d}`)}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 p=Object.keys(u);return p.length===1?String(u[p[0]]):void 0}}});var ip={};Tt(ip,{OnePasswordResolver:()=>vi});var rp,sp,wg,vi,Ol=E(()=>{"use strict";rp=require("child_process"),sp=require("util"),wg=(0,sp.promisify)(rp.execFile),vi=class{providerName="1password";defaultVault;constructor(e){this.defaultVault=e.vault}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;if(!s)return null;try{let{createClient:i}=require("@1password/sdk"),o=await i({auth:s,integrationName:"HTTP Forge",integrationVersion:"1.0.0"}),a=`op://${e}/${t}/${n}`;return await o.secrets.resolve(a)}catch(i){if(i?.name==="MODULE_NOT_FOUND"||i?.code==="MODULE_NOT_FOUND")return null;throw new Error(`[HTTP Forge] 1Password SDK error for "${e}/${t}/${n}": ${i?.message??i}`)}}async resolveViaCli(e,t,n){try{let{stdout:s}=await wg("op",["item","get",t,"--vault",e,"--field",n,"--format","json"],{env:{...process.env},timeout:1e4}),i=JSON.parse(s.trim());return typeof i=="string"?i:i&&typeof i.value=="string"?i.value:void 0}catch(s){if(s?.code==="ENOENT")throw new Error("[HTTP Forge] 1Password resolver requires either the @1password/sdk npm package or the `op` CLI to be installed.\n Service Account: set OP_SERVICE_ACCOUNT_TOKEN and install @1password/sdk\n CLI: install 1Password CLI and run `op signin`");if(s?.stderr?.includes("not found")||s?.code===1)return;throw new Error(`[HTTP Forge] 1Password CLI error: ${s?.message??s}`)}}}});var op={};Tt(op,{GcpSecretResolver:()=>bi});var bi,$l=E(()=>{"use strict";bi=class{providerName="gcp";projectId;moduleRequire;constructor(e,t){this.projectId=e.projectId??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCLOUD_PROJECT??process.env.GCP_PROJECT,this.moduleRequire=t??(n=>require(n))}async resolve(e){let t=e.split("/"),n=t[0],s=t[1]==="versions"&&t[2]?t[2]:"latest";if(!this.projectId)throw new Error("[HTTP Forge] GCP secret resolver: no projectId configured and GOOGLE_CLOUD_PROJECT env var is not set.");try{let{SecretManagerServiceClient:i}=this.moduleRequire("@google-cloud/secret-manager"),o=new i,a=`projects/${this.projectId}/secrets/${n}/versions/${s}`,[c]=await o.accessSecretVersion({name:a}),l=c.payload?.data;return l?Buffer.isBuffer(l)?l.toString("utf-8"):Buffer.from(l).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}}}});var cp={};Tt(cp,{DopplerResolver:()=>Si});var ap,Si,Fl=E(()=>{"use strict";ap=I(require("https")),Si=class{providerName="doppler";token;constructor(e){this.token=e.serviceToken??process.env.DOPPLER_TOKEN}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=ap.request(s,{method:"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}},c=>{let l=[];c.on("data",u=>l.push(u)),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 d=JSON.parse(u)?.value?.computed;i(d!=null?String(d):void 0)}catch{o(new Error(`[HTTP Forge] Doppler API returned non-JSON response for secret "${t}"`))}})});a.on("error",o),a.end()})}}});var Go,lp,up,ls,Nl=E(()=>{"use strict";Go=I(require("fs")),lp=require("module"),up=I(require("path")),ls=class{resolvers=new Map;moduleRequire;constructor(e){if(this.moduleRequire=this.buildModuleRequire(e),!e)return;let t;try{t=e.getConfig().secrets}catch{return}if(!(!t?.providers||typeof t.providers!="object"))for(let[n,s]of Object.entries(t.providers))try{let i=this.createResolver(s);i&&this.resolvers.set(n,i)}catch{}}async resolveSecretTokens(e,t){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)return;let l=a.slice(0,c),u=a.slice(c+1),p=this.resolvers.get(l);if(p)try{let d=await p.resolve(u);d!==void 0&&n.set(o,d)}catch(d){let m=d?.message??String(d);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.resolvers.size>0}collectTokens(e,t){if(typeof e=="string"){let n=/\{\{(secret:[^}]+)\}\}/g,s;for(;(s=n.exec(e))!==null;)t.add(s[1])}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))}createResolver(e){switch(e.provider){case"aws":{let{AwsSecretResolver:t}=(kl(),jn(ep));return new t(e,this.moduleRequire)}case"azure":{let{AzureKeyVaultResolver:t}=(Il(),jn(tp));return new t(e,this.moduleRequire)}case"vault":{let{HashiCorpVaultResolver:t}=(Tl(),jn(np));return new t(e)}case"1password":{let{OnePasswordResolver:t}=(Ol(),jn(ip));return new t(e)}case"gcp":{let{GcpSecretResolver:t}=($l(),jn(op));return new t(e,this.moduleRequire)}case"doppler":{let{DopplerResolver:t}=(Fl(),jn(cp));return new t(e)}default:return}}buildModuleRequire(e){let t=s=>require(s);if(!e)return t;let n=[];try{n=e.getModulePaths()??[]}catch{return t}for(let s of n)try{let i=up.resolve(s,"package.json");if(Go.existsSync(i)){let o=Go.realpathSync(i),a=(0,lp.createRequire)(o);return c=>{try{return a(c)}catch{return t(c)}}}}catch{}return t}}});function qe(r){return r.replace(/\//g,"%2F")}function Rg(r){return r.replace(/%2F/gi,"/")}function bt(r){return r?r.split("/").map(Rg).join(" / "):""}function sr(r){return r.includes(" / ")?r.split(" / ").map(e=>qe(e.trim())).join("/"):qe(r)}function Q(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=qe(i.name),a=t?`${t}/${o}`:o;n.push(...Q(r,i.items??[],a))}return n}function Ce(r,e=r.items,t=""){let n=[];for(let s of e)if(s.type==="folder"){let i=s,o=qe(i.name),a=t?`${t}/${o}`:o;n.push({folderId:i.id,folderPath:a,requestCount:Wo(i.items??[])}),n.push(...Ce(r,i.items??[],a))}return n}function Wo(r){let e=0;for(let t of r)t.type==="request"?e++:e+=Wo(t.items??[]);return e}var Ye=E(()=>{"use strict"});var Zt,Ml=E(()=>{"use strict";Zt={iterations:1,delayBetweenRequests:0,stopOnError:!1,readFromSharedSession:!1,writeToSharedSession:!1}});var de,St,us,_l=E(()=>{"use strict";de=I(require("fs")),St=I(require("path"));Ye();We();Ml();us=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(){de.existsSync(this.suitesDir)||de.mkdirSync(this.suitesDir,{recursive:!0})}setupFileWatcher(){try{this.fileWatcher=de.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(),!de.existsSync(this.suitesDir))return;let e=de.readdirSync(this.suitesDir);for(let t of e)if(t.endsWith(".suite.json"))try{let n=St.join(this.suitesDir,t),s=de.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??{...Zt},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:ae(e),name:e,nodes:[],config:{...Zt},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=St.join(this.suitesDir,e),a=St.join(this.suitesDir,i.id);return de.existsSync(o)&&this.copyDirRecursive(o,a),await this.saveSuiteToDisk(i),this.suites.set(i.id,i),i}copyDirRecursive(e,t){de.existsSync(t)||de.mkdirSync(t,{recursive:!0});for(let n of de.readdirSync(e,{withFileTypes:!0})){let s=St.join(e,n.name),i=St.join(t,n.name);n.isDirectory()?this.copyDirRecursive(s,i):de.copyFileSync(s,i)}}async deleteSuite(e){let t=this.suites.get(e);if(!t)return!1;let n=`${t.id}.suite.json`,s=St.join(this.suitesDir,n),i=St.join(this.suitesDir,t.id);try{return de.existsSync(s)&&de.unlinkSync(s),de.existsSync(i)&&de.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:{...Zt},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(p=>n?p.folderPath===o||p.folderPath.startsWith(`${o}/`):p.folderPath===o);if(a.length===0){console.error(`[TestSuiteService] No requests under folder "${t}" in collection: ${e}`);return}let c=a.map(p=>({type:"request",name:p.description||p.name,request:p,enabled:p.enabled!==!1})),l=Date.now();return{id:`temp-${e}-${this.slugifyFolderPath(o)}`,name:`${s.name} / ${bt(o)}`,nodes:c,config:{...Zt},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:{...Zt},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=St.join(this.suitesDir,e.id),i={...e,id:ae(t),name:t,isTemporary:!1,createdAt:n,updatedAt:n},o=St.join(this.suitesDir,i.id);return de.existsSync(s)&&(de.existsSync(o)&&de.rmSync(o,{recursive:!0,force:!0}),de.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}/${qe(o.name)}`:qe(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}/${qe(o.name)}`:qe(o.name);this.extractRequestsFromCollection(o,t,n,a,i)}}async saveSuiteToDisk(e){this.ensureSuitesDir();let t=`${e.id}.suite.json`,n=St.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??{...Zt},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);de.writeFileSync(s,o,"utf-8"),de.renameSync(s,n)}}});var $,Ko=E(()=>{"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"),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")}});function xi(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 Jt(t,n,s)),r.registerSingleton($.Console,()=>u??Cg),r.registerSingleton($.EnvironmentConfig,d=>new ss(t,i,d.resolve($.Config),n,a,e.persistOverrides??!0)),r.registerSingleton($.Cookie,()=>new ns(o)),r.registerSingleton($.Collection,d=>new ts(d.resolve($.Config),n)),r.registerSingleton($.TestSuite,d=>new us(d.resolve($.Collection),d.resolve($.Config))),r.registerSingleton($.HttpClient,d=>{let m=d.resolve($.Config),f=d.resolve($.EnvironmentConfig);return new yn(()=>f.getResolvedConfig().request,t,()=>f.getResolvedConfig()?.proxy??null)}),r.registerSingleton($.UrlBuilder,()=>new ct),r.registerSingleton($.InterceptorChain,()=>new Ft),r.registerSingleton($.HttpRequest,d=>new $t(d.resolve($.UrlBuilder),d.resolve($.InterceptorChain),d.resolve($.HttpClient))),r.registerSingleton($.RequestPreprocessor,()=>new vn),r.registerSingleton($.RequestHistory,d=>{let m=d.resolve($.EnvironmentConfig);return new cs(m.getHistoriesPath(),dp.join(m.getRootPath(),"shared-histories"))}),a&&c&&r.registerSingleton($.OAuth2TokenManager,d=>new Zr(a,c,d.resolve($.EnvironmentConfig),d.resolve($.HttpRequest))),r.registerSingleton($.GraphQLSchemaService,d=>new os(d.resolve($.HttpClient))),r.registerSingleton($.SecretResolverRegistry,d=>new ls(d.resolve($.Config)));let p=l??{name:"HttpForge",version:"0.0.0"};r.registerSingleton($.RequestPreparer,d=>new is(d.resolve($.EnvironmentConfig),d.resolve($.HttpRequest),d.resolve($.RequestPreprocessor),d.has($.OAuth2TokenManager)?d.resolve($.OAuth2TokenManager):void 0,p,d.resolve($.SecretResolverRegistry))),r.registerSingleton($.ScriptExecutor,d=>{let m=d.resolve($.Config);return new Nt(d.resolve($.HttpRequest),m.getModulePaths(),d.resolve($.SecretResolverRegistry),m.getScriptScope(),m.getScriptTimeout())}),r.registerSingleton($.DataFileParser,()=>new Sn),r.registerSingleton($.CollectionRequestExecutor,d=>new Mt(d.resolve($.HttpRequest),d.resolve($.ScriptExecutor),d.resolve($.EnvironmentConfig),d.resolve($.RequestPreparer),"")),r.registerSingleton($.PersistentCookieJar,d=>new rs(d.resolve($.Cookie))),r.registerSingleton($.SchemaInferrer,()=>new Wt),r.registerSingleton($.HistoryAnalyzer,d=>new er(d.resolve($.RequestHistory),d.resolve($.SchemaInferrer))),r.registerSingleton($.ScriptAnalyzer,()=>new rr),r.registerSingleton($.SchemaInferenceService,d=>new Qt(d.resolve($.HistoryAnalyzer),d.resolve($.ScriptAnalyzer),d.resolve($.SchemaInferrer))),r.registerSingleton($.OpenApiExporter,d=>new Kt(d.resolve($.Collection),d.resolve($.EnvironmentConfig),d.resolve($.SchemaInferenceService))),r.registerSingleton($.OpenApiImporter,d=>new _t(d.resolve($.Collection),d.resolve($.EnvironmentConfig)))}var dp,Cg,Dl=E(()=>{"use strict";dp=I(require("path"));sl();ll();To();dl();pl();ml();ui();hl();gl();bl();Ys();Xs();qo();Ao();Dr();Sl();Bo();Vo();zo();Do();Pl();Po();oi();Nl();_l();Ko();Cg={log:()=>{},trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},logBatch:()=>{},logRawLines:()=>{},show:()=>{},clear:()=>{},dispose:()=>{}}});function jl(){return Cn.instance}var Cn,Ll=E(()=>{"use strict";Ko();Cn=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 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)}}});function Dt(r){return{kind:"collection",snapshot:()=>({kind:"collection",heading:"Collection",body:Hl(r),generatedAt:Date.now()}),freshness:()=>r.items.length>0?"fresh":"stale"}}function Xe(r,e){return{kind:"collection",snapshot:()=>({kind:"collection",heading:"Request",body:Zo(r,e),generatedAt:Date.now()}),freshness:()=>Zo(r,e)?"fresh":"stale"}}function et(r){return{kind:"workspace-knowledge",snapshot:()=>({kind:"workspace-knowledge",heading:"Business Knowledge",body:ps(r),generatedAt:Date.now()}),freshness:()=>ps(r)?"fresh":"stale"}}function wi(r,e){return{kind:"run-results",snapshot:()=>({kind:"run-results",heading:"Test Results",body:Bl(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 fp(r){Yo.push(r)}function mp(){Yo.length=0}function hp(){return Yo.slice()}function Zo(r,e){let t=[],n=e&&e!=="(root)"?`${e} / ${r.name}`:r.name;return r.description?.trim()&&t.push(`Description: ${ir(r.description,400)}`),r.doc?.trim()&&t.push(`Docs (doc.md): ${ir(r.doc,Eg)}`),r.operationId&&t.push(`OpenAPI operationId: ${r.operationId}`),r.summary?.trim()&&t.push(`OpenAPI summary: ${ir(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: ${ir(JSON.stringify(r.responseSchema),400)}`),r.bodySchema&&t.push(`Request body schema: ${ir(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}
325
325
  ${t.join(`
326
- `)}`}function _l(r){let e=[];r.description?.trim()&&e.push(`Description: ${nr(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(`
326
+ `)}`}function Hl(r){let e=[];r.description?.trim()&&e.push(`Description: ${ir(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(`
327
327
  `);let i=new Set(n.map(c=>c.folderPath)),o=[...i].sort().map(c=>` ${c} (${n.filter(l=>l.folderPath===c).length} requests)`).join(`
328
328
  `);e.push(`Requests: ${n.length} across ${i.size} folder(s)`),o&&e.push(`Folders:
329
329
  ${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(`
330
- `).slice(0,wg)}function us(r){if(!r||!rr.existsSync(r))return"";let e=[],t=0,n=(i,o)=>{let a=Go-t;if(a<=0)return;let c;try{c=rr.readFileSync(o,"utf-8")}catch{return}c.trim()&&(e.push({title:i,body:nr(c,Math.min(a,1500))}),t+=e[e.length-1].body.length)},s=ls.join(r,".http-forge","knowledge");for(let i of Cg(s)){if(t>=Go)break;n(`Knowledge: ${ls.relative(r,i)}`,i)}for(let i of["README.md","AGENTS.md"]){if(t>=Go)break;n(`Workspace: ${i}`,ls.join(r,i))}return e.length===0?"":e.map(i=>`### ${i.title}
330
+ `).slice(0,qg)}function ps(r){if(!r||!or.existsSync(r))return"";let e=[],t=0,n=(i,o)=>{let a=Qo-t;if(a<=0)return;let c;try{c=or.readFileSync(o,"utf-8")}catch{return}c.trim()&&(e.push({title:i,body:ir(c,Math.min(a,1500))}),t+=e[e.length-1].body.length)},s=ds.join(r,".http-forge","knowledge");for(let i of Pg(s)){if(t>=Qo)break;n(`Knowledge: ${ds.relative(r,i)}`,i)}for(let i of["README.md","AGENTS.md"]){if(t>=Qo)break;n(`Workspace: ${i}`,ds.join(r,i))}return e.length===0?"":e.map(i=>`### ${i.title}
331
331
  ${i.body}`).join(`
332
332
 
333
- `).slice(0,Go)}function Dl(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(`
334
- `).slice(0,Rg)}function jl(r){let e=[];return e.push(jt(r.collection)),r.request&&e.push(et(r.request,r.requestFolderPath)),r.workspaceFolder&&e.push(tt(r.workspaceFolder)),r.runStore&&r.runId&&e.push(Si(r.runStore,r.runId)),e}function cp(r){let e=[];for(let t of[...r,...Ko]){let n=t.snapshot();n.body&&e.push({heading:n.heading,body:n.body})}return e.length===0?"":e.map(t=>`## ${t.heading}
333
+ `).slice(0,Qo)}function Bl(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(`
334
+ `).slice(0,Ag)}function Ul(r){let e=[];return e.push(Dt(r.collection)),r.request&&e.push(Xe(r.request,r.requestFolderPath)),r.workspaceFolder&&e.push(et(r.workspaceFolder)),r.runStore&&r.runId&&e.push(wi(r.runStore,r.runId)),e}function pp(r){let e=[];for(let t of[...r,...Yo]){let n=t.snapshot();n.body&&e.push({heading:n.heading,body:n.body})}return e.length===0?"":e.map(t=>`## ${t.heading}
335
335
  ${t.body}`).join(`
336
336
 
337
- `)}function ds(r){return Array.isArray(r)?cp(r):cp(jl(r))}function nr(r,e){return!r||r.length<=e?r:r.slice(0,e)+`\u2026 (truncated, ${r.length-e} chars omitted)`}function Cg(r){if(!rr.existsSync(r))return[];let e=[],t=n=>{let s;try{s=rr.readdirSync(n,{withFileTypes:!0})}catch{return}for(let i of s){let o=ls.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 rr,ls,xg,wg,Go,Rg,Ko,sr=E(()=>{"use strict";rr=I(require("fs")),ls=I(require("path")),xg=1200,wg=800,Go=4e3,Rg=2500;Ko=[]});function wt(r){if(typeof r!="string"||r.trim()==="")return null;let e=r.trim();for(let s of[e,...Ag(e)])try{return JSON.parse(s)}catch{}let t=/[[{]/g,n;for(;(n=t.exec(e))!==null;){let s=qg(e,n.index);if(s!==-1)try{return JSON.parse(e.slice(n.index,s))}catch{}}return null}async function nt(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 Eg(n*2**o)}throw i}function Eg(r){return new Promise(e=>setTimeout(e,r))}function Ag(r){let e=[],t=/```(?:json)?\s*([\s\S]*?)```/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1].trim());return e}function qg(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 ir=E(()=>{"use strict"});function xi(r){return/\{\{[^}]+\}\}/.test(r)}function Rt(r,e=16){return!!r&&r.length>=e&&!xi(r)}function Xt(r){return r.toUpperCase().replace(/[^A-Z0-9]/g,"_")}var Qo,Zo,Yo=E(()=>{"use strict";Qo=new Set(["x-api-key","x-auth-token","x-access-token","x-token","x-secret","api-key","apikey","x-client-secret","x-rapidapi-key"]),Zo=new Set(["api_key","apikey","api-key","access_token","token","auth_token","client_id","client_secret","key","secret"])});function wi(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 Ri(r,e=1){let t=Q(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&&Rt(u[2])?wi(n,u[2],`${u[1].toUpperCase()}_TOKEN`,`Authorization ${u[1]} token`,o(`header:${a.key}`),1):Rt(l)&&wi(n,l,"AUTH_TOKEN","Authorization header value",o(`header:${a.key}`),1)}else Qo.has(c)&&Rt(l)?wi(n,l,Xt(a.key),`Sensitive header: ${a.key}`,o(`header:${a.key}`),2):Rt(l,20)&&!l.includes(" ")&&/^[A-Za-z0-9+/=_.-]+$/.test(l)&&wi(n,l,Xt(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&&Zo.has(a.key.toLowerCase())&&Rt(a.value)&&wi(n,a.value,Xt(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||xi(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 Xo(r,e){let t={};return pp(r,e,t),t}function pp(r,e,t){for(let n of r){if(n.type==="folder"){n.items&&pp(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 Ll=E(()=>{"use strict";Xe();Yo()});function Pg(r){return r.replace(/^\{\{\w+\}\}/,"").replace(/^\//,"/").replace(/:([a-zA-Z_]\w*)/g,"{$1}")}function fp(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 kg(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 Ig(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 ea(r){let e=[],t=fp(r.auth),n=s=>{for(let i of s){if(i.type==="folder"){n(i.items??[]);continue}let o=i,a=Pg(o.url),c=fp(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:kg(o),responses:Ig(o),auth:l})}};return n(r.items),e}var Hl=E(()=>{"use strict"});function ta(r,e={}){let t=e.baseUrl||"http://localhost:3000",n=e.collectionName||"Designed API",s=e.workspaceKnowledge?`
337
+ `)}function fs(r){return Array.isArray(r)?pp(r):pp(Ul(r))}function ir(r,e){return!r||r.length<=e?r:r.slice(0,e)+`\u2026 (truncated, ${r.length-e} chars omitted)`}function Pg(r){if(!or.existsSync(r))return[];let e=[],t=n=>{let s;try{s=or.readdirSync(n,{withFileTypes:!0})}catch{return}for(let i of s){let o=ds.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 or,ds,Eg,qg,Qo,Ag,Yo,ar=E(()=>{"use strict";or=I(require("fs")),ds=I(require("path")),Eg=1200,qg=800,Qo=4e3,Ag=2500;Yo=[]});function xt(r){if(typeof r!="string"||r.trim()==="")return null;let e=r.trim();for(let s of[e,...Ig(e)])try{return JSON.parse(s)}catch{}let t=/[[{]/g,n;for(;(n=t.exec(e))!==null;){let s=Tg(e,n.index);if(s!==-1)try{return JSON.parse(e.slice(n.index,s))}catch{}}return null}async function tt(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 kg(n*2**o)}throw i}function kg(r){return new Promise(e=>setTimeout(e,r))}function Ig(r){let e=[],t=/```(?:json)?\s*([\s\S]*?)```/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1].trim());return e}function Tg(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 cr=E(()=>{"use strict"});function Ri(r){return/\{\{[^}]+\}\}/.test(r)}function wt(r,e=16){return!!r&&r.length>=e&&!Ri(r)}function Yt(r){return r.toUpperCase().replace(/[^A-Z0-9]/g,"_")}var Xo,ea,ta=E(()=>{"use strict";Xo=new Set(["x-api-key","x-auth-token","x-access-token","x-token","x-secret","api-key","apikey","x-client-secret","x-rapidapi-key"]),ea=new Set(["api_key","apikey","api-key","access_token","token","auth_token","client_id","client_secret","key","secret"])});function Ci(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 Ei(r,e=1){let t=Q(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])?Ci(n,u[2],`${u[1].toUpperCase()}_TOKEN`,`Authorization ${u[1]} token`,o(`header:${a.key}`),1):wt(l)&&Ci(n,l,"AUTH_TOKEN","Authorization header value",o(`header:${a.key}`),1)}else Xo.has(c)&&wt(l)?Ci(n,l,Yt(a.key),`Sensitive header: ${a.key}`,o(`header:${a.key}`),2):wt(l,20)&&!l.includes(" ")&&/^[A-Za-z0-9+/=_.-]+$/.test(l)&&Ci(n,l,Yt(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&&ea.has(a.key.toLowerCase())&&wt(a.value)&&Ci(n,a.value,Yt(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||Ri(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 na(r,e){let t={};return gp(r,e,t),t}function gp(r,e,t){for(let n of r){if(n.type==="folder"){n.items&&gp(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 Vl=E(()=>{"use strict";Ye();ta()});function Og(r){return r.replace(/^\{\{\w+\}\}/,"").replace(/^\//,"/").replace(/:([a-zA-Z_]\w*)/g,"{$1}")}function yp(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 $g(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 Fg(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 ra(r){let e=[],t=yp(r.auth),n=s=>{for(let i of s){if(i.type==="folder"){n(i.items??[]);continue}let o=i,a=Og(o.url),c=yp(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:$g(o),responses:Fg(o),auth:l})}};return n(r.items),e}var zl=E(()=>{"use strict"});function sa(r,e={}){let t=e.baseUrl||"http://localhost:3000",n=e.collectionName||"Designed API",s=e.workspaceKnowledge?`
338
338
 
339
339
  === Workspace context ===
340
340
  ${e.workspaceKnowledge}
@@ -364,9 +364,9 @@ Requirements:
364
364
  entry (e.g. bearerAuth, http/bearer) and apply a global "security" array.
365
365
  - Do not invent unrelated endpoints; keep the surface focused on the intent.${s}
366
366
 
367
- Now output the OpenAPI JSON document for the intent.`}var Bl=E(()=>{"use strict"});function ps(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 or(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??ps(t),name:t,description:"Auto-generated from source-code discovery (Phase 2a).",nodes:n,config:{...Yt},ai_generated:!0,derived_from:r.map(c=>c.id).filter(Boolean),createdAt:o,updatedAt:o},derived:s}}function ar(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):Tg(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(`
368
- `)}function Tg(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 na=E(()=>{"use strict";Ol()});function Fg(r){return r.auth?.required?!0:(r.middleware??[]).some(e=>$g.test(e.name))}function Ng(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 mp(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 hp(r){return{endpointId:r.id,requestName:r.source?.symbolName||`${r.method||"GET"} ${r.pathExpression}`,method:r.method||"GET",path:r.pathExpression}}function gp(r){return{endpointId:r.id,requestName:r.source?.symbolName||`${r.method||"GET"} ${r.pathExpression}`,method:r.method||"GET",path:r.pathExpression}}function sa(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 Cn(r,e){let t=[],n=r.filter(a=>Og.some(c=>c.test(a.pathExpression))),s=r.filter(Fg);for(let a of n){let c=s.filter(p=>p.id!==a.id);if(c.length===0)continue;let l=sa(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('${ra}', token);`]),u=c.map(p=>sa(p,e)),d=[l,{type:"if",if:`!!pm.variables.get('${ra}')`,then:u}];t.push({id:mp("auth",a.pathExpression,ra),kind:"auth",name:`${a.method} ${a.pathExpression} \u2192 protected endpoints`,confidence:"high",producer:hp(a),dependents:c.map(gp),variableName:ra,nodes:d})}let i=new Map;for(let a of r){let c=Ng(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=sa(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=>sa(h,e)),f=[p,{type:"if",if:`pm.variables.get('${d}') !== undefined`,then:m}];o.push({id:mp("crud",l.pathExpression,d),kind:"crud",name:`Create ${a} \u2192 id-scoped operations`,confidence:"high",producer:hp(l),dependents:u.map(gp),variableName:d,nodes:f})}return o.sort((a,c)=>a.name<c.name?-1:1),t.push(...o),t}var Og,ra,$g,ia=E(()=>{"use strict";Og=[/(^|\/)(login|signin|token|oauth|auth|sessions?)(\/|$)/i,/token|jwt|bearer/i],ra="authToken",$g=/(auth|require|protect|token|jwt|guard|secured)/i});function Ul(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 Vl(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(`
369
- `)}var fs,zl=E(()=>{"use strict";ir();sr();Hl();Bl();na();ia();fs=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?us(t.workspaceFolder):"",s=await this.designSpec(e,t,n),i=await this.importer.importFromString(JSON.stringify(s),{collectionName:t.collectionName,environmentName:t.environmentName}),o=ea(i.collection),a=or(o,{collectionId:i.collection.id,collectionName:i.collection.name,folderPath:t.suiteFolderPath,assertBodySchema:t.assertBodySchema,name:`${i.collection.name} \u2014 designed from intent`}),l=Cn(o,{collectionId:i.collection.id,collectionName:i.collection.name,folderPath:t.suiteFolderPath}),u=ar(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=Vl(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=ta(e,{collectionName:t.collectionName,baseUrl:t.baseUrl,workspaceKnowledge:n}),i=await nt(()=>this.aiProvider.complete(s)),o=wt(i),a=Ul(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 hs(){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 ms(e,process.env.ANTHROPIC_MODEL):null}return process.env.OPENAI_API_KEY?new Ci(process.env.OPENAI_API_KEY,process.env.OPENAI_MODEL):process.env.ANTHROPIC_API_KEY?new ms(process.env.ANTHROPIC_API_KEY,process.env.ANTHROPIC_MODEL):null}var Ci,ms,oa=E(()=>{"use strict";Ci=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}},ms=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 je(r,e){let t={type:"string",description:r};return e.length>0&&(t.enum=[...e]),t}function ki(r,e,t){let n=s=>je("Name of the collection to act on."+(s?"":" Optional."),e);return[{name:`${r}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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.'},...Ei.properties},required:["collection","request"]},annotations:{readOnlyHint:!1,openWorldHint:!0}},{name:`${r}${S.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").'},...qi.properties},required:["collection","folder"]},annotations:{readOnlyHint:!1,openWorldHint:!0}},{name:`${r}${S.runCollection}`,description:"Run every request in a collection.",inputSchema:{type:"object",properties:{collection:n(!0),...Ai.properties},required:["collection"]},annotations:{readOnlyHint:!1,openWorldHint:!0}},{name:`${r}${S.runSuite}`,description:"Run a saved test suite.",inputSchema:{type:"object",properties:{suite:je("Name of the test suite to run.",t),...Pi.properties},required:["suite"]},annotations:{readOnlyHint:!1,openWorldHint:!0}},{name:`${r}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.listSuites}`,description:"List all test suites with name, id, request count, and configuration summary.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:!0}},{name:`${r}${S.getSuite}`,description:"Get full details of a test suite including flow nodes (suite.nodes) and a flattened request list.",inputSchema:{type:"object",properties:{suite:je("Name or id of the test suite.",t)},required:["suite"]},annotations:{readOnlyHint:!0}},{name:`${r}${S.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}${S.updateSuiteConfig}`,description:"Change a suite's name/description/run configuration and optionally replace the full suite.nodes flow graph.",inputSchema:{type:"object",properties:{suite:je("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}${S.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:je("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}${S.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:je("Name or id of the suite.",t),includeBranches:{type:"boolean",description:"Include branch-array paths (default: true)."}},required:["suite"]},annotations:{readOnlyHint:!0}},{name:`${r}${S.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:je("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}${S.updateSuiteNode}`,description:"Replace a flow node at a specific path in suite.nodes.",inputSchema:{type:"object",properties:{suite:je("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}${S.removeSuiteNode}`,description:"Remove a flow node at a specific path from suite.nodes.",inputSchema:{type:"object",properties:{suite:je("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}${S.moveSuiteNode}`,description:"Move a flow node from one path to another parent/branch/index within suite.nodes.",inputSchema:{type:"object",properties:{suite:je("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}${S.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:je("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}${S.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:je("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}${S.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:je("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}${S.duplicateSuite}`,description:"Clone an existing suite under a new name.",inputSchema:{type:"object",properties:{suite:je("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}${S.deleteSuite}`,description:"Delete a test suite permanently. Set confirm:true to proceed.",inputSchema:{type:"object",properties:{suite:je("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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.getGlobals}`,description:"Return all global variables (merged _global.json + runtime pm.globals.set() values).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:!0}},{name:`${r}${S.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}${S.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}${S.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}${S.suggestEnvVars}`,description:`Scan a collection for hardcoded values (API keys, base URLs, tokens, tenant IDs) that should become environment variables.
367
+ Now output the OpenAPI JSON document for the intent.`}var Jl=E(()=>{"use strict"});function ms(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 lr(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,p=["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"&&p.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:p}),s.push({endpointId:c.id,requestName:l,method:c.method||"GET",path:c.pathExpression})}let o=Date.now();return{suite:{id:e.id??ms(t),name:t,description:"Auto-generated from source-code discovery (Phase 2a).",nodes:n,config:{...Zt},ai_generated:!0,derived_from:r.map(c=>c.id).filter(Boolean),createdAt:o,updatedAt:o},derived:s}}function ur(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):Ng(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(`
368
+ `)}function Ng(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 ia=E(()=>{"use strict";Ml()});function Dg(r){return r.auth?.required?!0:(r.middleware??[]).some(e=>_g.test(e.name))}function jg(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 vp(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 bp(r){return{endpointId:r.id,requestName:r.source?.symbolName||`${r.method||"GET"} ${r.pathExpression}`,method:r.method||"GET",path:r.pathExpression}}function Sp(r){return{endpointId:r.id,requestName:r.source?.symbolName||`${r.method||"GET"} ${r.pathExpression}`,method:r.method||"GET",path:r.pathExpression}}function aa(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 En(r,e){let t=[],n=r.filter(a=>Mg.some(c=>c.test(a.pathExpression))),s=r.filter(Dg);for(let a of n){let c=s.filter(d=>d.id!==a.id);if(c.length===0)continue;let l=aa(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('${oa}', token);`]),u=c.map(d=>aa(d,e)),p=[l,{type:"if",if:`!!pm.variables.get('${oa}')`,then:u}];t.push({id:vp("auth",a.pathExpression,oa),kind:"auth",name:`${a.method} ${a.pathExpression} \u2192 protected endpoints`,confidence:"high",producer:bp(a),dependents:c.map(Sp),variableName:oa,nodes:p})}let i=new Map;for(let a of r){let c=jg(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 p=`${a.replace(/[^a-zA-Z0-9]/g,"_")}Id`,d=aa(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('${p}', id);`]),m=u.map(h=>aa(h,e)),f=[d,{type:"if",if:`pm.variables.get('${p}') !== undefined`,then:m}];o.push({id:vp("crud",l.pathExpression,p),kind:"crud",name:`Create ${a} \u2192 id-scoped operations`,confidence:"high",producer:bp(l),dependents:u.map(Sp),variableName:p,nodes:f})}return o.sort((a,c)=>a.name<c.name?-1:1),t.push(...o),t}var Mg,oa,_g,ca=E(()=>{"use strict";Mg=[/(^|\/)(login|signin|token|oauth|auth|sessions?)(\/|$)/i,/token|jwt|bearer/i],oa="authToken",_g=/(auth|require|protect|token|jwt|guard|secured)/i});function Gl(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 Wl(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(`
369
+ `)}var hs,Kl=E(()=>{"use strict";cr();ar();zl();Jl();ia();ca();hs=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?ps(t.workspaceFolder):"",s=await this.designSpec(e,t,n),i=await this.importer.importFromString(JSON.stringify(s),{collectionName:t.collectionName,environmentName:t.environmentName}),o=ra(i.collection),a=lr(o,{collectionId:i.collection.id,collectionName:i.collection.name,folderPath:t.suiteFolderPath,assertBodySchema:t.assertBodySchema,name:`${i.collection.name} \u2014 designed from intent`}),l=En(o,{collectionId:i.collection.id,collectionName:i.collection.name,folderPath:t.suiteFolderPath}),u=ur(o,{name:`${i.collection.name}-designed`}),p=await this.exporter.export(i.collection.id,{format:t.openapiFormat??"json",info:t.openapiInfo,environments:t.environmentName?[t.environmentName]:void 0}),d=Wl(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:p,docs:d,ai_generated:!0,derivedFrom:o.map(m=>m.id).filter(Boolean)}}async designSpec(e,t,n){let s=sa(e,{collectionName:t.collectionName,baseUrl:t.baseUrl,workspaceKnowledge:n}),i=await tt(()=>this.aiProvider.complete(s)),o=xt(i),a=Gl(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 ys(){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 gs(e,process.env.ANTHROPIC_MODEL):null}return process.env.OPENAI_API_KEY?new qi(process.env.OPENAI_API_KEY,process.env.OPENAI_MODEL):process.env.ANTHROPIC_API_KEY?new gs(process.env.ANTHROPIC_API_KEY,process.env.ANTHROPIC_MODEL):null}var qi,gs,la=E(()=>{"use strict";qi=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}},gs=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 He(r,e){let t={type:"string",description:r};return e.length>0&&(t.enum=[...e]),t}function Ti(r,e,t){let n=s=>He("Name of the collection to act on."+(s?"":" Optional."),e);return[{name:`${r}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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.'},...Ai.properties},required:["collection","request"]},annotations:{readOnlyHint:!1,openWorldHint:!0}},{name:`${r}${S.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").'},...ki.properties},required:["collection","folder"]},annotations:{readOnlyHint:!1,openWorldHint:!0}},{name:`${r}${S.runCollection}`,description:"Run every request in a collection.",inputSchema:{type:"object",properties:{collection:n(!0),...Pi.properties},required:["collection"]},annotations:{readOnlyHint:!1,openWorldHint:!0}},{name:`${r}${S.runSuite}`,description:"Run a saved test suite.",inputSchema:{type:"object",properties:{suite:He("Name of the test suite to run.",t),...Ii.properties},required:["suite"]},annotations:{readOnlyHint:!1,openWorldHint:!0}},{name:`${r}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.listSuites}`,description:"List all test suites with name, id, request count, and configuration summary.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:!0}},{name:`${r}${S.getSuite}`,description:"Get full details of a test suite including flow nodes (suite.nodes) and a flattened request list.",inputSchema:{type:"object",properties:{suite:He("Name or id of the test suite.",t)},required:["suite"]},annotations:{readOnlyHint:!0}},{name:`${r}${S.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}${S.updateSuiteConfig}`,description:"Change a suite's name/description/run configuration and optionally replace the full suite.nodes flow graph.",inputSchema:{type:"object",properties:{suite:He("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}${S.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:He("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}${S.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:He("Name or id of the suite.",t),includeBranches:{type:"boolean",description:"Include branch-array paths (default: true)."}},required:["suite"]},annotations:{readOnlyHint:!0}},{name:`${r}${S.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:He("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}${S.updateSuiteNode}`,description:"Replace a flow node at a specific path in suite.nodes.",inputSchema:{type:"object",properties:{suite:He("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}${S.removeSuiteNode}`,description:"Remove a flow node at a specific path from suite.nodes.",inputSchema:{type:"object",properties:{suite:He("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}${S.moveSuiteNode}`,description:"Move a flow node from one path to another parent/branch/index within suite.nodes.",inputSchema:{type:"object",properties:{suite:He("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}${S.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:He("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}${S.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:He("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}${S.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:He("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}${S.duplicateSuite}`,description:"Clone an existing suite under a new name.",inputSchema:{type:"object",properties:{suite:He("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}${S.deleteSuite}`,description:"Delete a test suite permanently. Set confirm:true to proceed.",inputSchema:{type:"object",properties:{suite:He("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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.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}${S.getGlobals}`,description:"Return all global variables (merged _global.json + runtime pm.globals.set() values).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:!0}},{name:`${r}${S.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}${S.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}${S.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}${S.suggestEnvVars}`,description:`Scan a collection for hardcoded values (API keys, base URLs, tokens, tenant IDs) that should become environment variables.
370
370
 
371
371
  Returns:
372
372
  \u2022 heuristicSuggestions \u2014 values identified by pattern-matching rules (ready to apply)
@@ -447,8 +447,8 @@ This tool returns request details AND a structured task. You MUST:
447
447
  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.
448
448
  4. Respond with the JSON array directly so the user can pass it to run_collection or the CLI --variables flag.
449
449
 
450
- 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 Ei,Ai,qi,Pi,S,Ne=E(()=>{"use strict";Ei={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."}}},Ai={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."}}},qi={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."}}},Pi={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)"}}},S={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",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 T(r){return new Error(`Bad request: ${r}`)}function z(r,e){if(typeof r!="string"||!r.trim())throw T('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 T(`collection not found: "${r}". Available collections: ${s||"(none)"}. Call list_collections to see all.`)}return n}function Ve(r,e){if(typeof r!="string"||!r.trim())throw T('the "request" argument is required');let t=Q(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 T(`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 Jl(r,e){for(let t of r){if(t.type!=="folder")continue;let n=t;if(n.id===e)return n;let s=Jl(n.items??[],e);if(s)return s}}async function Ae(r,e){if(typeof r!="string"||!r.trim())throw T('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 T(`suite "${r}" not found. Available suites: ${i||"(none)"}. Call list_suites to see all.`)}return s}function yp(r,e){if(e.includes("fullBody")||r==null)return r;let t=typeof r=="string"?r:JSON.stringify(r);if(t.length<=aa)return r;let n;try{n=JSON.parse(t.slice(0,aa))}catch{n=t.slice(0,aa)}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 Lt(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=yp(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=yp(a.body,e);return c!==a.body?{...a,body:c}:a});s.failedRequests=i,n=!0}return n?s:r}var aa,Me=E(()=>{"use strict";Xe();Xe();aa=4096});function Wl(r,e){return e&&!pt.isAbsolute(r)?pt.join(e,r):r}async function vp(r){let e=dt.readFileSync(r,"utf8");if(r.endsWith(".json"))return JSON.parse(e);let{parse:t}=await import("yaml");return t(e)}function bp(r){return Q(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 Sp(r,e){return Q(r).find(({request:n})=>n.id===e.id||n.name===e.name)?.folderPath}function Mg(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(`
451
- `)}async function _g(r,e,t,n,s){let i=et(e).snapshot().body,o=`You are an API testing expert. Suggest high-value post-response pm.test() assertions for the request below.
450
+ 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 Ai,Pi,ki,Ii,S,Me=E(()=>{"use strict";Ai={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."}}},Pi={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."}}},ki={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."}}},Ii={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)"}}},S={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",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 T(r){return new Error(`Bad request: ${r}`)}function G(r,e){if(typeof r!="string"||!r.trim())throw T('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 T(`collection not found: "${r}". Available collections: ${s||"(none)"}. Call list_collections to see all.`)}return n}function Ue(r,e){if(typeof r!="string"||!r.trim())throw T('the "request" argument is required');let t=Q(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 T(`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 Xt(r,e,t){return r.collection.getRequestDetail(e,t.id)??t}function Ql(r,e){for(let t of r){if(t.type!=="folder")continue;let n=t;if(n.id===e)return n;let s=Ql(n.items??[],e);if(s)return s}}async function Ae(r,e){if(typeof r!="string"||!r.trim())throw T('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 T(`suite "${r}" not found. Available suites: ${i||"(none)"}. Call list_suites to see all.`)}return s}function xp(r,e){if(e.includes("fullBody")||r==null)return r;let t=typeof r=="string"?r:JSON.stringify(r);if(t.length<=ua)return r;let n;try{n=JSON.parse(t.slice(0,ua))}catch{n=t.slice(0,ua)}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 jt(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=xp(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=xp(a.body,e);return c!==a.body?{...a,body:c}:a});s.failedRequests=i,n=!0}return n?s:r}var ua,_e=E(()=>{"use strict";Ye();Ye();ua=4096});function Yl(r,e){return e&&!dt.isAbsolute(r)?dt.join(e,r):r}async function wp(r){let e=ut.readFileSync(r,"utf8");if(r.endsWith(".json"))return JSON.parse(e);let{parse:t}=await import("yaml");return t(e)}function Rp(r){return Q(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 Cp(r,e){return Q(r).find(({request:n})=>n.id===e.id||n.name===e.name)?.folderPath}function Lg(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(`
451
+ `)}async function Hg(r,e,t,n,s){let i=Xe(e).snapshot().body,o=`You are an API testing expert. Suggest high-value post-response pm.test() assertions for the request below.
452
452
 
453
453
  `+(i?`Business context for this endpoint (docs, OpenAPI contract, schema):
454
454
  ${i}
@@ -456,7 +456,7 @@ ${i}
456
456
  `:"")+(s?`Workspace business knowledge (Confluence exports, Jiras, project docs):
457
457
  ${s}
458
458
 
459
- `:"")+`${Mg(e,t)}
459
+ `:"")+`${Lg(e,t)}
460
460
 
461
461
  Rules:
462
462
  - Prefer business-logic and contract checks (status code, key fields, types, shapes, auth behaviour) over trivial ones.
@@ -464,7 +464,7 @@ Rules:
464
464
  - If an observed response body is provided, write assertions that match its actual shape.
465
465
  - Return at most ${n} assertions.
466
466
  Return ONLY a valid JSON array (no markdown fences):
467
- [{"snippet":"<full pm.test JS>","rationale":"<one sentence>"}]`;try{let a=await nt(()=>r.complete(o)),c=wt(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 Dg(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.
467
+ [{"snippet":"<full pm.test JS>","rationale":"<one sentence>"}]`;try{let a=await tt(()=>r.complete(o)),c=xt(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 Bg(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.
468
468
 
469
469
  `+(t?`Business context for this endpoint (docs, OpenAPI contract, workspace knowledge):
470
470
  ${t}
@@ -482,7 +482,7 @@ ${n.map(i=>`- ${i.name}${i.message?`: ${i.message}`:""}`).join(`
482
482
  `:"")+`
483
483
  Diagnose the likely root cause and give concrete, ordered fixes.
484
484
  Return ONLY a valid JSON object (no markdown fences):
485
- {"diagnosis":"<2-4 sentences>","suggestedFixes":["<fix 1>","<fix 2>"]}`;try{let i=await nt(()=>r.complete(s)),o=wt(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 jg(r,e,t){let n=[],s=e?.status;s?n.push({snippet:`pm.test("Status code is ${s}", function () {
485
+ {"diagnosis":"<2-4 sentences>","suggestedFixes":["<fix 1>","<fix 2>"]}`;try{let i=await tt(()=>r.complete(s)),o=xt(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 Ug(r,e,t){let n=[],s=e?.status;s?n.push({snippet:`pm.test("Status code is ${s}", function () {
486
486
  pm.response.to.have.status(${s});
487
487
  });`,rationale:`Observed status ${s} in the most recent run.`}):n.push({snippet:`pm.test("Status code is 2xx", function () {
488
488
  pm.expect(pm.response.code).to.be.within(200, 299);
@@ -495,34 +495,34 @@ Return ONLY a valid JSON object (no markdown fences):
495
495
  pm.expect(${l}).to.have.property("${c}");
496
496
  });`,rationale:`Field "${c}" was present in the observed response body.`})}}}catch{n.push({snippet:`pm.test("Response body is not empty", function () {
497
497
  pm.expect(pm.response.text()).to.not.be.empty;
498
- });`,rationale:"Response body was non-JSON text."})}return n}var dt,pt,Gl,xp,wp=E(()=>{"use strict";dt=I(require("fs")),pt=I(require("path"));sr();ir();Ll();Ho();jo();Bo();zl();oa();Xe();Ne();Me();Gl=["get","post","put","patch","delete","head","options"];xp=[{toolNames:[S.scaffoldCollectionFromOpenApi],async handle({args:r,services:e}){let t=typeof r.specPath=="string"?r.specPath.trim():"";if(!t)throw T('"specPath" is required');let n=Wl(t,e.workspaceFolder);if(!dt.existsSync(n))throw T(`OpenAPI spec file not found: "${n}"`);let i=await new Dt(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:[S.suggestAssertions],async handle({args:r,services:e,collections:t,runStore:n}){let s=r.collection;if(!(typeof r.request=="string"?r.request.trim():""))throw T('"request" is required');let o=z(s,t),a=Ve(r.request,o),c=typeof r.maxSuggestions=="number"?Math.min(20,Math.max(1,r.maxSuggestions)):10,u=Array.from(n.values()).filter(m=>m.status!=="running").flatMap(m=>m.allResults??[]).filter(m=>m.name===a.name||typeof m.name=="string"&&m.name.toLowerCase()===a.name.toLowerCase()),d=u[u.length-1];if(e.aiProvider){let m=await _g(e.aiProvider,a,d,c,tt(e.workspaceFolder).snapshot().body);if(m.length>0)return{collection:o.name,request:a.name,source:"ai",suggestions:m.slice(0,c),hint:"Paste the snippets into the request's post-response script using set_request_script."}}let p=jg(a,d,c);return{collection:o.name,request:a.name,source:"heuristic",suggestions:p.slice(0,c),hint:"Paste the snippets into the request's post-response script using set_request_script."}}},{toolNames:[S.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 T('"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=[tt(e.workspaceFolder).snapshot().body,Si(n,s).snapshot().body].filter(Boolean).join(`
498
+ });`,rationale:"Response body was non-JSON text."})}return n}var ut,dt,Zl,Ep,qp=E(()=>{"use strict";ut=I(require("fs")),dt=I(require("path"));ar();cr();Vl();Vo();Bo();zo();Kl();la();Ye();Me();_e();Zl=["get","post","put","patch","delete","head","options"];Ep=[{toolNames:[S.scaffoldCollectionFromOpenApi],async handle({args:r,services:e}){let t=typeof r.specPath=="string"?r.specPath.trim():"";if(!t)throw T('"specPath" is required');let n=Yl(t,e.workspaceFolder);if(!ut.existsSync(n))throw T(`OpenAPI spec file not found: "${n}"`);let i=await new _t(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:[S.suggestAssertions],async handle({args:r,services:e,collections:t,runStore:n}){let s=r.collection;if(!(typeof r.request=="string"?r.request.trim():""))throw T('"request" is required');let o=G(s,t),a=Ue(r.request,o),c=Xt(e,o.id,a),l=typeof r.maxSuggestions=="number"?Math.min(20,Math.max(1,r.maxSuggestions)):10,p=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()),d=p[p.length-1];if(e.aiProvider){let f=await Hg(e.aiProvider,c,d,l,et(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=Ug(c,d,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:[S.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 T('"request" is required when "runId" is provided');let p=u.allResults.find(v=>v.iteration===o&&(v.name===i||typeof v.name=="string"&&v.name.toLowerCase()===i.toLowerCase()));if(!p)throw new Error(`Request "${i}" (iteration ${o}) not found in run "${s}".`);let d=p.assertions?.every(v=>v.passed)??!0,m=p.error,f=p.assertions?.filter(v=>!v.passed)??[],h="",g=[];if(e.aiProvider&&(m||f.length>0)){let v=[et(e.workspaceFolder).snapshot().body,wi(n,s).snapshot().body].filter(Boolean).join(`
499
499
 
500
- `),y=await Dg(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 T('"request" is required');let c=z(a,t);return{request:Ve(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:[S.aiSuggestEnvVars],handle({args:r,services:e,collections:t}){let n=z(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=Ri(n,s),c=bp(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:jt(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:[S.aiEnhanceCollection],handle({args:r,services:e,collections:t}){let n=z(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=Q(n).filter(({folderPath:u})=>!o||u.toLowerCase().includes(o)),c=a.slice(s,s+i).map(({request:u,folderPath:d})=>({id:u.id,name:u.name,folder:d,method:u.method,url:u.url,headers:(u.headers??[]).filter(p=>p.enabled!==!1).map(p=>({key:p.key,value:p.value})),query:(u.query??[]).filter(p=>p.enabled!==!1).map(p=>({key:p.key,value:p.value})),currentBody:u.body?.type==="raw"&&typeof u.body.content=="string"?u.body.content:void 0,currentTestScript:e.collection.getRequestScript(n.id,u.id,"post-response")??void 0,description:u.description?.slice(0,200),doc:u.doc?u.doc.slice(0,600):void 0,operationId:u.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:[S.suggestEnvVars],handle({args:r,collections:e}){let t=z(r.collection,e),n=typeof r.minOccurrences=="number"?Math.max(1,r.minOccurrences):1,s=Ri(t,n),i=bp(t);return{collection:t.name,businessContext:jt(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:[S.applyEnvVars],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=r.suggestions;if(!Array.isArray(s)||s.length===0)throw T('"suggestions" must be a non-empty array of {value, varName} objects');let i=s,o=Xo(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:[S.getRequestsForEnhancement],handle({args:r,services:e,collections:t}){let n=z(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=Q(n).filter(({folderPath:l})=>!o||l.toLowerCase().includes(o)),c=a.slice(s,s+i).map(({request:l,folderPath:u})=>({id:l.id,name:l.name,folder:u,method:l.method,url:l.url,headers:(l.headers??[]).filter(d=>d.enabled!==!1).map(d=>({key:d.key,value:d.value})),query:(l.query??[]).filter(d=>d.enabled!==!1).map(d=>({key:d.key,value:d.value})),currentBody:l.body?.type==="raw"&&typeof l.body.content=="string"?l.body.content:void 0,currentTestScript:e.collection.getRequestScript(n.id,l.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:[S.applyRequestEnhancements],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=r.enhancements;if(!Array.isArray(s)||s.length===0)throw T('"enhancements" must be a non-empty array');let i=[];for(let o of s){let{requestId:a,body:c,testScript:l}=o;if(!Q(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:[S.analyzeCoverage,S.aiAnalyzeCoverage],async handle({args:r,services:e,collections:t,tool:n}){let s=z(r.collection,t),i=typeof r.folder=="string"?r.folder.toLowerCase():void 0,o=Q(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=Wl(p,e.workspaceFolder),g=(await vp(f)).paths??{};for(let[v,y]of Object.entries(g))for(let x of Gl){if(!(x in y))continue;let b=x.toUpperCase();o.some(({request:C})=>C.method.toUpperCase()===b&&(C.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===S.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:[S.generateRequestFromIntent],handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=typeof r.intent=="string"?r.intent.trim():"";if(!s)throw T('"intent" is required \u2014 describe what to test in plain English');let o=Q(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=tt(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:[jt(n).snapshot().body,c].filter(Boolean).join(`
500
+ `),y=await Bg(e.aiProvider,p,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.`:d?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:p.name,iteration:o,status:p.status??"unknown",passed:p.passed??!0,error:m??null,failedAssertions:f,allAssertions:p.assertions??[],requestDetails:{method:p.method,url:p.url,requestBody:p.requestBody},responseDetails:{status:p.responseStatus,headers:p.responseHeaders,body:(()=>{let v=p.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 T('"request" is required');let c=G(a,t);return{request:Ue(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:[S.aiSuggestEnvVars],handle({args:r,services:e,collections:t}){let n=G(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=Ei(n,s),c=Rp(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:Dt(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:[S.aiEnhanceCollection],handle({args:r,services:e,collections:t}){let n=G(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=Q(n).filter(({folderPath:u})=>!o||u.toLowerCase().includes(o)),c=a.slice(s,s+i).map(({request:u,folderPath:p})=>{let d=Xt(e,n.id,u);return{id:d.id,name:d.name,folder:p,method:d.method,url:d.url,headers:(d.headers??[]).filter(m=>m.enabled!==!1).map(m=>({key:m.key,value:m.value})),query:(d.query??[]).filter(m=>m.enabled!==!1).map(m=>({key:m.key,value:m.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,description:d.description?.slice(0,200),doc:d.doc?d.doc.slice(0,600):void 0,operationId:d.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:[S.suggestEnvVars],handle({args:r,collections:e}){let t=G(r.collection,e),n=typeof r.minOccurrences=="number"?Math.max(1,r.minOccurrences):1,s=Ei(t,n),i=Rp(t);return{collection:t.name,businessContext:Dt(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:[S.applyEnvVars],async handle({args:r,services:e,collections:t}){let n=G(r.collection,t),s=r.suggestions;if(!Array.isArray(s)||s.length===0)throw T('"suggestions" must be a non-empty array of {value, varName} objects');let i=s,o=na(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,p)=>u+p,0);return{collection:n.name,applied:i.map(u=>({varName:u.varName,replacements:o[u.varName]??0})),totalReplacements:l,...c?{writtenToEnvironment:c}:{}}}},{toolNames:[S.getRequestsForEnhancement],handle({args:r,services:e,collections:t}){let n=G(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=Q(n).filter(({folderPath:l})=>!o||l.toLowerCase().includes(o)),c=a.slice(s,s+i).map(({request:l,folderPath:u})=>{let p=Xt(e,n.id,l);return{id:p.id,name:p.name,folder:u,method:p.method,url:p.url,headers:(p.headers??[]).filter(d=>d.enabled!==!1).map(d=>({key:d.key,value:d.value})),query:(p.query??[]).filter(d=>d.enabled!==!1).map(d=>({key:d.key,value:d.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}});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:[S.applyRequestEnhancements],async handle({args:r,services:e,collections:t}){let n=G(r.collection,t),s=r.enhancements;if(!Array.isArray(s)||s.length===0)throw T('"enhancements" must be a non-empty array');let i=[];for(let o of s){let{requestId:a,body:c,testScript:l}=o;if(!Q(n).find(({request:d})=>d.id===a)){i.push({requestId:a,applied:["skipped: request not found"]});continue}let p=[];typeof c=="string"&&(await e.collection.updateRequest(n.id,a,{body:{type:"raw",content:c,format:"json"}}),p.push("body")),typeof l=="string"&&(await e.collection.setRequestScript(n.id,a,"post-response",l),p.push("testScript")),i.push({requestId:a,applied:p})}return{collection:n.name,results:i,totalUpdated:i.filter(o=>o.applied.length>0&&!o.applied[0].startsWith("skipped")).length}}},{toolNames:[S.analyzeCoverage,S.aiAnalyzeCoverage],async handle({args:r,services:e,collections:t,tool:n}){let s=G(r.collection,t),i=typeof r.folder=="string"?r.folder.toLowerCase():void 0,o=Q(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),p=[],d=typeof r.specPath=="string"?r.specPath.trim():"";if(d)try{let f=Yl(d,e.workspaceFolder),g=(await wp(f)).paths??{};for(let[v,y]of Object.entries(g))for(let x of Zl){if(!(x in y))continue;let b=x.toUpperCase();o.some(({request:R})=>R.method.toUpperCase()===b&&(R.url??"").replace(/\{\{[^}]+\}\}/g,"{param}").includes(v.replace(/\{[^}]+\}/g,"{param}").replace(/^\//,"")))||p.push({method:b,path:v})}}catch{}let m=a.filter(f=>!f.hasAssertions);if(n===S.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.`),p.length>0&&f.push(`${p.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:p,expectedCallAfterThis:m.length>0?"ai_enhance_collection":p.length>0?"generate_scenarios":null}}}return{collection:s.name,coveragePct:u,covered:c,total:l,requests:a,...p.length>0?{untestedOperations:p}:{}}}},{toolNames:[S.generateRequestFromIntent],handle({args:r,services:e,collections:t}){let n=G(r.collection,t),s=typeof r.intent=="string"?r.intent.trim():"";if(!s)throw T('"intent" is required \u2014 describe what to test in plain English');let o=Q(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=et(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:[Dt(n).snapshot().body,c].filter(Boolean).join(`
501
501
 
502
- `)||void 0,existingRequests:o,availableEnvVars:a,targetFolder:typeof r.folder=="string"?r.folder:void 0,expectedCallAfterThis:"create_request"}}}},{toolNames:[S.designApiFromIntent],async handle({args:r,services:e}){let t=typeof r.intent=="string"?r.intent.trim():"";if(!t)throw T('"intent" is required \u2014 describe the API you want designed');let n=e.aiProvider??hs();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 Dt(e.collection,e.environmentConfig),i=new Qt(e.collection,e.environmentConfig,new Zt({},{},{})),a=await new fs(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=>pt.isAbsolute(u)?u:pt.join(e.workspaceFolder,u);if(typeof r.flowOut=="string"&&r.flowOut){let u=l(r.flowOut);dt.mkdirSync(pt.dirname(u),{recursive:!0}),dt.writeFileSync(u,a.flow,"utf-8"),c.push(`flow:${u}`)}if(typeof r.docsOut=="string"&&r.docsOut){let u=l(r.docsOut);dt.mkdirSync(pt.dirname(u),{recursive:!0}),dt.writeFileSync(u,a.docs,"utf-8"),c.push(`docs:${u}`)}if(typeof r.openapiOut=="string"&&r.openapiOut){let u=l(r.openapiOut);dt.mkdirSync(pt.dirname(u),{recursive:!0}),dt.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:[S.validateAgainstSpec],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=typeof r.specPath=="string"?r.specPath.trim():"";if(!s)throw T('"specPath" is required');let i=Wl(s,e.workspaceFolder),o;try{o=await vp(i)}catch(f){throw new Error(`Could not load spec at "${i}": ${f instanceof Error?f.message:String(f)}`)}let a=o.paths??{},c=Q(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 Gl){if(!(g in h))continue;let v=h[g],y=g.toUpperCase(),x=p(f),b=c.find(({request:R})=>R.method.toUpperCase()===y&&p(R.url??"").includes(x));if(!b)l.push({method:y,path:f,operationId:v.operationId});else{let R=e.collection.getRequestScript(n.id,b.request.id,"post-response")??"";/pm\.test\s*\(/.test(R)||u.push({method:y,path:f,requestName:b.request.name})}}let m=new Set(Object.entries(a).flatMap(([f,h])=>Gl.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:pt.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:[S.generateScenarios],handle({args:r,services:e,collections:t}){let n=z(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=Q(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})=>({id:d.id,name:d.name,method:d.method,url:d.url??"",folder:p,headers:(d.headers??[]).filter(m=>m.enabled!==!1).map(m=>({key:m.key,value:m.value})),body: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,description:d.description?.slice(0,200),doc:d.doc?d.doc.slice(0,600):void 0,operationId:d.operationId})),u=tt(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:[jt(n).snapshot().body,u].filter(Boolean).join(`
502
+ `)||void 0,existingRequests:o,availableEnvVars:a,targetFolder:typeof r.folder=="string"?r.folder:void 0,expectedCallAfterThis:"create_request"}}}},{toolNames:[S.designApiFromIntent],async handle({args:r,services:e}){let t=typeof r.intent=="string"?r.intent.trim():"";if(!t)throw T('"intent" is required \u2014 describe the API you want designed');let n=e.aiProvider??ys();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 _t(e.collection,e.environmentConfig),i=new Kt(e.collection,e.environmentConfig,new Qt({},{},{})),a=await new hs(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=>dt.isAbsolute(u)?u:dt.join(e.workspaceFolder,u);if(typeof r.flowOut=="string"&&r.flowOut){let u=l(r.flowOut);ut.mkdirSync(dt.dirname(u),{recursive:!0}),ut.writeFileSync(u,a.flow,"utf-8"),c.push(`flow:${u}`)}if(typeof r.docsOut=="string"&&r.docsOut){let u=l(r.docsOut);ut.mkdirSync(dt.dirname(u),{recursive:!0}),ut.writeFileSync(u,a.docs,"utf-8"),c.push(`docs:${u}`)}if(typeof r.openapiOut=="string"&&r.openapiOut){let u=l(r.openapiOut);ut.mkdirSync(dt.dirname(u),{recursive:!0}),ut.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:[S.validateAgainstSpec],async handle({args:r,services:e,collections:t}){let n=G(r.collection,t),s=typeof r.specPath=="string"?r.specPath.trim():"";if(!s)throw T('"specPath" is required');let i=Yl(s,e.workspaceFolder),o;try{o=await wp(i)}catch(f){throw new Error(`Could not load spec at "${i}": ${f instanceof Error?f.message:String(f)}`)}let a=o.paths??{},c=Q(n),l=[],u=[],p=[],d=f=>f.replace(/\{\{[^}]+\}\}/g,"{p}").replace(/\{[^}]+\}/g,"{p}").replace(/\/+$/,"");for(let[f,h]of Object.entries(a))for(let g of Zl){if(!(g in h))continue;let v=h[g],y=g.toUpperCase(),x=d(f),b=c.find(({request:C})=>C.method.toUpperCase()===y&&d(C.url??"").includes(x));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])=>Zl.filter(g=>g in h).map(g=>`${g.toUpperCase()}:${d(f)}`)));for(let{request:f}of c){let h=d(f.url??""),g=`${f.method.toUpperCase()}:`;[...m].some(y=>y.startsWith(g)&&h.includes(y.split(":")[1]))||p.push({method:f.method,url:f.url??"",requestName:f.name})}return{collection:n.name,spec:dt.basename(s),summary:{untestedOperations:l.length,matchedWithoutAssertions:u.length,extraRequests:p.length},untestedOperations:l,matchedWithoutAssertions:u,extraRequests:p,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:[S.generateScenarios],handle({args:r,services:e,collections:t}){let n=G(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=Q(n).filter(({request:p,folderPath:d})=>!(s&&p.name.toLowerCase()!==s&&!p.name.toLowerCase().includes(s)||i&&!d.toLowerCase().includes(i))),l=c.slice(o,o+a).map(({request:p,folderPath:d})=>{let m=Xt(e,n.id,p);return{id:m.id,name:m.name,method:m.method,url:m.url??"",folder:d,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=et(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:[Dt(n).snapshot().body,u].filter(Boolean).join(`
503
503
 
504
- `)||void 0,requests:l,total:c.length,offset:o,hasMore:o+a<c.length,nextOffset:o+a,expectedCallAfterThis:"create_request"}}}},{toolNames:[S.healAssertions],handle({args:r,services:e,collections:t,runStore:n}){let s=z(r.collection,t),i=Ve(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:[et(i,Sp(s,i)).snapshot().body,tt(e.workspaceFolder).snapshot().body].filter(Boolean).join(`
504
+ `)||void 0,requests:l,total:c.length,offset:o,hasMore:o+a<c.length,nextOffset:o+a,expectedCallAfterThis:"create_request"}}}},{toolNames:[S.healAssertions],handle({args:r,services:e,collections:t,runStore:n}){let s=G(r.collection,t),i=Xt(e,s.id,Ue(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(p=>typeof p.name=="string"&&p.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:[Xe(i,Cp(s,i)).snapshot().body,et(e.workspaceFolder).snapshot().body].filter(Boolean).join(`
505
505
 
506
- `)||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:[S.generateIterationData],handle({args:r,collections:e}){let t=z(r.collection,e),n=Ve(r.request,t),s=typeof r.iterations=="number"?Math.min(50,Math.max(1,r.iterations)):5,i=n.body?.type==="raw"&&typeof n.body.content=="string"?n.body.content:void 0,o=(n.headers??[]).filter(u=>u.enabled!==!1).map(u=>({key:u.key,value:u.value})),a=(n.query??[]).filter(u=>u.enabled!==!1).map(u=>({key:u.key,value:u.value})),c=/\{\{([^}]+)\}\}/g,l=new Set;for(let u of[n.url??"",i??"",...o.map(d=>d.value),...a.map(d=>d.value)]){let d;for(c.lastIndex=0;(d=c.exec(u))!==null;)l.add(d[1])}return{task:{action:"generate_iteration_data",instructions:[`Generate ${s} test data rows for: ${n.method} ${n.url??""}`,`The request uses these {{variable}} placeholders: ${[...l].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:t.name,request:n.name,method:n.method,url:n.url??"",businessContext:et(n,Sp(t,n)).snapshot().body||void 0,body:i??null,headers:o,queryParams:a,placeholders:[...l],iterations:s}}}}]});function Rp(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=Rp(n.items??[],e);if(s)return s}}var Cp,Ep=E(()=>{"use strict";Ne();Me();Me();Cp=[{toolNames:[S.createCollection],async handle({args:r,services:e}){let t=typeof r.name=="string"?r.name.trim():"";if(!t)throw T('"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:[S.renameCollection],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=typeof r.newName=="string"?r.newName.trim():"";if(!s)throw T('"newName" is required');return await e.collection.renameCollection(n.id,s),{id:n.id,oldName:n.name,newName:s,renamed:!0}}},{toolNames:[S.deleteCollection],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw T('"confirm" must be true to delete a collection');let n=z(r.collection,t);return await e.collection.deleteCollection(n.id),{deleted:!0,collection:n.name}}},{toolNames:[S.duplicateCollection],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=typeof r.newName=="string"?r.newName.trim():"";if(!s)throw T('"newName" is required');let i=await e.collection.duplicateCollection(n.id,s);return{id:i.id,name:i.name,duplicatedFrom:n.name}}},{toolNames:[S.createFolder],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=typeof r.name=="string"?r.name.trim():"";if(!s)throw T('"name" is required');let i;if(typeof r.parentFolder=="string"&&r.parentFolder.trim()){let a=r.parentFolder.toLowerCase(),c=Re(n);if(Q(n).map(u=>u.folderPath)&&c.find(u=>u.folderPath===r.parentFolder||u.folderPath.toLowerCase()===a)){let d=Re(n).find(p=>p.folderPath===r.parentFolder||p.folderPath.toLowerCase()===a);if(d){let p=n.items;i=Rp(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:[S.deleteFolder],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw T('"confirm" must be true to delete a folder');let n=z(r.collection,t);if(typeof r.folder!="string"||!r.folder.trim())throw T('"folder" is required');let s=r.folder.toLowerCase(),i=Re(n).find(c=>c.folderPath===r.folder||c.folderPath.toLowerCase()===s);if(!i)throw T(`folder "${r.folder}" not found in collection "${n.name}"`);let o=Jl(n.items,i.folderId);if(!o)throw T(`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 Kl=E(()=>{"use strict"});var Ap=E(()=>{"use strict"});var Ct,gs,Lg,Hg,Bg,cr,ca=E(()=>{"use strict";Ct=I(require("fs")),gs=I(require("path")),Lg=["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"],Hg={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:[]},Bg={express:[".ts",".js"],nestjs:[".ts",".js"],fastify:[".ts",".js"],lambda:[".ts",".js"],spring:[".java"],fastapi:[".py"]},cr=class{buildFingerprint(e){let t=[],n=gs.join(e,"package.json"),s;for(let i of Lg){let o=gs.join(e,i);Ct.existsSync(o)&&t.push(o)}if(Ct.existsSync(n))try{let i=JSON.parse(Ct.readFileSync(n,"utf-8"));s={dependencies:i.dependencies,devDependencies:i.devDependencies,scripts:i.scripts}}catch{}return{projectRoot:e,packageJsonPath:Ct.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 Ct.existsSync(gs.join(e.projectRoot,t))}hasSourceHint(e,t){let n=["src","app"],s=Hg[t],i=Bg[t],o=0,a=120;for(let c of n){let l=gs.join(e.projectRoot,c);if(!Ct.existsSync(l))continue;let u=[l];for(;u.length>0&&o<a;){let d=u.shift(),p;try{p=Ct.readdirSync(d,{withFileTypes:!0})}catch{continue}for(let m of p){let f=gs.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=Ct.readFileSync(f,"utf-8")}catch{continue}if(s.some(g=>h.includes(g)))return!0}}}return!1}}});function rt(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=qp.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=Pp.join(n,i.name);if(i.isDirectory()){Ug.has(i.name)||t.push(o);continue}i.isFile()&&(Vg.test(i.name)||(o.endsWith(".ts")||o.endsWith(".js"))&&e.push(o))}}return e}var qp,Pp,Ug,Vg,En=E(()=>{"use strict";qp=I(require("fs")),Pp=I(require("path")),Ug=new Set(["node_modules",".git",".next","dist","build","out","coverage","__tests__","__mocks__","__fixtures__"]),Vg=/\.(?:test|spec|stories|min)\.[cm]?[tj]sx?$|\.d\.[cm]?ts$/});function Ii(r,e){let t=e.customSeedLoaderModulePath?.trim();if(!t)return{endpoints:[],warnings:[]};let n=la.isAbsolute(t)?t:la.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=require(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 kp,la,ua=E(()=>{"use strict";kp=I(require("fs")),la=I(require("path"))});function Ql(r,e){let t=r.projectName?.trim();if(t)return t;let n=Ip(r.source.filePath),s=zg(n);if(s)return s;let i;for(let a of e){let c=Ip(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 zg(r){return r.match(/(?:^|\/)agl-config-([^/]+)(?:\/|$)/)?.[1]}function Ip(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var Zl=E(()=>{"use strict"});function en(r,e){return r==="high"&&e==="high"?"high":r==="low"||e==="low"?"low":"medium"}function tn(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 Ti(r,e,t,n,s={visitedSymbols:new Set},i,o=["locals"]){let a=[],c=[],l=[],u,d=new Map,p=cy(o),m=oy(r,e,p),f=py(r,e,p);if(i?.requestAliases)for(let C of i.requestAliases)m.add(C);if(i?.responseAliases)for(let C of i.responseAliases)f.add(C);let h=_p(e),g=Jg(e,t),v=ay(r,t,h,g,m,f),y=(C,q)=>{let _=l.find(M=>M.statusCode===C);return _||(_={statusCode:C},l.push(_)),q&&(_.body={type:q,schema:_.body?.schema}),_};w.isFunctionLike(r)&&sy(r,e,d,m,f,p);let x=(C,q)=>{let _=h.get(C);if(_){let Z=`${t}:${C}`;if(s.visitedSymbols.has(Z))return;s.visitedSymbols.add(Z);let X=v.get(Z),Ge=q?ma(q,_,m,f):void 0,ln=Mp(X,Ge),It=Ti(_,e,t,n,s,ln,o);Xl({parameters:a,requestBody:u,cookies:c,responses:l},It),!u&&It.requestBody&&(u=It.requestBody);return}let M=g.get(C);if(!M||s.visitedSymbols.has(M.symbolKey))return;s.visitedSymbols.add(M.symbolKey);let D=v.get(M.symbolKey),V=q?ma(q,M.node,m,f):void 0,O=Mp(D,V),H=Ti(M.node,M.sourceFile,M.filePath,n,s,O,o);Xl({parameters:a,requestBody:u,cookies:c,responses:l},H),!u&&H.requestBody&&(u=H.requestBody)},b=["POST","PUT","PATCH"].includes(n),R=C=>{w.isVariableDeclaration(C)&&ry(C,e,d,m,f,p),w.isIdentifier(C)&&(w.isCallExpression(C.parent)&&C.parent.expression===C||x(C.text));let q=ys(C,e,"query",d,m,f,p);if(q){let O=e.getLineAndCharacterOfPosition(C.getStart(e));a.push({name:q.path,location:"query",type:pa(C,e),detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}let _=ys(C,e,"params",d,m,f,p);if(_){let O=e.getLineAndCharacterOfPosition(C.getStart(e));a.push({name:_.path,location:"path",required:!0,type:pa(C,e),detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}if(ny(C,e,m)&&!u){let O=e.getLineAndCharacterOfPosition(C.getStart(e));u={type:"json",required:b,detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}}}let M=ys(C,e,"body",d,m,f,p);if(M){let O=e.getLineAndCharacterOfPosition(C.getStart(e));a.push({name:M.path,location:"body",type:pa(C,e),detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}}),u||(u={type:"json",required:b})}let D=ys(C,e,"headers",d,m,f,p);if(D){let O=e.getLineAndCharacterOfPosition(C.getStart(e));a.push({name:D.path,location:"header",type:"string",detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}let V=ys(C,e,"cookies",d,m,f,p);if(V){let O=e.getLineAndCharacterOfPosition(C.getStart(e));c.push({name:V.path,type:"request",detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}for(let O of p){let H=ys(C,e,O,d,m,f,p);if(!H)continue;let Z=e.getLineAndCharacterOfPosition(C.getStart(e));a.push({name:H.path,location:O,type:pa(C,e),detectionLocation:{filePath:t,line:Z.line+1,column:Z.character+1,accessMode:"read"}})}if(w.isCallExpression(C)){let O=ly(C,e,f);O&&y(O.statusCode,O.bodyType)}if(w.isCallExpression(C)){let O=uy(C,f);if(O){let H=y(O.statusCode);if(!H.headers?.some(Z=>Z.name===O.headerName)){let Z=e.getLineAndCharacterOfPosition(C.getStart(e));H.headers=H.headers??[],H.headers.push({name:O.headerName,location:"header",type:"string",detectionLocation:{filePath:t,line:Z.line+1,column:Z.character+1,accessMode:"write"}})}}}if(w.isCallExpression(C)&&w.isPropertyAccessExpression(C.expression)&&fy(C.expression.expression,f)&&C.expression.name.text==="cookie"&&C.arguments[0]&&w.isStringLiteral(C.arguments[0])){let O=C.arguments[0].text;if(O&&!c.some(H=>H.name===O&&H.type==="response")){let H=e.getLineAndCharacterOfPosition(C.getStart(e));c.push({name:O,type:"response",httpOnly:!0,detectionLocation:{filePath:t,line:H.line+1,column:H.character+1,accessMode:"write"}})}}w.isCallExpression(C)&&w.isIdentifier(C.expression)&&x(C.expression.text,C),w.forEachChild(C,R)};return r&&R(r),{parameters:a,requestBody:b?u||{type:"json",required:!0}:void 0,cookies:c,responses:l.length>0?l:[{statusCode:200}]}}function vs(r,e,t,n,s=["locals"]){let i={parameters:[],requestBody:void 0,cookies:[],responses:[]};for(let o of r){let a=Ti(o,e,t,n,void 0,void 0,s);Xl(i,a)}return i.parameters=nn(i.parameters),i.cookies=ty(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 _p(r){let e=new Map,t=n=>{w.isFunctionDeclaration(n)&&n.name&&e.set(n.name.text,n),w.isVariableDeclaration(n)&&w.isIdentifier(n.name)&&n.initializer&&(w.isArrowFunction(n.initializer)||w.isFunctionExpression(n.initializer))&&e.set(n.name.text,n.initializer),w.forEachChild(n,t)};return t(r),e}function Jg(r,e){let t=new Map,n=(s,i)=>{if(!s.startsWith("."))return;let o=Wg(e,s);if(!o)return;let a=Gg(o);if(!a)return;let c=Kg(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(w.isImportDeclaration(s)&&s.importClause&&w.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&&w.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(w.isVariableStatement(s))for(let i of s.declarationList.declarations){if(!i.initializer||!w.isCallExpression(i.initializer)||!w.isIdentifier(i.initializer.expression)||i.initializer.expression.text!=="require")continue;let o=i.initializer.arguments[0];if(!o||!w.isStringLiteral(o))continue;let a=o.text,c=[];if(w.isIdentifier(i.name))c.push({localName:i.name.text,importedName:"default"});else if(w.isObjectBindingPattern(i.name))for(let l of i.name.elements){if(!w.isIdentifier(l.name))continue;let u=l.propertyName&&(w.isIdentifier(l.propertyName)||w.isStringLiteral(l.propertyName))?l.propertyName.text:l.name.text;c.push({localName:l.name.text,importedName:u})}n(a,c)}}return t}function Gg(r){let e="";try{e=ha.readFileSync(r,"utf-8")}catch{return}return w.createSourceFile(r,e,w.ScriptTarget.Latest,!0,r.endsWith(".ts")?w.ScriptKind.TS:w.ScriptKind.JS)}function Wg(r,e){let t=ur.resolve(ur.dirname(r),e),n=[t,`${t}.ts`,`${t}.js`,ur.join(t,"index.ts"),ur.join(t,"index.js")];for(let s of n)try{if(ha.statSync(s).isFile())return s}catch{continue}}function Kg(r,e){let t=new Map,n=_p(r),s=(i,o)=>{t.set(i,o)};for(let i of r.statements){if(w.isFunctionDeclaration(i)&&i.name&&Tp(i)){s(i.name.text,i),Op(i)&&s("default",i);continue}if(w.isVariableStatement(i)&&Tp(i)){for(let c of i.declarationList.declarations)!w.isIdentifier(c.name)||!c.initializer||(w.isArrowFunction(c.initializer)||w.isFunctionExpression(c.initializer))&&(s(c.name.text,c.initializer),Op(i)&&s("default",c.initializer));continue}if(w.isExportAssignment(i)){let c=i.expression;if(w.isIdentifier(c)){let l=n.get(c.text);l&&s("default",l)}else(w.isFunctionExpression(c)||w.isArrowFunction(c))&&s("default",c);continue}if(!w.isExpressionStatement(i)||!w.isBinaryExpression(i.expression))continue;let o=i.expression.left,a=i.expression.right;if(w.isPropertyAccessExpression(o)&&o.expression.getText(r)==="module.exports"){let c=o.name.text,l=Yl(a,n);l&&s(c,l);continue}if(o.getText(r)==="module.exports"){let c=Yl(a,n);c&&s("default",c);continue}if(w.isPropertyAccessExpression(o)&&o.expression.getText(r)==="exports"){let c=Yl(a,n);c&&s(o.name.text,c)}}return t}function Yl(r,e){if(w.isFunctionExpression(r)||w.isArrowFunction(r))return r;if(w.isIdentifier(r))return e.get(r.text)}function Tp(r){return w.canHaveModifiers(r)?!!w.getModifiers(r)?.some(e=>e.kind===w.SyntaxKind.ExportKeyword):!1}function Op(r){return w.canHaveModifiers(r)?!!w.getModifiers(r)?.some(e=>e.kind===w.SyntaxKind.DefaultKeyword):!1}function Xl(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=nn([...s,...i])}}function nn(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:$p([],i)});continue}if(a.required=!!(a.required||i.required),a.evidenceLocations=$p(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=>Qg(i)),n=t.filter(i=>i.location==="body"),s=new Map(n.map(i=>[i.name,i]));for(let i of[...n]){let o=da(i.name);for(;o;){if(!s.has(o)){let a={name:o,location:"body",type:"object"};s.set(o,a),t.push(a)}o=da(o)}}for(let i of s.values()){let o=da(i.name);for(;o;){let a=s.get(o);a&&(a.type="object"),o=da(o)}}return t}function $p(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 Qg(r){let e=Xg([...r.detectionLocation?[r.detectionLocation]:[],...r.evidenceLocations??[]]);if(e.length===0)return{...r,detectionLocation:void 0,evidenceLocations:void 0};let t=Zg(e),n=e.filter(s=>!ey(s,t));return{...r,detectionLocation:t,evidenceLocations:n.length>0?n:void 0}}function Zg(r){return[...r].sort(Yg)[0]}function Yg(r,e){let t=Fp(r),n=Fp(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 Fp(r){let e=0;return r.accessMode&&(e+=8),r.symbolName&&(e+=4),typeof r.column=="number"&&(e+=2),e}function Xg(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 ey(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 ty(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 ny(r,e,t){return w.isPropertyAccessExpression(r)&&w.isIdentifier(r.expression)&&t.has(r.expression.text)&&r.name.text==="body"}function ys(r,e,t,n,s,i,o){return tu(r,e,t,n,!1,s,i,o)}function tu(r,e,t,n,s,i,o,a){let c=[],l=r;for(;l&&(w.isPropertyAccessExpression(l)||w.isElementAccessExpression(l)||w.isPropertyAccessChain(l)||w.isElementAccessChain(l));){if(w.isPropertyAccessExpression(l)||w.isPropertyAccessChain(l)){c.unshift(l.name.text),l=l.expression;continue}if(w.isElementAccessExpression(l)||w.isElementAccessChain(l)){let h=l.argumentExpression;if(h&&(w.isStringLiteral(h)||w.isNumericLiteral(h))){let g=h.text;w.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&&w.isIdentifier(l)&&((o?.has(l.text)??!1)||(i?.has(l.text)??!1)):l&&w.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:fa(h)}}if(!l||!w.isIdentifier(l)||!n)return;let m=n.get(l.text);if(!m||m.target!==t)return;let f=fa(c);return m.path?f?{path:`${m.path}.${f}`}:{path:m.path}:f?{path:f}:s?{path:""}:void 0}function ry(r,e,t,n,s,i){let o=r.initializer;if(!o)return;w.isIdentifier(o)&&n.has(o.text)&&w.isIdentifier(r.name)&&n.add(r.name.text),w.isIdentifier(o)&&s.has(o.text)&&w.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=tu(o,e,u,t,!0,n,s,i);if(d){c=u,l=d.path;break}}if(c){if(w.isIdentifier(r.name)){t.set(r.name.text,{target:c,path:l});return}(w.isObjectBindingPattern(r.name)||w.isArrayBindingPattern(r.name))&&Oi(r.name,c,l,t)}}function sy(r,e,t,n,s,i){let o=["body","query","params","headers","cookies",...i];for(let a of r.parameters){if((w.isObjectBindingPattern(a.name)||w.isArrayBindingPattern(a.name))&&!a.initializer){iy(a.name,t,i);continue}let c=a.initializer;if(!c)continue;let l,u="";for(let d of o){let p=tu(c,e,d,t,!0,n,s,i);if(p){l=d,u=p.path;break}}if(l){if(w.isIdentifier(a.name)){t.set(a.name.text,{target:l,path:u});continue}(w.isObjectBindingPattern(a.name)||w.isArrayBindingPattern(a.name))&&Oi(a.name,l,u,t)}}}function iy(r,e,t){if(!w.isObjectBindingPattern(r))return;let n=new Set(["body","query","params","headers","cookies",...t]);for(let s of r.elements){let i=eu(s);if(!i||!n.has(i))continue;let o=i;if(w.isIdentifier(s.name)){e.set(s.name.text,{target:o,path:""});continue}(w.isObjectBindingPattern(s.name)||w.isArrayBindingPattern(s.name))&&Oi(s.name,o,"",e)}}function oy(r,e,t){let n=new Set,s=new Set(["query","params","body","headers","cookies",...t]),i=o=>{if(w.isPropertyAccessExpression(o)||w.isPropertyAccessChain(o)){let a=o.name.text;if(s.has(a)){let c=lr(o.expression);c&&n.add(c)}}if(w.isElementAccessExpression(o)||w.isElementAccessChain(o)){let a=o.argumentExpression;if(a&&w.isStringLiteral(a)&&s.has(a.text)){let c=lr(o.expression);c&&n.add(c)}}w.isVariableDeclaration(o)&&o.initializer&&w.isIdentifier(o.name)&&w.isIdentifier(o.initializer)&&n.has(o.initializer.text)&&n.add(o.name.text),w.forEachChild(o,i)};return i(r),n}function Oi(r,e,t,n){if(w.isObjectBindingPattern(r)){for(let s of r.elements){let i=eu(s);if(!i)continue;let o=Np(t,i);if(w.isIdentifier(s.name)){n.set(s.name.text,{target:e,path:o});continue}(w.isObjectBindingPattern(s.name)||w.isArrayBindingPattern(s.name))&&Oi(s.name,e,o,n)}return}for(let s of r.elements){if(!w.isBindingElement(s))continue;let i=eu(s)??"[]",o=Np(t,/^\d+$/.test(i)?"[]":i);if(w.isIdentifier(s.name)){n.set(s.name.text,{target:e,path:o});continue}(w.isObjectBindingPattern(s.name)||w.isArrayBindingPattern(s.name))&&Oi(s.name,e,o,n)}}function eu(r){let e=r.propertyName;if(!e)return w.isIdentifier(r.name)?r.name.text:void 0;if(w.isIdentifier(e)||w.isStringLiteral(e)||w.isNumericLiteral(e))return e.text}function Np(r,e){return fa(r?`${r}.${e}`.split("."):[e])}function fa(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 da(r){let e=r.lastIndexOf(".");if(!(e<=0))return r.slice(0,e)}function ay(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(w.isCallExpression(l)&&w.isIdentifier(l.expression)){let u=l.expression.text,d=t.get(u);if(d){let m=ma(l,d,s,i);m&&a(`${e}:${u}`,m)}let p=n.get(u);if(p){let m=ma(l,p.node,s,i);m&&a(p.symbolKey,m)}}w.forEachChild(l,c)};return c(r),o}function Mp(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 cy(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 ma(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(!w.isIdentifier(c.name))continue;let l=r.arguments[a],u=lr(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 pa(r,e){if(!r||!r.parent)return"string";if(w.isCallExpression(r.parent)&&w.isIdentifier(r.parent.expression)){let t=r.parent.expression.text;if(t==="parseInt"||t==="parseFloat")return"number"}if(w.isBinaryExpression(r.parent)&&(r.parent.operatorToken.kind===w.SyntaxKind.EqualsEqualsToken||r.parent.operatorToken.kind===w.SyntaxKind.EqualsEqualsEqualsToken)){let t=r.parent.left===r?r.parent.right:r.parent.left;if(w.isNumericLiteral(t))return"number"}return"string"}function ly(r,e,t){let n=r.expression;if(!w.isPropertyAccessExpression(n))return;let s=n.name.text;if(s!=="json"&&s!=="send")return;let i=Dp(r,t);if(i)return{statusCode:i.statusCode,bodyType:s==="json"?"json":dy(r.arguments[0])}}function uy(r,e){let t=r.expression;if(!w.isPropertyAccessExpression(t))return;let n=t.name.text;if(n!=="header"&&n!=="set")return;let s=r.arguments[0];if(!s||!w.isStringLiteral(s))return;let i=Dp(r,e);if(i)return{statusCode:i.statusCode,headerName:s.text}}function Dp(r,e){if(!w.isPropertyAccessExpression(r.expression))return;let t=200,n=r.expression.expression;for(;;){if(w.isIdentifier(n)&&e.has(n.text))return{receiver:n.text,statusCode:t};if(!w.isCallExpression(n)||!w.isPropertyAccessExpression(n.expression))return;let s=n.expression.name.text;if(s==="status"||s==="code"){let i=n.arguments[0];i&&w.isNumericLiteral(i)&&(t=Number(i.text))}n=n.expression.expression}}function dy(r){return r&&(w.isObjectLiteralExpression(r)||w.isArrayLiteralExpression(r))?"json":"text"}function py(r,e,t){let n=new Set,s=new Set(["status","code","json","send","header","set","cookie"]),i=new Set(t),o=a=>{if(w.isPropertyAccessExpression(a)||w.isPropertyAccessChain(a)){let c=a.name.text;if(i.has(c)){let l=lr(a.expression);l&&n.add(l)}}if(w.isElementAccessExpression(a)||w.isElementAccessChain(a)){let c=a.argumentExpression;if(c&&w.isStringLiteral(c)&&i.has(c.text)){let l=lr(a.expression);l&&n.add(l)}}if(w.isCallExpression(a)&&w.isPropertyAccessExpression(a.expression)){let c=a.expression.name.text;if(s.has(c)){let l=lr(a.expression.expression);l&&n.add(l)}}w.isVariableDeclaration(a)&&a.initializer&&w.isIdentifier(a.name)&&w.isIdentifier(a.initializer)&&n.has(a.initializer.text)&&n.add(a.name.text),w.forEachChild(a,o)};return o(r),n}function fy(r,e){let t=lr(r);return t?e.has(t):!1}function lr(r){let e=r;for(;;){if(w.isIdentifier(e))return e.text;if(w.isPropertyAccessExpression(e)||w.isPropertyAccessChain(e)){e=e.expression;continue}if(w.isElementAccessExpression(e)||w.isElementAccessChain(e)){e=e.expression;continue}if(w.isCallExpression(e)&&w.isPropertyAccessExpression(e.expression)){e=e.expression.expression;continue}return}}var ha,ur,w,ga=E(()=>{"use strict";ha=I(require("fs")),ur=I(require("path")),w=I(require("typescript"))});function bs(r,e,t){let n={},s=o=>{if(de.isVariableDeclaration(o)&&de.isIdentifier(o.name)&&o.initializer){let a=An(o.initializer,r,{variables:n});a!==void 0&&(n[o.name.text]=a)}de.forEachChild(o,s)};s(r);let i={...hy(e),...t};return{variables:n,env:i}}function Et(r,e,t){if(!r)return{pathExpression:"/",resolvedPath:"/",confidence:"high"};let n=An(r,e,t);if(n!==void 0)return{pathExpression:n,resolvedPath:n,confidence:"high"};if(de.isStringLiteral(r)||de.isNoSubstitutionTemplateLiteral(r)){let s=r.text||"/";return{pathExpression:s,resolvedPath:s,confidence:"high"}}if(de.isTemplateExpression(r)){let s=my(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 de.isIdentifier(r)?{pathExpression:r.getText(e),confidence:"low"}:{pathExpression:r.getText(e),confidence:"low"}}function rn(r,e){let t=jp(r??""),n=jp(e??""),s=Lp(`${t}/${n}`);return(r??"").includes("${")||(e??"").includes("${")?{pathExpression:s}:{pathExpression:s,resolvedPath:s}}function jp(r){return r?r.replace(/^['"`]/,"").replace(/['"`]$/,"").replace(/^\/+/,"").replace(/\/+$/,""):""}function Lp(r){let e=r.replace(/\/{2,}/g,"/").replace(/\/$/,"");return!e||e==="/"?"/":e.startsWith("/")?e:`/${e}`}function An(r,e,t){if(de.isStringLiteral(r)||de.isNoSubstitutionTemplateLiteral(r))return r.text;if(de.isParenthesizedExpression(r))return An(r.expression,e,t);if(de.isIdentifier(r))return t?.variables?.[r.text];if(de.isBinaryExpression(r)&&r.operatorToken.kind===de.SyntaxKind.PlusToken){let n=An(r.left,e,t),s=An(r.right,e,t);if(n!==void 0&&s!==void 0)return`${n}${s}`}if(de.isBinaryExpression(r)&&(r.operatorToken.kind===de.SyntaxKind.BarBarToken||r.operatorToken.kind===de.SyntaxKind.QuestionQuestionToken))return An(r.left,e,t)??An(r.right,e,t);if(de.isPropertyAccessExpression(r)){let n=r.getText(e);if(n.startsWith("process.env.")){let s=n.substring(12);return t?.env?.[s]}}}function my(r,e,t){let n=[r.head.text],s=!0;for(let o of r.templateSpans){let a=An(o.expression,e,t);a===void 0?(s=!1,n.push("${...}")):n.push(a),n.push(o.literal.text)}let i=s?Lp(n.join("")):void 0;return{pathExpression:r.getText(e),resolvedPath:i,confidence:s?"high":"medium"}}function hy(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=require("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 de,ya=E(()=>{"use strict";de=I(require("typescript"))});function Hp(r){return{get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",options:"OPTIONS",head:"HEAD",all:"ALL"}[r]}function gy(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 yy(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=rn(u.pathExpression,a.prefix.pathExpression),p=en(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 vy(r){return ce.isStringLiteral(r)||ce.isNoSubstitutionTemplateLiteral(r)||ce.isTemplateExpression(r)}function by(r){if(ce.isStringLiteral(r)||ce.isNoSubstitutionTemplateLiteral(r))return r.text}function Sy(r,e,t,n){let s=new Set(tn(n).map(a=>a.name));if(s.size===0)return[];let i=xy(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 xy(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 ce,Ss,Bp=E(()=>{"use strict";ce=I(require("typescript"));ya();ga();Ss=class{async analyzeFile(e,t,n,s){let i=ce.createSourceFile(e,t,ce.ScriptTarget.Latest,!0,e.endsWith(".ts")?ce.ScriptKind.TS:ce.ScriptKind.JS),o=new Set(["app","router"]),a=[],c=[],l=new Map,u=new Map,d=bs(i,n.projectRoot,s.envOverrides),p=g=>{if(ce.isVariableDeclaration(g)&&ce.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)}ce.forEachChild(g,p)};p(i);let m=g=>{if(ce.isCallExpression(g)&&ce.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&&ce.isIdentifier(b)&&o.has(b.text)&&ce.isIdentifier(b)){let C=Et(g.arguments[0],i,d);a.push({parent:v,child:b.text,prefix:C,middlewareNodes:g.arguments.slice(1,-1)})}else{let C=vy(g.arguments[0])?g.arguments.slice(1):g.arguments.slice(0),q=l.get(v)??[];q.push(...C),l.set(v,q)}}if(y==="param"&&g.arguments.length>=2&&o.has(v)){let b=by(g.arguments[0]),R=g.arguments[1];if(b&&R&&ce.isExpression(R)){let C=u.get(v)??[];C.push({paramName:b,node:R}),u.set(v,C)}}let x=Hp(y);if(x&&o.has(v)&&g.arguments.length>=1){let b=Et(g.arguments[0],i,d),R=gy(g.arguments,i),C=g.arguments[g.arguments.length-1],q=i.getLineAndCharacterOfPosition(C.getStart(i));c.push({owner:v,method:x,pathExpression:b.pathExpression,resolvedPath:b.resolvedPath,confidence:b.confidence,middleware:R,middlewareNodes:g.arguments.slice(1,-1),handlerNode:C,source:{filePath:e,line:q.line+1,column:q.character+1,symbolName:C.getText(i)}})}if(y==="route"&&g.arguments[0]){let b=Et(g.arguments[0],i,d),R=g.parent;if(ce.isCallExpression(R)&&ce.isPropertyAccessExpression(R.expression)){let C=Hp(R.expression.name.text);if(C){let q=R.arguments[0]??g.arguments[0],_=i.getLineAndCharacterOfPosition(q.getStart(i));c.push({owner:v,method:C,pathExpression:b.pathExpression,resolvedPath:b.resolvedPath,confidence:b.confidence,middleware:[],middlewareNodes:[],handlerNode:q,source:{filePath:e,line:_.line+1,column:_.character+1,symbolName:q.getText(i)}})}}}}ce.forEachChild(g,m)};m(i);let f=[],h=yy(a);for(let g of c){let v=h.get(g.owner)??[],y=v.length>0?v:[{pathExpression:"",confidence:"high",middlewareNodes:[]}];for(let x of y){let b=rn(x.pathExpression,g.pathExpression),R=en(x.confidence,g.confidence),C=!!b.resolvedPath,q=tn(b.pathExpression),_=l.get(g.owner)??[],M=Sy(g.owner,a,u,b.pathExpression),D=[...x.middlewareNodes,..._,...M,...g.middlewareNodes,g.handlerNode],V=vs(D,i,e,g.method,s.contextProperties);V.parameters.unshift(...q),V.parameters=nn(V.parameters),f.push({id:"",method:g.method,framework:"express",pathExpression:b.pathExpression,resolvedPath:R==="high"&&C?b.resolvedPath:void 0,confidence:R,source:g.source,middleware:g.middleware,params:V.parameters.length>0?V.parameters:void 0,requestBody:V.requestBody,cookies:V.cookies.length>0?V.cookies:void 0,responses:V.responses})}}return f}}});function wy(r,e,t,n,s,i){let o=r.arguments[0],a=r.arguments[1],c=Ry(a,e,i),l=c?n.map(u=>{let d=rn(u.pathExpression,c.pathExpression);return{pathExpression:d.pathExpression,resolvedPath:u.resolvedPath&&c.resolvedPath?d.resolvedPath:void 0,confidence:en(u.confidence,c.confidence)}}):n;if(F.isArrowFunction(o)||F.isFunctionExpression(o)){let u=new Set(t),d=o.parameters[0];d&&F.isIdentifier(d.name)&&u.add(d.name.text),o.body&&F.forEachChild(o.body,p=>s(p,u,l))}}function Ry(r,e,t){if(!r||!F.isObjectLiteralExpression(r))return;let n=qe(r,"prefix");if(!n)return;let s=Et(n,e,t);return{pathExpression:s.pathExpression,resolvedPath:s.resolvedPath,confidence:s.confidence}}function Cy(r){return{get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",options:"OPTIONS",head:"HEAD",all:"ALL"}[r]}function qe(r,e){for(let t of r.properties){if(!F.isPropertyAssignment(t))continue;if((F.isIdentifier(t.name)||F.isStringLiteral(t.name)?t.name.text:void 0)===e)return t.initializer}}function Ey(r,e){return r?F.isStringLiteral(r)||F.isNoSubstitutionTemplateLiteral(r)?[r.text.toUpperCase()]:F.isArrayLiteralExpression(r)?r.elements.map(t=>F.isStringLiteral(t)||F.isNoSubstitutionTemplateLiteral(t)?t.text.toUpperCase():t.getText(e).toUpperCase()).filter(Boolean):[r.getText(e).toUpperCase()]:["GET"]}function Up(r,e){return r?F.isArrayLiteralExpression(r)?r.elements.map(t=>({name:`preHandler:${t.getText(e)}`})):[{name:`preHandler:${r.getText(e)}`}]:[]}function Vp(r){return r?F.isArrayLiteralExpression(r)?r.elements.filter(e=>F.isExpression(e)):[r]:[]}function Ay(r){if(r&&(F.isArrowFunction(r)||F.isFunctionExpression(r))&&r.parameters[0]&&F.isIdentifier(r.parameters[0].name))return r.parameters[0].name.text}function qy(r,e){if(!r||!F.isStringLiteral(r))return!1;let t=r.text;return t==="onRequest"||t==="preParsing"||t==="preValidation"||t==="preHandler"}function Py(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 ky(r,e){return e?{parameters:nn([...e.parameters,...r.parameters]),requestBody:e.requestBody??r.requestBody,cookies:r.cookies,responses:r.responses}:r}function zp(r,e,t){if(!r||!F.isObjectLiteralExpression(r))return;let n=[],s=qe(r,"params");s&&n.push(...$i(s,"path",""));let i=qe(r,"querystring")??qe(r,"query");i&&n.push(...$i(i,"query",""));let o=qe(r,"headers");o&&n.push(...$i(o,"header",""));let a=qe(r,"body");a&&n.push(...$i(a,"body",""));let c=a?Jp(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 Jp(r,e){if(F.isStringLiteral(r)||F.isNoSubstitutionTemplateLiteral(r))return{type:"string"};if(F.isNumericLiteral(r))return{type:"number"};if(!F.isObjectLiteralExpression(r))return;let t={};for(let n of r.properties){if(!F.isPropertyAssignment(n))continue;let s=n.name,i=F.isIdentifier(s)||F.isStringLiteral(s)||F.isNumericLiteral(s)?s.text:void 0;if(!i)continue;let o=Gp(n.initializer,e);o!==void 0&&(t[i]=o)}return Object.keys(t).length>0?t:void 0}function Gp(r,e){if(F.isStringLiteral(r)||F.isNoSubstitutionTemplateLiteral(r))return r.text;if(F.isNumericLiteral(r))return Number(r.text);if(r.kind===F.SyntaxKind.TrueKeyword||r.kind===F.SyntaxKind.FalseKeyword)return r.kind===F.SyntaxKind.TrueKeyword;if(r.kind===F.SyntaxKind.NullKeyword)return null;if(F.isArrayLiteralExpression(r)){let t=r.elements.map(n=>Gp(n,e));return t.every(n=>n!==void 0)?t:void 0}if(F.isObjectLiteralExpression(r))return Jp(r,e)}function $i(r,e,t){if(!F.isObjectLiteralExpression(r))return[];let n=qe(r,"properties");if(!n||!F.isObjectLiteralExpression(n))return[];let s=qe(r,"required"),i=new Set;if(s&&F.isArrayLiteralExpression(s))for(let a of s.elements)(F.isStringLiteral(a)||F.isNoSubstitutionTemplateLiteral(a))&&i.add(a.text);let o=[];for(let a of n.properties){if(!F.isPropertyAssignment(a))continue;let c=F.isIdentifier(a.name)||F.isStringLiteral(a.name)||F.isNumericLiteral(a.name)?a.name.text:void 0;if(!c)continue;let l=t?`${t}.${c}`:c,u=Iy(a.initializer);o.push({name:l,location:e,type:u,required:i.has(c)}),o.push(...$i(a.initializer,e,l))}return o}function Iy(r){if(!F.isObjectLiteralExpression(r))return;let e=qe(r,"type");if(e&&(F.isStringLiteral(e)||F.isNoSubstitutionTemplateLiteral(e)))return e.text;let t=qe(r,"properties");if(t&&F.isObjectLiteralExpression(t))return"object"}var F,xs,Wp=E(()=>{"use strict";F=I(require("typescript"));ya();ga();xs=class{async analyzeFile(e,t,n,s){let i=F.createSourceFile(e,t,F.ScriptTarget.Latest,!0,e.endsWith(".ts")?F.ScriptKind.TS:F.ScriptKind.JS),o=new Set(["fastify"]),a=[{pathExpression:"",resolvedPath:"",confidence:"high"}],c=[],l=new Map,u=new Map,d=bs(i,n.projectRoot,s.envOverrides),p=(f,h,g)=>{if(F.isVariableDeclaration(f)&&F.isIdentifier(f.name)&&f.initializer){let v=f.initializer.getText(i);(v.includes("fastify(")||v.includes("Fastify("))&&h.add(f.name.text)}if(F.isCallExpression(f)&&F.isPropertyAccessExpression(f.expression)){let v=f.expression.expression.getText(i),y=f.expression.name.text;if(y==="register"){let b=Ay(f.arguments[0]);b&&u.set(b,v),wy(f,i,h,g,p,d)}if(y==="addHook"&&h.has(v)&&f.arguments.length>=2&&qy(f.arguments[0],i)){let b=l.get(v)??[];b.push(f.arguments[1]),l.set(v,b)}let x=Cy(y);if(x&&h.has(v)&&f.arguments[0]){let b=Et(f.arguments[0],i,d),R=f.arguments.length>=2&&F.isObjectLiteralExpression(f.arguments[1])?f.arguments[1]:void 0,C=R&&f.arguments[2]?f.arguments[2]:f.arguments[f.arguments.length-1],q=i.getLineAndCharacterOfPosition(C.getStart(i)),_=R?qe(R,"preHandler"):void 0,M=Up(_,i),D=Vp(_),V=R?zp(qe(R,"schema"),i,x):void 0;for(let O of g){let H=rn(O.pathExpression,b.pathExpression),Z=en(O.confidence,b.confidence),X=!!H.resolvedPath;c.push({owner:v,method:x,pathExpression:H.pathExpression,resolvedPath:Z==="high"&&X?H.resolvedPath:void 0,confidence:Z,handlerNode:C,middlewareNodes:D,schemaMetadata:V,source:{filePath:e,line:q.line+1,column:q.character+1,symbolName:C.getText(i)},middleware:M})}}if(y==="route"&&h.has(v)&&f.arguments[0]&&F.isObjectLiteralExpression(f.arguments[0])){let b=f.arguments[0],R=qe(b,"method"),C=qe(b,"url")??qe(b,"path"),q=qe(b,"handler"),_=qe(b,"preHandler"),M=qe(b,"schema"),D=Et(C,i,d),V=Ey(R,i),O=Up(_,i);for(let H of V){let Z=q?i.getLineAndCharacterOfPosition(q.getStart(i)):i.getLineAndCharacterOfPosition(b.getStart(i));for(let X of g){let Ge=rn(X.pathExpression,D.pathExpression),ln=en(X.confidence,D.confidence),It=!!Ge.resolvedPath;c.push({owner:v,method:H,pathExpression:Ge.pathExpression,resolvedPath:ln==="high"&&It?Ge.resolvedPath:void 0,confidence:ln,handlerNode:q??b,middlewareNodes:Vp(_),schemaMetadata:zp(M,i,H),source:{filePath:e,line:Z.line+1,column:Z.character+1,symbolName:q?.getText(i)},middleware:O})}}}}F.forEachChild(f,v=>p(v,h,g))};p(i,o,a);let m=[];for(let f of c){let h=tn(f.pathExpression),v=[...Py(f.owner,l,u),...f.middlewareNodes,f.handlerNode],y=vs(v,i,e,f.method,s.contextProperties);y.parameters.unshift(...h),y.parameters=nn(y.parameters);let x=ky(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:x.parameters.length>0?x.parameters:void 0,requestBody:x.requestBody,cookies:x.cookies.length>0?x.cookies:void 0,responses:x.responses})}return m}}});function Ty(r,e){L.forEachChild(r,t=>Oy(t,r,e))}function Oy(r,e,t){if(L.isExpressionStatement(r)&&L.isBinaryExpression(r.expression)&&r.expression.operatorToken.kind===L.SyntaxKind.EqualsToken){let n=r.expression.left,s=r.expression.right;if(L.isPropertyAccessExpression(n)){let i=n.expression.getText(e),o=n.name.text;if(i==="exports"&&va(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=nu(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"&&va(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=nu(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(L.isVariableStatement(r)&&Kp(r)&&r.declarationList.declarations.length>0){for(let n of r.declarationList.declarations)if(!(!L.isIdentifier(n.name)||!n.initializer)&&va(n.initializer,e)){let s=n.name.text,i=e.getLineAndCharacterOfPosition(n.initializer.getStart(e)),{handlerNode:o,middlewareNodes:a}=nu(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(L.isFunctionDeclaration(r)&&Kp(r)&&r.name&&$y(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 va(r,e){if(L.isArrowFunction(r)||L.isFunctionExpression(r))return Fy(r);if(L.isCallExpression(r)){let t=r.expression.getText(e);if(t==="middy"||t.endsWith(".middy"))return!0;if(L.isPropertyAccessExpression(r.expression)&&r.expression.name.text==="use")return va(r.expression.expression,e)}return L.isIdentifier(r)?/handler/i.test(r.text):!1}function $y(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function Fy(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function Kp(r){return(L.getCombinedModifierFlags(r)&L.ModifierFlags.Export)!==0}function nu(r,e){let t=[],n=r;for(;L.isCallExpression(n)&&L.isPropertyAccessExpression(n.expression)&&n.expression.name.text==="use";)t.unshift(...n.arguments),n=n.expression.expression;return L.isCallExpression(n)&&(n.expression.getText(e)==="middy"||n.expression.getText(e).endsWith(".middy"))?{handlerNode:n.arguments[0]??n,middlewareNodes:t}:{handlerNode:r,middlewareNodes:[]}}function Ny(r,e,t){return r.map(n=>{let s=My(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 My(r,e){return L.isIdentifier(r)?r.text:L.isCallExpression(r)&&L.isIdentifier(r.expression)?r.expression.text:L.isCallExpression(r)&&L.isPropertyAccessExpression(r.expression)?r.expression.name.text:r.getText(e).slice(0,40).replace(/\s+/g," ")}function Dy(r,e,t){let n=jy(r);if(!n)return[];let s=new Map,i=o=>{if(L.isPropertyAccessExpression(o)||L.isElementAccessExpression(o)){let a=Fi(o,e);if(a.length>=2&&a[0]===n){let c=a[1],l=_y[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(L.isCallExpression(o)&&L.isPropertyAccessExpression(o.expression)&&o.expression.expression.getText(e)==="JSON"&&o.expression.name.text==="parse"&&o.arguments.length===1){let a=o.arguments[0],c=Fi(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}})}}}L.forEachChild(o,i)};return i(r),Array.from(s.values())}function jy(r){if(L.isArrowFunction(r)||L.isFunctionExpression(r)||L.isFunctionDeclaration(r)){let e=r.parameters[0];if(e&&L.isIdentifier(e.name))return e.name.text}return L.isIdentifier(r),"event"}function Fi(r,e){return L.isIdentifier(r)?[r.text]:L.isPropertyAccessExpression(r)?[...Fi(r.expression,e),r.name.text]:r.kind===L.SyntaxKind.PropertyAccessExpression||L.isNonNullExpression(r)?Fi(r.expression,e):L.isElementAccessExpression(r)&&L.isStringLiteral(r.argumentExpression)?[...Fi(r.expression,e),r.argumentExpression.text]:r.getText(e).replace(/\?/g,"").replace(/\s/g,"").split(".")}var L,ws,_y,ru=E(()=>{"use strict";L=I(require("typescript")),ws=class{async analyzeFile(e,t,n,s){let i=L.createSourceFile(e,t,L.ScriptTarget.Latest,!0,e.endsWith(".ts")?L.ScriptKind.TS:L.ScriptKind.JS),o=[];return Ty(i,o),o.length===0?[]:o.map(a=>{let c=Dy(a.handlerNode,i,e),l=Ny(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}})}};_y={pathParameters:"path",queryStringParameters:"query",multiValueQueryStringParameters:"query",headers:"header",multiValueHeaders:"header",body:"body"}});var Rs=E(()=>{"use strict";ga();Bp();Wp();ru()});function Qp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function Ly(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 ba,dr,su=E(()=>{"use strict";ba=I(require("fs"));Rs();En();dr=class{id="provider.express";framework="express";analyzer=new Ss;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(Qp(t)===Qp(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??rt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=ba.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=ba.readFileSync(a,"utf-8")}catch{continue}let d=await this.analyzer.analyzeFile(a,u,t,e),p=Ly(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)}}});function Zp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function Hy(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 Sa,pr,iu=E(()=>{"use strict";Sa=I(require("fs"));Rs();En();pr=class{id="provider.fastify";framework="fastify";analyzer=new xs;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(Zp(t)===Zp(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??rt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=Sa.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=Sa.readFileSync(a,"utf-8")}catch{continue}let d=await this.analyzer.analyzeFile(a,u,t,e),p=Hy(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)}}});function Yp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function ou(r,e){let t=r.expression;if(me.isCallExpression(t))return me.isIdentifier(t.expression)?t.expression.text:t.expression.getText(e);if(me.isIdentifier(t))return t.text}function Xp(r){let e=r.expression;if(me.isCallExpression(e))return e.arguments[0]}function By(r){return{Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE",Patch:"PATCH",Options:"OPTIONS",Head:"HEAD",All:"ALL"}[r]}function ef(r){return me.canHaveDecorators(r)?me.getDecorators(r)??[]:[]}function tf(r,e){if(!r||r.length===0)return[];let t=new Set(["UseGuards","UseInterceptors","UsePipes","UseFilters"]),n=[];for(let s of r){let i=ou(s,e);if(!i||!t.has(i))continue;let o=s.expression;if(!me.isCallExpression(o)){n.push({name:i});continue}for(let a of o.arguments)n.push({name:`${i}:${a.getText(e)}`})}return n}function Uy(r,e){return r==="low"||e==="low"?"low":r==="medium"||e==="medium"?"medium":"high"}var xa,me,fr,au=E(()=>{"use strict";xa=I(require("fs")),me=I(require("typescript"));ya();En();fr=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(Yp(t)===Yp(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??rt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){if(!a.endsWith(".ts")&&!a.endsWith(".js"))continue;let c;try{c=xa.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=xa.readFileSync(a,"utf-8")}catch{continue}let d=[],p=[],m=me.createSourceFile(a,u,me.ScriptTarget.Latest,!0,a.endsWith(".ts")?me.ScriptKind.TS:me.ScriptKind.JS),f=bs(m,t.projectRoot,e.envOverrides),h=g=>{if(me.isClassDeclaration(g)){let v=ef(g),y=v.find(x=>ou(x,m)==="Controller");if(y){let x=Et(Xp(y),m,f),b=tf(v,m);for(let R of g.members){if(!me.isMethodDeclaration(R))continue;let C=ef(R),q=C.map(_=>({decorator:_,name:ou(_,m)})).filter(_=>!!_.name);for(let _ of q){let M=By(_.name);if(!M)continue;let D=Et(Xp(_.decorator),m,f),V=rn(x.pathExpression,D.pathExpression),O=tf(C,m),H=R.name?.getText(m),Z=R.name??R,X=m.getLineAndCharacterOfPosition(Z.getStart(m)),Ge=Uy(x.confidence,D.confidence);p.push({id:"",method:M,framework:"nestjs",pathExpression:V.pathExpression,resolvedPath:Ge==="high"?V.resolvedPath:void 0,confidence:Ge,source:{filePath:a,line:X.line+1,column:X.character+1,symbolName:H},middleware:[...b,...O]}),Ge!=="high"&&d.push({code:"dynamic-path-unresolved",framework:"nestjs",filePath:a,message:`Dynamic NestJS route path unresolved at ${H??"unknown handler"} in ${a}`})}}}}me.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)}}});function Vy(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}=sf(c,e),d=of(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 x=typeof f.authorizer=="string"?f.authorizer:"authorizer";y.push({name:x})}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 nf(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}=sf(l,e),p=of(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 x=af(v),b=g.Auth,R=[];b?.Authorizer&&R.push({name:String(b.Authorizer)}),n.push({id:"",method:y.toUpperCase(),framework:"lambda",pathExpression:x,resolvedPath:x,confidence:"high",source:{filePath:p??u,line:1,column:1,symbolName:d},middleware:R})}}return n}function sf(r,e){let t=r.lastIndexOf(".");return t===-1?{filePath:r,exportName:"handler"}:{filePath:r.slice(0,t),exportName:r.slice(t+1)}}function of(r,e){let t=[ft.join(e,`${r}.ts`),ft.join(e,`${r}.js`),ft.join(e,r,"index.ts"),ft.join(e,r,"index.js")];for(let n of t)if(_e.existsSync(n))return n}function af(r){return r.startsWith("/")?r:`/${r}`}function lu(r){let e=r.split(`
507
- `);return Ni(e,0,-1).value}function Ni(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=zy(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=Ni(r,o+1,l),v={};v[h]=g.value,s.push(v),o=g.nextLine}else{let h=Ni(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 x=Ni(r,o+1,l);h[v]=x.value,s.push(h),o=x.nextLine}else h[v]=cu(y),s.push(h),o++}else s.push(cu(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=Ni(r,o+1,l);n[p]=f.value,o=f.nextLine}else n[p]=cu(m),o++}return i?{value:s,nextLine:o}:{value:n,nextLine:o}}function zy(r){let e=0;for(let t of r)if(t===" ")e++;else if(t===" ")e+=2;else break;return e}function cu(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 Jy(r){return lu(r)}function rf(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var _e,ft,mr,uu=E(()=>{"use strict";_e=I(require("fs")),ft=I(require("path"));ru();En();mr=class{id="provider.lambda";framework="lambda";analyzer=new ws;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(rf(t)===rf(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=_e.existsSync(ft.join(e.projectRoot,"serverless.yml"))||_e.existsSync(ft.join(e.projectRoot,"serverless.yaml"))||_e.existsSync(ft.join(e.projectRoot,"template.yaml"))||_e.existsSync(ft.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=ft.join(o,a);if(_e.existsSync(c)){try{let l=_e.readFileSync(c,"utf-8"),u=Jy(l),d=Vy(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=ft.join(o,"template.yaml"),c=ft.join(o,"template.json");if(_e.existsSync(c))try{let l=_e.readFileSync(c,"utf-8"),u=JSON.parse(l),d=nf(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(_e.existsSync(a))try{let l=_e.readFileSync(a,"utf-8"),u=lu(l),d=nf(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??rt(o);this.pruneDeletedFiles(o,a);for(let c of a){let l;try{l=_e.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=_e.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)}}});function Wy(r,e){let t=[],n=[r];for(;n.length>0;){let s=n.pop(),i;try{i=wa.readdirSync(s,{withFileTypes:!0})}catch{continue}for(let o of i){let a=lf.join(s,o.name);o.isDirectory()?Gy.has(o.name)||n.push(a):o.isFile()&&e.test(o.name)&&t.push(a)}}return t}function Mi(r){return Wy(r,/\.java$/)}function _i(r){return wa.promises.readFile(r,"utf-8")}function du(r){let e=r.replace(/\\/g,"/");return/^[A-Z]:\//.test(e)&&(e=e[0].toLowerCase()+e.substring(1)),e}function pu(r){return r.replace(/\\/g,"/").split("/").pop()||""}function uf(r,e){let t=cf.get(e);if(t&&Date.now()-t.ts<Ky)return Promise.resolve(t.files);let n=new RegExp(`^${e}\\.java$`),s=Mi(r).filter(i=>n.test(pu(i)));return cf.set(e,{ts:Date.now(),files:s}),Promise.resolve(s)}var wa,lf,Gy,cf,Ky,Ra=E(()=>{"use strict";wa=I(require("fs")),lf=I(require("path")),Gy=new Set(["target","build","bin","out","dist","node_modules",".git",".svn",".hg",".gradle",".mvn",".idea",".vscode",".settings",".history","__pycache__"]);cf=new Map,Ky=3e4});function Qy(r){if(r.includes("/"))return r;if(sn[r])return sn[r];let e=`MediaType.${r}`;if(sn[e])return sn[e];for(let[s,i]of Object.entries(sn))if(s.endsWith(r))return i;let t=r.lastIndexOf(".");if(t>=0){let s=r.substring(t+1),i=`MediaType.${s}`;if(sn[i])return sn[i];let o=`MediaType.${s}_VALUE`;if(sn[o])return sn[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 Di(r){return r.map(Qy)}function on(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 Zy.has(t)?on(n.trim()):r}function Cs(r){return/MultipartFile/.test(r)}var sn,Zy,Ca=E(()=>{"use strict";sn={"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"};Zy=new Set(["HttpEntity","RequestEntity","ResponseEntity","Mono","Flux","Optional","CompletableFuture","DeferredResult","ListenableFuture","Callable"])});var hr,df=E(()=>{"use strict";Ra();Ca();hr=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 uf(this.projectRoot,a);if(u.length>1&&c){let m=/^\s*package\s+([\w.]+);/m;for(let f of u){let h=await _i(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 _i(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=on(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],x=g[1]||"";if(v&&y&&!/^(class|interface|enum|return|if|for|while|void)\b/.test(v)){let b=/\bstatic\b/.test(m),R=/\btransient\b/.test(m),C=[...d,m],q=C.join(" ");!b&&!R&&!/@JsonIgnore\b/.test(q)&&(x==="public"||l||u||/@JsonProperty\b/.test(q))&&n.push(this.parseFieldAnnotations(y,v,C))}}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(O=>O.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 x=this.extractAttr(s,"Schema","maxLength");x&&(i.maxLength=Number(x));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 R=this.extractAttr(s,"Size","min");R&&!i.minLength&&(i.minLength=Number(R));let C=this.extractAttr(s,"Size","max");C&&!i.maxLength&&(i.maxLength=Number(C));let q=this.extractAttr(s,"Min","value")||this.extractSingleArg(s,"Min");q&&i.minimum===void 0&&(i.minimum=Number(q));let _=this.extractAttr(s,"Max","value")||this.extractSingleArg(s,"Max");_&&i.maximum===void 0&&(i.maximum=Number(_));let M=this.extractAttr(s,"DecimalMin","value")||this.extractSingleArg(s,"DecimalMin");M&&i.minimum===void 0&&(i.minimum=Number(M));let D=this.extractAttr(s,"DecimalMax","value")||this.extractSingleArg(s,"DecimalMax");D&&i.maximum===void 0&&(i.maximum=Number(D)),/@Email\b/.test(s)&&(i.format=i.format||"email");let V=this.extractAttr(s,"Pattern","regexp");return V&&!i.pattern&&(i.pattern=V),/@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}}});function fu(r){let e=[],t=/:(\w+)|\{(\w+)\}/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]||n[2]);return e}var pf,Ea,ff=E(()=>{"use strict";pf=require("java-parser");Ca();Ea=class extends pf.BaseJavaCstVisitorWithDefaults{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=Di(f.map(h=>h.replace(/^['\"]|['\"]$/g,""))):typeof f=="string"&&(a=Di([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:fu(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,on(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 on(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 R=this.getAnnotationStringValue(b)||p;t.push(R),y=this.buildParameterMeta(R,"header",g,v,f);let C=b.attributes.get("required");y&&typeof C=="string"&&(C==="true"||C==="false")&&(y.required=C==="true")}else if(b.name==="RequestParam")if(Cs(g)){o=!0;let R=this.getAnnotationStringValue(b)||p;s.push({name:R,type:g,isFile:!0})}else{let R=this.getAnnotationStringValue(b)||p;n.push(R);let C=b.attributes.get("required");y=this.buildParameterMeta(R,"query",g,v,f),y&&typeof C=="string"&&(C==="true"||C==="false")&&(y.required=C==="true")}else if(b.name==="RequestBody")o=!0,g&&(a=on(g));else if(b.name==="RequestPart"){o=!0;let R=this.getAnnotationStringValue(b)||p,C=Cs(g);s.push({name:R,type:g,isFile:C})}else b.name==="ModelAttribute"&&(o=!0,g&&(c=g));let x=f.find(b=>b.name==="PathVariable");if(x){let b=this.getAnnotationStringValue(x)||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 hf={};Ot(hf,{EndpointParser:()=>mu});var mf,mu,gf=E(()=>{"use strict";mf=require("java-parser");Ra();Ca();ff();mu=class r{fileCache=new Map;generatedRe=/_[0-9a-zA-Z]+\.java$/;clearCache(){this.fileCache.clear()}evictPaths(e){let t=e.map(n=>du(n.trim()));for(let n of[...this.fileCache.keys()]){let s=du(n);t.some(i=>s.startsWith(i+"/"))&&this.fileCache.delete(n)}}async parseControllers(e){let t=Mi(e),n=[],s=new Set,i=[];for(let a of t)if(!this.generatedRe.test(pu(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 _i(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=(0,mf.parse)(e),n=new Ea;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="",x=o.get("RequestMapping");x!==void 0&&(y=this.extractPathFromArgs(x)),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),x=[];g&&x.push({name:g[1],args:g[2]||""});for(let b of i)/Mapping$/.test(b)&&(!g||b!==g[1])&&x.push({name:b,args:o.get(b)||""});for(let b of x){let R=b.name.replace("Mapping","").toUpperCase();R==="REQUEST"&&(R="");let C="",q=[],_=b.args;if(_){C=this.extractPathFromArgs(_);let V=/consumes\s*=\s*\{?\s*([^}]*)\}?/.exec(_);if(V){let O=V[1],H=[...O.matchAll(/["']([^"']+)["']/g)].map(X=>X[1]),Z=[...O.matchAll(/MediaType\.([A-Z_]+)/g)].map(X=>`MediaType.${X[1]}`);q=Di([...H,...Z])}if(b.name==="RequestMapping"){let O=/method\s*=\s*(?:\{?\s*)?RequestMethod\.([A-Z]+)/.exec(_);O&&(R=O[1])}}!R&&b.name==="RequestMapping"&&(R="GET");let M=C;a.basePath&&(M&&!M.startsWith("/")?M=a.basePath+"/"+M:M=a.basePath+M),M&&!M.startsWith("/")&&(M="/"+M);let D=this.extractParameterMetadataFromSig(y);a.endpoints.push({method:R,path:M,file:t,line:u+1,pathParams:fu(M),consumes:q,bodyType:D.bodyType,headers:D.headers,queryParams:D.queryParams,hasBody:D.hasBody,formParts:D.formParts.length>0?D.formParts:void 0,modelAttributeType:D.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(Cs(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=on(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=Cs(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)})}}});function ev(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 Aa,yf,Yy,Xy,gr,hu=E(()=>{"use strict";Aa=I(require("fs")),yf=I(require("path"));Ra();df();Yy=["pom.xml","build.gradle","build.gradle.kts","settings.gradle"],Xy=/@(?:RestController|Controller)\b/,gr=class{id="provider.spring";framework="spring";parserModule;supports(e){for(let s of Yy)if(Aa.existsSync(yf.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=Mi(e.projectRoot));let n=0;for(let s of t)if(s.endsWith(".java")){if(n>=40)break;n+=1;try{let i=Aa.readFileSync(s,"utf-8");if(Xy.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 hr(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(()=>(gf(),hf))),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:ev(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=hr.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=hr.javaTypeToParamType(e.schemaType);let n=hr.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"}}}});function gu(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=Pa.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=wf.join(n,i.name);if(i.isDirectory()){tv.has(i.name)||t.push(o);continue}i.isFile()&&o.endsWith(".py")&&e.push(o)}}return e.sort()}function Rf(r){let e=gu(r),t=new Map,n=new Map,s=new Map,i=[];for(let u of e){let d="";try{d=Pa.readFileSync(u,"utf-8")}catch{continue}let p=rv(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=bf(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=bf(d.imports,m.object),h=d.appNames.has(m.object)||d.appNames.has(f),g=s.get(f);if(!h&&!g)continue;let v=cv(m.method,m.args);if(v.length===0)continue;let y=lv(m.args),x=m.unresolved||y.startsWith("f"),b=g?o.get(f)??[g.constructorPrefix]:[""];for(let R of b){if(g&&c.has(f)&&R===g.constructorPrefix)continue;let C=g?gv(R,y):y,q=yv(p.signature,hv(C)),_=g?a.get(f):void 0,D=Cf(m.args)??_;l.push({methods:v,path:C,file:u,line:m.line,functionName:p.functionName,statusCode:uv(m.args),responseModel:dv(m.args)??ov(p.signature),tags:D,deprecated:pv(m.args),summary:fv(m.args),params:q.params,security:mv(m.args,p.signature),pathUnresolved:x})}}return{endpoints:l,models:t,warnings:i}}function bf(r,e){let t=r.find(n=>n.alias===e);return t?t.target:e}function an(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 an(n[1],e);let s=/^Union\[(.+)\]$/.exec(t);if(s){let l=s[1].split(",").map(u=>u.trim())[0];return an(l,e)}let i=/^(?:List|list|Sequence)\[(.+)\]$/.exec(t);if(i)return{type:"array",items:an(i[1],e)??{type:"object"}};let o=/^(?:Dict|dict)\[([^,]+),\s*(.+)\]$/.exec(t);if(o)return{type:"object",additionalProperties:an(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=an(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 rv(r,e,t){let n={routes:[],appNames:new Set,routers:[],includes:[],imports:[]},i=Sv(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 x=y.trim();if(!x)continue;let b=/^([\w.]+)\s+as\s+(\w+)$/.exec(x);if(b)n.imports.push({alias:b[2],target:b[1].split(".").pop()});else if(/^[\w.]+$/.test(x)){let R=x.split(".").pop();n.imports.push({alias:R,target:R})}}o=[];continue}if(u.startsWith("@")){let{joined:v,nextIndex:y}=qa(i,a-1),x=av(v,l);x&&o.push(x),a=y+1;continue}let p=/^(?:async\s+)?def\s+(\w+)\s*\(/.exec(u);if(p){let{joined:v,nextIndex:y}=qa(i,a-1),x=v.slice(v.indexOf("(")),b=iv(i,a-1,x);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}=sv(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}=qa(i,a-1),y=v.slice(v.indexOf("("));n.routers.push({name:h[1],constructorPrefix:xf(y)}),o=[];continue}let g=/^(\w+)\.include_router\(\s*(\w+)(.*)$/.exec(u);if(g){let{joined:v}=qa(i,a-1),y=v.slice(v.indexOf("("));n.includes.push({object:g[1],routerName:g[2],prefix:xf(y),tags:Cf(y),line:l}),o=[];continue}o=[]}return n}function sv(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 qa(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+=`
508
- `+a}return{joined:n,nextIndex:s}}function iv(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+=`
509
- `+l}let c=Sf(i);if(c!==-1)return i.slice(0,c);for(;o+1<r.length;){o+=1;let l=r[o],u=Sf(l);if(u!==-1){i+=`
506
+ `)||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:[S.generateIterationData],handle({args:r,services:e,collections:t}){let n=G(r.collection,t),s=Xt(e,n.id,Ue(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(p=>p.enabled!==!1).map(p=>({key:p.key,value:p.value})),c=(s.query??[]).filter(p=>p.enabled!==!1).map(p=>({key:p.key,value:p.value})),l=/\{\{([^}]+)\}\}/g,u=new Set;for(let p of[s.url??"",o??"",...a.map(d=>d.value),...c.map(d=>d.value)]){let d;for(l.lastIndex=0;(d=l.exec(p))!==null;)u.add(d[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:Xe(s,Cp(n,s)).snapshot().body||void 0,body:o??null,headers:a,queryParams:c,placeholders:[...u],iterations:i}}}}]});function Ap(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=Ap(n.items??[],e);if(s)return s}}var Pp,kp=E(()=>{"use strict";Me();_e();_e();Pp=[{toolNames:[S.createCollection],async handle({args:r,services:e}){let t=typeof r.name=="string"?r.name.trim():"";if(!t)throw T('"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:[S.renameCollection],async handle({args:r,services:e,collections:t}){let n=G(r.collection,t),s=typeof r.newName=="string"?r.newName.trim():"";if(!s)throw T('"newName" is required');return await e.collection.renameCollection(n.id,s),{id:n.id,oldName:n.name,newName:s,renamed:!0}}},{toolNames:[S.deleteCollection],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw T('"confirm" must be true to delete a collection');let n=G(r.collection,t);return await e.collection.deleteCollection(n.id),{deleted:!0,collection:n.name}}},{toolNames:[S.duplicateCollection],async handle({args:r,services:e,collections:t}){let n=G(r.collection,t),s=typeof r.newName=="string"?r.newName.trim():"";if(!s)throw T('"newName" is required');let i=await e.collection.duplicateCollection(n.id,s);return{id:i.id,name:i.name,duplicatedFrom:n.name}}},{toolNames:[S.createFolder],async handle({args:r,services:e,collections:t}){let n=G(r.collection,t),s=typeof r.name=="string"?r.name.trim():"";if(!s)throw T('"name" is required');let i;if(typeof r.parentFolder=="string"&&r.parentFolder.trim()){let a=r.parentFolder.toLowerCase(),c=Ce(n);if(Q(n).map(u=>u.folderPath)&&c.find(u=>u.folderPath===r.parentFolder||u.folderPath.toLowerCase()===a)){let p=Ce(n).find(d=>d.folderPath===r.parentFolder||d.folderPath.toLowerCase()===a);if(p){let d=n.items;i=Ap(d,p.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:[S.deleteFolder],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw T('"confirm" must be true to delete a folder');let n=G(r.collection,t);if(typeof r.folder!="string"||!r.folder.trim())throw T('"folder" is required');let s=r.folder.toLowerCase(),i=Ce(n).find(c=>c.folderPath===r.folder||c.folderPath.toLowerCase()===s);if(!i)throw T(`folder "${r.folder}" not found in collection "${n.name}"`);let o=Ql(n.items,i.folderId);if(!o)throw T(`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 Xl=E(()=>{"use strict"});var Ip=E(()=>{"use strict"});var Rt,vs,Vg,zg,Jg,dr,da=E(()=>{"use strict";Rt=I(require("fs")),vs=I(require("path")),Vg=["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"],zg={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:[]},Jg={express:[".ts",".js"],nestjs:[".ts",".js"],fastify:[".ts",".js"],lambda:[".ts",".js"],spring:[".java"],fastapi:[".py"]},dr=class{buildFingerprint(e){let t=[],n=vs.join(e,"package.json"),s;for(let i of Vg){let o=vs.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(vs.join(e.projectRoot,t))}hasSourceHint(e,t){let n=["src","app"],s=zg[t],i=Jg[t],o=0,a=120;for(let c of n){let l=vs.join(e.projectRoot,c);if(!Rt.existsSync(l))continue;let u=[l];for(;u.length>0&&o<a;){let p=u.shift(),d;try{d=Rt.readdirSync(p,{withFileTypes:!0})}catch{continue}for(let m of d){let f=vs.join(p,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}}});function nt(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=Tp.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=Op.join(n,i.name);if(i.isDirectory()){Gg.has(i.name)||t.push(o);continue}i.isFile()&&(Wg.test(i.name)||(o.endsWith(".ts")||o.endsWith(".js"))&&e.push(o))}}return e}var Tp,Op,Gg,Wg,qn=E(()=>{"use strict";Tp=I(require("fs")),Op=I(require("path")),Gg=new Set(["node_modules",".git",".next","dist","build","out","coverage","__tests__","__mocks__","__fixtures__"]),Wg=/\.(?:test|spec|stories|min)\.[cm]?[tj]sx?$|\.d\.[cm]?ts$/});function Oi(r,e){let t=e.customSeedLoaderModulePath?.trim();if(!t)return{endpoints:[],warnings:[]};let n=pa.isAbsolute(t)?t:pa.join(r,t);if(!$p.existsSync(n))return{endpoints:[],warnings:[{code:"seed-loader-failed",filePath:n,message:`Custom seed loader module not found: ${n}`}]};try{let s=require(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 $p,pa,fa=E(()=>{"use strict";$p=I(require("fs")),pa=I(require("path"))});function eu(r,e){let t=r.projectName?.trim();if(t)return t;let n=Fp(r.source.filePath),s=Kg(n);if(s)return s;let i;for(let a of e){let c=Fp(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 Kg(r){return r.match(/(?:^|\/)agl-config-([^/]+)(?:\/|$)/)?.[1]}function Fp(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var tu=E(()=>{"use strict"});function en(r,e){return r==="high"&&e==="high"?"high":r==="low"||e==="low"?"low":"medium"}function tn(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 $i(r,e,t,n,s={visitedSymbols:new Set},i,o=["locals"]){let a=[],c=[],l=[],u,p=new Map,d=py(o),m=uy(r,e,d),f=gy(r,e,d);if(i?.requestAliases)for(let R of i.requestAliases)m.add(R);if(i?.responseAliases)for(let R of i.responseAliases)f.add(R);let h=Hp(e),g=Qg(e,t),v=dy(r,t,h,g,m,f),y=(R,q)=>{let N=l.find(M=>M.statusCode===R);return N||(N={statusCode:R},l.push(N)),q&&(N.body={type:q,schema:N.body?.schema}),N};w.isFunctionLike(r)&&cy(r,e,p,m,f,d);let x=(R,q)=>{let N=h.get(R);if(N){let Z=`${t}:${R}`;if(s.visitedSymbols.has(Z))return;s.visitedSymbols.add(Z);let X=v.get(Z),Je=q?ya(q,N,m,f):void 0,ln=Lp(X,Je),kt=$i(N,e,t,n,s,ln,o);ru({parameters:a,requestBody:u,cookies:c,responses:l},kt),!u&&kt.requestBody&&(u=kt.requestBody);return}let M=g.get(R);if(!M||s.visitedSymbols.has(M.symbolKey))return;s.visitedSymbols.add(M.symbolKey);let _=v.get(M.symbolKey),H=q?ya(q,M.node,m,f):void 0,O=Lp(_,H),L=$i(M.node,M.sourceFile,M.filePath,n,s,O,o);ru({parameters:a,requestBody:u,cookies:c,responses:l},L),!u&&L.requestBody&&(u=L.requestBody)},b=["POST","PUT","PATCH"].includes(n),C=R=>{w.isVariableDeclaration(R)&&ay(R,e,p,m,f,d),w.isIdentifier(R)&&(w.isCallExpression(R.parent)&&R.parent.expression===R||x(R.text));let q=bs(R,e,"query",p,m,f,d);if(q){let O=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:q.path,location:"query",type:ha(R,e),detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}let N=bs(R,e,"params",p,m,f,d);if(N){let O=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:N.path,location:"path",required:!0,type:ha(R,e),detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}if(oy(R,e,m)&&!u){let O=e.getLineAndCharacterOfPosition(R.getStart(e));u={type:"json",required:b,detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}}}let M=bs(R,e,"body",p,m,f,d);if(M){let O=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:M.path,location:"body",type:ha(R,e),detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}}),u||(u={type:"json",required:b})}let _=bs(R,e,"headers",p,m,f,d);if(_){let O=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:_.path,location:"header",type:"string",detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}let H=bs(R,e,"cookies",p,m,f,d);if(H){let O=e.getLineAndCharacterOfPosition(R.getStart(e));c.push({name:H.path,type:"request",detectionLocation:{filePath:t,line:O.line+1,column:O.character+1,accessMode:"read"}})}for(let O of d){let L=bs(R,e,O,p,m,f,d);if(!L)continue;let Z=e.getLineAndCharacterOfPosition(R.getStart(e));a.push({name:L.path,location:O,type:ha(R,e),detectionLocation:{filePath:t,line:Z.line+1,column:Z.character+1,accessMode:"read"}})}if(w.isCallExpression(R)){let O=fy(R,e,f);O&&y(O.statusCode,O.bodyType)}if(w.isCallExpression(R)){let O=my(R,f);if(O){let L=y(O.statusCode);if(!L.headers?.some(Z=>Z.name===O.headerName)){let Z=e.getLineAndCharacterOfPosition(R.getStart(e));L.headers=L.headers??[],L.headers.push({name:O.headerName,location:"header",type:"string",detectionLocation:{filePath:t,line:Z.line+1,column:Z.character+1,accessMode:"write"}})}}}if(w.isCallExpression(R)&&w.isPropertyAccessExpression(R.expression)&&yy(R.expression.expression,f)&&R.expression.name.text==="cookie"&&R.arguments[0]&&w.isStringLiteral(R.arguments[0])){let O=R.arguments[0].text;if(O&&!c.some(L=>L.name===O&&L.type==="response")){let L=e.getLineAndCharacterOfPosition(R.getStart(e));c.push({name:O,type:"response",httpOnly:!0,detectionLocation:{filePath:t,line:L.line+1,column:L.character+1,accessMode:"write"}})}}w.isCallExpression(R)&&w.isIdentifier(R.expression)&&x(R.expression.text,R),w.forEachChild(R,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 Ss(r,e,t,n,s=["locals"]){let i={parameters:[],requestBody:void 0,cookies:[],responses:[]};for(let o of r){let a=$i(o,e,t,n,void 0,void 0,s);ru(i,a)}return i.parameters=nn(i.parameters),i.cookies=iy(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 Hp(r){let e=new Map,t=n=>{w.isFunctionDeclaration(n)&&n.name&&e.set(n.name.text,n),w.isVariableDeclaration(n)&&w.isIdentifier(n.name)&&n.initializer&&(w.isArrowFunction(n.initializer)||w.isFunctionExpression(n.initializer))&&e.set(n.name.text,n.initializer),w.forEachChild(n,t)};return t(r),e}function Qg(r,e){let t=new Map,n=(s,i)=>{if(!s.startsWith("."))return;let o=Yg(e,s);if(!o)return;let a=Zg(o);if(!a)return;let c=Xg(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(w.isImportDeclaration(s)&&s.importClause&&w.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&&w.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(w.isVariableStatement(s))for(let i of s.declarationList.declarations){if(!i.initializer||!w.isCallExpression(i.initializer)||!w.isIdentifier(i.initializer.expression)||i.initializer.expression.text!=="require")continue;let o=i.initializer.arguments[0];if(!o||!w.isStringLiteral(o))continue;let a=o.text,c=[];if(w.isIdentifier(i.name))c.push({localName:i.name.text,importedName:"default"});else if(w.isObjectBindingPattern(i.name))for(let l of i.name.elements){if(!w.isIdentifier(l.name))continue;let u=l.propertyName&&(w.isIdentifier(l.propertyName)||w.isStringLiteral(l.propertyName))?l.propertyName.text:l.name.text;c.push({localName:l.name.text,importedName:u})}n(a,c)}}return t}function Zg(r){let e="";try{e=va.readFileSync(r,"utf-8")}catch{return}return w.createSourceFile(r,e,w.ScriptTarget.Latest,!0,r.endsWith(".ts")?w.ScriptKind.TS:w.ScriptKind.JS)}function Yg(r,e){let t=fr.resolve(fr.dirname(r),e),n=[t,`${t}.ts`,`${t}.js`,fr.join(t,"index.ts"),fr.join(t,"index.js")];for(let s of n)try{if(va.statSync(s).isFile())return s}catch{continue}}function Xg(r,e){let t=new Map,n=Hp(r),s=(i,o)=>{t.set(i,o)};for(let i of r.statements){if(w.isFunctionDeclaration(i)&&i.name&&Np(i)){s(i.name.text,i),Mp(i)&&s("default",i);continue}if(w.isVariableStatement(i)&&Np(i)){for(let c of i.declarationList.declarations)!w.isIdentifier(c.name)||!c.initializer||(w.isArrowFunction(c.initializer)||w.isFunctionExpression(c.initializer))&&(s(c.name.text,c.initializer),Mp(i)&&s("default",c.initializer));continue}if(w.isExportAssignment(i)){let c=i.expression;if(w.isIdentifier(c)){let l=n.get(c.text);l&&s("default",l)}else(w.isFunctionExpression(c)||w.isArrowFunction(c))&&s("default",c);continue}if(!w.isExpressionStatement(i)||!w.isBinaryExpression(i.expression))continue;let o=i.expression.left,a=i.expression.right;if(w.isPropertyAccessExpression(o)&&o.expression.getText(r)==="module.exports"){let c=o.name.text,l=nu(a,n);l&&s(c,l);continue}if(o.getText(r)==="module.exports"){let c=nu(a,n);c&&s("default",c);continue}if(w.isPropertyAccessExpression(o)&&o.expression.getText(r)==="exports"){let c=nu(a,n);c&&s(o.name.text,c)}}return t}function nu(r,e){if(w.isFunctionExpression(r)||w.isArrowFunction(r))return r;if(w.isIdentifier(r))return e.get(r.text)}function Np(r){return w.canHaveModifiers(r)?!!w.getModifiers(r)?.some(e=>e.kind===w.SyntaxKind.ExportKeyword):!1}function Mp(r){return w.canHaveModifiers(r)?!!w.getModifiers(r)?.some(e=>e.kind===w.SyntaxKind.DefaultKeyword):!1}function ru(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=nn([...s,...i])}}function nn(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:_p([],i)});continue}if(a.required=!!(a.required||i.required),a.evidenceLocations=_p(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=>ey(i)),n=t.filter(i=>i.location==="body"),s=new Map(n.map(i=>[i.name,i]));for(let i of[...n]){let o=ma(i.name);for(;o;){if(!s.has(o)){let a={name:o,location:"body",type:"object"};s.set(o,a),t.push(a)}o=ma(o)}}for(let i of s.values()){let o=ma(i.name);for(;o;){let a=s.get(o);a&&(a.type="object"),o=ma(o)}}return t}function _p(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 ey(r){let e=ry([...r.detectionLocation?[r.detectionLocation]:[],...r.evidenceLocations??[]]);if(e.length===0)return{...r,detectionLocation:void 0,evidenceLocations:void 0};let t=ty(e),n=e.filter(s=>!sy(s,t));return{...r,detectionLocation:t,evidenceLocations:n.length>0?n:void 0}}function ty(r){return[...r].sort(ny)[0]}function ny(r,e){let t=Dp(r),n=Dp(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 Dp(r){let e=0;return r.accessMode&&(e+=8),r.symbolName&&(e+=4),typeof r.column=="number"&&(e+=2),e}function ry(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 sy(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 iy(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 oy(r,e,t){return w.isPropertyAccessExpression(r)&&w.isIdentifier(r.expression)&&t.has(r.expression.text)&&r.name.text==="body"}function bs(r,e,t,n,s,i,o){return iu(r,e,t,n,!1,s,i,o)}function iu(r,e,t,n,s,i,o,a){let c=[],l=r;for(;l&&(w.isPropertyAccessExpression(l)||w.isElementAccessExpression(l)||w.isPropertyAccessChain(l)||w.isElementAccessChain(l));){if(w.isPropertyAccessExpression(l)||w.isPropertyAccessChain(l)){c.unshift(l.name.text),l=l.expression;continue}if(w.isElementAccessExpression(l)||w.isElementAccessChain(l)){let h=l.argumentExpression;if(h&&(w.isStringLiteral(h)||w.isNumericLiteral(h))){let g=h.text;w.isNumericLiteral(h)||/^\d+$/.test(g)?c.unshift("[]"):c.unshift(g)}else return;l=l.expression}}let u=c.indexOf(t),d=a?.has(t)??!1?l&&w.isIdentifier(l)&&((o?.has(l.text)??!1)||(i?.has(l.text)??!1)):l&&w.isIdentifier(l)&&i?.has(l.text)===!0;if(u!==-1&&d){let h=c.slice(u+1);return h.length===0?s?{path:""}:void 0:{path:ga(h)}}if(!l||!w.isIdentifier(l)||!n)return;let m=n.get(l.text);if(!m||m.target!==t)return;let f=ga(c);return m.path?f?{path:`${m.path}.${f}`}:{path:m.path}:f?{path:f}:s?{path:""}:void 0}function ay(r,e,t,n,s,i){let o=r.initializer;if(!o)return;w.isIdentifier(o)&&n.has(o.text)&&w.isIdentifier(r.name)&&n.add(r.name.text),w.isIdentifier(o)&&s.has(o.text)&&w.isIdentifier(r.name)&&s.add(r.name.text);let a=["body","query","params","headers","cookies",...i],c,l="";for(let u of a){let p=iu(o,e,u,t,!0,n,s,i);if(p){c=u,l=p.path;break}}if(c){if(w.isIdentifier(r.name)){t.set(r.name.text,{target:c,path:l});return}(w.isObjectBindingPattern(r.name)||w.isArrayBindingPattern(r.name))&&Fi(r.name,c,l,t)}}function cy(r,e,t,n,s,i){let o=["body","query","params","headers","cookies",...i];for(let a of r.parameters){if((w.isObjectBindingPattern(a.name)||w.isArrayBindingPattern(a.name))&&!a.initializer){ly(a.name,t,i);continue}let c=a.initializer;if(!c)continue;let l,u="";for(let p of o){let d=iu(c,e,p,t,!0,n,s,i);if(d){l=p,u=d.path;break}}if(l){if(w.isIdentifier(a.name)){t.set(a.name.text,{target:l,path:u});continue}(w.isObjectBindingPattern(a.name)||w.isArrayBindingPattern(a.name))&&Fi(a.name,l,u,t)}}}function ly(r,e,t){if(!w.isObjectBindingPattern(r))return;let n=new Set(["body","query","params","headers","cookies",...t]);for(let s of r.elements){let i=su(s);if(!i||!n.has(i))continue;let o=i;if(w.isIdentifier(s.name)){e.set(s.name.text,{target:o,path:""});continue}(w.isObjectBindingPattern(s.name)||w.isArrayBindingPattern(s.name))&&Fi(s.name,o,"",e)}}function uy(r,e,t){let n=new Set,s=new Set(["query","params","body","headers","cookies",...t]),i=o=>{if(w.isPropertyAccessExpression(o)||w.isPropertyAccessChain(o)){let a=o.name.text;if(s.has(a)){let c=pr(o.expression);c&&n.add(c)}}if(w.isElementAccessExpression(o)||w.isElementAccessChain(o)){let a=o.argumentExpression;if(a&&w.isStringLiteral(a)&&s.has(a.text)){let c=pr(o.expression);c&&n.add(c)}}w.isVariableDeclaration(o)&&o.initializer&&w.isIdentifier(o.name)&&w.isIdentifier(o.initializer)&&n.has(o.initializer.text)&&n.add(o.name.text),w.forEachChild(o,i)};return i(r),n}function Fi(r,e,t,n){if(w.isObjectBindingPattern(r)){for(let s of r.elements){let i=su(s);if(!i)continue;let o=jp(t,i);if(w.isIdentifier(s.name)){n.set(s.name.text,{target:e,path:o});continue}(w.isObjectBindingPattern(s.name)||w.isArrayBindingPattern(s.name))&&Fi(s.name,e,o,n)}return}for(let s of r.elements){if(!w.isBindingElement(s))continue;let i=su(s)??"[]",o=jp(t,/^\d+$/.test(i)?"[]":i);if(w.isIdentifier(s.name)){n.set(s.name.text,{target:e,path:o});continue}(w.isObjectBindingPattern(s.name)||w.isArrayBindingPattern(s.name))&&Fi(s.name,e,o,n)}}function su(r){let e=r.propertyName;if(!e)return w.isIdentifier(r.name)?r.name.text:void 0;if(w.isIdentifier(e)||w.isStringLiteral(e)||w.isNumericLiteral(e))return e.text}function jp(r,e){return ga(r?`${r}.${e}`.split("."):[e])}function ga(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 ma(r){let e=r.lastIndexOf(".");if(!(e<=0))return r.slice(0,e)}function dy(r,e,t,n,s,i){let o=new Map,a=(l,u)=>{let p=o.get(l);if(!p){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(!p.requestAliases)p.requestAliases=new Set(u.requestAliases);else for(let d of u.requestAliases)p.requestAliases.add(d);if(u.responseAliases)if(!p.responseAliases)p.responseAliases=new Set(u.responseAliases);else for(let d of u.responseAliases)p.responseAliases.add(d)},c=l=>{if(w.isCallExpression(l)&&w.isIdentifier(l.expression)){let u=l.expression.text,p=t.get(u);if(p){let m=ya(l,p,s,i);m&&a(`${e}:${u}`,m)}let d=n.get(u);if(d){let m=ya(l,d.node,s,i);m&&a(d.symbolKey,m)}}w.forEachChild(l,c)};return c(r),o}function Lp(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 py(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 ya(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(!w.isIdentifier(c.name))continue;let l=r.arguments[a],u=pr(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 ha(r,e){if(!r||!r.parent)return"string";if(w.isCallExpression(r.parent)&&w.isIdentifier(r.parent.expression)){let t=r.parent.expression.text;if(t==="parseInt"||t==="parseFloat")return"number"}if(w.isBinaryExpression(r.parent)&&(r.parent.operatorToken.kind===w.SyntaxKind.EqualsEqualsToken||r.parent.operatorToken.kind===w.SyntaxKind.EqualsEqualsEqualsToken)){let t=r.parent.left===r?r.parent.right:r.parent.left;if(w.isNumericLiteral(t))return"number"}return"string"}function fy(r,e,t){let n=r.expression;if(!w.isPropertyAccessExpression(n))return;let s=n.name.text;if(s!=="json"&&s!=="send")return;let i=Bp(r,t);if(i)return{statusCode:i.statusCode,bodyType:s==="json"?"json":hy(r.arguments[0])}}function my(r,e){let t=r.expression;if(!w.isPropertyAccessExpression(t))return;let n=t.name.text;if(n!=="header"&&n!=="set")return;let s=r.arguments[0];if(!s||!w.isStringLiteral(s))return;let i=Bp(r,e);if(i)return{statusCode:i.statusCode,headerName:s.text}}function Bp(r,e){if(!w.isPropertyAccessExpression(r.expression))return;let t=200,n=r.expression.expression;for(;;){if(w.isIdentifier(n)&&e.has(n.text))return{receiver:n.text,statusCode:t};if(!w.isCallExpression(n)||!w.isPropertyAccessExpression(n.expression))return;let s=n.expression.name.text;if(s==="status"||s==="code"){let i=n.arguments[0];i&&w.isNumericLiteral(i)&&(t=Number(i.text))}n=n.expression.expression}}function hy(r){return r&&(w.isObjectLiteralExpression(r)||w.isArrayLiteralExpression(r))?"json":"text"}function gy(r,e,t){let n=new Set,s=new Set(["status","code","json","send","header","set","cookie"]),i=new Set(t),o=a=>{if(w.isPropertyAccessExpression(a)||w.isPropertyAccessChain(a)){let c=a.name.text;if(i.has(c)){let l=pr(a.expression);l&&n.add(l)}}if(w.isElementAccessExpression(a)||w.isElementAccessChain(a)){let c=a.argumentExpression;if(c&&w.isStringLiteral(c)&&i.has(c.text)){let l=pr(a.expression);l&&n.add(l)}}if(w.isCallExpression(a)&&w.isPropertyAccessExpression(a.expression)){let c=a.expression.name.text;if(s.has(c)){let l=pr(a.expression.expression);l&&n.add(l)}}w.isVariableDeclaration(a)&&a.initializer&&w.isIdentifier(a.name)&&w.isIdentifier(a.initializer)&&n.has(a.initializer.text)&&n.add(a.name.text),w.forEachChild(a,o)};return o(r),n}function yy(r,e){let t=pr(r);return t?e.has(t):!1}function pr(r){let e=r;for(;;){if(w.isIdentifier(e))return e.text;if(w.isPropertyAccessExpression(e)||w.isPropertyAccessChain(e)){e=e.expression;continue}if(w.isElementAccessExpression(e)||w.isElementAccessChain(e)){e=e.expression;continue}if(w.isCallExpression(e)&&w.isPropertyAccessExpression(e.expression)){e=e.expression.expression;continue}return}}var va,fr,w,ba=E(()=>{"use strict";va=I(require("fs")),fr=I(require("path")),w=I(require("typescript"))});function xs(r,e,t){let n={},s=o=>{if(fe.isVariableDeclaration(o)&&fe.isIdentifier(o.name)&&o.initializer){let a=An(o.initializer,r,{variables:n});a!==void 0&&(n[o.name.text]=a)}fe.forEachChild(o,s)};s(r);let i={...by(e),...t};return{variables:n,env:i}}function Ct(r,e,t){if(!r)return{pathExpression:"/",resolvedPath:"/",confidence:"high"};let n=An(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=vy(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 rn(r,e){let t=Up(r??""),n=Up(e??""),s=Vp(`${t}/${n}`);return(r??"").includes("${")||(e??"").includes("${")?{pathExpression:s}:{pathExpression:s,resolvedPath:s}}function Up(r){return r?r.replace(/^['"`]/,"").replace(/['"`]$/,"").replace(/^\/+/,"").replace(/\/+$/,""):""}function Vp(r){let e=r.replace(/\/{2,}/g,"/").replace(/\/$/,"");return!e||e==="/"?"/":e.startsWith("/")?e:`/${e}`}function An(r,e,t){if(fe.isStringLiteral(r)||fe.isNoSubstitutionTemplateLiteral(r))return r.text;if(fe.isParenthesizedExpression(r))return An(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=An(r.left,e,t),s=An(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 An(r.left,e,t)??An(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 vy(r,e,t){let n=[r.head.text],s=!0;for(let o of r.templateSpans){let a=An(o.expression,e,t);a===void 0?(s=!1,n.push("${...}")):n.push(a),n.push(o.literal.text)}let i=s?Vp(n.join("")):void 0;return{pathExpression:r.getText(e),resolvedPath:i,confidence:s?"high":"medium"}}function by(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=require("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 fe,Sa=E(()=>{"use strict";fe=I(require("typescript"))});function zp(r){return{get:"GET",post:"POST",put:"PUT",delete:"DELETE",patch:"PATCH",options:"OPTIONS",head:"HEAD",all:"ALL"}[r]}function Sy(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 xy(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 p=rn(u.pathExpression,a.prefix.pathExpression),d=en(u.confidence,a.prefix.confidence),m={pathExpression:p.pathExpression,resolvedPath:u.resolvedPath&&a.prefix.resolvedPath?p.resolvedPath:void 0,confidence:d,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 wy(r){return le.isStringLiteral(r)||le.isNoSubstitutionTemplateLiteral(r)||le.isTemplateExpression(r)}function Ry(r){if(le.isStringLiteral(r)||le.isNoSubstitutionTemplateLiteral(r))return r.text}function Cy(r,e,t,n){let s=new Set(tn(n).map(a=>a.name));if(s.size===0)return[];let i=Ey(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 Ey(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 le,ws,Jp=E(()=>{"use strict";le=I(require("typescript"));Sa();ba();ws=class{async analyzeFile(e,t,n,s){let i=le.createSourceFile(e,t,le.ScriptTarget.Latest,!0,e.endsWith(".ts")?le.ScriptKind.TS:le.ScriptKind.JS),o=new Set(["app","router"]),a=[],c=[],l=new Map,u=new Map,p=xs(i,n.projectRoot,s.envOverrides),d=g=>{if(le.isVariableDeclaration(g)&&le.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)}le.forEachChild(g,d)};d(i);let m=g=>{if(le.isCallExpression(g)&&le.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&&le.isIdentifier(b)&&o.has(b.text)&&le.isIdentifier(b)){let R=Ct(g.arguments[0],i,p);a.push({parent:v,child:b.text,prefix:R,middlewareNodes:g.arguments.slice(1,-1)})}else{let R=wy(g.arguments[0])?g.arguments.slice(1):g.arguments.slice(0),q=l.get(v)??[];q.push(...R),l.set(v,q)}}if(y==="param"&&g.arguments.length>=2&&o.has(v)){let b=Ry(g.arguments[0]),C=g.arguments[1];if(b&&C&&le.isExpression(C)){let R=u.get(v)??[];R.push({paramName:b,node:C}),u.set(v,R)}}let x=zp(y);if(x&&o.has(v)&&g.arguments.length>=1){let b=Ct(g.arguments[0],i,p),C=Sy(g.arguments,i),R=g.arguments[g.arguments.length-1],q=i.getLineAndCharacterOfPosition(R.getStart(i));c.push({owner:v,method:x,pathExpression:b.pathExpression,resolvedPath:b.resolvedPath,confidence:b.confidence,middleware:C,middlewareNodes:g.arguments.slice(1,-1),handlerNode:R,source:{filePath:e,line:q.line+1,column:q.character+1,symbolName:R.getText(i)}})}if(y==="route"&&g.arguments[0]){let b=Ct(g.arguments[0],i,p),C=g.parent;if(le.isCallExpression(C)&&le.isPropertyAccessExpression(C.expression)){let R=zp(C.expression.name.text);if(R){let q=C.arguments[0]??g.arguments[0],N=i.getLineAndCharacterOfPosition(q.getStart(i));c.push({owner:v,method:R,pathExpression:b.pathExpression,resolvedPath:b.resolvedPath,confidence:b.confidence,middleware:[],middlewareNodes:[],handlerNode:q,source:{filePath:e,line:N.line+1,column:N.character+1,symbolName:q.getText(i)}})}}}}le.forEachChild(g,m)};m(i);let f=[],h=xy(a);for(let g of c){let v=h.get(g.owner)??[],y=v.length>0?v:[{pathExpression:"",confidence:"high",middlewareNodes:[]}];for(let x of y){let b=rn(x.pathExpression,g.pathExpression),C=en(x.confidence,g.confidence),R=!!b.resolvedPath,q=tn(b.pathExpression),N=l.get(g.owner)??[],M=Cy(g.owner,a,u,b.pathExpression),_=[...x.middlewareNodes,...N,...M,...g.middlewareNodes,g.handlerNode],H=Ss(_,i,e,g.method,s.contextProperties);H.parameters.unshift(...q),H.parameters=nn(H.parameters),f.push({id:"",method:g.method,framework:"express",pathExpression:b.pathExpression,resolvedPath:C==="high"&&R?b.resolvedPath:void 0,confidence:C,source:g.source,middleware:g.middleware,params:H.parameters.length>0?H.parameters:void 0,requestBody:H.requestBody,cookies:H.cookies.length>0?H.cookies:void 0,responses:H.responses})}}return f}}});function qy(r,e,t,n,s,i){let o=r.arguments[0],a=r.arguments[1],c=Ay(a,e,i),l=c?n.map(u=>{let p=rn(u.pathExpression,c.pathExpression);return{pathExpression:p.pathExpression,resolvedPath:u.resolvedPath&&c.resolvedPath?p.resolvedPath:void 0,confidence:en(u.confidence,c.confidence)}}):n;if(F.isArrowFunction(o)||F.isFunctionExpression(o)){let u=new Set(t),p=o.parameters[0];p&&F.isIdentifier(p.name)&&u.add(p.name.text),o.body&&F.forEachChild(o.body,d=>s(d,u,l))}}function Ay(r,e,t){if(!r||!F.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 Py(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(!F.isPropertyAssignment(t))continue;if((F.isIdentifier(t.name)||F.isStringLiteral(t.name)?t.name.text:void 0)===e)return t.initializer}}function ky(r,e){return r?F.isStringLiteral(r)||F.isNoSubstitutionTemplateLiteral(r)?[r.text.toUpperCase()]:F.isArrayLiteralExpression(r)?r.elements.map(t=>F.isStringLiteral(t)||F.isNoSubstitutionTemplateLiteral(t)?t.text.toUpperCase():t.getText(e).toUpperCase()).filter(Boolean):[r.getText(e).toUpperCase()]:["GET"]}function Gp(r,e){return r?F.isArrayLiteralExpression(r)?r.elements.map(t=>({name:`preHandler:${t.getText(e)}`})):[{name:`preHandler:${r.getText(e)}`}]:[]}function Wp(r){return r?F.isArrayLiteralExpression(r)?r.elements.filter(e=>F.isExpression(e)):[r]:[]}function Iy(r){if(r&&(F.isArrowFunction(r)||F.isFunctionExpression(r))&&r.parameters[0]&&F.isIdentifier(r.parameters[0].name))return r.parameters[0].name.text}function Ty(r,e){if(!r||!F.isStringLiteral(r))return!1;let t=r.text;return t==="onRequest"||t==="preParsing"||t==="preValidation"||t==="preHandler"}function Oy(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 $y(r,e){return e?{parameters:nn([...e.parameters,...r.parameters]),requestBody:e.requestBody??r.requestBody,cookies:r.cookies,responses:r.responses}:r}function Kp(r,e,t){if(!r||!F.isObjectLiteralExpression(r))return;let n=[],s=Pe(r,"params");s&&n.push(...Ni(s,"path",""));let i=Pe(r,"querystring")??Pe(r,"query");i&&n.push(...Ni(i,"query",""));let o=Pe(r,"headers");o&&n.push(...Ni(o,"header",""));let a=Pe(r,"body");a&&n.push(...Ni(a,"body",""));let c=a?Qp(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 Qp(r,e){if(F.isStringLiteral(r)||F.isNoSubstitutionTemplateLiteral(r))return{type:"string"};if(F.isNumericLiteral(r))return{type:"number"};if(!F.isObjectLiteralExpression(r))return;let t={};for(let n of r.properties){if(!F.isPropertyAssignment(n))continue;let s=n.name,i=F.isIdentifier(s)||F.isStringLiteral(s)||F.isNumericLiteral(s)?s.text:void 0;if(!i)continue;let o=Zp(n.initializer,e);o!==void 0&&(t[i]=o)}return Object.keys(t).length>0?t:void 0}function Zp(r,e){if(F.isStringLiteral(r)||F.isNoSubstitutionTemplateLiteral(r))return r.text;if(F.isNumericLiteral(r))return Number(r.text);if(r.kind===F.SyntaxKind.TrueKeyword||r.kind===F.SyntaxKind.FalseKeyword)return r.kind===F.SyntaxKind.TrueKeyword;if(r.kind===F.SyntaxKind.NullKeyword)return null;if(F.isArrayLiteralExpression(r)){let t=r.elements.map(n=>Zp(n,e));return t.every(n=>n!==void 0)?t:void 0}if(F.isObjectLiteralExpression(r))return Qp(r,e)}function Ni(r,e,t){if(!F.isObjectLiteralExpression(r))return[];let n=Pe(r,"properties");if(!n||!F.isObjectLiteralExpression(n))return[];let s=Pe(r,"required"),i=new Set;if(s&&F.isArrayLiteralExpression(s))for(let a of s.elements)(F.isStringLiteral(a)||F.isNoSubstitutionTemplateLiteral(a))&&i.add(a.text);let o=[];for(let a of n.properties){if(!F.isPropertyAssignment(a))continue;let c=F.isIdentifier(a.name)||F.isStringLiteral(a.name)||F.isNumericLiteral(a.name)?a.name.text:void 0;if(!c)continue;let l=t?`${t}.${c}`:c,u=Fy(a.initializer);o.push({name:l,location:e,type:u,required:i.has(c)}),o.push(...Ni(a.initializer,e,l))}return o}function Fy(r){if(!F.isObjectLiteralExpression(r))return;let e=Pe(r,"type");if(e&&(F.isStringLiteral(e)||F.isNoSubstitutionTemplateLiteral(e)))return e.text;let t=Pe(r,"properties");if(t&&F.isObjectLiteralExpression(t))return"object"}var F,Rs,Yp=E(()=>{"use strict";F=I(require("typescript"));Sa();ba();Rs=class{async analyzeFile(e,t,n,s){let i=F.createSourceFile(e,t,F.ScriptTarget.Latest,!0,e.endsWith(".ts")?F.ScriptKind.TS:F.ScriptKind.JS),o=new Set(["fastify"]),a=[{pathExpression:"",resolvedPath:"",confidence:"high"}],c=[],l=new Map,u=new Map,p=xs(i,n.projectRoot,s.envOverrides),d=(f,h,g)=>{if(F.isVariableDeclaration(f)&&F.isIdentifier(f.name)&&f.initializer){let v=f.initializer.getText(i);(v.includes("fastify(")||v.includes("Fastify("))&&h.add(f.name.text)}if(F.isCallExpression(f)&&F.isPropertyAccessExpression(f.expression)){let v=f.expression.expression.getText(i),y=f.expression.name.text;if(y==="register"){let b=Iy(f.arguments[0]);b&&u.set(b,v),qy(f,i,h,g,d,p)}if(y==="addHook"&&h.has(v)&&f.arguments.length>=2&&Ty(f.arguments[0],i)){let b=l.get(v)??[];b.push(f.arguments[1]),l.set(v,b)}let x=Py(y);if(x&&h.has(v)&&f.arguments[0]){let b=Ct(f.arguments[0],i,p),C=f.arguments.length>=2&&F.isObjectLiteralExpression(f.arguments[1])?f.arguments[1]:void 0,R=C&&f.arguments[2]?f.arguments[2]:f.arguments[f.arguments.length-1],q=i.getLineAndCharacterOfPosition(R.getStart(i)),N=C?Pe(C,"preHandler"):void 0,M=Gp(N,i),_=Wp(N),H=C?Kp(Pe(C,"schema"),i,x):void 0;for(let O of g){let L=rn(O.pathExpression,b.pathExpression),Z=en(O.confidence,b.confidence),X=!!L.resolvedPath;c.push({owner:v,method:x,pathExpression:L.pathExpression,resolvedPath:Z==="high"&&X?L.resolvedPath:void 0,confidence:Z,handlerNode:R,middlewareNodes:_,schemaMetadata:H,source:{filePath:e,line:q.line+1,column:q.character+1,symbolName:R.getText(i)},middleware:M})}}if(y==="route"&&h.has(v)&&f.arguments[0]&&F.isObjectLiteralExpression(f.arguments[0])){let b=f.arguments[0],C=Pe(b,"method"),R=Pe(b,"url")??Pe(b,"path"),q=Pe(b,"handler"),N=Pe(b,"preHandler"),M=Pe(b,"schema"),_=Ct(R,i,p),H=ky(C,i),O=Gp(N,i);for(let L of H){let Z=q?i.getLineAndCharacterOfPosition(q.getStart(i)):i.getLineAndCharacterOfPosition(b.getStart(i));for(let X of g){let Je=rn(X.pathExpression,_.pathExpression),ln=en(X.confidence,_.confidence),kt=!!Je.resolvedPath;c.push({owner:v,method:L,pathExpression:Je.pathExpression,resolvedPath:ln==="high"&&kt?Je.resolvedPath:void 0,confidence:ln,handlerNode:q??b,middlewareNodes:Wp(N),schemaMetadata:Kp(M,i,L),source:{filePath:e,line:Z.line+1,column:Z.character+1,symbolName:q?.getText(i)},middleware:O})}}}}F.forEachChild(f,v=>d(v,h,g))};d(i,o,a);let m=[];for(let f of c){let h=tn(f.pathExpression),v=[...Oy(f.owner,l,u),...f.middlewareNodes,f.handlerNode],y=Ss(v,i,e,f.method,s.contextProperties);y.parameters.unshift(...h),y.parameters=nn(y.parameters);let x=$y(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:x.parameters.length>0?x.parameters:void 0,requestBody:x.requestBody,cookies:x.cookies.length>0?x.cookies:void 0,responses:x.responses})}return m}}});function Ny(r,e){j.forEachChild(r,t=>My(t,r,e))}function My(r,e,t){if(j.isExpressionStatement(r)&&j.isBinaryExpression(r.expression)&&r.expression.operatorToken.kind===j.SyntaxKind.EqualsToken){let n=r.expression.left,s=r.expression.right;if(j.isPropertyAccessExpression(n)){let i=n.expression.getText(e),o=n.name.text;if(i==="exports"&&xa(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=ou(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"&&xa(s,e)){let a=e.getLineAndCharacterOfPosition(s.getStart(e)),{handlerNode:c,middlewareNodes:l}=ou(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(j.isVariableStatement(r)&&Xp(r)&&r.declarationList.declarations.length>0){for(let n of r.declarationList.declarations)if(!(!j.isIdentifier(n.name)||!n.initializer)&&xa(n.initializer,e)){let s=n.name.text,i=e.getLineAndCharacterOfPosition(n.initializer.getStart(e)),{handlerNode:o,middlewareNodes:a}=ou(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(j.isFunctionDeclaration(r)&&Xp(r)&&r.name&&_y(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 xa(r,e){if(j.isArrowFunction(r)||j.isFunctionExpression(r))return Dy(r);if(j.isCallExpression(r)){let t=r.expression.getText(e);if(t==="middy"||t.endsWith(".middy"))return!0;if(j.isPropertyAccessExpression(r.expression)&&r.expression.name.text==="use")return xa(r.expression.expression,e)}return j.isIdentifier(r)?/handler/i.test(r.text):!1}function _y(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function Dy(r){return r.parameters.length>=1&&/^(event|evt)$/i.test(r.parameters[0].name.getText())}function Xp(r){return(j.getCombinedModifierFlags(r)&j.ModifierFlags.Export)!==0}function ou(r,e){let t=[],n=r;for(;j.isCallExpression(n)&&j.isPropertyAccessExpression(n.expression)&&n.expression.name.text==="use";)t.unshift(...n.arguments),n=n.expression.expression;return j.isCallExpression(n)&&(n.expression.getText(e)==="middy"||n.expression.getText(e).endsWith(".middy"))?{handlerNode:n.arguments[0]??n,middlewareNodes:t}:{handlerNode:r,middlewareNodes:[]}}function jy(r,e,t){return r.map(n=>{let s=Ly(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 Ly(r,e){return j.isIdentifier(r)?r.text:j.isCallExpression(r)&&j.isIdentifier(r.expression)?r.expression.text:j.isCallExpression(r)&&j.isPropertyAccessExpression(r.expression)?r.expression.name.text:r.getText(e).slice(0,40).replace(/\s+/g," ")}function By(r,e,t){let n=Uy(r);if(!n)return[];let s=new Map,i=o=>{if(j.isPropertyAccessExpression(o)||j.isElementAccessExpression(o)){let a=Mi(o,e);if(a.length>=2&&a[0]===n){let c=a[1],l=Hy[c];if(l==="body"){let u="body::body";if(!s.has(u)){let p=e.getLineAndCharacterOfPosition(o.getStart(e));s.set(u,{name:"body",location:"body",detectionLocation:{filePath:t,line:p.line+1,column:p.character+1}})}}else if(l&&a.length>=3){let u=a[2],p=`${l}::${u}`;if(!s.has(p)){let d=e.getLineAndCharacterOfPosition(o.getStart(e));s.set(p,{name:u,location:l,detectionLocation:{filePath:t,line:d.line+1,column:d.character+1}})}}}}if(j.isCallExpression(o)&&j.isPropertyAccessExpression(o.expression)&&o.expression.expression.getText(e)==="JSON"&&o.expression.name.text==="parse"&&o.arguments.length===1){let a=o.arguments[0],c=Mi(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}})}}}j.forEachChild(o,i)};return i(r),Array.from(s.values())}function Uy(r){if(j.isArrowFunction(r)||j.isFunctionExpression(r)||j.isFunctionDeclaration(r)){let e=r.parameters[0];if(e&&j.isIdentifier(e.name))return e.name.text}return j.isIdentifier(r),"event"}function Mi(r,e){return j.isIdentifier(r)?[r.text]:j.isPropertyAccessExpression(r)?[...Mi(r.expression,e),r.name.text]:r.kind===j.SyntaxKind.PropertyAccessExpression||j.isNonNullExpression(r)?Mi(r.expression,e):j.isElementAccessExpression(r)&&j.isStringLiteral(r.argumentExpression)?[...Mi(r.expression,e),r.argumentExpression.text]:r.getText(e).replace(/\?/g,"").replace(/\s/g,"").split(".")}var j,Cs,Hy,au=E(()=>{"use strict";j=I(require("typescript")),Cs=class{async analyzeFile(e,t,n,s){let i=j.createSourceFile(e,t,j.ScriptTarget.Latest,!0,e.endsWith(".ts")?j.ScriptKind.TS:j.ScriptKind.JS),o=[];return Ny(i,o),o.length===0?[]:o.map(a=>{let c=By(a.handlerNode,i,e),l=jy(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}})}};Hy={pathParameters:"path",queryStringParameters:"query",multiValueQueryStringParameters:"query",headers:"header",multiValueHeaders:"header",body:"body"}});var Es=E(()=>{"use strict";ba();Jp();Yp();au()});function ef(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function Vy(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 wa,mr,cu=E(()=>{"use strict";wa=I(require("fs"));Es();qn();mr=class{id="provider.express";framework="express";analyzer=new ws;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(ef(t)===ef(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??nt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=wa.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=wa.readFileSync(a,"utf-8")}catch{continue}let p=await this.analyzer.analyzeFile(a,u,t,e),d=Vy(p);i.push(...p),s.push(...d),this.fileCache.set(a,{mtimeMs:c.mtimeMs,size:c.size,endpoints:p.map(m=>structuredClone(m)),warnings:d.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)}}});function tf(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function zy(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 Ra,hr,lu=E(()=>{"use strict";Ra=I(require("fs"));Es();qn();hr=class{id="provider.fastify";framework="fastify";analyzer=new Rs;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(tf(t)===tf(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??nt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){let c;try{c=Ra.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=Ra.readFileSync(a,"utf-8")}catch{continue}let p=await this.analyzer.analyzeFile(a,u,t,e),d=zy(p);i.push(...p),s.push(...d),this.fileCache.set(a,{mtimeMs:c.mtimeMs,size:c.size,endpoints:p.map(m=>structuredClone(m)),warnings:d.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)}}});function nf(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}function uu(r,e){let t=r.expression;if(ge.isCallExpression(t))return ge.isIdentifier(t.expression)?t.expression.text:t.expression.getText(e);if(ge.isIdentifier(t))return t.text}function rf(r){let e=r.expression;if(ge.isCallExpression(e))return e.arguments[0]}function Jy(r){return{Get:"GET",Post:"POST",Put:"PUT",Delete:"DELETE",Patch:"PATCH",Options:"OPTIONS",Head:"HEAD",All:"ALL"}[r]}function sf(r){return ge.canHaveDecorators(r)?ge.getDecorators(r)??[]:[]}function of(r,e){if(!r||r.length===0)return[];let t=new Set(["UseGuards","UseInterceptors","UsePipes","UseFilters"]),n=[];for(let s of r){let i=uu(s,e);if(!i||!t.has(i))continue;let o=s.expression;if(!ge.isCallExpression(o)){n.push({name:i});continue}for(let a of o.arguments)n.push({name:`${i}:${a.getText(e)}`})}return n}function Gy(r,e){return r==="low"||e==="low"?"low":r==="medium"||e==="medium"?"medium":"high"}var Ca,ge,gr,du=E(()=>{"use strict";Ca=I(require("fs")),ge=I(require("typescript"));Sa();qn();gr=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(nf(t)===nf(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??nt(t.projectRoot);this.pruneDeletedFiles(t.projectRoot,o);for(let a of o){if(!a.endsWith(".ts")&&!a.endsWith(".js"))continue;let c;try{c=Ca.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=Ca.readFileSync(a,"utf-8")}catch{continue}let p=[],d=[],m=ge.createSourceFile(a,u,ge.ScriptTarget.Latest,!0,a.endsWith(".ts")?ge.ScriptKind.TS:ge.ScriptKind.JS),f=xs(m,t.projectRoot,e.envOverrides),h=g=>{if(ge.isClassDeclaration(g)){let v=sf(g),y=v.find(x=>uu(x,m)==="Controller");if(y){let x=Ct(rf(y),m,f),b=of(v,m);for(let C of g.members){if(!ge.isMethodDeclaration(C))continue;let R=sf(C),q=R.map(N=>({decorator:N,name:uu(N,m)})).filter(N=>!!N.name);for(let N of q){let M=Jy(N.name);if(!M)continue;let _=Ct(rf(N.decorator),m,f),H=rn(x.pathExpression,_.pathExpression),O=of(R,m),L=C.name?.getText(m),Z=C.name??C,X=m.getLineAndCharacterOfPosition(Z.getStart(m)),Je=Gy(x.confidence,_.confidence);d.push({id:"",method:M,framework:"nestjs",pathExpression:H.pathExpression,resolvedPath:Je==="high"?H.resolvedPath:void 0,confidence:Je,source:{filePath:a,line:X.line+1,column:X.character+1,symbolName:L},middleware:[...b,...O]}),Je!=="high"&&p.push({code:"dynamic-path-unresolved",framework:"nestjs",filePath:a,message:`Dynamic NestJS route path unresolved at ${L??"unknown handler"} in ${a}`})}}}}ge.forEachChild(g,h)};h(m),i.push(...d),s.push(...p),this.fileCache.set(a,{mtimeMs:c.mtimeMs,size:c.size,endpoints:d.map(g=>structuredClone(g)),warnings:p.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)}}});function Wy(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}=lf(c,e),p=uf(l,e);p||t.push({code:"dynamic-path-unresolved",framework:"lambda",message:`Lambda handler file not found for function '${i}': ${c}`});let d=a.events;if(Array.isArray(d))for(let m of d){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=df(h),y=[];if(f.authorizer){let x=typeof f.authorizer=="string"?f.authorizer:"authorizer";y.push({name:x})}n.push({id:"",method:g.toUpperCase(),framework:"lambda",pathExpression:v,resolvedPath:v,confidence:"high",source:{filePath:p??l,line:1,column:1,symbolName:u},middleware:y})}}return n}function af(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:p}=lf(l,e),d=uf(u,e);d||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 x=df(v),b=g.Auth,C=[];b?.Authorizer&&C.push({name:String(b.Authorizer)}),n.push({id:"",method:y.toUpperCase(),framework:"lambda",pathExpression:x,resolvedPath:x,confidence:"high",source:{filePath:d??u,line:1,column:1,symbolName:p},middleware:C})}}return n}function lf(r,e){let t=r.lastIndexOf(".");return t===-1?{filePath:r,exportName:"handler"}:{filePath:r.slice(0,t),exportName:r.slice(t+1)}}function uf(r,e){let t=[pt.join(e,`${r}.ts`),pt.join(e,`${r}.js`),pt.join(e,r,"index.ts"),pt.join(e,r,"index.js")];for(let n of t)if(De.existsSync(n))return n}function df(r){return r.startsWith("/")?r:`/${r}`}function fu(r){let e=r.split(`
507
+ `);return _i(e,0,-1).value}function _i(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=Ky(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=_i(r,o+1,l),v={};v[h]=g.value,s.push(v),o=g.nextLine}else{let h=_i(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 x=_i(r,o+1,l);h[v]=x.value,s.push(h),o=x.nextLine}else h[v]=pu(y),s.push(h),o++}else s.push(pu(f)),o++;continue}let p=u.indexOf(":");if(p===-1){o++;continue}let d=u.slice(0,p).trim(),m=u.slice(p+1).trim();if(m===""||m.startsWith("#")){let f=_i(r,o+1,l);n[d]=f.value,o=f.nextLine}else n[d]=pu(m),o++}return i?{value:s,nextLine:o}:{value:n,nextLine:o}}function Ky(r){let e=0;for(let t of r)if(t===" ")e++;else if(t===" ")e+=2;else break;return e}function pu(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 Qy(r){return fu(r)}function cf(r){return r.replace(/\\/g,"/").replace(/\/+$/,"")}var De,pt,yr,mu=E(()=>{"use strict";De=I(require("fs")),pt=I(require("path"));au();qn();yr=class{id="provider.lambda";framework="lambda";analyzer=new Cs;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(cf(t)===cf(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=De.existsSync(pt.join(e.projectRoot,"serverless.yml"))||De.existsSync(pt.join(e.projectRoot,"serverless.yaml"))||De.existsSync(pt.join(e.projectRoot,"template.yaml"))||De.existsSync(pt.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=pt.join(o,a);if(De.existsSync(c)){try{let l=De.readFileSync(c,"utf-8"),u=Qy(l),p=Wy(u,o,s);i.push(...p)}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=pt.join(o,"template.yaml"),c=pt.join(o,"template.json");if(De.existsSync(c))try{let l=De.readFileSync(c,"utf-8"),u=JSON.parse(l),p=af(u,o,s);i.push(...p)}catch{s.push({code:"provider-failed",framework:"lambda",filePath:c,message:`Failed to parse SAM template: ${c}`})}else if(De.existsSync(a))try{let l=De.readFileSync(a,"utf-8"),u=fu(l),p=af(u,o,s);i.push(...p)}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??nt(o);this.pruneDeletedFiles(o,a);for(let c of a){let l;try{l=De.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 p="";try{p=De.readFileSync(c,"utf-8")}catch{continue}let d=await this.analyzer.analyzeFile(c,p,t,e),m=d.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(...d),s.push(...m),this.fileCache.set(c,{mtimeMs:l.mtimeMs,size:l.size,endpoints:d.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)}}});function Yy(r,e){let t=[],n=[r];for(;n.length>0;){let s=n.pop(),i;try{i=Ea.readdirSync(s,{withFileTypes:!0})}catch{continue}for(let o of i){let a=ff.join(s,o.name);o.isDirectory()?Zy.has(o.name)||n.push(a):o.isFile()&&e.test(o.name)&&t.push(a)}}return t}function Di(r){return Yy(r,/\.java$/)}function ji(r){return Ea.promises.readFile(r,"utf-8")}function hu(r){let e=r.replace(/\\/g,"/");return/^[A-Z]:\//.test(e)&&(e=e[0].toLowerCase()+e.substring(1)),e}function gu(r){return r.replace(/\\/g,"/").split("/").pop()||""}function mf(r,e){let t=pf.get(e);if(t&&Date.now()-t.ts<Xy)return Promise.resolve(t.files);let n=new RegExp(`^${e}\\.java$`),s=Di(r).filter(i=>n.test(gu(i)));return pf.set(e,{ts:Date.now(),files:s}),Promise.resolve(s)}var Ea,ff,Zy,pf,Xy,qa=E(()=>{"use strict";Ea=I(require("fs")),ff=I(require("path")),Zy=new Set(["target","build","bin","out","dist","node_modules",".git",".svn",".hg",".gradle",".mvn",".idea",".vscode",".settings",".history","__pycache__"]);pf=new Map,Xy=3e4});function ev(r){if(r.includes("/"))return r;if(sn[r])return sn[r];let e=`MediaType.${r}`;if(sn[e])return sn[e];for(let[s,i]of Object.entries(sn))if(s.endsWith(r))return i;let t=r.lastIndexOf(".");if(t>=0){let s=r.substring(t+1),i=`MediaType.${s}`;if(sn[i])return sn[i];let o=`MediaType.${s}_VALUE`;if(sn[o])return sn[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 Li(r){return r.map(ev)}function on(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 tv.has(t)?on(n.trim()):r}function qs(r){return/MultipartFile/.test(r)}var sn,tv,Aa=E(()=>{"use strict";sn={"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"};tv=new Set(["HttpEntity","RequestEntity","ResponseEntity","Mono","Flux","Optional","CompletableFuture","DeferredResult","ListenableFuture","Callable"])});var vr,hf=E(()=>{"use strict";qa();Aa();vr=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 mf(this.projectRoot,a);if(u.length>1&&c){let m=/^\s*package\s+([\w.]+);/m;for(let f of u){let h=await ji(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 p=await ji(u[0]),d=this.buildTypeParamMap(p,a,s);return await this.parseClassToSchema(p,a,l,d),l.required&&l.required.length===0&&delete l.required,l}async generateResponseSchema(e){if(!e||e==="void")return;let t=on(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),p=[];for(let d of s){let m=d.trim();if(!i){new RegExp(`class\\s+${t}\\b`).test(m)&&(i=!0,o+=(d.match(/\{/g)||[]).length,o-=(d.match(/\}/g)||[]).length);continue}let f=o;if(o+=(d.match(/\{/g)||[]).length,o-=(d.match(/\}/g)||[]).length,o<=0)break;if(f>1)continue;if(/^@(\w+)/.exec(m)&&!/(?:private|public|protected)\s/.test(m)&&!m.includes(";")){p.push(m);continue}if(/^public\s+\S+\s+(get|is|set)[A-Z]\w*\s*\(/.test(m)){p=[];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],x=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),R=[...p,m],q=R.join(" ");!b&&!C&&!/@JsonIgnore\b/.test(q)&&(x==="public"||l||u||/@JsonProperty\b/.test(q))&&n.push(this.parseFieldAnnotations(y,v,R))}}p=[]}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(O=>O.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 x=this.extractAttr(s,"Schema","maxLength");x&&(i.maxLength=Number(x));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 R=this.extractAttr(s,"Size","max");R&&!i.maxLength&&(i.maxLength=Number(R));let q=this.extractAttr(s,"Min","value")||this.extractSingleArg(s,"Min");q&&i.minimum===void 0&&(i.minimum=Number(q));let N=this.extractAttr(s,"Max","value")||this.extractSingleArg(s,"Max");N&&i.maximum===void 0&&(i.maximum=Number(N));let M=this.extractAttr(s,"DecimalMin","value")||this.extractSingleArg(s,"DecimalMin");M&&i.minimum===void 0&&(i.minimum=Number(M));let _=this.extractAttr(s,"DecimalMax","value")||this.extractSingleArg(s,"DecimalMax");_&&i.maximum===void 0&&(i.maximum=Number(_)),/@Email\b/.test(s)&&(i.format=i.format||"email");let H=this.extractAttr(s,"Pattern","regexp");return H&&!i.pattern&&(i.pattern=H),/@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}}});function yu(r){let e=[],t=/:(\w+)|\{(\w+)\}/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]||n[2]);return e}var gf,Pa,yf=E(()=>{"use strict";gf=require("java-parser");Aa();Pa=class extends gf.BaseJavaCstVisitorWithDefaults{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=Li(f.map(h=>h.replace(/^['\"]|['\"]$/g,""))):typeof f=="string"&&(a=Li([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),p=this.extractReturnType(n),d=this.extractOpenApiAnnotations(t.annotations,s.annotations);return{method:i,path:l,file:"",line:t.line,pathParams:yu(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:p||void 0,summary:d.summary,description:d.description,operationId:d.operationId,tags:d.tags.length>0?d.tags:void 0,deprecated:d.deprecated||void 0,responses:d.responses.length>0?d.responses:void 0,parameterMeta:u.parameterMeta.length>0?u.parameterMeta:void 0,security:d.security.length>0?d.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 p=this.getAnnotationAttrString(u,"name");p&&o.push(p)}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 p=u.attributes.get("deprecated");typeof p=="string"&&p==="true"&&(a=!0);let d=u.attributes.get("tags");if(Array.isArray(d))d.forEach(m=>{let f=m.replace(/^['"]|['"]$/g,"");f&&o.push(f)});else if(typeof d=="string"){let m=d.replace(/^['"]|['"]$/g,"");m&&o.push(m)}break}case"ApiOperation":{n=this.getAnnotationAttrString(u,"value")||n,s=this.getAnnotationAttrString(u,"notes")||s;let p=u.attributes.get("tags");Array.isArray(p)&&p.forEach(d=>{let m=d.replace(/^['"]|['"]$/g,"");m&&o.push(m)});break}case"Tag":{let p=this.getAnnotationAttrString(u,"name");p&&o.push(p);break}case"Deprecated":{a=!0;break}case"ApiResponse":{let p=this.parseApiResponse(u);p&&c.push(p);break}case"ApiResponses":break;case"SecurityRequirement":{let p=this.getAnnotationAttrString(u,"name");p&&l.push(p);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,on(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 p=this.extractAttrFromRaw(s,"type")||this.extractImplementationType(s);p&&(o.schemaType=p),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 on(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 p=u.children?.variableParaRegularParameter?.[0]?.children;if(!p)continue;let d=p.variableDeclaratorId?.[0]?.children?.Identifier?.[0]?.image||"",m=p.variableModifier||[],f=this.collectAnnotationsFromModifiers(m),h=p.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)||d;t.push(C),y=this.buildParameterMeta(C,"header",g,v,f);let R=b.attributes.get("required");y&&typeof R=="string"&&(R==="true"||R==="false")&&(y.required=R==="true")}else if(b.name==="RequestParam")if(qs(g)){o=!0;let C=this.getAnnotationStringValue(b)||d;s.push({name:C,type:g,isFile:!0})}else{let C=this.getAnnotationStringValue(b)||d;n.push(C);let R=b.attributes.get("required");y=this.buildParameterMeta(C,"query",g,v,f),y&&typeof R=="string"&&(R==="true"||R==="false")&&(y.required=R==="true")}else if(b.name==="RequestBody")o=!0,g&&(a=on(g));else if(b.name==="RequestPart"){o=!0;let C=this.getAnnotationStringValue(b)||d,R=qs(g);s.push({name:C,type:g,isFile:R})}else b.name==="ModelAttribute"&&(o=!0,g&&(c=g));let x=f.find(b=>b.name==="PathVariable");if(x){let b=this.getAnnotationStringValue(x)||d;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(p=>p.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,p=this.extractElementValue(l.children.elementValue[0]);p!==void 0&&a.set(u,p)}}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 bf={};Tt(bf,{EndpointParser:()=>vu});var vf,vu,Sf=E(()=>{"use strict";vf=require("java-parser");qa();Aa();yf();vu=class r{fileCache=new Map;generatedRe=/_[0-9a-zA-Z]+\.java$/;clearCache(){this.fileCache.clear()}evictPaths(e){let t=e.map(n=>hu(n.trim()));for(let n of[...this.fileCache.keys()]){let s=hu(n);t.some(i=>s.startsWith(i+"/"))&&this.fileCache.delete(n)}}async parseControllers(e){let t=Di(e),n=[],s=new Set,i=[];for(let a of t)if(!this.generatedRe.test(gu(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(p=>({filePath:u,ctrls:p})).catch(()=>({filePath:u,ctrls:[]}))));for(let{filePath:u,ctrls:p}of l)this.fileCache.set(u,p),n.push(...p)}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 ji(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=(0,vf.parse)(e),n=new Pa;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 p=s[u],d=p.trim(),m=/^@(\w+)\s*(?:\(([^)]*)\))?/.exec(d);if(m&&!/\b(class|interface|enum)\b/.test(d)&&(i.push(m[1]),m[2]!==void 0&&o.set(m[1],m[2]),!/(private|public|protected|static|final|void|class)\b/.test(d)))continue;let f=/\bclass\s+(\w+)/.exec(d);if(f){if(a&&(this.deduplicateEndpoints(a),n.push(a),a=null),i.some(y=>y==="RestController"||y==="Controller")){let y="",x=o.get("RequestMapping");x!==void 0&&(y=this.extractPathFromArgs(x)),a={name:f[1],basePath:y,file:t,line:u+1,endpoints:[]}}l=!0,c=0,c+=(p.match(/\{/g)||[]).length,c-=(p.match(/\}/g)||[]).length,i=[],o=new Map;continue}if(l&&(c+=(p.match(/\{/g)||[]).length,c-=(p.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(d);if(h||g){let v=u,y=this.collectMethodSignature(s,v),x=[];g&&x.push({name:g[1],args:g[2]||""});for(let b of i)/Mapping$/.test(b)&&(!g||b!==g[1])&&x.push({name:b,args:o.get(b)||""});for(let b of x){let C=b.name.replace("Mapping","").toUpperCase();C==="REQUEST"&&(C="");let R="",q=[],N=b.args;if(N){R=this.extractPathFromArgs(N);let H=/consumes\s*=\s*\{?\s*([^}]*)\}?/.exec(N);if(H){let O=H[1],L=[...O.matchAll(/["']([^"']+)["']/g)].map(X=>X[1]),Z=[...O.matchAll(/MediaType\.([A-Z_]+)/g)].map(X=>`MediaType.${X[1]}`);q=Li([...L,...Z])}if(b.name==="RequestMapping"){let O=/method\s*=\s*(?:\{?\s*)?RequestMethod\.([A-Z]+)/.exec(N);O&&(C=O[1])}}!C&&b.name==="RequestMapping"&&(C="GET");let M=R;a.basePath&&(M&&!M.startsWith("/")?M=a.basePath+"/"+M:M=a.basePath+M),M&&!M.startsWith("/")&&(M="/"+M);let _=this.extractParameterMetadataFromSig(y);a.endpoints.push({method:C,path:M,file:t,line:u+1,pathParams:yu(M),consumes:q,bodyType:_.bodyType,headers:_.headers,queryParams:_.queryParams,hasBody:_.hasBody,formParts:_.formParts.length>0?_.formParts:void 0,modelAttributeType:_.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(qs(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 d=/@RequestBody\s+([A-Za-z0-9_<>\[\]]+)\s+\w+/.exec(e);d?(i=!0,o=on(d[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=qs(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)})}}});function sv(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 ka,xf,nv,rv,br,bu=E(()=>{"use strict";ka=I(require("fs")),xf=I(require("path"));qa();hf();nv=["pom.xml","build.gradle","build.gradle.kts","settings.gradle"],rv=/@(?:RestController|Controller)\b/,br=class{id="provider.spring";framework="spring";parserModule;supports(e){for(let s of nv)if(ka.existsSync(xf.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=Di(e.projectRoot));let n=0;for(let s of t)if(s.endsWith(".java")){if(n>=40)break;n+=1;try{let i=ka.readFileSync(s,"utf-8");if(rv.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(p){let d=p instanceof Error?p.message:String(p);s.push({code:"provider-failed",framework:"spring",message:`Spring discovery failed for ${i}: ${d}`})}let l=new vr(i),u=[];for(let p of c)for(let d of p.endpoints)u.push(await this.endpointToDiscoveredApi(d,l));return{endpoints:u,warnings:s,stats:{frameworksDetected:["spring"],providersRun:[this.id],endpointCount:u.length,unresolvedEndpointCount:u.filter(p=>!p.resolvedPath).length,scanDurationMs:Date.now()-n}}}clearCache(){this.parserModule=void 0}async loadParser(){return this.parserModule||(this.parserModule=await Promise.resolve().then(()=>(Sf(),bf))),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:sv(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=vr.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=vr.javaTypeToParamType(e.schemaType);let n=vr.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"}}}});function Su(r){let e=[],t=[r];for(;t.length>0;){let n=t.shift(),s;try{s=Ta.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let i of s){let o=qf.join(n,i.name);if(i.isDirectory()){iv.has(i.name)||t.push(o);continue}i.isFile()&&o.endsWith(".py")&&e.push(o)}}return e.sort()}function Af(r){let e=Su(r),t=new Map,n=new Map,s=new Map,i=[];for(let u of e){let p="";try{p=Ta.readFileSync(u,"utf-8")}catch{continue}let d=av(p,u,t);n.set(u,d);for(let m of d.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 p of u.includes){let d=Rf(u.imports,p.routerName);if(!s.has(d)){i.push(`include_router references unknown router '${p.routerName}' at ${p.line}`);continue}let m=s.get(d);if(p.prefix){c.add(d);let f=o.get(d),h=`${p.prefix.replace(/\/+$/,"")}/${m.constructorPrefix.replace(/^\/+/,"")}`;f.includes(h)||f.push(h)}p.tags&&p.tags.length>0&&a.set(d,[...a.get(d)??[],...p.tags])}let l=[];for(let[u,p]of n.entries())for(let d of p.routes)for(let m of d.decorators){let f=Rf(p.imports,m.object),h=p.appNames.has(m.object)||p.appNames.has(f),g=s.get(f);if(!h&&!g)continue;let v=pv(m.method,m.args);if(v.length===0)continue;let y=fv(m.args),x=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 R=g?Sv(C,y):y,q=xv(d.signature,bv(R)),N=g?a.get(f):void 0,_=Pf(m.args)??N;l.push({methods:v,path:R,file:u,line:m.line,functionName:d.functionName,statusCode:mv(m.args),responseModel:hv(m.args)??uv(d.signature),tags:_,deprecated:gv(m.args),summary:yv(m.args),params:q.params,security:vv(m.args,d.signature),pathUnresolved:x})}}return{endpoints:l,models:t,warnings:i}}function Rf(r,e){let t=r.find(n=>n.alias===e);return t?t.target:e}function an(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 an(n[1],e);let s=/^Union\[(.+)\]$/.exec(t);if(s){let l=s[1].split(",").map(u=>u.trim())[0];return an(l,e)}let i=/^(?:List|list|Sequence)\[(.+)\]$/.exec(t);if(i)return{type:"array",items:an(i[1],e)??{type:"object"}};let o=/^(?:Dict|dict)\[([^,]+),\s*(.+)\]$/.exec(t);if(o)return{type:"object",additionalProperties:an(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 d of c.fields){let m=an(d.type,e)??{type:"string"};l[d.name]=d.description?{...m,description:d.description}:m,d.required&&u.push(d.name)}let p={type:"object",properties:l};return u.length>0&&(p.required=u),p}return{type:"object"}}function av(r,e,t){let n={routes:[],appNames:new Set,routers:[],includes:[],imports:[]},i=Cv(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 p=/^from\s+[\w.]+(?:\s+import\s+(.+))?$/.exec(u)||/^import\s+([\w.,\s]+)$/.exec(u);if(p){let v=p[1]??"";for(let y of v.split(",")){let x=y.trim();if(!x)continue;let b=/^([\w.]+)\s+as\s+(\w+)$/.exec(x);if(b)n.imports.push({alias:b[2],target:b[1].split(".").pop()});else if(/^[\w.]+$/.test(x)){let C=x.split(".").pop();n.imports.push({alias:C,target:C})}}o=[];continue}if(u.startsWith("@")){let{joined:v,nextIndex:y}=Ia(i,a-1),x=dv(v,l);x&&o.push(x),a=y+1;continue}let d=/^(?:async\s+)?def\s+(\w+)\s*\(/.exec(u);if(d){let{joined:v,nextIndex:y}=Ia(i,a-1),x=v.slice(v.indexOf("(")),b=lv(i,a-1,x);o.length>0&&n.routes.push({decorators:o,functionName:d[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}=cv(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}=Ia(i,a-1),y=v.slice(v.indexOf("("));n.routers.push({name:h[1],constructorPrefix:Ef(y)}),o=[];continue}let g=/^(\w+)\.include_router\(\s*(\w+)(.*)$/.exec(u);if(g){let{joined:v}=Ia(i,a-1),y=v.slice(v.indexOf("("));n.includes.push({object:g[1],routerName:g[2],prefix:Ef(y),tags:Pf(y),line:l}),o=[];continue}o=[]}return n}function cv(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(),p=/^Optional\[/.test(l)||/None\s*\|/.test(l)||u==="None"||u.startsWith("None")||u!==""&&!u.startsWith("Field("),d,m=/Field\(([^)]*)\)/.exec(a);if(m){let f=/description\s*=\s*["']([^"']+)["']/.exec(m[1]);f&&(d=f[1])}t.push({name:c[1],type:l,required:!p,description:d})}n+=1}return{nextIndex:n,fields:t}}function Ia(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+=`
508
+ `+a}return{joined:n,nextIndex:s}}function lv(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+=`
509
+ `+l}let c=Cf(i);if(c!==-1)return i.slice(0,c);for(;o+1<r.length;){o+=1;let l=r[o],u=Cf(l);if(u!==-1){i+=`
510
510
  `+l.slice(0,u);break}i+=`
511
- `+l}return i}function Sf(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 ov(r){let e=/->\s*([^:\n]+?)\s*$/.exec(r.trim());return e?e[1].trim():void 0}function av(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 cv(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=nv[r.toLowerCase()];return t?[t]:[]}function lv(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 uv(r){let e=/status_code\s*=\s*(\d+)/.exec(r);return e?parseInt(e[1],10):void 0}function dv(r){let e=/response_model\s*=\s*([^\s,]+)/.exec(r);return e?e[1]:void 0}function Cf(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 pv(r){return/deprecated\s*=\s*True/.test(r)?!0:void 0}function fv(r){let e=/summary\s*=\s*["']([^"']+)["']/.exec(r);return e?e[1]:void 0}function mv(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 xf(r){let e=/prefix\s*=\s*["']([^"']+)["']/.exec(r);return e?e[1]:""}function hv(r){let e=[],t=/\{([^}:]+)(?::[^}]+)?\}/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]);return e}function gv(r,e){return e?r?`${r.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`:e.startsWith("/")?e:"/"+e:r||"/"}function yv(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=bv(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(vf.has(d))continue;let f=/^([A-Za-z_]\w*)/.exec(p)?.[1]??"";if(vf.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=vv(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 vv(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 bv(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 Sv(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(`
512
- `)}var Pa,wf,tv,nv,vf,Ef=E(()=>{"use strict";Pa=I(require("fs")),wf=I(require("path")),tv=new Set(["node_modules",".git",".venv","venv","env","__pycache__","site-packages",".mypy_cache",".pytest_cache",".tox","dist","build","out"]),nv={get:"GET",post:"POST",put:"PUT",patch:"PATCH",delete:"DELETE",options:"OPTIONS",head:"HEAD"},vf=new Set(["Request","Response","WebSocket","BackgroundTasks","Depends","Header","Cookie"])});function Cv(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 ka,Af,xv,wv,Rv,yr,yu=E(()=>{"use strict";ka=I(require("fs")),Af=I(require("path"));Ef();xv=["requirements.txt","pyproject.toml","poetry.lock","Pipfile","setup.py"],wv=/^\s*from\s+fastapi\s+import|^\s*import\s+fastapi/m,Rv=/@[\w.]+\.(get|post|put|patch|delete|options|head|api_route)\(/,yr=class{id="provider.fastapi";framework="fastapi";supports(e){for(let s of xv)if(ka.existsSync(Af.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=gu(e.projectRoot));let n=0;for(let s of t)if(s.endsWith(".py")){if(n>=60)break;n+=1;try{let i=ka.readFileSync(s,"utf-8");if(wv.test(i)&&Rv.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=Rf(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=Cv(e.type),s=an(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=an(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=an(o,t);a&&(s.body={type:"json",schema:i?{type:"array",items:a}:a})}return[s]}}});function vr(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]=vr(i);return n}if(e==="array"){let t=r.items;return[vr(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 qn(r){let e=r.source?.symbolName||"";return e||`${r.method||"GET"} ${r.pathExpression}`}function Pn(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=Ev(r,e);return{headers:t,query:n,params:s,body:i}}function Ev(r,e){let t=r.requestBody;if(!t)return;let n=t.type??"json";if(n==="json"){let s=t.schema,i=e&&s?vr(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 kn(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(`
513
- `)}function vu(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}=Pn(r,!0);return{collectionId:e,name:qn(r),method:r.method||"GET",url:s,headers:i,query:o,params:a,body:c,description:kn(r)}}var bu=E(()=>{"use strict"});function As(r){let e;try{let n=(0,kf.execSync)("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=Ia.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let a of o){let c=Pf.join(i,a.name);if(a.isDirectory()){s.has(a.name)||n.push(c);continue}if(!(!a.isFile()||!Av.some(l=>c.endsWith(l))))try{let l=Ia.statSync(c);l.mtimeMs>t&&(t=l.mtimeMs)}catch{}}}}catch{t=0}return{gitHash:e,maxSourceMtime:t}}function qs(r,e){let t=As(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 Su(r){let e=r.projects.map(t=>qs(t.projectRoot,t.freshness));return{projects:e,staleCount:e.filter(t=>t.status==="stale").length,checkedAt:new Date().toISOString()}}function Es(r,e){let t=r.split(`
511
+ `+l}return i}function Cf(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 uv(r){let e=/->\s*([^:\n]+?)\s*$/.exec(r.trim());return e?e[1].trim():void 0}function dv(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 pv(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=ov[r.toLowerCase()];return t?[t]:[]}function fv(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 mv(r){let e=/status_code\s*=\s*(\d+)/.exec(r);return e?parseInt(e[1],10):void 0}function hv(r){let e=/response_model\s*=\s*([^\s,]+)/.exec(r);return e?e[1]:void 0}function Pf(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 gv(r){return/deprecated\s*=\s*True/.test(r)?!0:void 0}function yv(r){let e=/summary\s*=\s*["']([^"']+)["']/.exec(r);return e?e[1]:void 0}function vv(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 Ef(r){let e=/prefix\s*=\s*["']([^"']+)["']/.exec(r);return e?e[1]:""}function bv(r){let e=[],t=/\{([^}:]+)(?::[^}]+)?\}/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]);return e}function Sv(r,e){return e?r?`${r.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`:e.startsWith("/")?e:"/"+e:r||"/"}function xv(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=Rv(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 p=u[1],d=(u[2]??"").trim(),m=(u[3]??"").trim();if(wf.has(p))continue;let f=/^([A-Za-z_]\w*)/.exec(d)?.[1]??"";if(wf.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(p)?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(p)&&(g="path");let v=wv(d,m);t.push({name:p,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 wv(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 Rv(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 Cv(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(`
512
+ `)}var Ta,qf,iv,ov,wf,kf=E(()=>{"use strict";Ta=I(require("fs")),qf=I(require("path")),iv=new Set(["node_modules",".git",".venv","venv","env","__pycache__","site-packages",".mypy_cache",".pytest_cache",".tox","dist","build","out"]),ov={get:"GET",post:"POST",put:"PUT",patch:"PATCH",delete:"DELETE",options:"OPTIONS",head:"HEAD"},wf=new Set(["Request","Response","WebSocket","BackgroundTasks","Depends","Header","Cookie"])});function Pv(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 Oa,If,Ev,qv,Av,Sr,xu=E(()=>{"use strict";Oa=I(require("fs")),If=I(require("path"));kf();Ev=["requirements.txt","pyproject.toml","poetry.lock","Pipfile","setup.py"],qv=/^\s*from\s+fastapi\s+import|^\s*import\s+fastapi/m,Av=/@[\w.]+\.(get|post|put|patch|delete|options|head|api_route)\(/,Sr=class{id="provider.fastapi";framework="fastapi";supports(e){for(let s of Ev)if(Oa.existsSync(If.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=Oa.readFileSync(s,"utf-8");if(qv.test(i)&&Av.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=Af(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=Pv(e.type),s=an(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=an(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=an(o,t);a&&(s.body={type:"json",schema:i?{type:"array",items:a}:a})}return[s]}}});function xr(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]=xr(i);return n}if(e==="array"){let t=r.items;return[xr(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 Pn(r){let e=r.source?.symbolName||"";return e||`${r.method||"GET"} ${r.pathExpression}`}function kn(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=kv(r,e);return{headers:t,query:n,params:s,body:i}}function kv(r,e){let t=r.requestBody;if(!t)return;let n=t.type??"json";if(n==="json"){let s=t.schema,i=e&&s?xr(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 In(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(`
513
+ `)}function wu(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}=kn(r,!0);return{collectionId:e,name:Pn(r),method:r.method||"GET",url:s,headers:i,query:o,params:a,body:c,description:In(r)}}var Ru=E(()=>{"use strict"});function Ps(r){let e;try{let n=(0,$f.execSync)("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=$a.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let a of o){let c=Of.join(i,a.name);if(a.isDirectory()){s.has(a.name)||n.push(c);continue}if(!(!a.isFile()||!Iv.some(l=>c.endsWith(l))))try{let l=$a.statSync(c);l.mtimeMs>t&&(t=l.mtimeMs)}catch{}}}}catch{t=0}return{gitHash:e,maxSourceMtime:t}}function ks(r,e){let t=Ps(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 Cu(r){let e=r.projects.map(t=>ks(t.projectRoot,t.freshness));return{projects:e,staleCount:e.filter(t=>t.status==="stale").length,checkedAt:new Date().toISOString()}}function As(r,e){let t=r.split(`
514
514
  `),n=e.split(`
515
- `),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 Ta(r,e,t){let n=Es(r,e),s=Es(r,t),i=n.filter(o=>o.type!=="same").length;return{userChanges:n,regeneratedChanges:s,changed:t!==r,userEditedLineCount:i}}function Oa(r,e,t){let n=t.split(`
515
+ `),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 p=i-1;p>=0;p--)o[u][p]=t[u]===n[p]?o[u+1][p+1]+1:Math.max(o[u+1][p],o[u][p+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 Fa(r,e,t){let n=As(r,e),s=As(r,t),i=n.filter(o=>o.type!=="same").length;return{userChanges:n,regeneratedChanges:s,changed:t!==r,userEditedLineCount:i}}function Na(r,e,t){let n=t.split(`
516
516
  `),s=r.split(`
517
517
  `),i=e.split(`
518
- `),o=qf(n,s),a=qf(n,i);if(a.changedCount===0)return{merged:r,conflicts:[]};if(o.changedCount===0)return{merged:e,conflicts:[]};let c=[],l=[],u=n.length;for(let d=0;d<u;d++){let p=o.byLine[d],m=a.byLine[d],f=p==="removed",h=m==="removed";if(f&&h){let g=o.insertionsBefore[d].join(`
519
- `),v=a.insertionsBefore[d].join(`
520
- `);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(`
521
- `),conflicts:l}}function qf(r,e){let t=r.length,n=new Array(t).fill("kept"),s=Array.from({length:t+1},()=>[]),i=0,o=Es(r.join(`
518
+ `),o=Tf(n,s),a=Tf(n,i);if(a.changedCount===0)return{merged:r,conflicts:[]};if(o.changedCount===0)return{merged:e,conflicts:[]};let c=[],l=[],u=n.length;for(let p=0;p<u;p++){let d=o.byLine[p],m=a.byLine[p],f=d==="removed",h=m==="removed";if(f&&h){let g=o.insertionsBefore[p].join(`
519
+ `),v=a.insertionsBefore[p].join(`
520
+ `);for(let y of o.insertionsBefore[p])c.push(y);if(g!==v&&v!==""){l.push({type:"removed",line:p+1,text:n[p]});for(let y of a.insertionsBefore[p])c.push(y)}continue}if(f&&!h){for(let g of o.insertionsBefore[p])c.push(g);continue}if(!f&&h){for(let g of a.insertionsBefore[p])c.push(g);continue}for(let g of o.insertionsBefore[p])c.push(g);for(let g of a.insertionsBefore[p])c.push(g);c.push(n[p])}for(let p of o.insertionsBefore[u])c.push(p);for(let p of a.insertionsBefore[u])c.push(p);return{merged:c.join(`
521
+ `),conflicts:l}}function Tf(r,e){let t=r.length,n=new Array(t).fill("kept"),s=Array.from({length:t+1},()=>[]),i=0,o=As(r.join(`
522
522
  `),e.join(`
523
- `)),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 ji(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=Ta(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 Li(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}=Oa(e,t,n);return{canApply:!0,merged:s,conflicts:i.length}}var Ia,Pf,kf,Av,xu=E(()=>{"use strict";Ia=I(require("fs")),Pf=I(require("path")),kf=require("child_process"),Av=[".ts",".js",".java",".py"]});function Iv(r){if(!r||r.length===0)return;let e=r.filter(s=>qv.test(s.name));if(e.length===0)return;let t=e.map(s=>s.name).join(" ");return{required:!0,type:Pv.find(s=>s.re.test(t))?.type,annotation:e.map(s=>s.name).join(", ")}}function Tv(r){if(!r||r.length===0)return;let e=r.filter(t=>kv.test(t.name)).map(t=>t.name);if(e.length!==0)return[...new Set(e)]}function Ov(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 If(r){r.auth||(r.auth=Iv(r.middleware)),r.validation||(r.validation=Tv(r.middleware)??Ov(r.requestBody?.schema))}var qv,Pv,kv,Tf=E(()=>{"use strict";qv=/(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,Pv=[{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"}],kv=/(validat|schema|sanitiz|zod|joi|yup|ajv|express-validator|class-validator|validationpipe|dto)/i});function $f(r,e){let t=(Of[r.method.toUpperCase()]??99)-(Of[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 $v(r){let e=r.resolvedPath??r.pathExpression;if(!e)return;let t=new Set;for(let i of r.params??[])t.add(Ff(i.location,i.name));let n=tn(e);if(n.length===0)return;let s=[];for(let i of n){let o=Ff(i.location,i.name);t.has(o)||(t.add(o),s.push(i))}s.length>0&&(r.params=[...r.params??[],...s])}function Ff(r,e){return`${r}:${e.toLowerCase()}`}function Fv(r){return`${r.framework}:${r.method.toUpperCase()}:${r.resolvedPath??r.pathExpression}:${r.source.filePath}:${r.source.line}`}var Of,br,wu=E(()=>{"use strict";Tf();Rs();ca();ua();En();Of={GET:0,POST:1,PUT:2,PATCH:3,DELETE:4,HEAD:5,OPTIONS:6};br=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 cr}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=rt(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=Ii(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)$v(a);for(let a of i.endpoints)If(a);let o=this.dedupeAndSort(i.endpoints);for(let a of o)a.id=Fv(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)}
524
- `)}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($f);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($f)}}});var Nf=E(()=>{"use strict";Kl();Ap();ca();En();ua();Zl();su();iu();au();uu();hu();yu();Rs();bu();na();ia();xu();wu()});async function $a(r){return{endpoints:(await new br({providers:Nv()}).discover({workspaceFolder:r})).endpoints}}async function Mv(r,e){let{endpoints:t}=await $a(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 Nv,Mf,_f=E(()=>{"use strict";Ne();Nf();Me();Nv=()=>[new dr,new fr,new pr,new mr,new gr,new yr],Mf=[{toolNames:[S.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 T('"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 T('Provide "method" + "path", or "endpointId" to select the endpoint.');let o=await Mv(n,{endpointId:typeof r.endpointId=="string"?r.endpointId:void 0,method:s,pathExpression:i});if(!o)throw T(`No endpoint matched in ${n}`+(s&&i?` for ${s} ${i}`:""));let a=z(r.collection,t),c=typeof r.name=="string"&&r.name.trim()?r.name.trim():qn(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}=Pn(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:kn(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:[S.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 T('"projectPath" is required (or set services.workspaceFolder).');let s=z(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 $a(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:x}=Pn(h,r.sampleData===!0),b=(h.resolvedPath??h.pathExpression).replace(/^\/+/,""),R=i?`${i}/${b}`:h.resolvedPath??h.pathExpression,C={collectionId:s.id,name:qn(h),method:h.method||"GET",url:R,headers:g,query:v,params:y,body:x,description:kn(h)},q=await e.collection.createRequest(C);d.push({...h,id:q.id}),u.push({name:q.name,id:q.id})}let{suite:p,derived:m}=or(d,{collectionId:s.id,collectionName:s.name,folderPath:"",name:c,assertBodySchema:o}),f=ar(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:[S.suggestWorkflow],async handle({args:r,services:e}){let t=typeof r.projectPath=="string"&&r.projectPath.trim()?r.projectPath.trim():e.workspaceFolder;if(!t)throw T('"projectPath" is required (or set services.workspaceFolder).');let{endpoints:n}=await $a(t),s=Cn(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:[S.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 T('"projectPath" is required (or set services.workspaceFolder).');let s=z(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 $a(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}=Pn(f,r.sampleData===!0),x=(f.resolvedPath??f.pathExpression).replace(/^\/+/,""),b=i?`${i}/${x}`:f.resolvedPath??f.pathExpression,R={collectionId:s.id,name:qn(f),method:f.method||"GET",url:b,headers:h,query:g,params:v,body:y,description:kn(f)},C=await e.collection.createRequest(R);u.push({...f,id:C.id}),l.push({name:C.name,id:C.id})}let d=Cn(u,{collectionId:s.id,collectionName:s.name}),p=Date.now(),m={id:`wf_${ps(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:[S.checkDrift],async handle({args:r,services:e}){let t=typeof r.projectPath=="string"&&r.projectPath.trim()?r.projectPath.trim():e.workspaceFolder;if(!t)throw T('"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=As(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=qs(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:[S.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 T('"staleEndpointIds" must be a non-empty array (e.g. from check_drift).');if(t.length===0)throw T('"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=ji(e,o,n,s);return{proposedCount:a.length,proposals:a.map(c=>{let l=o.find(d=>d.id===c.suiteId),u=i?Li(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 Df,jf=E(()=>{"use strict";Ne();Me();Df=[{toolNames:[S.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 T(`environment "${t}" not found`);return{name:n.name,variables:n.variables}}},{toolNames:[S.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 T('"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 Lf,Hf=E(()=>{"use strict";Ne();Me();Lf=[{toolNames:[S.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:[S.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 T(`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:[S.selectEnvironment],async handle({args:r,services:e}){let t=typeof r.environment=="string"?r.environment.trim():"";if(!t)throw T('"environment" is required');return await e.environmentConfig.setSelectedEnvironment(t),{selected:!0,environment:t}}},{toolNames:[S.createEnvironment],async handle({args:r,services:e}){let t=typeof r.name=="string"?r.name.trim():"";if(!t)throw T('"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:[S.deleteEnvironment],async handle({args:r,services:e}){if(r.confirm!==!0)throw T('"confirm" must be true to delete an environment');let t=typeof r.environment=="string"?r.environment.trim():"";if(!t)throw T('"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:[S.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 T('"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:[S.unsetEnvironmentVariable],handle({args:r,services:e}){let t=typeof r.key=="string"?r.key.trim():"";if(!t)throw T('"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:[S.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 T('"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:[S.getGlobals],handle({services:r}){return{globals:r.environmentConfig.getGlobalVariables()}}}]});var Bf,Uf=E(()=>{"use strict";Ne();Me();Bf=[{toolNames:[S.runRequest],handle({args:r,services:e,collections:t,callbacks:n}){let s=z(r.collection,t),i=Q(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 T(`request with id "${o}" not found in collection "${s.name}"`)}else{if(typeof a!="string"||!a.trim())throw T('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 T(`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=>Lt(u,l))}},{toolNames:[S.runFolder],handle({args:r,collections:e,callbacks:t}){let n=z(r.collection,e);if(typeof r.folder!="string"||!r.folder.trim())throw T('the "folder" argument is required');let s=r.folder.toLowerCase(),i=tr(r.folder),o=i.toLowerCase(),a=Re(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 T(`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=>Lt(u,l))}},{toolNames:[S.runCollection],handle({args:r,collections:e,callbacks:t}){let n=z(r.collection,e),s=Array.isArray(r.include)?r.include:[];return t.runCollection(n,r).then(i=>Lt(i,s))}},{toolNames:[S.runSuite],handle({args:r,services:e,callbacks:t}){let n=r.suite;if(typeof n!="string"||!n.trim())throw T('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=>Lt(o,i))})}}]});var Vf,zf=E(()=>{"use strict";Ne();Me();Vf=[{toolNames:[S.listCollections],handle({collections:r}){return{collections:r.map(e=>({name:e.name,id:e.id,description:e.description??"",requestCount:Q(e).length}))}}},{toolNames:[S.listFolders],handle({args:r,collections:e}){let t=z(r.collection,e);return{collection:t.name,folders:Re(t).map(({folderPath:n,requestCount:s})=>({path:St(n),requestCount:s}))}}},{toolNames:[S.listRequests],handle({args:r,collections:e}){let t=z(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=Q(t).filter(({folderPath:a})=>!n||a.toLowerCase().includes(n)).map(({request:a,folderPath:c})=>({id:a.id,name:a.name,method:a.method,folder:St(c),description:a.description??""}));return{collection:t.name,total:o.length,offset:s,limit:i,requests:o.slice(s,s+i)}}},{toolNames:[S.searchRequests],handle({args:r,collections:e}){let t=z(r.collection,e),n=typeof r.query=="string"?r.query.toLowerCase().trim():"";if(!n)throw T('the "query" argument is required');let s=Q(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:St(o),description:i.description??""}));return{collection:t.name,query:r.query,total:s.length,requests:s}}},{toolNames:[S.getRequest],handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=Ve(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 Jf,Gf=E(()=>{"use strict";Ne();Me();Me();Jf=[{toolNames:[S.createRequest],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=typeof r.name=="string"?r.name.trim():"";if(!s)throw T('"name" is required');let i=typeof r.method=="string"?r.method.toUpperCase():"GET",o=typeof r.url=="string"?r.url:"";if(!o)throw T('"url" is required');let a;if(typeof r.folder=="string"&&r.folder.trim()){let u=r.folder.toLowerCase(),d=Re(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:[S.updateRequest],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=Ve(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:[S.deleteRequest],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw T('"confirm" must be true to delete a request');let n=z(r.collection,t),s=Ve(r.request,n);return await e.collection.deleteRequest(n.id,s.id),{deleted:!0,request:s.name}}},{toolNames:[S.getRequestScript],handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=Ve(r.request,n),i=r.phase;if(i!=="pre-request"&&i!=="post-response")throw T('"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:[S.setRequestScript],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t),s=Ve(r.request,n),i=r.phase;if(i!=="pre-request"&&i!=="post-response")throw T('"phase" must be "pre-request" or "post-response"');if(typeof r.script!="string")throw T('"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:[S.reorderCollectionItems],async handle({args:r,services:e,collections:t}){let n=z(r.collection,t);if(!Array.isArray(r.order))throw T('"order" must be an array');let s;if(typeof r.folder=="string"&&r.folder.trim()){let a=r.folder.toLowerCase(),c=Re(n).find(l=>l.folderPath===r.folder||l.folderPath.toLowerCase()===a);if(!c)throw T(`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 Fa(r){return r.status??r.responseStatus}function Ru(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 jv(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 Lv(r){let e=Ru(r).map(t=>`${t.name} ${t.message??""}`).join(" ");return/401|403|unauthor|forbidden|auth/i.test(e)}function Hv(r){return Ru(r).length>0}function Bv(r,e){if(Fa(r)===void 0&&!r.error)return;let t=jv(r);t&&_v.test(t)&&Dv.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 Uv(r,e){let t=Fa(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 Vv(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 zv(r,e){let t=Ru(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 Jv(r,e){if((r.method??"").toUpperCase()!=="DELETE")return;let t=Fa(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 Gv(r,e){Hv(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 Wv(r,e){let t=Fa(r);t!==401&&t!==403||Lv(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 Kv(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 Hi(r,e,t){let n=t?.slowResponseMs??2e3,s=[];for(let c of e)Bv(c,s),Uv(c,s),Vv(c,s),zv(c,s),Jv(c,s),t?.allowNoAssertions||Gv(c,s),Wv(c,s),Kv(c,s,n);r&&r.nodes&&r.nodes.length>0&&Zv(r,e,s),s.sort((c,l)=>Wf(c.severity)-Wf(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:[...Qv]}}function Wf(r){return r==="error"?0:r==="warn"?1:2}function Zv(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 Bi(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 _v,Dv,Qv,Kf=E(()=>{"use strict";_v=/(password|passwd|pwd|secret|api[_-]?key|auth[_-]?token|access[_-]?token|refresh[_-]?token|client[_-]?secret|authorization|private[_-]?key|cookie|token)\b/i,Dv=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{6,}|bearer\s+[a-z0-9._~+/=-]{12,}|-----BEGIN/i;Qv=["response-leaks-secrets","server-error","request-error","failed-assertions","delete-not-204","missing-assertions","auth-failure-unhandled","slow-response"]});var Cu=E(()=>{"use strict";Kf()});function In(r,e=2e3){return!r||r.length<=e?r:r.slice(0,e)+`
525
- \u2026 (truncated, ${r.length-e} chars omitted)`}function Ui(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 Qf(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 Yv(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=tt(t).snapshot().body,d=`I ran an HTTP API test suite and got failures. Please analyze the results and provide:
523
+ `)),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 Hi(r,e,t,n){let s=new Set(r),i=[];for(let o of e){let a=o.derivedFrom.filter(p=>s.has(p));if(a.length===0)continue;let c=t[o.id]??"",l=n[o.id];if(l===void 0)continue;let u=Fa(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 Bi(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}=Na(e,t,n);return{canApply:!0,merged:s,conflicts:i.length}}var $a,Of,$f,Iv,Eu=E(()=>{"use strict";$a=I(require("fs")),Of=I(require("path")),$f=require("child_process"),Iv=[".ts",".js",".java",".py"]});function Fv(r){if(!r||r.length===0)return;let e=r.filter(s=>Tv.test(s.name));if(e.length===0)return;let t=e.map(s=>s.name).join(" ");return{required:!0,type:Ov.find(s=>s.re.test(t))?.type,annotation:e.map(s=>s.name).join(", ")}}function Nv(r){if(!r||r.length===0)return;let e=r.filter(t=>$v.test(t.name)).map(t=>t.name);if(e.length!==0)return[...new Set(e)]}function Mv(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 Ff(r){r.auth||(r.auth=Fv(r.middleware)),r.validation||(r.validation=Nv(r.middleware)??Mv(r.requestBody?.schema))}var Tv,Ov,$v,Nf=E(()=>{"use strict";Tv=/(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,Ov=[{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"}],$v=/(validat|schema|sanitiz|zod|joi|yup|ajv|express-validator|class-validator|validationpipe|dto)/i});function _f(r,e){let t=(Mf[r.method.toUpperCase()]??99)-(Mf[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 _v(r){let e=r.resolvedPath??r.pathExpression;if(!e)return;let t=new Set;for(let i of r.params??[])t.add(Df(i.location,i.name));let n=tn(e);if(n.length===0)return;let s=[];for(let i of n){let o=Df(i.location,i.name);t.has(o)||(t.add(o),s.push(i))}s.length>0&&(r.params=[...r.params??[],...s])}function Df(r,e){return`${r}:${e.toLowerCase()}`}function Dv(r){return`${r.framework}:${r.method.toUpperCase()}:${r.resolvedPath??r.pathExpression}:${r.source.filePath}:${r.source.line}`}var Mf,wr,qu=E(()=>{"use strict";Nf();Es();da();fa();qn();Mf={GET:0,POST:1,PUT:2,PATCH:3,DELETE:4,HEAD:5,OPTIONS:6};wr=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 dr}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=nt(a);l.length>0&&(c.sourceFiles=l);let u=e.frameworksByProjectRoot?.[a]??this.detector.detectFrameworks(c);i.stats.frameworksDetected.push(...u);let p=this.providers.filter(f=>f.framework==="unknown"||u.includes("unknown")||u.includes(f.framework)?f.supports(c).supported||n:!1);i.stats.providersRun.push(...p.map(f=>f.id));let d=await Promise.all(p.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 d){for(let h of f.endpoints)h.projectRoot=h.projectRoot??a;i.endpoints.push(...f.endpoints),i.warnings.push(...f.warnings)}let m=Oi(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)_v(a);for(let a of i.endpoints)Ff(a);let o=this.dedupeAndSort(i.endpoints);for(let a of o)a.id=Dv(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)}
524
+ `)}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(_f);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(_f)}}});var jf=E(()=>{"use strict";Xl();Ip();da();qn();fa();tu();cu();lu();du();mu();bu();xu();Es();Ru();ia();ca();Eu();qu()});async function Ma(r){return{endpoints:(await new wr({providers:jv()}).discover({workspaceFolder:r})).endpoints}}async function Lv(r,e){let{endpoints:t}=await Ma(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 jv,Lf,Hf=E(()=>{"use strict";Me();jf();_e();jv=()=>[new mr,new gr,new hr,new yr,new br,new Sr],Lf=[{toolNames:[S.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 T('"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 T('Provide "method" + "path", or "endpointId" to select the endpoint.');let o=await Lv(n,{endpointId:typeof r.endpointId=="string"?r.endpointId:void 0,method:s,pathExpression:i});if(!o)throw T(`No endpoint matched in ${n}`+(s&&i?` for ${s} ${i}`:""));let a=G(r.collection,t),c=typeof r.name=="string"&&r.name.trim()?r.name.trim():Pn(o),l=typeof r.baseUrl=="string"&&r.baseUrl.trim()?r.baseUrl.trim().replace(/\/+$/,""):"",u=(o.resolvedPath??o.pathExpression).replace(/^\/+/,""),p=l?`${l}/${u}`:o.resolvedPath??o.pathExpression,{headers:d,query:m,params:f,body:h}=kn(o,r.sampleData===!0),g={collectionId:a.id,name:c,method:o.method||"GET",url:p,headers:d,query:m,params:f,body:h,description:In(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:[S.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 T('"projectPath" is required (or set services.workspaceFolder).');let s=G(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 Ma(n);if(l.endpoints.length===0)return{generated:!1,endpointCount:0,message:"No endpoints discovered in "+n};let u=[],p=[];for(let h of l.endpoints){if(a){p.push(h);continue}let{headers:g,query:v,params:y,body:x}=kn(h,r.sampleData===!0),b=(h.resolvedPath??h.pathExpression).replace(/^\/+/,""),C=i?`${i}/${b}`:h.resolvedPath??h.pathExpression,R={collectionId:s.id,name:Pn(h),method:h.method||"GET",url:C,headers:g,query:v,params:y,body:x,description:In(h)},q=await e.collection.createRequest(R);p.push({...h,id:q.id}),u.push({name:q.name,id:q.id})}let{suite:d,derived:m}=lr(p,{collectionId:s.id,collectionName:s.name,folderPath:"",name:c,assertBodySchema:o}),f=ur(p,{requestPathOf:h=>h.source?.symbolName??h.pathExpression,name:`${c} flow`});return!a&&e.testSuite&&await e.testSuite.updateSuite(d),{generated:!0,suite:d.id,name:d.name,collection:s.name,endpointCount:d.nodes.length,dryRun:a,aiGenerated:d.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:[S.suggestWorkflow],async handle({args:r,services:e}){let t=typeof r.projectPath=="string"&&r.projectPath.trim()?r.projectPath.trim():e.workspaceFolder;if(!t)throw T('"projectPath" is required (or set services.workspaceFolder).');let{endpoints:n}=await Ma(t),s=En(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:[S.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 T('"projectPath" is required (or set services.workspaceFolder).');let s=G(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 Ma(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}=kn(f,r.sampleData===!0),x=(f.resolvedPath??f.pathExpression).replace(/^\/+/,""),b=i?`${i}/${x}`:f.resolvedPath??f.pathExpression,C={collectionId:s.id,name:Pn(f),method:f.method||"GET",url:b,headers:h,query:g,params:v,body:y,description:In(f)},R=await e.collection.createRequest(C);u.push({...f,id:R.id}),l.push({name:R.name,id:R.id})}let p=En(u,{collectionId:s.id,collectionName:s.name}),d=Date.now(),m={id:`wf_${ms(a)}`,name:a,description:"Workflow chains generated from source-code discovery (Phase 2a L3).",nodes:p.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:d,updatedAt:d};return!o&&e.testSuite&&await e.testSuite.updateSuite(m),{generated:p.length>0,suite:m.id,name:m.name,collection:s.name,chainCount:p.length,dryRun:o,aiGenerated:!0,chains:p.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:[S.checkDrift],async handle({args:r,services:e}){let t=typeof r.projectPath=="string"&&r.projectPath.trim()?r.projectPath.trim():e.workspaceFolder;if(!t)throw T('"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=Ps(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=ks(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:[S.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 T('"staleEndpointIds" must be a non-empty array (e.g. from check_drift).');if(t.length===0)throw T('"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=Hi(e,o,n,s);return{proposedCount:a.length,proposals:a.map(c=>{let l=o.find(p=>p.id===c.suiteId),u=i?Bi(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 Bf,Uf=E(()=>{"use strict";Me();_e();Bf=[{toolNames:[S.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 T(`environment "${t}" not found`);return{name:n.name,variables:n.variables}}},{toolNames:[S.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 T('"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 Vf,zf=E(()=>{"use strict";Me();_e();Vf=[{toolNames:[S.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:[S.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 T(`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:[S.selectEnvironment],async handle({args:r,services:e}){let t=typeof r.environment=="string"?r.environment.trim():"";if(!t)throw T('"environment" is required');return await e.environmentConfig.setSelectedEnvironment(t),{selected:!0,environment:t}}},{toolNames:[S.createEnvironment],async handle({args:r,services:e}){let t=typeof r.name=="string"?r.name.trim():"";if(!t)throw T('"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:[S.deleteEnvironment],async handle({args:r,services:e}){if(r.confirm!==!0)throw T('"confirm" must be true to delete an environment');let t=typeof r.environment=="string"?r.environment.trim():"";if(!t)throw T('"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:[S.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 T('"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:[S.unsetEnvironmentVariable],handle({args:r,services:e}){let t=typeof r.key=="string"?r.key.trim():"";if(!t)throw T('"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:[S.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 T('"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:[S.getGlobals],handle({services:r}){return{globals:r.environmentConfig.getGlobalVariables()}}}]});var Jf,Gf=E(()=>{"use strict";Me();_e();Jf=[{toolNames:[S.runRequest],handle({args:r,services:e,collections:t,callbacks:n}){let s=G(r.collection,t),i=Q(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 T(`request with id "${o}" not found in collection "${s.name}"`)}else{if(typeof a!="string"||!a.trim())throw T('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 T(`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=>jt(u,l))}},{toolNames:[S.runFolder],handle({args:r,collections:e,callbacks:t}){let n=G(r.collection,e);if(typeof r.folder!="string"||!r.folder.trim())throw T('the "folder" argument is required');let s=r.folder.toLowerCase(),i=sr(r.folder),o=i.toLowerCase(),a=Ce(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(p=>p.toLowerCase().includes(o)));if(!c){let u=a.map(p=>`"${p}"`).join(", ");throw T(`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=>jt(u,l))}},{toolNames:[S.runCollection],handle({args:r,collections:e,callbacks:t}){let n=G(r.collection,e),s=Array.isArray(r.include)?r.include:[];return t.runCollection(n,r).then(i=>jt(i,s))}},{toolNames:[S.runSuite],handle({args:r,services:e,callbacks:t}){let n=r.suite;if(typeof n!="string"||!n.trim())throw T('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=>jt(o,i))})}}]});var Wf,Kf=E(()=>{"use strict";Me();_e();Wf=[{toolNames:[S.listCollections],handle({collections:r}){return{collections:r.map(e=>({name:e.name,id:e.id,description:e.description??"",requestCount:Q(e).length}))}}},{toolNames:[S.listFolders],handle({args:r,collections:e}){let t=G(r.collection,e);return{collection:t.name,folders:Ce(t).map(({folderPath:n,requestCount:s})=>({path:bt(n),requestCount:s}))}}},{toolNames:[S.listRequests],handle({args:r,collections:e}){let t=G(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=Q(t).filter(({folderPath:a})=>!n||a.toLowerCase().includes(n)).map(({request:a,folderPath:c})=>({id:a.id,name:a.name,method:a.method,folder:bt(c),description:a.description??""}));return{collection:t.name,total:o.length,offset:s,limit:i,requests:o.slice(s,s+i)}}},{toolNames:[S.searchRequests],handle({args:r,collections:e}){let t=G(r.collection,e),n=typeof r.query=="string"?r.query.toLowerCase().trim():"";if(!n)throw T('the "query" argument is required');let s=Q(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:bt(o),description:i.description??""}));return{collection:t.name,query:r.query,total:s.length,requests:s}}},{toolNames:[S.getRequest],handle({args:r,services:e,collections:t}){let n=G(r.collection,t),s=Xt(e,n.id,Ue(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 Qf,Zf=E(()=>{"use strict";Me();_e();_e();Qf=[{toolNames:[S.createRequest],async handle({args:r,services:e,collections:t}){let n=G(r.collection,t),s=typeof r.name=="string"?r.name.trim():"";if(!s)throw T('"name" is required');let i=typeof r.method=="string"?r.method.toUpperCase():"GET",o=typeof r.url=="string"?r.url:"";if(!o)throw T('"url" is required');let a;if(typeof r.folder=="string"&&r.folder.trim()){let u=r.folder.toLowerCase(),p=Ce(n).find(d=>d.folderPath===r.folder||d.folderPath.toLowerCase()===u);p&&(a=p.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:[S.updateRequest],async handle({args:r,services:e,collections:t}){let n=G(r.collection,t),s=Ue(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:[S.deleteRequest],async handle({args:r,services:e,collections:t}){if(r.confirm!==!0)throw T('"confirm" must be true to delete a request');let n=G(r.collection,t),s=Ue(r.request,n);return await e.collection.deleteRequest(n.id,s.id),{deleted:!0,request:s.name}}},{toolNames:[S.getRequestScript],handle({args:r,services:e,collections:t}){let n=G(r.collection,t),s=Ue(r.request,n),i=r.phase;if(i!=="pre-request"&&i!=="post-response")throw T('"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:[S.setRequestScript],async handle({args:r,services:e,collections:t}){let n=G(r.collection,t),s=Ue(r.request,n),i=r.phase;if(i!=="pre-request"&&i!=="post-response")throw T('"phase" must be "pre-request" or "post-response"');if(typeof r.script!="string")throw T('"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:[S.reorderCollectionItems],async handle({args:r,services:e,collections:t}){let n=G(r.collection,t);if(!Array.isArray(r.order))throw T('"order" must be an array');let s;if(typeof r.folder=="string"&&r.folder.trim()){let a=r.folder.toLowerCase(),c=Ce(n).find(l=>l.folderPath===r.folder||l.folderPath.toLowerCase()===a);if(!c)throw T(`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 _a(r){return r.status??r.responseStatus}function Au(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 Uv(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 Vv(r){let e=Au(r).map(t=>`${t.name} ${t.message??""}`).join(" ");return/401|403|unauthor|forbidden|auth/i.test(e)}function zv(r){return Au(r).length>0}function Jv(r,e){if(_a(r)===void 0&&!r.error)return;let t=Uv(r);t&&Hv.test(t)&&Bv.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 Gv(r,e){let t=_a(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 Wv(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 Kv(r,e){let t=Au(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 Qv(r,e){if((r.method??"").toUpperCase()!=="DELETE")return;let t=_a(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 Zv(r,e){zv(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 Yv(r,e){let t=_a(r);t!==401&&t!==403||Vv(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 Xv(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 Ui(r,e,t){let n=t?.slowResponseMs??2e3,s=[];for(let c of e)Jv(c,s),Gv(c,s),Wv(c,s),Kv(c,s),Qv(c,s),t?.allowNoAssertions||Zv(c,s),Yv(c,s),Xv(c,s,n);r&&r.nodes&&r.nodes.length>0&&tb(r,e,s),s.sort((c,l)=>Yf(c.severity)-Yf(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:[...eb]}}function Yf(r){return r==="error"?0:r==="warn"?1:2}function tb(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 Vi(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 Hv,Bv,eb,Xf=E(()=>{"use strict";Hv=/(password|passwd|pwd|secret|api[_-]?key|auth[_-]?token|access[_-]?token|refresh[_-]?token|client[_-]?secret|authorization|private[_-]?key|cookie|token)\b/i,Bv=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{6,}|bearer\s+[a-z0-9._~+/=-]{12,}|-----BEGIN/i;eb=["response-leaks-secrets","server-error","request-error","failed-assertions","delete-not-204","missing-assertions","auth-failure-unhandled","slow-response"]});var Pu=E(()=>{"use strict";Xf()});function Tn(r,e=2e3){return!r||r.length<=e?r:r.slice(0,e)+`
525
+ \u2026 (truncated, ${r.length-e} chars omitted)`}function zi(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 em(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 nb(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(d=>s&&typeof d.name=="string"&&!d.name.toLowerCase().includes(s)?!1:d.passed===!1||Array.isArray(d.assertions)&&d.assertions.some(m=>!m.passed)),c=i.summary,l=a.length,u=et(t).snapshot().body,p=`I ran an HTTP API test suite and got failures. Please analyze the results and provide:
526
526
 
527
527
  1. **Root cause** for each failure
528
528
  2. **Specific fixes** (updated URLs, auth headers, request body, environment variables)
@@ -538,45 +538,45 @@ ${u}
538
538
  `+(i.error?`- Run error: ${i.error}
539
539
  `:"")+`
540
540
  ## Failed Requests
541
- `;if(l===0)d+=`
542
- (No failures found`,s&&(d+=` matching "${r.request}"`),d+=`. The run may have passed entirely or the filter matched nothing.)
543
- `;else{for(let p of a.slice(0,20)){let m=String(p.name??"(unknown)"),f=String(p.method??""),h=String(p.url??""),g=p.responseStatus??p.status??"?",v=p.error,x=(p.assertions??[]).filter(q=>!q.passed),b=p.failedTests??x,R=typeof p.body=="string"?In(Ui(p.body),600):p.body?In(Ui(JSON.stringify(p.body)),600):"",C=typeof p.requestBody=="string"?In(Ui(p.requestBody),400):p.requestBody?In(Ui(JSON.stringify(p.requestBody)),400):"";if(d+=`
544
- ### ${m}`,(f||h)&&(d+=` [${f} ${h}]`),d+=`
545
- - HTTP status received: ${g}`,v&&(d+=`
546
- - Request error: ${v}`),C&&(d+=`
541
+ `;if(l===0)p+=`
542
+ (No failures found`,s&&(p+=` matching "${r.request}"`),p+=`. The run may have passed entirely or the filter matched nothing.)
543
+ `;else{for(let d of a.slice(0,20)){let m=String(d.name??"(unknown)"),f=String(d.method??""),h=String(d.url??""),g=d.responseStatus??d.status??"?",v=d.error,x=(d.assertions??[]).filter(q=>!q.passed),b=d.failedTests??x,C=typeof d.body=="string"?Tn(zi(d.body),600):d.body?Tn(zi(JSON.stringify(d.body)),600):"",R=typeof d.requestBody=="string"?Tn(zi(d.requestBody),400):d.requestBody?Tn(zi(JSON.stringify(d.requestBody)),400):"";if(p+=`
544
+ ### ${m}`,(f||h)&&(p+=` [${f} ${h}]`),p+=`
545
+ - HTTP status received: ${g}`,v&&(p+=`
546
+ - Request error: ${v}`),R&&(p+=`
547
547
  - Request body sent:
548
548
  \`\`\`json
549
- ${C}
550
- \`\`\``),b.length>0){d+=`
551
- - Failed assertions:`;for(let q of b)d+=`
552
- - \`${q.name}\`: ${q.message??"assertion failed"}`}R&&(d+=`
549
+ ${R}
550
+ \`\`\``),b.length>0){p+=`
551
+ - Failed assertions:`;for(let q of b)p+=`
552
+ - \`${q.name}\`: ${q.message??"assertion failed"}`}C&&(p+=`
553
553
  - Response body:
554
554
  \`\`\`json
555
- ${R}
556
- \`\`\``),d+=`
557
- `}l>20&&(d+=`
555
+ ${C}
556
+ \`\`\``),p+=`
557
+ `}l>20&&(p+=`
558
558
  _(${l-20} more failures omitted \u2014 fix the above first)_
559
- `)}return d+=`
560
- 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 Xv(r,e,t,n){let s=Qf(r.collection,e),i=Q(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=a.request,l=e.getRequestScript(s.id,c.id,"pre-request")??"",u=e.getRequestScript(s.id,c.id,"post-response")??"",d=et(c,a.folderPath).snapshot().body,p=tt(n).snapshot().body,m="";if(r.runId){let v=t.get(r.runId);if(v&&v.status!=="running"){let x=(v.allResults??[]).find(b=>typeof b.name=="string"&&b.name.toLowerCase()===c.name.toLowerCase());if(x){let b=x.responseStatus??x.status,R=typeof x.responseBody=="string"?In(Ui(x.responseBody),1500):"",C=x.responseHeaders?In(JSON.stringify(x.responseHeaders,null,2),500):"";m=`
559
+ `)}return p+=`
560
+ Please diagnose each failure and provide concrete, actionable fixes.`,{description:`Analyze ${l} failure(s) from run "${n}"`,messages:[{role:"user",content:{type:"text",text:p}}]}}async function rb(r,e,t,n){let s=em(r.collection,e),i=Q(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")??"",p=Xe(c,a.folderPath).snapshot().body,d=et(n).snapshot().body,m="";if(r.runId){let v=t.get(r.runId);if(v&&v.status!=="running"){let x=(v.allResults??[]).find(b=>typeof b.name=="string"&&b.name.toLowerCase()===c.name.toLowerCase());if(x){let b=x.responseStatus??x.status,C=typeof x.responseBody=="string"?Tn(zi(x.responseBody),1500):"",R=x.responseHeaders?Tn(JSON.stringify(x.responseHeaders,null,2),500):"";m=`
561
561
  ## Observed Response (run ${r.runId})
562
562
  - Status: ${b}
563
- `,C&&(m+=`- Headers:
563
+ `,R&&(m+=`- Headers:
564
564
  \`\`\`json
565
- ${C}
565
+ ${R}
566
566
  \`\`\`
567
- `),R&&(m+=`- Body:
567
+ `),C&&(m+=`- Body:
568
568
  \`\`\`json
569
- ${R}
569
+ ${C}
570
570
  \`\`\`
571
571
  `)}}}let f=c.headers?.filter(v=>v.enabled!==!1).map(v=>` ${v.name}: ${v.value}`).join(`
572
- `)||" (none)",h=c.body?In(JSON.stringify(c.body,null,2),600):"(no body)",g=`Please write pm.test() assertion scripts for the following HTTP API request.
572
+ `)||" (none)",h=c.body?Tn(JSON.stringify(c.body,null,2),600):"(no body)",g=`Please write pm.test() assertion scripts for the following HTTP API request.
573
573
 
574
- `+(d?`## Business Context (request docs & OpenAPI contract)
575
- ${d}
576
-
577
- `:"")+(p?`## Business Context (workspace knowledge)
574
+ `+(p?`## Business Context (request docs & OpenAPI contract)
578
575
  ${p}
579
576
 
577
+ `:"")+(d?`## Business Context (workspace knowledge)
578
+ ${d}
579
+
580
580
  `:"")+`## Request: ${c.name}
581
581
  - Method: ${c.method}
582
582
  - URL: ${c.url??"(not set)"}
@@ -593,7 +593,7 @@ ${h}
593
593
  `+(l?`
594
594
  ## Pre-Request Script
595
595
  \`\`\`javascript
596
- ${In(l,600)}
596
+ ${Tn(l,600)}
597
597
  \`\`\`
598
598
  `:"")+m+`
599
599
  ## Existing Post-Response Script
@@ -609,8 +609,8 @@ Write comprehensive pm.test() assertions for the **post-response script**. Cover
609
609
  4. Key response body fields (existence, type, value constraints)
610
610
  5. Business logic validations specific to this endpoint
611
611
 
612
- 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 eb(r,e,t){let n=Qf(r.collection,e),s=Q(n),i=Re(n),o=jt(n).snapshot().body,a=tt(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(`
613
- `),p=c.map(f=>` [${f.method}] ${f.folder!=="(root)"?f.folder+" / ":""}${f.name}${f.hasAssertions?" \u2713":" \u26A0 no assertions"}`).join(`
612
+ 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 sb(r,e,t){let n=em(r.collection,e),s=Q(n),i=Ce(n),o=Dt(n).snapshot().body,a=et(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),{}),p=i.map(f=>` ${f.folderPath} (${f.requestCount} requests)`).join(`
613
+ `),d=c.map(f=>` [${f.method}] ${f.folder!=="(root)"?f.folder+" / ":""}${f.name}${f.hasAssertions?" \u2713":" \u26A0 no assertions"}`).join(`
614
614
  `),m=`Please review the following HTTP Forge API collection and provide actionable recommendations.
615
615
 
616
616
  `+(o?`## Business Context (collection)
@@ -626,10 +626,10 @@ ${a}
626
626
  - HTTP methods: ${Object.entries(u).map(([f,h])=>`${f}(${h})`).join(", ")}
627
627
 
628
628
  ## Folder Structure
629
- ${d||" (no folders \u2014 all requests at root)"}
629
+ ${p||" (no folders \u2014 all requests at root)"}
630
630
 
631
631
  ## Requests (\u2713 = has assertions, \u26A0 = missing)
632
- `+p+(s.length>60?`
632
+ `+d+(s.length>60?`
633
633
  \u2026 (${s.length-60} more requests omitted)`:"")+`
634
634
 
635
635
  ## Coverage Gaps
@@ -647,7 +647,7 @@ Please provide recommendations for:
647
647
  5. **Authentication** \u2014 is auth consistent across requests that need it?
648
648
  6. **Environment variables** \u2014 are URLs and credentials properly parameterized?
649
649
 
650
- Be specific: name the exact requests or folders that need attention.`;return{description:`Review collection "${n.name}" (${s.length} requests, ${l.length} without assertions)`,messages:[{role:"user",content:{type:"text",text:m}}]}}async function Zf(r){let{rec:e,suite:t,report:n}=r,s={error:"\u{1F534} error",warn:"\u{1F7E1} warning",info:"\u{1F535} info"},i=n.findings.map((o,a)=>`${a+1}. [${s[o.severity]??o.severity}] **${o.title}**`+(o.requestName?` (request: \`${o.requestName}\`)`:"")+`
650
+ Be specific: name the exact requests or folders that need attention.`;return{description:`Review collection "${n.name}" (${s.length} requests, ${l.length} without assertions)`,messages:[{role:"user",content:{type:"text",text:m}}]}}async function tm(r){let{rec:e,suite:t,report:n}=r,s={error:"\u{1F534} error",warn:"\u{1F7E1} warning",info:"\u{1F535} info"},i=n.findings.map((o,a)=>`${a+1}. [${s[o.severity]??o.severity}] **${o.title}**`+(o.requestName?` (request: \`${o.requestName}\`)`:"")+`
651
651
  ${o.message}`+(o.suggestion?`
652
652
  \u2192 ${o.suggestion}`:""));return`A deterministic review of a suite run produced ${n.summary.errors} error(s), ${n.summary.warnings} warning(s). Do NOT change severities or dismiss findings \u2014 prioritize them and give the developer concrete next steps.
653
653
 
@@ -664,34 +664,34 @@ Be specific: name the exact requests or folders that need attention.`;return{des
664
664
  1. Rank the findings by what to fix first (1 = most important).
665
665
  2. For the top 3, give a concrete remediation (exact assertion, config change, or code fix).
666
666
  3. Note anything the deterministic rules cannot see (spec compliance, business logic) as a separate "Manual review" section.
667
- Keep it under 600 words.`}async function Na(r,e,t,n,s){switch(r){case"analyze-test-failure":return Yv(e,n,s);case"suggest-assertions":return Xv(e,t,n,s);case"review-collection":return eb(e,t,s);default:throw new Error(`Unknown prompt: "${r}". Available: ${Vi.map(i=>i.name).join(", ")}`)}}var Vi,Ma=E(()=>{"use strict";sr();Xe();Vi=[{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 Yf,Xf=E(()=>{"use strict";ir();Cu();Ma();Ne();Me();Yf=[{toolNames:[S.reviewSuite],async handle({args:r,services:e,runStore:t}){let n=typeof r.runId=="string"?r.runId.trim():void 0;if(!n)throw T('"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=Hi(i,Bi(s),{slowResponseMs:o}),c;if(e.aiProvider&&a.findings.length>0)try{let l=await Zf({rec:s,suite:i,report:a});c=(await nt(()=>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 em,tm=E(()=>{"use strict";Ne();Me();em=[{toolNames:[S.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:[S.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:Lt({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:[S.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:[S.getRequestResult],handle({args:r,runStore:e}){let t=e.require(r.runId),n=r.request;if(typeof n!="string"||!n)throw T('"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:[S.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 nm(r){return(Array.isArray(r.nodes)?r.nodes:[]).every(t=>t?.type==="request")}function At(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(...At(s.nodes,`${i}.nodes`)),Array.isArray(s.then)&&t.push(...At(s.then,`${i}.then`)),Array.isArray(s.else)&&t.push(...At(s.else,`${i}.else`)),Array.isArray(s.default)&&t.push(...At(s.default,`${i}.default`)),Array.isArray(s.elseif)&&s.elseif.forEach((o,a)=>{Array.isArray(o?.nodes)&&t.push(...At(o.nodes,`${i}.elseif.${a}.nodes`)),Array.isArray(o?.then)&&t.push(...At(o.then,`${i}.elseif.${a}.then`))}),Array.isArray(s.cases)&&s.cases.forEach((o,a)=>{Array.isArray(o?.nodes)&&t.push(...At(o.nodes,`${i}.cases.${a}.nodes`)),Array.isArray(o?.then)&&t.push(...At(o.then,`${i}.cases.${a}.then`))}))}return t}function Au(r,e){if(typeof r!="string"||!r.trim())throw T(`"${e}" is required`);let t=r.trim(),n=t.split(".");if(n.some(s=>s===""))throw T(`"${e}" is invalid: "${t}"`);return n.map(s=>/^\d+$/.test(s)?Number(s):s)}function sm(r,e){let t=Au(e,"path"),n=r;for(let s of t)if(typeof s=="number"){if(!Array.isArray(n)||s<0||s>=n.length)throw T(`node path not found: "${String(e)}"`);n=n[s]}else{if(!n||typeof n!="object"||!(s in n))throw T(`node path not found: "${String(e)}"`);n=n[s]}return n}function Eu(r,e){let t=Au(e,"path"),n=t[t.length-1];if(typeof n!="number")throw T(`"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 T(`node path not found: "${String(e)}"`);s=s[o]}else{if(!s||typeof s!="object"||!(o in s))throw T(`node path not found: "${String(e)}"`);s=s[o]}}if(!Array.isArray(s)||n<0||n>=s.length)throw T(`node path not found: "${String(e)}"`);return{array:s,index:n}}function rm(r,e,t,n){if(e==null||e===""){if(t!=null&&t!=="")throw T(`"${n}" is only valid when a parent path is provided`);return{array:r,pathPrefix:""}}if(typeof t!="string"||!t.trim())throw T(`"${n}" is required when parent path is provided`);let s=String(e).trim(),i=t.trim(),o=sm(r,s),a=Au(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 T(`branch path not found: "${i}"`);c=c[u]}else{if(!c||typeof c!="object")throw T(`branch path not found: "${i}"`);if(!(u in c))if(d)c[u]=[];else throw T(`branch path not found: "${i}"`);c=c[u]}}if(!Array.isArray(c))throw T(`target branch must be an array: "${i}"`);return{array:c,pathPrefix:`${s}.${i}`}}function tb(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 im,om=E(()=>{"use strict";Ne();Me();Me();im=[{toolNames:[S.listSuites],async handle({services:r}){return{suites:(await r.testSuite.getAllSuites()).map(t=>({id:t.id,name:t.name,description:t.description??"",requestCount:At(t.nodes||[]).length,flowNodeCount:t.nodes?.length??0,iterations:t.config?.iterations??1}))}}},{toolNames:[S.getSuite],async handle({args:r,services:e}){let t=await Ae(r.suite,e),n=At(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:[S.createSuite],async handle({args:r,services:e,collections:t}){let n=typeof r.name=="string"?r.name.trim():"";if(!n)throw T('"name" is required');let s;if(typeof r.fromCollection=="string"&&r.fromCollection.trim()){let i=z(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=tr(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 T('"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:[S.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 T('"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:[S.getSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);Array.isArray(t.nodes)||(t.nodes=[]);let n=sm(t.nodes,r.path);return{suite:t.name,path:String(r.path),node:n}}},{toolNames:[S.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=tb(t.nodes);return{suite:t.name,nodeCount:s.nodePaths.length,nodePaths:s.nodePaths,branchPaths:n?s.branchPaths:void 0,rootBranchPath:""}}},{toolNames:[S.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 T('"node" must be an object');let{array:n,pathPrefix:s}=rm(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:[S.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 T('"node" must be an object');let n=Eu(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:[S.removeSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);Array.isArray(t.nodes)||(t.nodes=[]);let n=Eu(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:[S.moveSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);Array.isArray(t.nodes)||(t.nodes=[]);let n=Eu(t.nodes,r.fromPath),s=n.array[n.index];n.array.splice(n.index,1);let{array:i,pathPrefix:o}=rm(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:[S.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 T('"requests" array is required and must not be empty');let i=[];for(let c of s){let l=z(c.collection,t),u=Ve(c.request,l),d=Q(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:At(n.nodes||[]).length}}},{toolNames:[S.removeSuiteRequest],async handle({args:r,services:e}){let t=await Ae(r.suite,e);if(!nm(t))throw T('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 T(`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 T(`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 T('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:[S.reorderSuiteRequests],async handle({args:r,services:e}){let t=await Ae(r.suite,e);if(!nm(t))throw T('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 T('"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:[S.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 T('"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:[S.deleteSuite],async handle({args:r,services:e}){if(r.confirm!==!0)throw T('"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 rb(){let r=new Map;for(let e of nb)for(let t of e.toolNames)r.set(t,e);return r}var nb,qu,Nq,am=E(()=>{"use strict";wp();Ep();_f();jf();Hf();Uf();zf();Gf();Xf();tm();om();nb=[...Vf,...Df,...em,...Bf,...Cp,...Jf,...Yf,...Mf,...im,...Lf,...xp];qu=rb(),Nq=new Set([...qu.keys()].map(r=>r))});function sb(r){return new Error(`Bad request: ${r}`)}async function Da(r,e,t,n,s){let i=qu.get(r);if(!i)throw sb(`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 _a,Pu=E(()=>{"use strict";am();Ne();Me();_a=new Set([S.createCollection,S.renameCollection,S.deleteCollection,S.duplicateCollection,S.createFolder,S.deleteFolder,S.createRequest,S.updateRequest,S.deleteRequest,S.reorderCollectionItems,S.createSuite,S.updateSuiteConfig,S.addSuiteNode,S.updateSuiteNode,S.removeSuiteNode,S.moveSuiteNode,S.duplicateSuite,S.deleteSuite,S.designApiFromIntent])});var Ps,ku=E(()=>{"use strict";Ps=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)}}});function lm(r){return(0,cm.createHash)("sha256").update(r,"utf8").digest("hex").slice(0,ib)}function cb(r){let e=r.replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/__+/g,"_").replace(/^_+|_+$/g,"").toLowerCase();return e?e.slice(0,ob):"id"}function Tn(r){return`${cb(r)}_${lm(r)}`}function lb(r,e){return r.length>0&&r.length<=e&&/^[a-zA-Z0-9_-]+$/.test(r)&&!r.includes("__")}function ks(r,e=ab){return lb(r,e)?r:Tn(r)}function La(r,e,t){let n=`${r}request__${ks(e)}__${ks(t)}`;return n.length<=ja?n:`${r}request__${Tn(e)}__${Tn(t)}`}function Ha(r,e){let t=`${r}collection__${ks(e,100)}`;return t.length<=ja?t:`${r}collection__${Tn(e)}`}function Ba(r,e,t){let n=`${r}folder__${ks(e)}__${ks(t)}`;return n.length<=ja?n:`${r}folder__${Tn(e)}__${Tn(t)}`}function Ua(r,e){let t=`${r}suite__${ks(e,100)}`;return t.length<=ja?t:`${r}suite__${Tn(e)}`}function Va(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 Sr(r,e){let t=r.includes("_")?r.slice(r.lastIndexOf("_")+1):r;for(let n of e)if(lm(n)===t)return n;for(let n of e)if(Tn(n)===r)return n;for(let n of e)if(n===r)return n}function za(r,e){let t=Sr(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 Ja(r,e,t,n){let s=n?` in folder "${n}"`:"";return`Run the "${e}" request [${r}]${s} of the "${t}" collection.`}function Ga(r,e){return`Run all ${e} requests in the "${r}" collection.`}function Wa(r,e,t){return`Run all ${t} requests in folder "${r}" of the "${e}" collection.`}function Ka(r,e,t){return`Run the "${r}" test suite (${e} requests, ${t} iteration(s) by default).`}var cm,ib,ob,ab,ja,Qa=E(()=>{"use strict";cm=require("crypto"),ib=12,ob=16,ab=60,ja=126});function Iu(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 Za(r){return Buffer.from(String(r)).toString("base64url")}function Ya(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 Xa(r,e,t,n){let s=t.toolPrefix??"",i=t.toolMode??"auto",o=t.drilldownThreshold??100;if(i==="execution-only"){let u=ki(s,r.map(d=>d.name),e.map(d=>d.name));return Iu(u.filter(d=>!ub.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+=Q(u).length;let c=i==="drilldown"||i==="auto"&&a>o;if(c&&i==="auto"&&n){let u=dm.join(n,".http-forge","AGENTS.md");um.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 Iu(ki(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=Q(u);for(let{request:p,folderPath:m}of d)l.push({name:La(s,u.id,p.id),description:Ja(p.method,p.name,u.name,m),inputSchema:Ei});l.push({name:Ha(s,u.id),description:Ga(u.name,d.length),inputSchema:Ai});for(let{folderPath:p,requestCount:m}of Re(u))m!==0&&l.push({name:Ba(s,u.id,p),description:Wa(p,u.name,m),inputSchema:qi})}for(let u of e)l.push({name:Ua(s,u.id),description:Ka(u.name,u.nodes.filter(d=>d.type==="request").length,u.config.iterations),inputSchema:Pi});return Iu(l)}var um,dm,ub,Tu=E(()=>{"use strict";um=I(require("fs")),dm=I(require("path"));Xe();Qa();Ne();ub=["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","design_api_from_intent","review_suite"]});function Is(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 ec=E(()=>{"use strict"});var On,tc=E(()=>{"use strict";jn();On=class{cookies=new Map;getCookieKey(e,t,n){return ie.cookieKey(e,t,n)}getCookiesForDomain(e){let t=[];for(let n of this.cookies.values())ie.isExpired(n)||(!n.domain||ie.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&&!ie.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())ie.isExpired(n)||t.push(n);return t}setCookiesFromResponse(e,t){let n=ie.extractDomain(e),s=ie.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=ie.extractDomain(e),n=ie.extractPath(e),i=this.getCookiesForDomain(t).filter(o=>o.path?n.startsWith(o.path):!0);if(i.length!==0)return ie.formatCookieHeader(i)}clear(){this.cookies.clear()}}});function $n(r,e,t){let n=String(r).padStart(6,"0"),s=String(e).padStart(4,"0");return`result-${n}-iter-${s}-${t}.json`}var nc,st,Ts=E(()=>{"use strict";nc={GET:0,POST:1,PUT:2,DELETE:3,PATCH:4,HEAD:5,OPTIONS:6,TRACE:7,CONNECT:8},st={0:"GET",1:"POST",2:"PUT",3:"DELETE",4:"PATCH",5:"HEAD",6:"OPTIONS",7:"TRACE",8:"CONNECT"}});function ze(r){return String(r??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g,"")}function Ou(r){return(Math.max(0,r)/1e3).toFixed(3)}var $s,Os,Ht,zi=E(()=>{"use strict";$s=I(require("fs/promises")),Os=I(require("path"));Ts();Ht=class{constructor(e){this.basePath=e}basePath;async generate(e,t){let n=Os.join(this.basePath,e,t),s=JSON.parse(await $s.readFile(Os.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=Os.join(n,"junit.xml");return await $s.writeFile(c,a,"utf-8"),c}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 $s.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=$n(s.i,s.it,s.r),o=`${s.i}-${s.it}`;try{let a=JSON.parse(await $s.readFile(Os.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||st[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,x=0,b=[];for(let q of m.cases){h++,x+=q.durationMs;let _=!q.passed&&q.failedAssertions.length===0&&!!q.error,M=!q.passed&&!_;_&&v++,M&&g++,q.skippedAssertions>0&&y++;let D=[];if(M){let O=q.failedAssertions.length>0?q.failedAssertions.map(Z=>Z.name).join("; "):q.error||"Assertion failed",H=q.failedAssertions.map(Z=>Z.message?`${Z.name}: ${Z.message}`:Z.name).join(`
668
- `);D.push(` <failure message="${ze(O)}" type="AssertionFailure">${ze(H)}</failure>`)}_&&D.push(` <error message="${ze(q.error)}" type="RequestError">${ze(q.error)}</error>`),q.skippedAssertions>0&&D.push(` <skipped message="${q.skippedAssertions} assertion(s) skipped via pm.test.skip()" />`),q.consoleOutput&&q.consoleOutput.length>0&&D.push(` <system-out>${ze(q.consoleOutput.join(`
669
- `))}</system-out>`);let V=` <testcase name="${ze(q.name)}" classname="${ze(q.classname)}" time="${Ou(q.durationMs)}"`;D.length===0?b.push(`${V} />`):b.push(`${V}>
670
- ${D.join(`
667
+ Keep it under 600 words.`}async function Da(r,e,t,n,s){switch(r){case"analyze-test-failure":return nb(e,n,s);case"suggest-assertions":return rb(e,t,n,s);case"review-collection":return sb(e,t,s);default:throw new Error(`Unknown prompt: "${r}". Available: ${Ji.map(i=>i.name).join(", ")}`)}}var Ji,ja=E(()=>{"use strict";ar();Ye();Ji=[{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 nm,rm=E(()=>{"use strict";cr();Pu();ja();Me();_e();nm=[{toolNames:[S.reviewSuite],async handle({args:r,services:e,runStore:t}){let n=typeof r.runId=="string"?r.runId.trim():void 0;if(!n)throw T('"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=Ui(i,Vi(s),{slowResponseMs:o}),c;if(e.aiProvider&&a.findings.length>0)try{let l=await tm({rec:s,suite:i,report:a});c=(await tt(()=>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 sm,im=E(()=>{"use strict";Me();_e();sm=[{toolNames:[S.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:[S.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:jt({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:[S.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:[S.getRequestResult],handle({args:r,runStore:e}){let t=e.require(r.runId),n=r.request;if(typeof n!="string"||!n)throw T('"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:[S.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 om(r){return(Array.isArray(r.nodes)?r.nodes:[]).every(t=>t?.type==="request")}function Et(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(...Et(s.nodes,`${i}.nodes`)),Array.isArray(s.then)&&t.push(...Et(s.then,`${i}.then`)),Array.isArray(s.else)&&t.push(...Et(s.else,`${i}.else`)),Array.isArray(s.default)&&t.push(...Et(s.default,`${i}.default`)),Array.isArray(s.elseif)&&s.elseif.forEach((o,a)=>{Array.isArray(o?.nodes)&&t.push(...Et(o.nodes,`${i}.elseif.${a}.nodes`)),Array.isArray(o?.then)&&t.push(...Et(o.then,`${i}.elseif.${a}.then`))}),Array.isArray(s.cases)&&s.cases.forEach((o,a)=>{Array.isArray(o?.nodes)&&t.push(...Et(o.nodes,`${i}.cases.${a}.nodes`)),Array.isArray(o?.then)&&t.push(...Et(o.then,`${i}.cases.${a}.then`))}))}return t}function Iu(r,e){if(typeof r!="string"||!r.trim())throw T(`"${e}" is required`);let t=r.trim(),n=t.split(".");if(n.some(s=>s===""))throw T(`"${e}" is invalid: "${t}"`);return n.map(s=>/^\d+$/.test(s)?Number(s):s)}function cm(r,e){let t=Iu(e,"path"),n=r;for(let s of t)if(typeof s=="number"){if(!Array.isArray(n)||s<0||s>=n.length)throw T(`node path not found: "${String(e)}"`);n=n[s]}else{if(!n||typeof n!="object"||!(s in n))throw T(`node path not found: "${String(e)}"`);n=n[s]}return n}function ku(r,e){let t=Iu(e,"path"),n=t[t.length-1];if(typeof n!="number")throw T(`"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 T(`node path not found: "${String(e)}"`);s=s[o]}else{if(!s||typeof s!="object"||!(o in s))throw T(`node path not found: "${String(e)}"`);s=s[o]}}if(!Array.isArray(s)||n<0||n>=s.length)throw T(`node path not found: "${String(e)}"`);return{array:s,index:n}}function am(r,e,t,n){if(e==null||e===""){if(t!=null&&t!=="")throw T(`"${n}" is only valid when a parent path is provided`);return{array:r,pathPrefix:""}}if(typeof t!="string"||!t.trim())throw T(`"${n}" is required when parent path is provided`);let s=String(e).trim(),i=t.trim(),o=cm(r,s),a=Iu(i,n),c=o;for(let l=0;l<a.length;l+=1){let u=a[l],p=l===a.length-1;if(typeof u=="number"){if(!Array.isArray(c)||u<0||u>=c.length)throw T(`branch path not found: "${i}"`);c=c[u]}else{if(!c||typeof c!="object")throw T(`branch path not found: "${i}"`);if(!(u in c))if(p)c[u]=[];else throw T(`branch path not found: "${i}"`);c=c[u]}}if(!Array.isArray(c))throw T(`target branch must be an array: "${i}"`);return{array:c,pathPrefix:`${s}.${i}`}}function ib(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,p)=>{Array.isArray(u?.nodes)&&s(u.nodes,`${l}.cases.${p}.nodes`),Array.isArray(u?.then)&&s(u.then,`${l}.cases.${p}.then`)}),Array.isArray(c.elseif)&&c.elseif.forEach((u,p)=>{Array.isArray(u?.nodes)&&s(u.nodes,`${l}.elseif.${p}.nodes`),Array.isArray(u?.then)&&s(u.then,`${l}.elseif.${p}.then`)}))}}};return s(r,e),{nodePaths:t,branchPaths:n}}var lm,um=E(()=>{"use strict";Me();_e();_e();lm=[{toolNames:[S.listSuites],async handle({services:r}){return{suites:(await r.testSuite.getAllSuites()).map(t=>({id:t.id,name:t.name,description:t.description??"",requestCount:Et(t.nodes||[]).length,flowNodeCount:t.nodes?.length??0,iterations:t.config?.iterations??1}))}}},{toolNames:[S.getSuite],async handle({args:r,services:e}){let t=await Ae(r.suite,e),n=Et(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:[S.createSuite],async handle({args:r,services:e,collections:t}){let n=typeof r.name=="string"?r.name.trim():"";if(!n)throw T('"name" is required');let s;if(typeof r.fromCollection=="string"&&r.fromCollection.trim()){let i=G(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=sr(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 T('"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:[S.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 T('"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:[S.getSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);Array.isArray(t.nodes)||(t.nodes=[]);let n=cm(t.nodes,r.path);return{suite:t.name,path:String(r.path),node:n}}},{toolNames:[S.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=ib(t.nodes);return{suite:t.name,nodeCount:s.nodePaths.length,nodePaths:s.nodePaths,branchPaths:n?s.branchPaths:void 0,rootBranchPath:""}}},{toolNames:[S.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 T('"node" must be an object');let{array:n,pathPrefix:s}=am(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:[S.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 T('"node" must be an object');let n=ku(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:[S.removeSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);Array.isArray(t.nodes)||(t.nodes=[]);let n=ku(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:[S.moveSuiteNode],async handle({args:r,services:e}){let t=await Ae(r.suite,e);Array.isArray(t.nodes)||(t.nodes=[]);let n=ku(t.nodes,r.fromPath),s=n.array[n.index];n.array.splice(n.index,1);let{array:i,pathPrefix:o}=am(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:[S.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 T('"requests" array is required and must not be empty');let i=[];for(let c of s){let l=G(c.collection,t),u=Ue(c.request,l),p=Q(l).find(d=>d.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:p,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:Et(n.nodes||[]).length}}},{toolNames:[S.removeSuiteRequest],async handle({args:r,services:e}){let t=await Ae(r.suite,e);if(!om(t))throw T('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 T(`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 T(`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 T('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:[S.reorderSuiteRequests],async handle({args:r,services:e}){let t=await Ae(r.suite,e);if(!om(t))throw T('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 T('"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||"",p=n.findIndex(h=>h===l||h.toLowerCase()===l.toLowerCase()),d=n.findIndex(h=>h===u||h.toLowerCase()===u.toLowerCase());return(p===-1?1/0:p)-(d===-1?1/0:d)});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:[S.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 T('"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:[S.deleteSuite],async handle({args:r,services:e}){if(r.confirm!==!0)throw T('"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 ab(){let r=new Map;for(let e of ob)for(let t of e.toolNames)r.set(t,e);return r}var ob,Tu,UA,dm=E(()=>{"use strict";qp();kp();Hf();Uf();zf();Gf();Kf();Zf();rm();im();um();ob=[...Wf,...Bf,...sm,...Jf,...Pp,...Qf,...nm,...Lf,...lm,...Vf,...Ep];Tu=ab(),UA=new Set([...Tu.keys()].map(r=>r))});function cb(r){return new Error(`Bad request: ${r}`)}async function Ha(r,e,t,n,s){let i=Tu.get(r);if(!i)throw cb(`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 La,Ou=E(()=>{"use strict";dm();Me();_e();La=new Set([S.createCollection,S.renameCollection,S.deleteCollection,S.duplicateCollection,S.createFolder,S.deleteFolder,S.createRequest,S.updateRequest,S.deleteRequest,S.reorderCollectionItems,S.createSuite,S.updateSuiteConfig,S.addSuiteNode,S.updateSuiteNode,S.removeSuiteNode,S.moveSuiteNode,S.duplicateSuite,S.deleteSuite,S.designApiFromIntent])});var Is,$u=E(()=>{"use strict";Is=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)}}});function fm(r){return(0,pm.createHash)("sha256").update(r,"utf8").digest("hex").slice(0,lb)}function pb(r){let e=r.replace(/[^a-zA-Z0-9_-]+/g,"_").replace(/__+/g,"_").replace(/^_+|_+$/g,"").toLowerCase();return e?e.slice(0,ub):"id"}function On(r){return`${pb(r)}_${fm(r)}`}function fb(r,e){return r.length>0&&r.length<=e&&/^[a-zA-Z0-9_-]+$/.test(r)&&!r.includes("__")}function Ts(r,e=db){return fb(r,e)?r:On(r)}function Ua(r,e,t){let n=`${r}request__${Ts(e)}__${Ts(t)}`;return n.length<=Ba?n:`${r}request__${On(e)}__${On(t)}`}function Va(r,e){let t=`${r}collection__${Ts(e,100)}`;return t.length<=Ba?t:`${r}collection__${On(e)}`}function za(r,e,t){let n=`${r}folder__${Ts(e)}__${Ts(t)}`;return n.length<=Ba?n:`${r}folder__${On(e)}__${On(t)}`}function Ja(r,e){let t=`${r}suite__${Ts(e,100)}`;return t.length<=Ba?t:`${r}suite__${On(e)}`}function Ga(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 Rr(r,e){let t=r.includes("_")?r.slice(r.lastIndexOf("_")+1):r;for(let n of e)if(fm(n)===t)return n;for(let n of e)if(On(n)===r)return n;for(let n of e)if(n===r)return n}function Wa(r,e){let t=Rr(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 Ka(r,e,t,n){let s=n?` in folder "${n}"`:"";return`Run the "${e}" request [${r}]${s} of the "${t}" collection.`}function Qa(r,e){return`Run all ${e} requests in the "${r}" collection.`}function Za(r,e,t){return`Run all ${t} requests in folder "${r}" of the "${e}" collection.`}function Ya(r,e,t){return`Run the "${r}" test suite (${e} requests, ${t} iteration(s) by default).`}var pm,lb,ub,db,Ba,Xa=E(()=>{"use strict";pm=require("crypto"),lb=12,ub=16,db=60,Ba=126});function Fu(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 ec(r){return Buffer.from(String(r)).toString("base64url")}function tc(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 nc(r,e,t,n){let s=t.toolPrefix??"",i=t.toolMode??"auto",o=t.drilldownThreshold??100;if(i==="execution-only"){let u=Ti(s,r.map(p=>p.name),e.map(p=>p.name));return Fu(u.filter(p=>!mb.some(d=>p.name.endsWith(d))).map(p=>({name:p.name,description:p.description,inputSchema:p.inputSchema,...p.annotations&&{annotations:p.annotations}})))}let a=0;for(let u of r)a+=Q(u).length;let c=i==="drilldown"||i==="auto"&&a>o;if(c&&i==="auto"&&n){let u=hm.join(n,".http-forge","AGENTS.md");mm.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 Fu(Ti(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 p=Q(u);for(let{request:d,folderPath:m}of p)l.push({name:Ua(s,u.id,d.id),description:Ka(d.method,d.name,u.name,m),inputSchema:Ai});l.push({name:Va(s,u.id),description:Qa(u.name,p.length),inputSchema:Pi});for(let{folderPath:d,requestCount:m}of Ce(u))m!==0&&l.push({name:za(s,u.id,d),description:Za(d,u.name,m),inputSchema:ki})}for(let u of e)l.push({name:Ja(s,u.id),description:Ya(u.name,u.nodes.filter(p=>p.type==="request").length,u.config.iterations),inputSchema:Ii});return Fu(l)}var mm,hm,mb,Nu=E(()=>{"use strict";mm=I(require("fs")),hm=I(require("path"));Ye();Xa();Me();mb=["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","design_api_from_intent","review_suite"]});function Os(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 rc=E(()=>{"use strict"});var $n,sc=E(()=>{"use strict";Bn();$n=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 Fn(r,e,t){let n=String(r).padStart(6,"0"),s=String(e).padStart(4,"0");return`result-${n}-iter-${s}-${t}.json`}var ic,rt,$s=E(()=>{"use strict";ic={GET:0,POST:1,PUT:2,DELETE:3,PATCH:4,HEAD:5,OPTIONS:6,TRACE:7,CONNECT:8},rt={0:"GET",1:"POST",2:"PUT",3:"DELETE",4:"PATCH",5:"HEAD",6:"OPTIONS",7:"TRACE",8:"CONNECT"}});function Ve(r){return String(r??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g,"")}function Mu(r){return(Math.max(0,r)/1e3).toFixed(3)}var Ns,Fs,Lt,Gi=E(()=>{"use strict";Ns=I(require("fs/promises")),Fs=I(require("path"));$s();Lt=class{constructor(e){this.basePath=e}basePath;async generate(e,t){let n=Fs.join(this.basePath,e,t),s=JSON.parse(await Ns.readFile(Fs.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=Fs.join(n,"junit.xml");return await Ns.writeFile(c,a,"utf-8"),c}async loadAllSummaries(e,t){let n=[];for(let s=1;s<=t;s++){let i=Fs.join(e,"index",`page-${String(s).padStart(4,"0")}.json`);try{let o=JSON.parse(await Ns.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=Fn(s.i,s.it,s.r),o=`${s.i}-${s.it}`;try{let a=JSON.parse(await Ns.readFile(Fs.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||"",p=`${l}\0${u}`;if(!o.has(p)){let g=[l,u].filter(Boolean).join(" / ")||e.suiteName||"Requests";o.set(p,{label:g,cases:[]}),i.push(p)}let d=a.n||c?.name||rt[a.m]||"request",m=s?`${d} (iteration ${a.it})`:d,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(p).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,x=0,b=[];for(let q of m.cases){h++,x+=q.durationMs;let N=!q.passed&&q.failedAssertions.length===0&&!!q.error,M=!q.passed&&!N;N&&v++,M&&g++,q.skippedAssertions>0&&y++;let _=[];if(M){let O=q.failedAssertions.length>0?q.failedAssertions.map(Z=>Z.name).join("; "):q.error||"Assertion failed",L=q.failedAssertions.map(Z=>Z.message?`${Z.name}: ${Z.message}`:Z.name).join(`
668
+ `);_.push(` <failure message="${Ve(O)}" type="AssertionFailure">${Ve(L)}</failure>`)}N&&_.push(` <error message="${Ve(q.error)}" type="RequestError">${Ve(q.error)}</error>`),q.skippedAssertions>0&&_.push(` <skipped message="${q.skippedAssertions} assertion(s) skipped via pm.test.skip()" />`),q.consoleOutput&&q.consoleOutput.length>0&&_.push(` <system-out>${Ve(q.consoleOutput.join(`
669
+ `))}</system-out>`);let H=` <testcase name="${Ve(q.name)}" classname="${Ve(q.classname)}" time="${Mu(q.durationMs)}"`;_.length===0?b.push(`${H} />`):b.push(`${H}>
670
+ ${_.join(`
671
671
  `)}
672
- </testcase>`)}i+=h,o+=g,a+=v,l+=x,c+=y;let C=` <properties>
673
- ${[` <property name="environment" value="${ze(e.environment)}" />`,` <property name="suiteName" value="${ze(e.suiteName)}" />`,` <property name="runId" value="${ze(e.runId)}" />`,` <property name="status" value="${ze(e.status)}" />`,` <property name="iterations" value="${e.config?.iterations??1}" />`,` <property name="delay" value="${e.config?.delayBetweenRequests??0}ms" />`,` <property name="stopOnError" value="${e.config?.stopOnError??!1}" />`].join(`
672
+ </testcase>`)}i+=h,o+=g,a+=v,l+=x,c+=y;let R=` <properties>
673
+ ${[` <property name="environment" value="${Ve(e.environment)}" />`,` <property name="suiteName" value="${Ve(e.suiteName)}" />`,` <property name="runId" value="${Ve(e.runId)}" />`,` <property name="status" value="${Ve(e.status)}" />`,` <property name="iterations" value="${e.config?.iterations??1}" />`,` <property name="delay" value="${e.config?.delayBetweenRequests??0}ms" />`,` <property name="stopOnError" value="${e.config?.stopOnError??!1}" />`].join(`
674
674
  `)}
675
- </properties>`;u.push(` <testsuite name="${ze(m.label)}" tests="${h}" failures="${g}" errors="${v}" skipped="${y}" time="${Ou(x)}" timestamp="${ze(e.startTime)}" id="${f}">
676
- ${C}
675
+ </properties>`;u.push(` <testsuite name="${Ve(m.label)}" tests="${h}" failures="${g}" errors="${v}" skipped="${y}" time="${Mu(x)}" timestamp="${Ve(e.startTime)}" id="${f}">
676
+ ${R}
677
677
  ${b.join(`
678
678
  `)}
679
- </testsuite>`)});let d='<?xml version="1.0" encoding="UTF-8"?>',p=`<testsuites name="${ze(e.suiteName)}" tests="${i}" failures="${o}" errors="${a}" skipped="${c}" time="${Ou(l)}">`;return`${d}
680
- ${p}
679
+ </testsuite>`)});let p='<?xml version="1.0" encoding="UTF-8"?>',d=`<testsuites name="${Ve(e.suiteName)}" tests="${i}" failures="${o}" errors="${a}" skipped="${c}" time="${Mu(l)}">`;return`${p}
680
+ ${d}
681
681
  ${u.join(`
682
682
  `)}
683
683
  </testsuites>
684
- `}}});function se(r){return String(r??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function hm(r,e=mm){if(r.length<=e)return r;let t=r.length-e;return r.slice(0,e)+`
684
+ `}}});function ie(r){return String(r??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function bm(r,e=vm){if(r.length<=e)return r;let t=r.length-e;return r.slice(0,e)+`
685
685
 
686
- \u2026 [truncated ${t.toLocaleString()} characters \u2014 open the full result file on disk to see the complete body] \u2026`}function it(r){return r>=1e3?`${(r/1e3).toFixed(2)}s`:`${r}ms`}function Ji(r){try{return new Date(r).toLocaleString()}catch{return r}}function rc(r){return r>=200&&r<300?"status-2xx":r>=300&&r<400?"status-3xx":r>=400&&r<500?"status-4xx":"status-5xx"}function $u(r,e){return e===0?"\u2014":`${Math.round(r/e*100)}%`}function gm(r){try{return typeof r=="string"&&(r=JSON.parse(r)),JSON.stringify(r,null,2)}catch{return String(r??"")}}function pm(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">${se(t)}</td><td class="kv-val">${se(s)}</td></tr>`}).join("")}</table>`}function db(r){return r==null||r===""?'<span class="dim">\u2014</span>':typeof r=="string"?se(r):typeof r=="number"||typeof r=="boolean"?se(String(r)):`<pre class="code">${se(gm(r))}</pre>`}function Fu(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])=>`
686
+ \u2026 [truncated ${t.toLocaleString()} characters \u2014 open the full result file on disk to see the complete body] \u2026`}function st(r){return r>=1e3?`${(r/1e3).toFixed(2)}s`:`${r}ms`}function Wi(r){try{return new Date(r).toLocaleString()}catch{return r}}function oc(r){return r>=200&&r<300?"status-2xx":r>=300&&r<400?"status-3xx":r>=400&&r<500?"status-4xx":"status-5xx"}function _u(r,e){return e===0?"\u2014":`${Math.round(r/e*100)}%`}function Sm(r){try{return typeof r=="string"&&(r=JSON.parse(r)),JSON.stringify(r,null,2)}catch{return String(r??"")}}function gm(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">${ie(t)}</td><td class="kv-val">${ie(s)}</td></tr>`}).join("")}</table>`}function hb(r){return r==null||r===""?'<span class="dim">\u2014</span>':typeof r=="string"?ie(r):typeof r=="number"||typeof r=="boolean"?ie(String(r)):`<pre class="code">${ie(Sm(r))}</pre>`}function Du(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])=>`
687
687
  <tr>
688
- <td class="kv-key">${se(t)}</td>
689
- <td class="kv-val">${db(n)}</td>
690
- </tr>`).join("")}</table>`}function pb(r){return!r||r.length===0?'<span class="dim">\u2014</span>':`<table class="kv-table">${r.map(t=>`
688
+ <td class="kv-key">${ie(t)}</td>
689
+ <td class="kv-val">${hb(n)}</td>
690
+ </tr>`).join("")}</table>`}function gb(r){return!r||r.length===0?'<span class="dim">\u2014</span>':`<table class="kv-table">${r.map(t=>`
691
691
  <tr>
692
- <td class="kv-key">${se(t.name??"(unnamed)")}</td>
693
- <td class="kv-val">${se(t.value??"")}</td>
694
- </tr>`).join("")}</table>`}function fm(r,e,t){if(r==null||r==="")return'<span class="dim">\u2014 empty \u2014</span>';let n=hm(gm(r),e);return`<pre class="code">${se(n)}</pre>`}var Ns,Fs,mm,fb,mb,xr,Nu=E(()=>{"use strict";Ns=I(require("fs/promises")),Fs=I(require("path"));Ts();mm=1e5;fb={maxBodyChars:mm,embedBodies:"failed"},mb=`
692
+ <td class="kv-key">${ie(t.name??"(unnamed)")}</td>
693
+ <td class="kv-val">${ie(t.value??"")}</td>
694
+ </tr>`).join("")}</table>`}function ym(r,e,t){if(r==null||r==="")return'<span class="dim">\u2014 empty \u2014</span>';let n=bm(Sm(r),e);return`<pre class="code">${ie(n)}</pre>`}var _s,Ms,vm,yb,vb,Cr,ju=E(()=>{"use strict";_s=I(require("fs/promises")),Ms=I(require("path"));$s();vm=1e5;yb={maxBodyChars:vm,embedBodies:"failed"},vb=`
695
695
  (function(){
696
696
  var ROOT = {};
697
697
  try { ROOT = JSON.parse(document.getElementById('hf-details').textContent || '{}'); } catch(e){ ROOT = {}; }
@@ -741,50 +741,50 @@ ${u.join(`
741
741
  b.setAttribute('data-rendered','1');
742
742
  }, true);
743
743
  })();
744
- `,xr=class{constructor(e,t){this.basePath=e;this.options={...fb,...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=Fs.join(this.basePath,e,t),s=JSON.parse(await Ns.readFile(Fs.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=Fs.join(n,this.buildReportFileName(s));return await Ns.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=Fs.join(e,"index",`page-${String(s).padStart(4,"0")}.json`);try{let o=JSON.parse(await Ns.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=$n(s.i,s.it,s.r),o=`${s.i}-${s.it}`;try{let a=JSON.parse(await Ns.readFile(Fs.join(e,"results",i),"utf-8"));this.shouldEmbedBody(s.p)?typeof a.response?.body=="string"&&(a.response.body=hm(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=se(t||"(unnamed block)"):t&&(o=t.split("/").map(c=>se(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`
744
+ `,Cr=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=Ms.join(this.basePath,e,t),s=JSON.parse(await _s.readFile(Ms.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=Ms.join(n,this.buildReportFileName(s));return await _s.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=Ms.join(e,"index",`page-${String(s).padStart(4,"0")}.json`);try{let o=JSON.parse(await _s.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=Fn(s.i,s.it,s.r),o=`${s.i}-${s.it}`;try{let a=JSON.parse(await _s.readFile(Ms.join(e,"results",i),"utf-8"));this.shouldEmbedBody(s.p)?typeof a.response?.body=="string"&&(a.response.body=bm(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=ie(t||"(unnamed block)"):t&&(o=t.split("/").map(c=>ie(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 p=l.items.filter(g=>g.p).length,d=l.items.length,m=p<d,f=l.items.map(n).join(""),h=l.gt==="block"?"\u{1F9E9}":"\u{1F4C1}";return`
745
745
  <details class="group-block${m?" group-fail":""}" open>
746
746
  <summary class="group-head">
747
747
  <span class="group-title">${h} ${this.groupLabel(l.cn,l.fp,l.gt,u+1)}</span>
748
- <span class="group-count ${m?"fail":"dim"}">(${d}/${p})</span>
748
+ <span class="group-count ${m?"fail":"dim"}">(${p}/${d})</span>
749
749
  </summary>
750
750
  <div class="group-body">${f}</div>
751
- </details>`}).join(""),a=i.groups.reduce((l,u)=>l+u.items.filter(d=>d.p).length,0),c=i.groups.reduce((l,u)=>l+u.items.length,0);return`
751
+ </details>`}).join(""),a=i.groups.reduce((l,u)=>l+u.items.filter(p=>p.p).length,0),c=i.groups.reduce((l,u)=>l+u.items.length,0);return`
752
752
  <details class="iter-block" open>
753
753
  <summary class="iter-head">
754
754
  <span class="iter-title">Iteration ${i.it}</span>
755
755
  <span class="dim iter-count">(${a}/${c} passed)</span>
756
756
  </summary>
757
757
  <div class="iter-body">${o}</div>
758
- </details>`}).join("")}renderGroupedTimeline(e,t,n){return this.groupByIterCollectionFolder(e).map(o=>{let a="";return a+=`<tr class="group-row iter-row"><td colspan="8">Iteration ${o.it}</td></tr>`,o.groups.forEach((c,l)=>{let u=c.gt==="block"?"\u{1F9E9}":"\u{1F4C1}";a+=`<tr class="group-row folder-row"><td colspan="8">${u} ${this.groupLabel(c.cn,c.fp,c.gt,l+1)}</td></tr>`,a+=c.items.map(n).join("")}),a}).join("")}buildHtml(e,t,n){let s=it(e.stats.totalDuration),i=e.stats.failed===0,o={},a=t.reduce((A,te)=>A+(te.ap??0),0),c=t.reduce((A,te)=>A+(te.af??0),0),l=t.reduce((A,te)=>A+(te.as??0),0),u=a+c+l,d=new Map;for(let A of t){let te=d.get(A.r);te?(te.ap+=A.ap??0,te.af+=A.af??0,te.durations.push(A.d)):d.set(A.r,{name:A.n,fp:A.fp,gp:A.gp,gt:A.gt,cn:A.cn,ap:A.ap??0,af:A.af??0,durations:[A.d]})}let p=new Set,m=[];for(let A of t)p.has(A.r)||(p.add(A.r),m.push(A));let f=A=>{let te=d.get(A.r);if(!te)return"";let Ce=te.ap+te.af,B=$u(te.ap,Ce),Ie=te.durations.length?Math.round(te.durations.reduce((at,he)=>at+he,0)/te.durations.length):0,We=te.af>0?' class="row-fail"':"",Pe=st[A.m]??"GET";return`
759
- <tr${We}>
760
- <td><span class="method method-${Pe.toLowerCase()}">${Pe}</span></td>
761
- <td>${se(te.name)}</td>
762
- <td>${Ce||'<span class="dim">\u2014</span>'}</td>
763
- <td class="pass">${te.ap}</td>
764
- <td class="${te.af>0?"fail":""}">${te.af}</td>
765
- <td>${it(Ie)}</td>
766
- <td class="${te.af>0?"fail":"pass"}">${B}</td>
767
- </tr>`},h=this.renderGroupedTimeline(m,e,f),g=Math.max(...t.map(A=>A.d),1),v=A=>{let te=st[A.m]??"GET",Ce=Math.max(2,Math.round(A.d/g*100)),B=A.p?"bar-pass":"bar-fail",Ie=A.p?"":' class="row-fail"',We=`req-${A.i}-${A.it}`;return`
768
- <tr${Ie}>
758
+ </details>`}).join("")}renderGroupedTimeline(e,t,n){return this.groupByIterCollectionFolder(e).map(o=>{let a="";return a+=`<tr class="group-row iter-row"><td colspan="8">Iteration ${o.it}</td></tr>`,o.groups.forEach((c,l)=>{let u=c.gt==="block"?"\u{1F9E9}":"\u{1F4C1}";a+=`<tr class="group-row folder-row"><td colspan="8">${u} ${this.groupLabel(c.cn,c.fp,c.gt,l+1)}</td></tr>`,a+=c.items.map(n).join("")}),a}).join("")}buildHtml(e,t,n){let s=st(e.stats.totalDuration),i=e.stats.failed===0,o={},a=t.reduce((A,ne)=>A+(ne.ap??0),0),c=t.reduce((A,ne)=>A+(ne.af??0),0),l=t.reduce((A,ne)=>A+(ne.as??0),0),u=a+c+l,p=new Map;for(let A of t){let ne=p.get(A.r);ne?(ne.ap+=A.ap??0,ne.af+=A.af??0,ne.durations.push(A.d)):p.set(A.r,{name:A.n,fp:A.fp,gp:A.gp,gt:A.gt,cn:A.cn,ap:A.ap??0,af:A.af??0,durations:[A.d]})}let d=new Set,m=[];for(let A of t)d.has(A.r)||(d.add(A.r),m.push(A));let f=A=>{let ne=p.get(A.r);if(!ne)return"";let Ee=ne.ap+ne.af,B=_u(ne.ap,Ee),Oe=ne.durations.length?Math.round(ne.durations.reduce((ot,ye)=>ot+ye,0)/ne.durations.length):0,Ge=ne.af>0?' class="row-fail"':"",ke=rt[A.m]??"GET";return`
759
+ <tr${Ge}>
760
+ <td><span class="method method-${ke.toLowerCase()}">${ke}</span></td>
761
+ <td>${ie(ne.name)}</td>
762
+ <td>${Ee||'<span class="dim">\u2014</span>'}</td>
763
+ <td class="pass">${ne.ap}</td>
764
+ <td class="${ne.af>0?"fail":""}">${ne.af}</td>
765
+ <td>${st(Oe)}</td>
766
+ <td class="${ne.af>0?"fail":"pass"}">${B}</td>
767
+ </tr>`},h=this.renderGroupedTimeline(m,e,f),g=Math.max(...t.map(A=>A.d),1),v=A=>{let ne=rt[A.m]??"GET",Ee=Math.max(2,Math.round(A.d/g*100)),B=A.p?"bar-pass":"bar-fail",Oe=A.p?"":' class="row-fail"',Ge=`req-${A.i}-${A.it}`;return`
768
+ <tr${Oe}>
769
769
  <td class="dim">${A.i}</td>
770
770
  <td>${A.it}</td>
771
- <td><span class="method method-${te.toLowerCase()}">${te}</span></td>
772
- <td><a href="#${We}" class="req-link">${se(A.n)}</a></td>
773
- <td class="${rc(A.s)}">${A.s}</td>
774
- <td>${it(A.d)}</td>
775
- <td><div class="bar-wrap"><div class="${B}" style="width:${Ce}%"></div></div></td>
771
+ <td><span class="method method-${ne.toLowerCase()}">${ne}</span></td>
772
+ <td><a href="#${Ge}" class="req-link">${ie(A.n)}</a></td>
773
+ <td class="${oc(A.s)}">${A.s}</td>
774
+ <td>${st(A.d)}</td>
775
+ <td><div class="bar-wrap"><div class="${B}" style="width:${Ee}%"></div></div></td>
776
776
  <td class="${A.p?"pass":"fail"}">${A.p?"\u2713":"\u2717"}</td>
777
- </tr>`},y=this.renderGroupedTimeline(t,e,v),x=(A,te={})=>{let Ce=`${A.i}-${A.it}`,B=n.get(Ce),Ie=st[A.m]??"GET",We=`req-${A.i}-${A.it}`,Pe=A.p,at=Pe?"#1f6feb40":"#f8514940",he=B?.assertions?.length?`<ul class="assert-list">${B.assertions.map(gt=>gt.skipped?`
777
+ </tr>`},y=this.renderGroupedTimeline(t,e,v),x=(A,ne={})=>{let Ee=`${A.i}-${A.it}`,B=n.get(Ee),Oe=rt[A.m]??"GET",Ge=`req-${A.i}-${A.it}`,ke=A.p,ot=ke?"#1f6feb40":"#f8514940",ye=B?.assertions?.length?`<ul class="assert-list">${B.assertions.map(ht=>ht.skipped?`
778
778
  <li class="skip">
779
779
  <span class="assert-icon">\u2298</span>
780
- <span class="assert-skip-name">${se(gt.name)}</span>
780
+ <span class="assert-skip-name">${ie(ht.name)}</span>
781
781
  <span class="assert-msg"> \u2014 skipped</span>
782
782
  </li>`:`
783
- <li class="${gt.passed?"pass":"fail"}">
784
- <span class="assert-icon">${gt.passed?"\u2713":"\u2717"}</span>
785
- ${se(gt.name)}
786
- ${gt.message?`<span class="assert-msg"> \u2014 ${se(gt.message)}</span>`:""}
787
- </li>`).join("")}</ul>`:'<span class="dim">No assertions</span>',mt=pm(B?.request?.headers),un=Fu(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),ye=B?.request?.body,Hs=ye&&typeof ye=="object"?ye.type:void 0,Ir=ye&&typeof ye=="object"&&"content"in ye?ye.content:ye,qc=Hs!=="none"&&!(Ir==null||Ir===""),ht=this.shouldEmbedBody(A.p),Yi=qc?ht?fm(Ir,this.options.maxBodyChars):this.bodyOmittedNote():"",Tt=pm(B?.response?.headers),P=Fu(B?{status:B.status,statusText:B.statusText,durationMs:B.duration,responseTimeMs:B.response?.time,responseSizeBytes:B.response?.size}:void 0),k=ht?B?.response?.body!==void 0&&B.response.body!==null?fm(B.response.body,this.options.maxBodyChars):'<span class="dim">\u2014 no body \u2014</span>':this.bodyOmittedNote(),K=pb(B?.response?.cookies),U=Fu(B?{timestamp:B.timestamp?new Date(B.timestamp).toISOString():void 0,nextRequest:B.nextRequest,visualizerTemplate:B.visualizerData?.template,visualizerData:B.visualizerData?.data}:void 0),J=`
783
+ <li class="${ht.passed?"pass":"fail"}">
784
+ <span class="assert-icon">${ht.passed?"\u2713":"\u2717"}</span>
785
+ ${ie(ht.name)}
786
+ ${ht.message?`<span class="assert-msg"> \u2014 ${ie(ht.message)}</span>`:""}
787
+ </li>`).join("")}</ul>`:'<span class="dim">No assertions</span>',ft=gm(B?.request?.headers),un=Du(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),be=B?.request?.body,Us=be&&typeof be=="object"?be.type:void 0,$r=be&&typeof be=="object"&&"content"in be?be.content:be,Ic=Us!=="none"&&!($r==null||$r===""),mt=this.shouldEmbedBody(A.p),eo=Ic?mt?ym($r,this.options.maxBodyChars):this.bodyOmittedNote():"",It=gm(B?.response?.headers),k=Du(B?{status:B.status,statusText:B.statusText,durationMs:B.duration,responseTimeMs:B.response?.time,responseSizeBytes:B.response?.size}:void 0),P=mt?B?.response?.body!==void 0&&B.response.body!==null?ym(B.response.body,this.options.maxBodyChars):'<span class="dim">\u2014 no body \u2014</span>':this.bodyOmittedNote(),K=gb(B?.response?.cookies),U=Du(B?{timestamp:B.timestamp?new Date(B.timestamp).toISOString():void 0,nextRequest:B.nextRequest,visualizerTemplate:B.visualizerData?.template,visualizerData:B.visualizerData?.data}:void 0),W=`
788
788
  <div class="detail-section">
789
789
  <div class="pane-section-title">Assertions
790
790
  <span class="assert-counts">
@@ -793,100 +793,100 @@ ${u.join(`
793
793
  ${(A.as??0)>0?`<span class="skip-badge"> \xB7 ${A.as} skipped</span>`:""}
794
794
  </span>
795
795
  </div>
796
- ${he}
796
+ ${ye}
797
797
  </div>`,ue=`
798
798
  <div class="col-pane exec-meta-box">
799
799
  <div class="pane-title">Execution Metadata</div>
800
800
  <div class="pane-section">${U}</div>
801
- </div>`,fe=`
801
+ </div>`,he=`
802
802
  <div class="pane-section"><div class="pane-section-title">Overview</div>${un}</div>
803
- <div class="pane-section"><div class="pane-section-title">Headers</div>${mt}</div>
804
- ${qc?`<div class="pane-section"><div class="pane-section-title">Body</div>${Yi}</div>`:""}`,Te=`
805
- <div class="pane-section"><div class="pane-section-title">Overview</div>${P}</div>
806
- <div class="pane-section"><div class="pane-section-title">Headers</div>${Tt}</div>
803
+ <div class="pane-section"><div class="pane-section-title">Headers</div>${ft}</div>
804
+ ${Ic?`<div class="pane-section"><div class="pane-section-title">Body</div>${eo}</div>`:""}`,$e=`
805
+ <div class="pane-section"><div class="pane-section-title">Overview</div>${k}</div>
806
+ <div class="pane-section"><div class="pane-section-title">Headers</div>${It}</div>
807
807
  <div class="pane-section"><div class="pane-section-title">Cookies</div>${K}</div>
808
- <div class="pane-section"><div class="pane-section-title">Body</div>${k}</div>`,N=fe.length<=Te.length,Le=N?ue:"",He=N?"":ue,be=B?.consoleOutput?.length?`<div class="console-block"><pre class="code console-code">${B.consoleOutput.map(gt=>se(typeof gt=="string"?gt:JSON.stringify(gt))).join(`
809
- `)}</pre></div>`:"",Se=B?.error?`<div class="error-box">\u26A0 ${se(B.error)}</div>`:"",Mn=B?`<span class="${rc(B.status)} status-badge">${B.status} ${se(B.statusText??"")}</span>`:"",eh=`<span class="dur-badge">${it(A.d)}</span>`,th=e.config.iterations>1?`<span class="iter-badge">iter ${A.it}</span>`:"";o[`${A.i}-${A.it}`]={d:B??null,method:Ie,s:A.s,ap:A.ap,af:A.af,as:A.as??0,embed:ht};let nh=se(`${A.n} ${B?.url??""}`.toLowerCase());return`
810
- <details class="req-detail ${Pe?"req-pass":"req-fail"}" id="${We}" data-key="${A.i}-${A.it}" data-search="${nh}" style="--border:${at}">
808
+ <div class="pane-section"><div class="pane-section-title">Body</div>${P}</div>`,ee=he.length<=$e.length,z=ee?ue:"",_n=ee?"":ue,pe=B?.consoleOutput?.length?`<div class="console-block"><pre class="code console-code">${B.consoleOutput.map(ht=>ie(typeof ht=="string"?ht:JSON.stringify(ht))).join(`
809
+ `)}</pre></div>`:"",xe=B?.error?`<div class="error-box">\u26A0 ${ie(B.error)}</div>`:"",Dn=B?`<span class="${oc(B.status)} status-badge">${B.status} ${ie(B.statusText??"")}</span>`:"",sh=`<span class="dur-badge">${st(A.d)}</span>`,ih=e.config.iterations>1?`<span class="iter-badge">iter ${A.it}</span>`:"";o[`${A.i}-${A.it}`]={d:B??null,method:Oe,s:A.s,ap:A.ap,af:A.af,as:A.as??0,embed:mt};let oh=ie(`${A.n} ${B?.url??""}`.toLowerCase());return`
810
+ <details class="req-detail ${ke?"req-pass":"req-fail"}" id="${Ge}" data-key="${A.i}-${A.it}" data-search="${oh}" style="--border:${ot}">
811
811
  <summary class="req-summary">
812
812
  <span class="toggle-icon">\u25B6</span>
813
813
  <span class="req-index dim">#${A.i}</span>
814
- <span class="method method-${Ie.toLowerCase()}">${Ie}</span>
815
- <span class="req-name">${se(A.n)}</span>
816
- ${Mn}
817
- ${eh}
818
- ${th}
819
- <span class="req-outcome ${Pe?"pass":"fail"}">${Pe?"\u2713":"\u2717"}</span>
814
+ <span class="method method-${Oe.toLowerCase()}">${Oe}</span>
815
+ <span class="req-name">${ie(A.n)}</span>
816
+ ${Dn}
817
+ ${sh}
818
+ ${ih}
819
+ <span class="req-outcome ${ke?"pass":"fail"}">${ke?"\u2713":"\u2717"}</span>
820
820
  </summary>
821
821
  <div class="req-body" data-lazy="1"></div>
822
- </details>`},b=A=>x(A),R=this.renderGroupedDetails(t,e,b),C=t.filter(A=>!A.p),q=A=>{let te=`${A.i}-${A.it}`,Ce=n.get(te),B=st[A.m]??"GET",Ie=`req-${A.i}-${A.it}`,We=Ce?`<span class="${rc(Ce.status)} status-badge">${Ce.status} ${se(Ce.statusText??"")}</span>`:`<span class="${rc(A.s)} status-badge">${A.s}</span>`,Pe=`<span class="dur-badge">${it(A.d)}</span>`,at=e.config.iterations>1?`<span class="iter-badge">iter ${A.it}</span>`:"",he=Ce?.error??A.e?`<div class="fail-assert-error">\u26A0 ${se(Ce?.error??A.e??"")}</div>`:"",mt=Ce?.assertions?.filter(ye=>!ye.passed)??[],un=mt.length?`<ul class="assert-list fail-assert-list">${mt.map(ye=>`
822
+ </details>`},b=A=>x(A),C=this.renderGroupedDetails(t,e,b),R=t.filter(A=>!A.p),q=A=>{let ne=`${A.i}-${A.it}`,Ee=n.get(ne),B=rt[A.m]??"GET",Oe=`req-${A.i}-${A.it}`,Ge=Ee?`<span class="${oc(Ee.status)} status-badge">${Ee.status} ${ie(Ee.statusText??"")}</span>`:`<span class="${oc(A.s)} status-badge">${A.s}</span>`,ke=`<span class="dur-badge">${st(A.d)}</span>`,ot=e.config.iterations>1?`<span class="iter-badge">iter ${A.it}</span>`:"",ye=Ee?.error??A.e?`<div class="fail-assert-error">\u26A0 ${ie(Ee?.error??A.e??"")}</div>`:"",ft=Ee?.assertions?.filter(be=>!be.passed)??[],un=ft.length?`<ul class="assert-list fail-assert-list">${ft.map(be=>`
823
823
  <li class="fail">
824
824
  <span class="assert-icon">\u2717</span>
825
825
  <div class="fail-assert-detail">
826
- <div class="fail-assert-name">${se(ye.name)}</div>
827
- ${ye.message?`<div class="fail-assert-msg">${se(ye.message)}</div>`:""}
826
+ <div class="fail-assert-name">${ie(be.name)}</div>
827
+ ${be.message?`<div class="fail-assert-msg">${ie(be.message)}</div>`:""}
828
828
  </div>
829
829
  </li>`).join("")}</ul>`:"";return`
830
830
  <div class="fail-entry">
831
- <a href="#${Ie}" onclick="jumpToRequest('${Ie}')" class="fail-entry-link">
831
+ <a href="#${Oe}" onclick="jumpToRequest('${Oe}')" class="fail-entry-link">
832
832
  <div class="fail-entry-header">
833
833
  <span class="toggle-icon fail-toggle">\u25B6</span>
834
834
  <span class="req-index dim">#${A.i}</span>
835
835
  <span class="method method-${B.toLowerCase()}">${B}</span>
836
- <span class="req-name">${se(A.n)}</span>
837
- ${We}
838
- ${Pe}
839
- ${at}
836
+ <span class="req-name">${ie(A.n)}</span>
837
+ ${Ge}
838
+ ${ke}
839
+ ${ot}
840
840
  <span class="fail-count-badge">${A.af} failed</span>
841
841
  </div>
842
842
  </a>
843
- ${un||he?`
843
+ ${un||ye?`
844
844
  <details class="fail-assertions-block">
845
845
  <summary class="fail-assertions-toggle">
846
846
  <span class="fail-toggle-icon">\u25B6</span>
847
- <span class="fail-assertions-label">${mt.length} failed assertion${mt.length!==1?"s":""}</span>
847
+ <span class="fail-assertions-label">${ft.length} failed assertion${ft.length!==1?"s":""}</span>
848
848
  </summary>
849
849
  <div class="fail-assertions-body">
850
- ${he}
850
+ ${ye}
851
851
  ${un}
852
852
  </div>
853
853
  </details>`:""}
854
- </div>`},_=C.length>0?this.renderGroupedDetails(C,e,q):"",M=A=>{let te=`${A.i}-${A.it}`,Ce=n.get(te),B=st[A.m]??"GET",Ie=`req-${A.i}-${A.it}`,We=`<span class="dur-badge">${it(A.d)}</span>`,Pe=e.config.iterations>1?`<span class="iter-badge">iter ${A.it}</span>`:"",at=A.s===0&&A.p,he=Ce?.assertions?.filter(ye=>ye.skipped)??[],mt=he.length?`<ul class="assert-list fail-assert-list">${he.map(ye=>`
854
+ </div>`},N=R.length>0?this.renderGroupedDetails(R,e,q):"",M=A=>{let ne=`${A.i}-${A.it}`,Ee=n.get(ne),B=rt[A.m]??"GET",Oe=`req-${A.i}-${A.it}`,Ge=`<span class="dur-badge">${st(A.d)}</span>`,ke=e.config.iterations>1?`<span class="iter-badge">iter ${A.it}</span>`:"",ot=A.s===0&&A.p,ye=Ee?.assertions?.filter(be=>be.skipped)??[],ft=ye.length?`<ul class="assert-list fail-assert-list">${ye.map(be=>`
855
855
  <li class="skip">
856
856
  <span class="assert-icon">\u2298</span>
857
857
  <div class="fail-assert-detail">
858
- <div class="fail-assert-name">${se(ye.name)}</div>
858
+ <div class="fail-assert-name">${ie(be.name)}</div>
859
859
  <div class="fail-assert-msg">skipped via pm.test.skip()</div>
860
860
  </div>
861
- </li>`).join("")}</ul>`:"",un=at?'<span class="skip-count-badge">request skipped</span>':`<span class="skip-count-badge">${A.as??he.length} assertion${(A.as??he.length)!==1?"s":""} skipped</span>`;return`
861
+ </li>`).join("")}</ul>`:"",un=ot?'<span class="skip-count-badge">request skipped</span>':`<span class="skip-count-badge">${A.as??ye.length} assertion${(A.as??ye.length)!==1?"s":""} skipped</span>`;return`
862
862
  <div class="fail-entry" style="border-color:#b08d5740">
863
- <a href="#${Ie}" onclick="jumpToRequest('${Ie}')" class="fail-entry-link">
863
+ <a href="#${Oe}" onclick="jumpToRequest('${Oe}')" class="fail-entry-link">
864
864
  <div class="fail-entry-header" style="background:#1a1600">
865
865
  <span class="toggle-icon fail-toggle">\u25B6</span>
866
866
  <span class="req-index dim">#${A.i}</span>
867
867
  <span class="method method-${B.toLowerCase()}">${B}</span>
868
- <span class="req-name">${se(A.n)}</span>
869
- ${We}
870
- ${Pe}
868
+ <span class="req-name">${ie(A.n)}</span>
869
+ ${Ge}
870
+ ${ke}
871
871
  ${un}
872
872
  </div>
873
873
  </a>
874
- ${mt?`
874
+ ${ft?`
875
875
  <details class="fail-assertions-block" style="border-top-color:#b08d5740">
876
876
  <summary class="fail-assertions-toggle">
877
877
  <span class="fail-toggle-icon">\u25B6</span>
878
- <span class="fail-assertions-label" style="color:#d29922">${he.length} skipped assertion${he.length!==1?"s":""}</span>
878
+ <span class="fail-assertions-label" style="color:#d29922">${ye.length} skipped assertion${ye.length!==1?"s":""}</span>
879
879
  </summary>
880
880
  <div class="fail-assertions-body">
881
- ${mt}
881
+ ${ft}
882
882
  </div>
883
883
  </details>`:""}
884
- </div>`},D=t.filter(A=>A.s===0&&A.p),V=t.filter(A=>(A.as??0)>0),O=new Set([...D,...V].map(A=>`${A.i}-${A.it}`)),H=t.filter(A=>O.has(`${A.i}-${A.it}`)),Z=H.length>0?H.length:e.stats.skipped??0,X=$u(a,a+c),Ge=$u(e.stats.passed,e.stats.totalRequests),ln=e.stats.avgDuration?it(Math.round(e.stats.avgDuration)):"\u2014",It=JSON.stringify({iterations:e.config.iterations,items:o}).replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");return`<!DOCTYPE html>
884
+ </div>`},_=t.filter(A=>A.s===0&&A.p),H=t.filter(A=>(A.as??0)>0),O=new Set([..._,...H].map(A=>`${A.i}-${A.it}`)),L=t.filter(A=>O.has(`${A.i}-${A.it}`)),Z=L.length>0?L.length:e.stats.skipped??0,X=_u(a,a+c),Je=_u(e.stats.passed,e.stats.totalRequests),ln=e.stats.avgDuration?st(Math.round(e.stats.avgDuration)):"\u2014",kt=JSON.stringify({iterations:e.config.iterations,items:o}).replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");return`<!DOCTYPE html>
885
885
  <html lang="en">
886
886
  <head>
887
887
  <meta charset="UTF-8">
888
888
  <meta name="viewport" content="width=device-width,initial-scale=1">
889
- <title>HTTP Forge \u2014 ${se(e.suiteName)}</title>
889
+ <title>HTTP Forge \u2014 ${ie(e.suiteName)}</title>
890
890
  <style>
891
891
  *{box-sizing:border-box;margin:0;padding:0}
892
892
  body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
@@ -1120,11 +1120,11 @@ ${u.join(`
1120
1120
  <div class="header">
1121
1121
  <div class="header-top">
1122
1122
  <div>
1123
- <div class="suite-name">${se(e.suiteName)}</div>
1123
+ <div class="suite-name">${ie(e.suiteName)}</div>
1124
1124
  <div class="meta">
1125
- Environment: <strong>${se(e.environment)}</strong> &nbsp;\xB7&nbsp;
1126
- Run ID: <code>${se(e.runId)}</code> &nbsp;\xB7&nbsp;
1127
- ${Ji(e.startTime)}${e.endTime?` \u2192 ${Ji(e.endTime)}`:""}
1125
+ Environment: <strong>${ie(e.environment)}</strong> &nbsp;\xB7&nbsp;
1126
+ Run ID: <code>${ie(e.runId)}</code> &nbsp;\xB7&nbsp;
1127
+ ${Wi(e.startTime)}${e.endTime?` \u2192 ${Wi(e.endTime)}`:""}
1128
1128
  &nbsp;\xB7&nbsp; Iterations: ${e.config.iterations}
1129
1129
  </div>
1130
1130
  </div>
@@ -1217,7 +1217,7 @@ ${u.join(`
1217
1217
  </div>
1218
1218
  <div class="summary-row">
1219
1219
  <span class="summary-row-label">Pass Rate</span>
1220
- <span class="summary-row-value ${e.stats.failed>0?"fail":"pass"}">${Ge}</span>
1220
+ <span class="summary-row-value ${e.stats.failed>0?"fail":"pass"}">${Je}</span>
1221
1221
  </div>
1222
1222
  <div class="summary-row">
1223
1223
  <span class="summary-row-label">Iterations</span>
@@ -1230,22 +1230,22 @@ ${u.join(`
1230
1230
  <h3>Timings</h3>
1231
1231
  <div class="summary-row">
1232
1232
  <span class="summary-row-label">Total Duration</span>
1233
- <span class="summary-row-value">${it(e.stats.totalDuration)}</span>
1233
+ <span class="summary-row-value">${st(e.stats.totalDuration)}</span>
1234
1234
  </div>
1235
1235
  <div class="summary-row">
1236
1236
  <span class="summary-row-label">Average Response</span>
1237
1237
  <span class="summary-row-value">${ln}</span>
1238
1238
  </div>
1239
- ${e.stats.p50!==void 0?`<div class="summary-row"><span class="summary-row-label">P50</span><span class="summary-row-value">${it(e.stats.p50)}</span></div>`:""}
1240
- ${e.stats.p95!==void 0?`<div class="summary-row"><span class="summary-row-label">P95</span><span class="summary-row-value">${it(e.stats.p95)}</span></div>`:""}
1241
- ${e.stats.p99!==void 0?`<div class="summary-row"><span class="summary-row-label">P99</span><span class="summary-row-value">${it(e.stats.p99)}</span></div>`:""}
1239
+ ${e.stats.p50!==void 0?`<div class="summary-row"><span class="summary-row-label">P50</span><span class="summary-row-value">${st(e.stats.p50)}</span></div>`:""}
1240
+ ${e.stats.p95!==void 0?`<div class="summary-row"><span class="summary-row-label">P95</span><span class="summary-row-value">${st(e.stats.p95)}</span></div>`:""}
1241
+ ${e.stats.p99!==void 0?`<div class="summary-row"><span class="summary-row-label">P99</span><span class="summary-row-value">${st(e.stats.p99)}</span></div>`:""}
1242
1242
  <div class="summary-row">
1243
1243
  <span class="summary-row-label">Min Response</span>
1244
- <span class="summary-row-value">${it(e.stats.minDuration)}</span>
1244
+ <span class="summary-row-value">${st(e.stats.minDuration)}</span>
1245
1245
  </div>
1246
1246
  <div class="summary-row">
1247
1247
  <span class="summary-row-label">Max Response</span>
1248
- <span class="summary-row-value">${it(e.stats.maxDuration)}</span>
1248
+ <span class="summary-row-value">${st(e.stats.maxDuration)}</span>
1249
1249
  </div>
1250
1250
  </div>
1251
1251
 
@@ -1254,11 +1254,11 @@ ${u.join(`
1254
1254
  <h3>Run Info</h3>
1255
1255
  <div class="summary-row">
1256
1256
  <span class="summary-row-label">Suite</span>
1257
- <span class="summary-row-value" style="text-align:right;max-width:60%;overflow:hidden;text-overflow:ellipsis">${se(e.suiteName)}</span>
1257
+ <span class="summary-row-value" style="text-align:right;max-width:60%;overflow:hidden;text-overflow:ellipsis">${ie(e.suiteName)}</span>
1258
1258
  </div>
1259
1259
  <div class="summary-row">
1260
1260
  <span class="summary-row-label">Environment</span>
1261
- <span class="summary-row-value" style="text-align:right">${se(e.environment)}</span>
1261
+ <span class="summary-row-value" style="text-align:right">${ie(e.environment)}</span>
1262
1262
  </div>
1263
1263
  <div class="summary-row">
1264
1264
  <span class="summary-row-label">Status</span>
@@ -1266,12 +1266,12 @@ ${u.join(`
1266
1266
  </div>
1267
1267
  <div class="summary-row">
1268
1268
  <span class="summary-row-label">Start Time</span>
1269
- <span class="summary-row-value dim" style="text-align:right;font-size:11px">${Ji(e.startTime)}</span>
1269
+ <span class="summary-row-value dim" style="text-align:right;font-size:11px">${Wi(e.startTime)}</span>
1270
1270
  </div>
1271
- ${e.endTime?`<div class="summary-row"><span class="summary-row-label">End Time</span><span class="summary-row-value dim" style="text-align:right;font-size:11px">${Ji(e.endTime)}</span></div>`:""}
1271
+ ${e.endTime?`<div class="summary-row"><span class="summary-row-label">End Time</span><span class="summary-row-value dim" style="text-align:right;font-size:11px">${Wi(e.endTime)}</span></div>`:""}
1272
1272
  <div class="summary-row">
1273
1273
  <span class="summary-row-label">Run ID</span>
1274
- <span class="summary-row-value dim" style="font-family:monospace;font-size:10px">${se(e.runId)}</span>
1274
+ <span class="summary-row-value dim" style="font-family:monospace;font-size:10px">${ie(e.runId)}</span>
1275
1275
  </div>
1276
1276
  </div>
1277
1277
  </div>
@@ -1289,7 +1289,7 @@ ${u.join(`
1289
1289
  <span class="result-count" id="req-count">${t.length} requests</span>
1290
1290
  </div>
1291
1291
  <div id="requests-list">
1292
- ${R}
1292
+ ${C}
1293
1293
  </div>
1294
1294
  </div>
1295
1295
 
@@ -1297,15 +1297,15 @@ ${u.join(`
1297
1297
  <!-- Tab: Failed Tests -->
1298
1298
  <!-- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 -->
1299
1299
  <div id="tab-failures" class="tab-content">
1300
- ${C.length===0?`<div class="no-tests-box">
1300
+ ${R.length===0?`<div class="no-tests-box">
1301
1301
  <div class="no-tests-icon">\u{1F389}</div>
1302
1302
  <p style="color:#3fb950;font-weight:600">No failed tests!</p>
1303
1303
  <p style="margin-top:6px">All ${u} assertion${u!==1?"s":""} passed.</p>
1304
1304
  </div>`:`<p class="dim" style="margin-bottom:12px">
1305
- ${c} failed assertion${c!==1?"s":""} across ${C.length} request${C.length!==1?"s":""} \u2014
1305
+ ${c} failed assertion${c!==1?"s":""} across ${R.length} request${R.length!==1?"s":""} \u2014
1306
1306
  click \u25B6 to expand assertions, or the request header to jump to full details.
1307
1307
  </p>
1308
- ${_}`}
1308
+ ${N}`}
1309
1309
  </div>
1310
1310
 
1311
1311
  <!-- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 -->
@@ -1317,11 +1317,11 @@ ${u.join(`
1317
1317
  <p style="font-weight:600">There are no skipped tests</p>
1318
1318
  </div>`:`<p class="dim" style="margin-bottom:12px">
1319
1319
  ${l>0?`${l} skipped assertion${l!==1?"s":""} (via pm.test.skip())`:""}
1320
- ${l>0&&D.length>0?" and ":""}
1321
- ${D.length>0?`${D.length} bypassed request${D.length!==1?"s":""} (via setNextRequest())`:""}
1320
+ ${l>0&&_.length>0?" and ":""}
1321
+ ${_.length>0?`${_.length} bypassed request${_.length!==1?"s":""} (via setNextRequest())`:""}
1322
1322
  \u2014 click \u25B6 to expand details, or the request header to jump to full details.
1323
1323
  </p>
1324
- ${this.renderGroupedDetails(H,e,M)}`}
1324
+ ${this.renderGroupedDetails(L,e,M)}`}
1325
1325
  </div>
1326
1326
 
1327
1327
  <!-- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550 -->
@@ -1364,11 +1364,11 @@ ${u.join(`
1364
1364
  </div>
1365
1365
 
1366
1366
  <p class="dim" style="margin-top:20px;text-align:center">
1367
- Generated by HTTP Forge &nbsp;\xB7&nbsp; ${Ji(new Date().toISOString())}
1367
+ Generated by HTTP Forge &nbsp;\xB7&nbsp; ${Wi(new Date().toISOString())}
1368
1368
  </p>
1369
1369
  </div>
1370
- <script id="hf-details" type="application/json">${It}</script>
1371
- <script>${mb}</script>
1370
+ <script id="hf-details" type="application/json">${kt}</script>
1371
+ <script>${vb}</script>
1372
1372
  <script>
1373
1373
  // \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
1374
1374
  function showTab(name, btn) {
@@ -1452,23 +1452,23 @@ ${u.join(`
1452
1452
  });
1453
1453
  </script>
1454
1454
  </body>
1455
- </html>`}}});function ym(r){return r>=1e3?`${(r/1e3).toFixed(2)}s`:`${r}ms`}function hb(r){try{return new Date(r).toLocaleString()}catch{return r}}function gb(r,e=bm){if(!r)return"";let t=typeof r=="string"?r:JSON.stringify(r,null,2);return t.length<=e?t:t.slice(0,e)+`
1456
- \u2026 [${t.length-e} chars truncated]`}function vm(r){if(r==null||r==="")return"*(empty)*";try{let e=typeof r=="string"?r:JSON.stringify(r,null,2);return"```json\n"+gb(e)+"\n```"}catch{return String(r).slice(0,bm)}}var Rr,wr,bm,sc,Sm=E(()=>{"use strict";Rr=I(require("fs/promises")),wr=I(require("path"));Ts();bm=2e3;sc=class{constructor(e,t){this.basePath=e;this.suitesPath=t}basePath;suitesPath;async generate(e,t){let n=wr.join(this.basePath,e,t),s=JSON.parse(await Rr.readFile(wr.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=wr.join(this.suitesPath,`${e}.suite.json`);c=JSON.parse(await Rr.readFile(d,"utf-8"))}catch{c=void 0}let l=this.buildMarkdown(s,i,o,a,e,c),u=wr.join(n,"run-summary.md");return await Rr.writeFile(u,l,"utf-8"),u}async loadAllSummaries(e,t){let n=[];for(let s=1;s<=t;s++){let i=wr.join(e,"index",`page-${String(s).padStart(4,"0")}.json`);try{let o=JSON.parse(await Rr.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=$n(s.i,s.it,s.r);try{let o=JSON.parse(await Rr.readFile(wr.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,x)=>y+x.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** | ${hb(e.startTime)} |`),p.push(`| **Status** | ${e.status} |`),p.push(`| **Duration** | ${ym(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,x)=>{let b=st[y.m]??String(y.m),R=s.get(`${y.i}-${y.it}`),C=R?.url??"",q=y.cn||R?.collectionName||"",_=y.fp||R?.folderPath||"";if(p.push(`### ${x+1}. ${y.n}`),p.push(""),p.push(`**Request:** \`${b} ${C}\``),q&&p.push(`**Collection:** ${q}${_?` / ${_.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&&R?.assertions?.length){let M=R.assertions.filter(D=>!D.passed&&!D.skipped);M.length&&(p.push(`**Failed assertions (${M.length}):**`),M.forEach(D=>{p.push(`- \`${D.name}\``+(D.message?` \u2192 ${D.message}`:""))}),p.push(""))}if(R?.request?.body){let M=R.request.body,D=typeof M=="object"&&"content"in M?M.content:M,V=typeof M=="object"&&"type"in M?M.type:void 0;D&&V!=="none"&&(p.push("**Request body:**"),p.push(vm(D)),p.push(""))}R?.response?.body!==void 0&&R.response.body!==null&&(p.push("**Response body:**"),p.push(vm(R.response.body)),p.push("")),R?.consoleOutput?.length&&(p.push("**Console output:**"),p.push("```"),p.push(R.consoleOutput.slice(0,20).join(`
1457
- `)),p.push("```"),p.push(""))}));let m=t.filter(y=>y.p);m.length>0&&(p.push("## \u2705 Passed Requests"),p.push(""),m.forEach((y,x)=>{let b=st[y.m]??String(y.m);p.push(`${x+1}. **${y.n}** \u2014 \`${b}\` \u2192 HTTP ${y.s} (${ym(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 x=1e4;y.length>x?(p.push(y.slice(0,x)),p.push(`
1458
- ... [${y.length-x} chars truncated]`)):p.push(y),p.push("```"),p.push("")}catch{}return p.join(`
1455
+ </html>`}}});function xm(r){return r>=1e3?`${(r/1e3).toFixed(2)}s`:`${r}ms`}function bb(r){try{return new Date(r).toLocaleString()}catch{return r}}function Sb(r,e=Rm){if(!r)return"";let t=typeof r=="string"?r:JSON.stringify(r,null,2);return t.length<=e?t:t.slice(0,e)+`
1456
+ \u2026 [${t.length-e} chars truncated]`}function wm(r){if(r==null||r==="")return"*(empty)*";try{let e=typeof r=="string"?r:JSON.stringify(r,null,2);return"```json\n"+Sb(e)+"\n```"}catch{return String(r).slice(0,Rm)}}var qr,Er,Rm,ac,Cm=E(()=>{"use strict";qr=I(require("fs/promises")),Er=I(require("path"));$s();Rm=2e3;ac=class{constructor(e,t){this.basePath=e;this.suitesPath=t}basePath;suitesPath;async generate(e,t){let n=Er.join(this.basePath,e,t),s=JSON.parse(await qr.readFile(Er.join(n,"manifest.json"),"utf-8")),i=await this.loadAllSummaries(n,s.totalIndexPages),o=i.filter(p=>!p.p),a=await this.loadDetails(n,o),c;if(this.suitesPath)try{let p=Er.join(this.suitesPath,`${e}.suite.json`);c=JSON.parse(await qr.readFile(p,"utf-8"))}catch{c=void 0}let l=this.buildMarkdown(s,i,o,a,e,c),u=Er.join(n,"run-summary.md");return await qr.writeFile(u,l,"utf-8"),u}async loadAllSummaries(e,t){let n=[];for(let s=1;s<=t;s++){let i=Er.join(e,"index",`page-${String(s).padStart(4,"0")}.json`);try{let o=JSON.parse(await qr.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=Fn(s.i,s.it,s.r);try{let o=JSON.parse(await qr.readFile(Er.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,x)=>y+x.d,0),p=a>0?Math.round(c/a*100):0,d=[];d.push("# HTTP Forge Run Summary"),d.push(""),d.push("> **Generated by HTTP Forge** \u2014 for AI tools (Claude Code, GitHub Copilot, Cursor, etc.)"),d.push(""),d.push("| Field | Value |"),d.push("|---|---|"),d.push(`| **Suite** | ${e.suiteName} |`),d.push(`| **Run ID** | ${e.runId} |`),d.push(`| **Environment** | ${e.environment||"\u2014"} |`),d.push(`| **Started** | ${bb(e.startTime)} |`),d.push(`| **Status** | ${e.status} |`),d.push(`| **Duration** | ${xm(u)} |`),d.push(""),d.push("## Results Overview"),d.push(""),d.push("| Metric | Value |"),d.push("|---|---|"),d.push(`| Total Requests | ${a} |`),d.push(`| \u2705 Passed | ${c} |`),d.push(`| \u274C Failed | ${l} |`),d.push(`| Pass Rate | ${p}% |`),d.push(""),l>0&&(d.push("## \u274C Failed Requests"),d.push(""),d.push("> These are the requests that need investigation."),d.push("> Full request/response details are in the `results/` folder alongside this file."),d.push(""),n.forEach((y,x)=>{let b=rt[y.m]??String(y.m),C=s.get(`${y.i}-${y.it}`),R=C?.url??"",q=y.cn||C?.collectionName||"",N=y.fp||C?.folderPath||"";if(d.push(`### ${x+1}. ${y.n}`),d.push(""),d.push(`**Request:** \`${b} ${R}\``),q&&d.push(`**Collection:** ${q}${N?` / ${N.replace(/\//g," / ")}`:""}`),d.push(`**Response status:** ${y.s}`),y.e&&d.push(`**Error:** ${y.e}`),e.config?.iterations>1&&d.push(`**Iteration:** ${y.it} of ${e.config.iterations}`),d.push(""),y.af>0&&C?.assertions?.length){let M=C.assertions.filter(_=>!_.passed&&!_.skipped);M.length&&(d.push(`**Failed assertions (${M.length}):**`),M.forEach(_=>{d.push(`- \`${_.name}\``+(_.message?` \u2192 ${_.message}`:""))}),d.push(""))}if(C?.request?.body){let M=C.request.body,_=typeof M=="object"&&"content"in M?M.content:M,H=typeof M=="object"&&"type"in M?M.type:void 0;_&&H!=="none"&&(d.push("**Request body:**"),d.push(wm(_)),d.push(""))}C?.response?.body!==void 0&&C.response.body!==null&&(d.push("**Response body:**"),d.push(wm(C.response.body)),d.push("")),C?.consoleOutput?.length&&(d.push("**Console output:**"),d.push("```"),d.push(C.consoleOutput.slice(0,20).join(`
1457
+ `)),d.push("```"),d.push(""))}));let m=t.filter(y=>y.p);m.length>0&&(d.push("## \u2705 Passed Requests"),d.push(""),m.forEach((y,x)=>{let b=rt[y.m]??String(y.m);d.push(`${x+1}. **${y.n}** \u2014 \`${b}\` \u2192 HTTP ${y.s} (${xm(y.d)})`)}),d.push("")),d.push("## \u{1F4C1} Source Files"),d.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"?(d.push("The collection folder definition is in the `.http-forge/assets/collections/<collectionName>/<folderPath>/` path of your HTTP Forge workspace."),d.push(`Run context: ${h}${i?` (${i})`:""}`),g&&d.push(`Collection: ${g}`),v&&d.push(`Folder: ${v.split("/").filter(Boolean).join(" / ")}`)):f==="collection"?(d.push("The collection definition is in the `.http-forge/assets/collections/<collectionName>/` directory of your HTTP Forge workspace."),d.push(`Run context: ${h}${i?` (${i})`:""}`),g&&d.push(`Collection: ${g}`)):(d.push("The suite definition is in the `suites/` directory of your HTTP Forge workspace."),d.push(`Suite ID: \`${i}\``),d.push(`Run context: ${h}${i?` (${i})`:""}`)),d.push(""),d.push("Each request definition (description, scripts, response schema) is in:"),d.push("`.http-forge/assets/collections/<collectionName>/<folderPath>/<requestName>/`"),d.push(""),d.push("## \u{1F4CE} Context Required Before Analysis"),d.push(""),d.push("HTTP Forge provides the test definitions, assertion scripts, and response data above."),d.push("To understand failures from a **business perspective**, you also need:"),d.push(""),d.push("**Ask the user to provide:**"),d.push("1. The backend service/controller handling these endpoints"),d.push(" *(e.g. `BookmarkController.java`, `UserService.ts`)*"),d.push("2. Domain model or entity classes if applicable"),d.push("3. Any relevant unit/integration tests"),d.push(""),d.push("> Without backend code, analysis is limited to HTTP mechanics only."),d.push("> With it, you can identify business rule violations, data dependency issues,"),d.push("> and whether a failure is a real regression or a test data problem."),d.push(""),d.push("## \u{1F916} How to Analyse These Failures"),d.push(""),d.push("**Step 1 \u2014 Gather business context** (in priority order):"),d.push("- Read the source request files linked above (description, scripts, response schema)"),d.push("- Read the workspace collections and test suites \u2014 they are the primary source of truth"),d.push("- Use the response bodies above as context"),d.push("- Optional: if a Confluence/Jira MCP server is configured (and the team keeps"),d.push(" knowledge pages there), search those for acceptance criteria, API specs, or known"),d.push(" issues \u2014 otherwise skip it. A complete analysis is possible from the workspace alone."),d.push(""),d.push("> **Note:** A Confluence/Jira MCP server is an optional extra \u2014 it may help surface"),d.push("> acceptance criteria and API specs if the team keeps knowledge pages there. Without it,"),d.push("> the workspace code, collections, and test suites are sufficient for a full analysis."),d.push(""),d.push("**Step 2 \u2014 Determine root cause for each failure:**"),d.push("- **Test data issue** \u2014 the resource doesn't exist yet or was deleted by a prior request"),d.push("- **API regression** \u2014 the endpoint changed behaviour unexpectedly"),d.push("- **Assertion bug** \u2014 the test expectation itself is wrong"),d.push("- **Environment/config issue** \u2014 wrong base URL, missing auth token, wrong environment"),d.push("- **Sequencing issue** \u2014 depends on a prior request that also failed"),d.push(""),d.push("**Step 3 \u2014 Suggest concrete fixes:**"),d.push("- Corrected `pm.test()` snippets"),d.push("- Request changes (headers, body, URL)"),d.push("- Environment variable adjustments"),d.push(""),d.push("> If source code and documentation conflict, **treat the source code as ground truth**."),d.push("> Do NOT suggest disabling or weakening assertions unless the assertion itself is wrong."),o)try{let y=JSON.stringify(o,null,2);d.push(""),d.push("## \u{1F527} Suite Definition"),d.push(""),d.push("```json");let x=1e4;y.length>x?(d.push(y.slice(0,x)),d.push(`
1458
+ ... [${y.length-x} chars truncated]`)):d.push(y),d.push("```"),d.push("")}catch{}return d.join(`
1459
1459
  `)+`
1460
- `}}});function Cr(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 we,Je,Fn,ic=E(()=>{"use strict";we=I(require("fs/promises")),Je=I(require("path"));Ke();is();Nu();zi();Sm();Ts();Fn=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=Je.join(this.basePath,e,o),await we.mkdir(Je.join(this.currentRunPath,"results"),{recursive:!0}),await we.mkdir(Je.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.");this.resultIndex++;let n=Date.now(),s=String(e).padStart(4,"0"),i=String(this.resultIndex).padStart(6,"0"),o=ve(t.requestId),a=`result-${i}-iter-${s}-${o}.json`,c=Je.join(this.currentRunPath,"results",a),l={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:n,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(f=>({name:f.name,passed:f.passed,message:f.message||null,...f.skipped?{skipped:!0}:{}})),error:t.error||null,consoleOutput:t.consoleOutput,nextRequest:t.nextRequest??null,visualizerData:t.visualizerData};await we.writeFile(c,JSON.stringify($o(l),null,2),"utf-8");let u=t.assertions.filter(f=>f.passed&&!f.skipped).length,d=t.assertions.filter(f=>!f.passed&&!f.skipped).length,p=t.assertions.filter(f=>f.skipped).length,m={i:this.resultIndex,it:e,n:t.name,m:nc[t.executedRequest.method.toUpperCase()]??0,s:t.response.status,d:t.duration,p:t.passed,ap:u,af:d,...p>0?{as:p}:{},r:t.requestId,e:t.passed?null:t.error||null,fp:t.folderPath||"",gp:t.groupPath||t.folderPath||"",gt:t.groupType,cn:t.collectionName||""};return this.currentIndexPage.push(m),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:n,iteration:e,requestName:t.name,status:t.response.status,error:t.error||`Status ${t.response.status}`,resultFile:a}),this.recentErrors.length>this.recentErrorsLimit&&this.recentErrors.pop()),m}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=Cr(u,50),l.p90=Cr(u,90),l.p95=Cr(u,95),l.p99=Cr(u,99))}let n=Object.values(this.requestDurations).flat();n.length>0&&(n.sort((c,l)=>c-l),this.currentManifest.stats.p50=Cr(n,50),this.currentManifest.stats.p95=Cr(n,95),this.currentManifest.stats.p99=Cr(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 xr(this.basePath,c).generate(o,a)}catch(c){console.warn("[ResultStorage] HTML report generation failed:",c)}try{let c=this.configService.getSuitesPath();await new sc(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 xr(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 Ht(this.basePath).generate(e,t)}catch(n){return console.warn("[ResultStorage] JUnit report generation failed:",n),null}}async getResultDetails(e,t,n){let s=Je.join(this.basePath,e,t,"results",n),i=await we.readFile(s,"utf-8");return JSON.parse(i)}async getIndexPage(e,t,n){let s=Je.join(this.basePath,e,t,"index",`page-${String(n).padStart(4,"0")}.json`),i=await we.readFile(s,"utf-8");return JSON.parse(i)}async getManifest(e,t){let n=Je.join(this.basePath,e,t,"manifest.json"),s=await we.readFile(n,"utf-8");return JSON.parse(s)}async listRuns(e){let t=Je.join(this.basePath,e);try{let n=await we.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 we.readdir(this.basePath,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}async deleteRun(e,t){let n=Je.join(this.basePath,e,t);await we.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=Je.join(this.basePath,a,l.runId),d=await this.getDirectorySize(u);await we.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=Je.join(this.currentRunPath,"manifest.json");await we.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=Je.join(this.currentRunPath,"index",e),n={page:this.currentPageNumber,startIndex:(this.currentPageNumber-1)*this.indexPageSize+1,count:this.currentIndexPage.length,summaries:this.currentIndexPage};await we.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 we.readdir(e,{withFileTypes:!0});for(let s of n){let i=Je.join(e,s.name);if(s.isDirectory())t+=await this.getDirectorySize(i);else{let o=await we.stat(i);t+=o.size}}}catch{}return t}}});function Gi(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(Ee).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=Gi(r,e,a.items??[],c,l,u);if(d)return d}}}function Mu(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(Ee).join("/")});else{let o=i,a=o.scripts?[...t,o.scripts]:[...t],c=[...n,o.name];s.push(...Mu(r,o.items??[],a,c))}return s}function xm(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 wm(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}var _u=E(()=>{"use strict";Xe()});function oc(r){let e=[r.testSuite,r.collection,r.environmentConfig,r.config,r.console];for(let t of e)try{t?.dispose?.()}catch{}}function Rm(r){return r==="1"||r==="true"||r==="yes"||r==="on"}function Cm(){return Rm(process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS)}function Em(){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 ac(r,e=[]){return Rm(process.env.HTTP_FORGE_GENERATE_REPORTS)||e.includes("html")?!0:r.includes("report")}function Wi(r){if(typeof r!="string")return r;try{return JSON.parse(r)}catch{return r}}function yb(r){return r?Object.fromEntries(Object.entries(r).filter(([e])=>e.toLowerCase()!=="set-cookie")):{}}function cc(r){return ut(yb(r))}function lc(r){return ml((r??[]).map(e=>({name:e.name,value:e.value})))}function Du(r){return r.replace(/[^a-zA-Z0-9_-]/g,"_")}function uc(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,method:r.method,url:r.url,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 dc(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 Ms(r){return r?Object.fromEntries(Object.entries(r).map(([e,t])=>[e,String(t)])):{}}function pc(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 ju=E(()=>{"use strict";is()});var qt,Er,Lu,fc,mc,hc,Am=E(()=>{"use strict";qt=I(require("fs")),Er=I(require("path")),Lu=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=qt.watch(n.watchPath,{recursive:n.recursive},(i,o)=>{if(!o)return;let a=typeof o=="string"?o:String(o),c=Er.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=Er.resolve(e,t);return{watchPath:Er.dirname(n),recursive:!1,matcher:s=>Er.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){qt.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()}},fc=class{createFileWatcher(e,t){return new Lu(e,t)}},mc=class{data={};storeFile;constructor(e){this.storeFile=e,this.load()}load(){try{if(qt.existsSync(this.storeFile)){let e=qt.readFileSync(this.storeFile,"utf-8");this.data=JSON.parse(e)}}catch{}}save(){try{let e=Er.dirname(this.storeFile);qt.mkdirSync(e,{recursive:!0}),qt.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()}},hc=class{async showInformation(e){console.log(`[INFO] ${e}`)}async showWarning(e){console.warn(`[WARN] ${e}`)}async showError(e){console.error(`[ERROR] ${e}`)}}});function vb(r){let e=Ar.resolve(r.workspaceFolder),{appInfo:t}=r,n=Rn.createFresh(),s=Ar.join(e,".http-forge",".cache","stores","global-state.json"),i=r.globalStorePath?Ar.isAbsolute(r.globalStorePath)?r.globalStorePath:Ar.resolve(e,r.globalStorePath):s,o={workspaceFolder:e,fileWatcherFactory:new fc,notificationService:new hc,globalStore:new mc(i),applicationInfo:t||{name:"http-forge-cli",version:"0.1.0"},persistOverrides:!1};return bi(n,o),n}function ot(r){return vb({workspaceFolder:r})}var Ar,gc=E(()=>{"use strict";Ar=I(require("path"));Fl();Ml();Am()});function bb(r){let e=[];return r.map(t=>{let n=ct(t,e);return e.push(n),n})}function qm(r,e,t,n){let s=r.find(l=>l.id===e);if(s)return{item:s,tier:"id"};let i=bb(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 _s(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 _s(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 yc(r,e){let{item:t,tier:n}=qm(r,e,"collection",()=>"");return{collection:t,tier:n}}function vc(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}=qm(a,o,"folder",d=>c?`${c}/${d.name}`:d.name);s.push(l.name),i.push(u),n=l.items??[]}return{folderPath:s.map(Ee).join("/"),tiers:i}}function Pm(r,e,t){let n=[];for(let s of r)if(s.type==="request"){let i=ct(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}/${Ee(i.name)}`:Ee(i.name);Pm(i.items??[],o,t)}}function bc(r,e,t){let n=[];Pm(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 _s("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 _s("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 _s,Hu=E(()=>{"use strict";dn();Xe();_s=class extends Error{constructor(t,n,s){super(`Ambiguous ${t} reference "${n}" matches ${s.length} items:
1460
+ `}}});function Ar(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 we,ze,Nn,cc=E(()=>{"use strict";we=I(require("fs/promises")),ze=I(require("path"));We();as();ju();Gi();Cm();$s();Nn=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=ze.join(this.basePath,e,o),await we.mkdir(ze.join(this.currentRunPath,"results"),{recursive:!0}),await we.mkdir(ze.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.");this.resultIndex++;let n=Date.now(),s=String(e).padStart(4,"0"),i=String(this.resultIndex).padStart(6,"0"),o=Se(t.requestId),a=`result-${i}-iter-${s}-${o}.json`,c=ze.join(this.currentRunPath,"results",a),l={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:n,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(f=>({name:f.name,passed:f.passed,message:f.message||null,...f.skipped?{skipped:!0}:{}})),error:t.error||null,consoleOutput:t.consoleOutput,nextRequest:t.nextRequest??null,visualizerData:t.visualizerData};await we.writeFile(c,JSON.stringify(Mo(l),null,2),"utf-8");let u=t.assertions.filter(f=>f.passed&&!f.skipped).length,p=t.assertions.filter(f=>!f.passed&&!f.skipped).length,d=t.assertions.filter(f=>f.skipped).length,m={i:this.resultIndex,it:e,n:t.name,m:ic[t.executedRequest.method.toUpperCase()]??0,s:t.response.status,d:t.duration,p:t.passed,ap:u,af:p,...d>0?{as:d}:{},r:t.requestId,e:t.passed?null:t.error||null,fp:t.folderPath||"",gp:t.groupPath||t.folderPath||"",gt:t.groupType,cn:t.collectionName||""};return this.currentIndexPage.push(m),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:n,iteration:e,requestName:t.name,status:t.response.status,error:t.error||`Status ${t.response.status}`,resultFile:a}),this.recentErrors.length>this.recentErrorsLimit&&this.recentErrors.pop()),m}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((p,d)=>p-d),l.p50=Ar(u,50),l.p90=Ar(u,90),l.p95=Ar(u,95),l.p99=Ar(u,99))}let n=Object.values(this.requestDurations).flat();n.length>0&&(n.sort((c,l)=>c-l),this.currentManifest.stats.p50=Ar(n,50),this.currentManifest.stats.p95=Ar(n,95),this.currentManifest.stats.p99=Ar(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 Cr(this.basePath,c).generate(o,a)}catch(c){console.warn("[ResultStorage] HTML report generation failed:",c)}try{let c=this.configService.getSuitesPath();await new ac(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 Cr(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 Lt(this.basePath).generate(e,t)}catch(n){return console.warn("[ResultStorage] JUnit report generation failed:",n),null}}async getResultDetails(e,t,n){let s=ze.join(this.basePath,e,t,"results",n),i=await we.readFile(s,"utf-8");return JSON.parse(i)}async getIndexPage(e,t,n){let s=ze.join(this.basePath,e,t,"index",`page-${String(n).padStart(4,"0")}.json`),i=await we.readFile(s,"utf-8");return JSON.parse(i)}async getManifest(e,t){let n=ze.join(this.basePath,e,t,"manifest.json"),s=await we.readFile(n,"utf-8");return JSON.parse(s)}async listRuns(e){let t=ze.join(this.basePath,e);try{let n=await we.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 we.readdir(this.basePath,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}async deleteRun(e,t){let n=ze.join(this.basePath,e,t);await we.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=ze.join(this.basePath,a,l.runId),p=await this.getDirectorySize(u);await we.rm(u,{recursive:!0,force:!0}),s++,i+=p}}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=ze.join(this.currentRunPath,"manifest.json");await we.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=ze.join(this.currentRunPath,"index",e),n={page:this.currentPageNumber,startIndex:(this.currentPageNumber-1)*this.indexPageSize+1,count:this.currentIndexPage.length,summaries:this.currentIndexPage};await we.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 we.readdir(e,{withFileTypes:!0});for(let s of n){let i=ze.join(e,s.name);if(s.isDirectory())t+=await this.getDirectorySize(i);else{let o=await we.stat(i);t+=o.size}}}catch{}return t}}});function Ki(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(qe).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],p=Ki(r,e,a.items??[],c,l,u);if(p)return p}}}function Lu(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(qe).join("/")});else{let o=i,a=o.scripts?[...t,o.scripts]:[...t],c=[...n,o.name];s.push(...Lu(r,o.items??[],a,c))}return s}function Em(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 qm(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}var Hu=E(()=>{"use strict";Ye()});function lc(r){let e=[r.testSuite,r.collection,r.environmentConfig,r.config,r.console];for(let t of e)try{t?.dispose?.()}catch{}}function Am(r){return r==="1"||r==="true"||r==="yes"||r==="on"}function Pm(){return Am(process.env.HTTP_FORGE_ENFORCE_MAX_REQUESTS)}function km(){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 uc(r,e=[]){return Am(process.env.HTTP_FORGE_GENERATE_REPORTS)||e.includes("html")?!0:r.includes("report")}function Qi(r){if(typeof r!="string")return r;try{return JSON.parse(r)}catch{return r}}function xb(r){return r?Object.fromEntries(Object.entries(r).filter(([e])=>e.toLowerCase()!=="set-cookie")):{}}function dc(r){return lt(xb(r))}function pc(r){return vl((r??[]).map(e=>({name:e.name,value:e.value})))}function Bu(r){return r.replace(/[^a-zA-Z0-9_-]/g,"_")}function fc(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,method:r.method,url:r.url,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 mc(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 Ds(r){return r?Object.fromEntries(Object.entries(r).map(([e,t])=>[e,String(t)])):{}}function hc(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 Uu=E(()=>{"use strict";as()});var qt,Pr,Vu,gc,yc,vc,Im=E(()=>{"use strict";qt=I(require("fs")),Pr=I(require("path")),Vu=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=qt.watch(n.watchPath,{recursive:n.recursive},(i,o)=>{if(!o)return;let a=typeof o=="string"?o:String(o),c=Pr.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=Pr.resolve(e,t);return{watchPath:Pr.dirname(n),recursive:!1,matcher:s=>Pr.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){qt.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()}},gc=class{createFileWatcher(e,t){return new Vu(e,t)}},yc=class{data={};storeFile;constructor(e){this.storeFile=e,this.load()}load(){try{if(qt.existsSync(this.storeFile)){let e=qt.readFileSync(this.storeFile,"utf-8");this.data=JSON.parse(e)}}catch{}}save(){try{let e=Pr.dirname(this.storeFile);qt.mkdirSync(e,{recursive:!0}),qt.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()}},vc=class{async showInformation(e){console.log(`[INFO] ${e}`)}async showWarning(e){console.warn(`[WARN] ${e}`)}async showError(e){console.error(`[ERROR] ${e}`)}}});function wb(r){let e=kr.resolve(r.workspaceFolder),{appInfo:t}=r,n=Cn.createFresh(),s=kr.join(e,".http-forge",".cache","stores","global-state.json"),i=r.globalStorePath?kr.isAbsolute(r.globalStorePath)?r.globalStorePath:kr.resolve(e,r.globalStorePath):s,o={workspaceFolder:e,fileWatcherFactory:new gc,notificationService:new vc,globalStore:new yc(i),applicationInfo:t||{name:"http-forge-cli",version:"0.1.0"},persistOverrides:!1};return xi(n,o),n}function it(r){return wb({workspaceFolder:r})}var kr,bc=E(()=>{"use strict";kr=I(require("path"));Dl();Ll();Im()});function Rb(r){let e=[];return r.map(t=>{let n=at(t,e);return e.push(n),n})}function Tm(r,e,t,n){let s=r.find(l=>l.id===e);if(s)return{item:s,tier:"id"};let i=Rb(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 js(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 js(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 Sc(r,e){let{item:t,tier:n}=Tm(r,e,"collection",()=>"");return{collection:t,tier:n}}function xc(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(p=>p.type==="folder"),c=s.join("/"),{item:l,tier:u}=Tm(a,o,"folder",p=>c?`${c}/${p.name}`:p.name);s.push(l.name),i.push(u),n=l.items??[]}return{folderPath:s.map(qe).join("/"),tiers:i}}function Om(r,e,t){let n=[];for(let s of r)if(s.type==="request"){let i=at(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}/${qe(i.name)}`:qe(i.name);Om(i.items??[],o,t)}}function wc(r,e,t){let n=[];Om(r.items,"",n);let s=t?t.replace(/\/+$/,""):void 0,i=s?n.filter(d=>d.folderPath===s||d.folderPath.startsWith(`${s}/`)):n,o=d=>d.folderPath?`${d.folderPath}/${d.item.name}`:d.item.name,a=i.find(d=>d.item.id===e);if(a)return{request:a.item,tier:"id",folderPath:a.folderPath};let c=i.filter(d=>d.slug===e);if(c.length===1)return{request:c[0].item,tier:"slug",folderPath:c[0].folderPath};if(c.length>1)throw new js("request",e,c.map(d=>({id:d.item.id,name:d.item.name,path:o(d)})));let l=e.toLowerCase(),u=i.filter(d=>d.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 js("request",e,u.map(d=>({id:d.item.id,name:d.item.name,path:o(d)})));let p=s?` under folder "${s}"`:"";throw new Error(`Request "${e}" not found in collection "${r.name}"${p}`)}var js,zu=E(()=>{"use strict";pn();Ye();js=class extends Error{constructor(t,n,s){super(`Ambiguous ${t} reference "${n}" matches ${s.length} items:
1461
1461
  `+s.map(i=>` - ${i.name} (id: ${i.id}, path: ${i.path||"/"})`).join(`
1462
1462
  `)+`
1463
- Disambiguate by passing the id or slug.`);this.kind=t;this.value=n;this.candidates=s;this.name="AmbiguousRefError"}kind;value;candidates}});function Ds(r){return typeof r=="string"?r:""+JSON.stringify(r)}function qr(r){if(typeof r=="string"&&r.charCodeAt(0)===30)try{return JSON.parse(r.slice(1))}catch{return r}return r}function Sc(r){if(!r)return{};let e={};for(let[t,n]of Object.entries(r))e[t]=qr(n);return e}var Bu=E(()=>{"use strict"});var Ki,km=E(()=>{"use strict";tc();ci();is();zi();ic();Gs();Bu();_u();ju();ec();Ki=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=Ms(t.variables),h=Cm(),g=ac(d,p),v=Math.max(1,Math.min(1e4,Number(t.maxNodeLoopIterations??100))),y={vars:{...f}};function x(P){if(typeof P=="string")return P;if(Array.isArray(P))return P.filter(K=>typeof K=="string").join(`
1464
- `)}function b(P){if(!(!P||typeof P!="object")){if(P.script!==void 0)return P.script;if(typeof P.scriptRef=="string"&&P.scriptRef.trim()){let k=e?.scripts;if(k&&typeof k=="object")return k[P.scriptRef]}}}function R(P){return P?.name||P?.label||P?.id||"flow-node"}function C(P,k){let K=s.environmentConfig.getResolvedEnvironment(i),U=Sc(y.vars),Te={variables:{get:N=>qr(y.vars[N]),set:(N,Le)=>{typeof N=="string"&&N.trim()&&(y.vars[N]=Ds(Le))},unset:N=>{typeof N=="string"&&N.trim()&&delete y.vars[N]},has:N=>Object.prototype.hasOwnProperty.call(y.vars,N),toObject:()=>({...U})},environment:{get:N=>qr(K?.variables?.[N]),set:(N,Le)=>{typeof N=="string"&&N.trim()&&s.environmentConfig.setEnvironmentVariable(N,Ds(Le),i)},unset:N=>{typeof N=="string"&&N.trim()&&s.environmentConfig.deleteEnvironmentVariable(N,i)},clear:()=>{s.environmentConfig.clearEnvironmentVariables(i)}},globals:{get:N=>qr(s.environmentConfig.getGlobalVariables()?.[N]),set:(N,Le)=>{typeof N=="string"&&N.trim()&&s.environmentConfig.setGlobalVariable(N,Ds(Le))},unset:N=>{typeof N=="string"&&N.trim()&&s.environmentConfig.deleteGlobalVariable(N)},clear:()=>{s.environmentConfig.clearGlobalVariables()}}};return{vars:U,lastResult:y.lastResult,iteration:k,node:P,pm:Te,ctx:Te,hf:Te}}function q(P,k,K){return typeof P!="string"||!P.trim()?!0:!!yt(P,C(k,K))}function _(P){if(!P)return{};let k={};for(let[K,U]of Object.entries(P))k[K]=Array.isArray(U)?U.join("; "):String(U);return k}function M(P){return{executedRequest:P.executedRequest,status:P.response?.status??0,statusText:P.response?.statusText??"",headers:_(P.response?.headers),body:P.response?.body,cookies:P.response?.cookies,responseTime:P.duration,responseSize:typeof P.response?.body=="string"?Buffer.byteLength(P.response.body,"utf8"):0}}async function D(P,k,K,U,J){let ue=x(P);if(!ue||!ue.trim())return;let fe=s.environmentConfig.getResolvedEnvironment(i),Te=s.environmentConfig.getGlobalVariables(),Le={request:{url:J?.request?.url??y.lastResult?.executedRequest?.url??"http://flow.local/node",method:J?.request?.method??y.lastResult?.executedRequest?.method??"GET",headers:_(J?.request?.headers),body:J?.request?.body??null,params:J?.request?.params??{},query:J?.request?.query??{}},variables:Ms(y.vars),environmentVariables:fe?.variables||{},globals:{...Te},environmentName:i,info:{eventName:U==="post"?"test":"prerequest",requestName:R(k),requestId:String(k?.id??R(k)),collectionName:e.name,iteration:K,iterationCount:o},onEnvironmentChange:(be,Se,Mn)=>{be==="set"&&Se&&Mn!==void 0?s.environmentConfig.setEnvironmentVariable(Se,Mn,i):be==="unset"&&Se?s.environmentConfig.deleteEnvironmentVariable(Se,i):be==="clear"&&s.environmentConfig.clearEnvironmentVariables(i)},onGlobalsChange:(be,Se,Mn)=>{be==="set"&&Se&&Mn!==void 0?s.environmentConfig.setGlobalVariable(Se,Mn):be==="unset"&&Se?s.environmentConfig.deleteGlobalVariable(Se):be==="clear"&&s.environmentConfig.clearGlobalVariables()}},He=s.scriptExecutor.createRequestSession(Le);try{if(U==="post"&&J?.response){let be=await He.executePostResponse(ue,J.response),Se=be.localVariables??be.modifiedVariables;Se&&typeof Se=="object"&&(y.vars={...Se})}else{let be=await He.executePreRequest(ue);if(!be.success)throw new Error(be.error||"Script execution failed");let Se=be.localVariables??be.modifiedVariables;Se&&typeof Se=="object"&&(y.vars={...Se})}}catch(be){let Se=be instanceof Error?be.message:String(be);throw new Error(`Suite ${U}-script failed on node "${R(k)}": ${Se}`)}finally{He.dispose?.()}}function V(P){let k=P?.type==="request"&&P?.request?P.request:P;if(!(!k||typeof k!="object")&&!(!k.collectionId||!k.requestId||!k.name))return{collectionId:k.collectionId,requestId:k.requestId,name:k.name,folderPath:k.folderPath,enabled:k.enabled}}function O(P){return!P||typeof P!="object"?!1:P.type==="request"?!!V(P):!!(P.collectionId&&P.requestId&&P.name)}function H(P,k){for(let K of k){let U=P?.[K];if(Array.isArray(U))return U}return[]}async function Z(P,k,K){if(he.signal.aborted||k.enabled===!1||u&&!u.some(He=>k.name.toLowerCase().includes(He.toLowerCase())))return;let U=s.collection.getCollection(k.collectionId);if(!U)return;let J=Gi(U,k.requestId);if(!J)return;let ue=pc(J.request.auth,J.folderAuthChain,U.auth),fe=new _t(s.httpRequest,s.scriptExecutor,s.environmentConfig,s.requestPreparer,i,mt,U.scripts,J.folderScriptsChain,void 0,U.name,U.auth,P,o),Te=dc(uc({...J.request,auth:ue}),{headers:t.headers,query:t.query,body:t.body,variables:{...y.vars,...t.variables}}),N=await fe.execute(Te,Ms(y.vars),he.signal);y.lastResult=N,N.modifiedVariables&&typeof N.modifiedVariables=="object"&&(y.vars={...N.modifiedVariables});let Le=Is({collectionName:U.name,folderPath:k.folderPath??"",blockLabel:K});N.folderPath=k.folderPath??"",N.collectionName=U.name,N.groupPath=Le.groupPath,N.groupType=Le.groupType,await te.saveResult(P,N),N.assertions?.length||at.add(k.name),N.passed?We++:Pe++,d.includes("perRequest")&&B.push({name:k.name,iteration:P,status:N.response?.status,ok:(N.response?.status??0)>=200&&(N.response?.status??0)<300,duration:`${N.duration}ms`,allPassed:N.passed,...d.includes("consoleOutput")&&N.consoleOutput?.length?{consoleOutput:N.consoleOutput}:{}}),N.passed||(Ie.push({name:k.name,iteration:P,method:N.executedRequest?.method,url:N.executedRequest?.url,requestBody:Wi(N.executedRequest?.body?.content)??N.executedRequest?.body?.content??null,requestHeaders:ut(N.executedRequest?.headers??{}),status:N.response?.status,duration:`${N.duration}ms`,body:Wi(N.response?.body),headers:cc(N.response?.headers),cookies:lc(N.response?.cookies),failedTests:N.assertions?.filter(He=>!He.passed).map(He=>({name:He.name,...He.message?{message:He.message}:{}})),...N.error?{error:N.error}:{},...d.includes("consoleOutput")&&N.consoleOutput?.length?{consoleOutput:N.consoleOutput}:{}}),a&&he.abort()),c>0&&!he.signal.aborted&&await new Promise(He=>setTimeout(He,c))}async function X(P,k,K){for(let U of k){if(he.signal.aborted)break;await Ge(P,U,K)}}async function Ge(P,k,K){if(!k||typeof k!="object"||k.enabled===!1||!q(k.condition,k,P))return;if(O(k)){let ue=V(k);ue&&await Z(P,ue,K);return}let U=typeof k.type=="string"?k.type.toLowerCase():"",J=H(k,["then","nodes","body"]);if(U==="block"){let ue=typeof k.name=="string"?k.name.trim():"";await X(P,J,ue||K);return}if(U==="script"){let ue=b(k),fe=k.phase==="post"?"post":"pre";await D(ue,k,P,fe);return}if(U==="if"){let ue=typeof k.if=="string"?k.if:k.condition;if(q(ue,k,P)){await X(P,J,K);return}if(Array.isArray(k.elseif)){for(let fe of k.elseif)if(q(fe?.condition,fe,P)){await X(P,H(fe,["then","nodes","body"]),K);return}}await X(P,H(k,["else","elseNodes"]),K);return}if(U==="switch"){let ue=yt(String(k.expression??""),C(k,P));if(Array.isArray(k.cases)){for(let fe of k.cases)if(Object.prototype.hasOwnProperty.call(fe??{},"equals")?fe.equals===ue:q(fe?.condition,fe,P)){await X(P,H(fe,["then","nodes","body"]),K);return}}await X(P,H(k,["default","defaultNodes"]),K);return}if(U==="while"){let ue=typeof k.while=="string"?k.while:k.condition,fe=Math.max(1,Math.min(1e4,Number(k.maxIterations??v))),Te=0;for(;q(ue,k,P);){if(Te+=1,Te>fe)throw new Error(`Suite while loop exceeded maxIterations (${fe}) on node "${R(k)}"`);if(await X(P,J,K),he.signal.aborted)break}return}if(U==="for"){let ue=Math.max(1,Math.min(1e4,Number(k.maxIterations??v))),fe=x(k.init),Te=x(k.update),N=typeof k.loopCondition=="string"&&k.loopCondition.trim()?k.loopCondition:typeof k.condition=="string"&&k.condition.trim()?k.condition:"true";fe&&await D(fe,k,P,"pre");let Le=0;for(;q(N,k,P);){if(Le+=1,Le>ue)throw new Error(`Suite for loop exceeded maxIterations (${ue}) on node "${R(k)}"`);if(await X(P,J,K),he.signal.aborted)break;Te&&await D(Te,k,P,"post")}return}J.length>0&&await X(P,J,K)}function ln(P){let k=0,K=[...P];for(;K.length>0;){let U=K.pop();if(!(!U||typeof U!="object"||U.enabled===!1)){if(O(U)){let J=V(U);J&&(!u||u.some(ue=>J.name.toLowerCase().includes(ue.toLowerCase())))&&(k+=1);continue}for(let J of["nodes","then","body","else","elseNodes","default","defaultNodes"])Array.isArray(U[J])&&K.push(...U[J]);if(Array.isArray(U.elseif))for(let J of U.elseif)Array.isArray(J?.nodes)&&K.push(...J.nodes),Array.isArray(J?.then)&&K.push(...J.then);if(Array.isArray(U.cases))for(let J of U.cases)Array.isArray(J?.nodes)&&K.push(...J.nodes),Array.isArray(J?.then)&&K.push(...J.then)}}return k}let It=Array.isArray(e.nodes)?e.nodes:Array.isArray(e.requests)?e.requests.map(P=>({type:"request",request:P})):[],A=ln(It);if(h){let P=Em(),k=A*o;if(k>P)throw new Error(`Suite "${e.name}" would execute ${k} request calls (${A} requests \xD7 ${o} iterations), which exceeds HTTP_FORGE_MAX_REQUESTS (${P}). Reduce iterations, use requestFilter, or increase HTTP_FORGE_MAX_REQUESTS.`)}let te=new Fn(s.config),Ce=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=[],Ie=[],We=0,Pe=0,at=new Set,he=new AbortController,mt=new On;async function un(P){await X(P,It)}for(let P=1;P<=o&&!he.signal.aborted;P+=l){let k=Math.min(P+l-1,o),K=Array.from({length:k-P+1},(U,J)=>P+J);await Promise.all(K.map(un))}let ye=await te.finalizeRun("completed",g),Hs=null;if(m)try{Hs=await new Ht(te.getBasePath()).generate(e.id,Ce)}catch(P){console.warn("[direct-execution] JUnit report generation failed:",P)}let Ir=n==="collection"?"collection":"suite",ht=te.getCurrentStats()?.stats,Yi=ht?{min:ht.minDuration,max:ht.maxDuration,avg:ht.avgDuration,p50:ht.p50??null,p95:ht.p95??null,p99:ht.p99??null}:null,Tt={[Ir]:e.name,environment:i,summary:{total:We+Pe,passed:We,failed:Pe,...o>1?{iterations:o}:{},...l>1?{concurrency:l}:{},allPassed:Pe===0,...Yi?{durationMs:Yi}:{}}};if((Pe>0||d.includes("failedOnly"))&&(Tt.failedRequests=Ie),d.includes("perRequest")&&(Tt.results=B),ye!==null&&(Tt.report={uri:`file://${ye}`,hint:"Click the URI to open the HTML report in your browser"}),Hs!==null&&(Tt.junitReport={path:Hs}),at.size>0){let P=Math.max(A,1),k=at.size,K=Array.from(at).slice(0,5);Tt.noAssertionExamples=K;let U=e.name;if(k/P>.5)Tt._suggestions=[`${k}/${P} 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 J=K.map(ue=>`"${ue}"`).join(", ");Tt._suggestions=[`${k} request(s) have no pm.test() assertions: ${J}. Invoke the "suggest-assertions" prompt (collection="${U}") to generate test coverage for them.`]}}return Tt}}});var Zi={};Ot(Zi,{runCollection:()=>cn,runFolder:()=>Sb,runRequest:()=>xc,runSuite:()=>Qi});function Im(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}=yc(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 Tm(r,e){if(e.folderPath)return e.folderPath;if(e.folderRef){let{folderPath:t}=vc(r,e.folderRef);return e.onResolve?.({kind:"folder",value:e.folderRef,tier:"name",id:t,path:t}),t}}async function xc(r){let e=ot(r.workspaceFolder),t=r.include??[],n=r.reporters??[],s=n.includes("junit"),i=ac(t,n);try{let o=e.collection,a=Im(o,r),c=Tm(a,r),l=r.requestId;if(!l){if(!r.requestRef)throw new Error("A request reference is required (requestId or requestRef)");let R=bc(a,r.requestRef,c);l=R.request.id,r.onResolve?.({kind:"request",value:r.requestRef,tier:R.tier,id:l,path:R.folderPath?`${R.folderPath}/${R.request.name}`:R.request.name})}let u=Gi(a,l);if(!u)throw new Error(`Request "${l}" not found in collection "${a.name}"`);let d=pc(u.request.auth,u.folderAuthChain,a.auth),p=r.environment||e.environmentConfig.getSelectedEnvironment(),m=dc(uc({...u.request,auth:d}),{headers:r.headers,query:r.query,body:r.body,variables:r.variables}),h=await new _t(e.httpRequest,e.scriptExecutor,e.environmentConfig,e.requestPreparer,p,new On,a.scripts,u.folderScriptsChain,void 0,a.name,a.auth).execute(m,Ms(r.variables)),g=Is({collectionName:a.name,folderPath:u.folderPath});h.folderPath=u.folderPath,h.collectionName=a.name,h.groupPath=g.groupPath,h.groupType=g.groupType;let v=null,y=null;if(i||s){let R=new Fn(e.config),C=`request-${Du(a.id)}-${Du(l)}`,q=`Request: ${u.request.name}`,_=await R.initializeRun(C,q,p,{iterations:1,delayBetweenRequests:0,stopOnError:!0},{targetType:"collection",targetName:a.name,collectionName:a.name,folderPath:u.folderPath||void 0});if(await R.saveResult(1,h),v=await R.finalizeRun("completed",i),s)try{y=await new Ht(R.getBasePath()).generate(C,_)}catch(M){console.warn("[direct-execution] JUnit report generation failed:",M)}}let x=cc(h.response?.headers),b=lc(h.response?.cookies);return{request:u.request.name,status:h.response?.status||0,ok:(h.response?.status??0)>=200&&(h.response?.status??0)<300,duration:`${h.duration}ms`,body:Wi(h.response?.body),allPassed:h.passed,assertions:h.assertions?.map(R=>({name:R.name,passed:R.passed,message:R.message})),...t.includes("headers")?{headers:x}:{},...t.includes("cookies")?{cookies:b}:{},...t.includes("tests")?{tests:h.assertions?.map(R=>({name:R.name,passed:R.passed,...R.message?{message:R.message}:{}}))}:{},...Object.keys(h.modifiedVariables??{}).length?{modifiedVariables:h.modifiedVariables}:{},...t.includes("consoleOutput")&&h.consoleOutput?.length?{consoleOutput:h.consoleOutput}:{},...v!==null?{report:{uri:`file://${v}`,hint:"Click the URI to open the HTML report in your browser"}}:{},...y!==null?{junitReport:{path:y}}:{},...h.error?{error:h.error}:{}}}catch(o){throw o}finally{oc(e)}}async function cn(r){let e=ot(r.workspaceFolder);try{let t=e.collection,n=Im(t,r),s=Tm(n,r),i=Mu(n),o=xm(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}-${wm(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 Ki(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{oc(e)}}async function Sb(r){return cn({recursive:!0,...r})}async function Qi(r){let e=ot(r.workspaceFolder);try{let n=await e.testSuite.getSuite(r.suiteId);if(!n)throw new Error(`Test suite "${r.suiteId}" not found`);return new Ki(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{oc(e)}}var js=E(()=>{"use strict";tc();ci();zi();ic();_u();ju();gc();Hu();ec();km()});var Mm={};Ot(Mm,{createMcpRuntime:()=>Fb});async function Pt(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 Ls(r){let e=[r.testSuite,r.collection,r.environmentConfig,r.config,r.console];for(let t of e)try{t?.dispose?.()}catch{}}async function Rb(r,e){let t=zu.get(r);if(t&&t.expiresAt>Date.now())return t.tools;let n=Uu.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 Xa(a,c,i,r)})().then(i=>(zu.set(r,{tools:i,expiresAt:Date.now()+wb}),i)).finally(()=>Uu.delete(r));return Uu.set(r,s),s}function Cb(r,e){let t=r.config.getMcpConfig().toolPrefix??"";return t&&e.startsWith(t)?e.slice(t.length):e}function Eb(r,e,t){return r.replace(/"uri"\s*:\s*"file:\/\/([^"]+)"/g,(n,s)=>`"uri":"http://${e}:${t}/report?path=${encodeURIComponent(s)}"`)}function Om(r,e,t,n){Pr(r,200,{jsonrpc:"2.0",id:e,error:{code:t,message:n}})}function Ab(r){return r.config.getMcpConfig().toolPageSize??200}async function qb(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 Rb(r.workspaceFolder,r.container),n=e.params??{},s=typeof n.cursor=="string"?n.cursor:void 0,i=Ab(r.container);if(i<=0||t.length<=i)return{tools:t};let o=Ya(s),a=t.slice(o,o+i),c=o+i,l={tools:a};return c<t.length&&(l.nextCursor=Za(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 Ju(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=Eb(c,r.host,r.port),u=l.match(/"uri"\s*:\s*"(http:\/\/[^"]+\/report\?[^"]+)"/),d=u?`
1463
+ Disambiguate by passing the id or slug.`);this.kind=t;this.value=n;this.candidates=s;this.name="AmbiguousRefError"}kind;value;candidates}});function Ls(r){return typeof r=="string"?r:""+JSON.stringify(r)}function Ir(r){if(typeof r=="string"&&r.charCodeAt(0)===30)try{return JSON.parse(r.slice(1))}catch{return r}return r}function Rc(r){if(!r)return{};let e={};for(let[t,n]of Object.entries(r))e[t]=Ir(n);return e}var Ju=E(()=>{"use strict"});var Zi,$m=E(()=>{"use strict";sc();ui();as();Gi();cc();Ks();Ju();Hu();Uu();rc();Zi=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,p=t.include??[],d=t.reporters??[],m=d.includes("junit"),f=Ds(t.variables),h=Pm(),g=uc(p,d),v=Math.max(1,Math.min(1e4,Number(t.maxNodeLoopIterations??100))),y={vars:{...f}};function x(k){if(typeof k=="string")return k;if(Array.isArray(k))return k.filter(K=>typeof K=="string").join(`
1464
+ `)}function b(k){if(!(!k||typeof k!="object")){if(k.script!==void 0)return k.script;if(typeof k.scriptRef=="string"&&k.scriptRef.trim()){let P=e?.scripts;if(P&&typeof P=="object")return P[k.scriptRef]}}}function C(k){return k?.name||k?.label||k?.id||"flow-node"}function R(k,P){let K=s.environmentConfig.getResolvedEnvironment(i),U=Rc(y.vars),$e={variables:{get:ee=>Ir(y.vars[ee]),set:(ee,z)=>{typeof ee=="string"&&ee.trim()&&(y.vars[ee]=Ls(z))},unset:ee=>{typeof ee=="string"&&ee.trim()&&delete y.vars[ee]},has:ee=>Object.prototype.hasOwnProperty.call(y.vars,ee),toObject:()=>({...U})},environment:{get:ee=>Ir(K?.variables?.[ee]),set:(ee,z)=>{typeof ee=="string"&&ee.trim()&&s.environmentConfig.setEnvironmentVariable(ee,Ls(z),i)},unset:ee=>{typeof ee=="string"&&ee.trim()&&s.environmentConfig.deleteEnvironmentVariable(ee,i)},clear:()=>{s.environmentConfig.clearEnvironmentVariables(i)}},globals:{get:ee=>Ir(s.environmentConfig.getGlobalVariables()?.[ee]),set:(ee,z)=>{typeof ee=="string"&&ee.trim()&&s.environmentConfig.setGlobalVariable(ee,Ls(z))},unset:ee=>{typeof ee=="string"&&ee.trim()&&s.environmentConfig.deleteGlobalVariable(ee)},clear:()=>{s.environmentConfig.clearGlobalVariables()}}};return{vars:U,lastResult:y.lastResult,iteration:P,node:k,pm:$e,ctx:$e,hf:$e}}function q(k,P,K){return typeof k!="string"||!k.trim()?!0:!!gt(k,R(P,K))}function N(k){if(!k)return{};let P={};for(let[K,U]of Object.entries(k))P[K]=Array.isArray(U)?U.join("; "):String(U);return P}function M(k){return{executedRequest:k.executedRequest,status:k.response?.status??0,statusText:k.response?.statusText??"",headers:N(k.response?.headers),body:k.response?.body,cookies:k.response?.cookies,responseTime:k.duration,responseSize:typeof k.response?.body=="string"?Buffer.byteLength(k.response.body,"utf8"):0}}async function _(k,P,K,U,W){let ue=x(k);if(!ue||!ue.trim())return;let he=s.environmentConfig.getResolvedEnvironment(i),$e=s.environmentConfig.getGlobalVariables(),z={request:{url:W?.request?.url??y.lastResult?.executedRequest?.url??"http://flow.local/node",method:W?.request?.method??y.lastResult?.executedRequest?.method??"GET",headers:N(W?.request?.headers),body:W?.request?.body??null,params:W?.request?.params??{},query:W?.request?.query??{}},variables:Ds(y.vars),environmentVariables:he?.variables||{},globals:{...$e},environmentName:i,info:{eventName:U==="post"?"test":"prerequest",requestName:C(P),requestId:String(P?.id??C(P)),collectionName:e.name,iteration:K,iterationCount:o},onEnvironmentChange:(pe,xe,Dn)=>{pe==="set"&&xe&&Dn!==void 0?s.environmentConfig.setEnvironmentVariable(xe,Dn,i):pe==="unset"&&xe?s.environmentConfig.deleteEnvironmentVariable(xe,i):pe==="clear"&&s.environmentConfig.clearEnvironmentVariables(i)},onGlobalsChange:(pe,xe,Dn)=>{pe==="set"&&xe&&Dn!==void 0?s.environmentConfig.setGlobalVariable(xe,Dn):pe==="unset"&&xe?s.environmentConfig.deleteGlobalVariable(xe):pe==="clear"&&s.environmentConfig.clearGlobalVariables()}},_n=s.scriptExecutor.createRequestSession(z);try{if(U==="post"&&W?.response){let pe=await _n.executePostResponse(ue,W.response),xe=pe.localVariables??pe.modifiedVariables;xe&&typeof xe=="object"&&(y.vars={...xe})}else{let pe=await _n.executePreRequest(ue);if(!pe.success)throw new Error(pe.error||"Script execution failed");let xe=pe.localVariables??pe.modifiedVariables;xe&&typeof xe=="object"&&(y.vars={...xe})}}catch(pe){let xe=pe instanceof Error?pe.message:String(pe);throw new Error(`Suite ${U}-script failed on node "${C(P)}": ${xe}`)}finally{_n.dispose?.()}}function H(k){let P=k?.type==="request"&&k?.request?k.request:k;if(!(!P||typeof P!="object")&&!(!P.collectionId||!P.requestId||!P.name))return{collectionId:P.collectionId,requestId:P.requestId,name:P.name,folderPath:P.folderPath,enabled:P.enabled}}function O(k){return!k||typeof k!="object"?!1:k.type==="request"?!!H(k):!!(k.collectionId&&k.requestId&&k.name)}function L(k,P){for(let K of P){let U=k?.[K];if(Array.isArray(U))return U}return[]}async function Z(k,P,K){if(ye.signal.aborted||P.enabled===!1||u&&!u.some(pe=>P.name.toLowerCase().includes(pe.toLowerCase())))return;let U=s.collection.getCollection(P.collectionId);if(!U)return;let W=Ki(U,P.requestId);if(!W)return;let ue=s.collection.findRequest(U.id,P.requestId)??W.request,he=hc(ue.auth,W.folderAuthChain,U.auth),$e=new Mt(s.httpRequest,s.scriptExecutor,s.environmentConfig,s.requestPreparer,i,ft,U.scripts,W.folderScriptsChain,void 0,U.name,U.auth,k,o),ee=mc(fc({...ue,auth:he}),{headers:t.headers,query:t.query,body:t.body,variables:{...y.vars,...t.variables}}),z=await $e.execute(ee,Ds(y.vars),ye.signal);y.lastResult=z,z.modifiedVariables&&typeof z.modifiedVariables=="object"&&(y.vars={...z.modifiedVariables});let _n=Os({collectionName:U.name,folderPath:P.folderPath??"",blockLabel:K});z.folderPath=P.folderPath??"",z.collectionName=U.name,z.groupPath=_n.groupPath,z.groupType=_n.groupType,await ne.saveResult(k,z),z.assertions?.length||ot.add(P.name),z.passed?Ge++:ke++,p.includes("perRequest")&&B.push({name:P.name,iteration:k,status:z.response?.status,ok:(z.response?.status??0)>=200&&(z.response?.status??0)<300,duration:`${z.duration}ms`,allPassed:z.passed,...p.includes("consoleOutput")&&z.consoleOutput?.length?{consoleOutput:z.consoleOutput}:{}}),z.passed||(Oe.push({name:P.name,iteration:k,method:z.executedRequest?.method,url:z.executedRequest?.url,requestBody:Qi(z.executedRequest?.body?.content)??z.executedRequest?.body?.content??null,requestHeaders:lt(z.executedRequest?.headers??{}),status:z.response?.status,duration:`${z.duration}ms`,body:Qi(z.response?.body),headers:dc(z.response?.headers),cookies:pc(z.response?.cookies),failedTests:z.assertions?.filter(pe=>!pe.passed).map(pe=>({name:pe.name,...pe.message?{message:pe.message}:{}})),...z.error?{error:z.error}:{},...p.includes("consoleOutput")&&z.consoleOutput?.length?{consoleOutput:z.consoleOutput}:{}}),a&&ye.abort()),c>0&&!ye.signal.aborted&&await new Promise(pe=>setTimeout(pe,c))}async function X(k,P,K){for(let U of P){if(ye.signal.aborted)break;await Je(k,U,K)}}async function Je(k,P,K){if(!P||typeof P!="object"||P.enabled===!1||!q(P.condition,P,k))return;if(O(P)){let ue=H(P);ue&&await Z(k,ue,K);return}let U=typeof P.type=="string"?P.type.toLowerCase():"",W=L(P,["then","nodes","body"]);if(U==="block"){let ue=typeof P.name=="string"?P.name.trim():"";await X(k,W,ue||K);return}if(U==="script"){let ue=b(P),he=P.phase==="post"?"post":"pre";await _(ue,P,k,he);return}if(U==="if"){let ue=typeof P.if=="string"?P.if:P.condition;if(q(ue,P,k)){await X(k,W,K);return}if(Array.isArray(P.elseif)){for(let he of P.elseif)if(q(he?.condition,he,k)){await X(k,L(he,["then","nodes","body"]),K);return}}await X(k,L(P,["else","elseNodes"]),K);return}if(U==="switch"){let ue=gt(String(P.expression??""),R(P,k));if(Array.isArray(P.cases)){for(let he of P.cases)if(Object.prototype.hasOwnProperty.call(he??{},"equals")?he.equals===ue:q(he?.condition,he,k)){await X(k,L(he,["then","nodes","body"]),K);return}}await X(k,L(P,["default","defaultNodes"]),K);return}if(U==="while"){let ue=typeof P.while=="string"?P.while:P.condition,he=Math.max(1,Math.min(1e4,Number(P.maxIterations??v))),$e=0;for(;q(ue,P,k);){if($e+=1,$e>he)throw new Error(`Suite while loop exceeded maxIterations (${he}) on node "${C(P)}"`);if(await X(k,W,K),ye.signal.aborted)break}return}if(U==="for"){let ue=Math.max(1,Math.min(1e4,Number(P.maxIterations??v))),he=x(P.init),$e=x(P.update),ee=typeof P.loopCondition=="string"&&P.loopCondition.trim()?P.loopCondition:typeof P.condition=="string"&&P.condition.trim()?P.condition:"true";he&&await _(he,P,k,"pre");let z=0;for(;q(ee,P,k);){if(z+=1,z>ue)throw new Error(`Suite for loop exceeded maxIterations (${ue}) on node "${C(P)}"`);if(await X(k,W,K),ye.signal.aborted)break;$e&&await _($e,P,k,"post")}return}W.length>0&&await X(k,W,K)}function ln(k){let P=0,K=[...k];for(;K.length>0;){let U=K.pop();if(!(!U||typeof U!="object"||U.enabled===!1)){if(O(U)){let W=H(U);W&&(!u||u.some(ue=>W.name.toLowerCase().includes(ue.toLowerCase())))&&(P+=1);continue}for(let W of["nodes","then","body","else","elseNodes","default","defaultNodes"])Array.isArray(U[W])&&K.push(...U[W]);if(Array.isArray(U.elseif))for(let W of U.elseif)Array.isArray(W?.nodes)&&K.push(...W.nodes),Array.isArray(W?.then)&&K.push(...W.then);if(Array.isArray(U.cases))for(let W of U.cases)Array.isArray(W?.nodes)&&K.push(...W.nodes),Array.isArray(W?.then)&&K.push(...W.then)}}return P}let kt=Array.isArray(e.nodes)?e.nodes:Array.isArray(e.requests)?e.requests.map(k=>({type:"request",request:k})):[],A=ln(kt);if(h){let k=km(),P=A*o;if(P>k)throw new Error(`Suite "${e.name}" would execute ${P} request calls (${A} requests \xD7 ${o} iterations), which exceeds HTTP_FORGE_MAX_REQUESTS (${k}). Reduce iterations, use requestFilter, or increase HTTP_FORGE_MAX_REQUESTS.`)}let ne=new Nn(s.config),Ee=await ne.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=[],Oe=[],Ge=0,ke=0,ot=new Set,ye=new AbortController,ft=new $n;async function un(k){await X(k,kt)}for(let k=1;k<=o&&!ye.signal.aborted;k+=l){let P=Math.min(k+l-1,o),K=Array.from({length:P-k+1},(U,W)=>k+W);await Promise.all(K.map(un))}let be=await ne.finalizeRun("completed",g),Us=null;if(m)try{Us=await new Lt(ne.getBasePath()).generate(e.id,Ee)}catch(k){console.warn("[direct-execution] JUnit report generation failed:",k)}let $r=n==="collection"?"collection":"suite",mt=ne.getCurrentStats()?.stats,eo=mt?{min:mt.minDuration,max:mt.maxDuration,avg:mt.avgDuration,p50:mt.p50??null,p95:mt.p95??null,p99:mt.p99??null}:null,It={[$r]:e.name,environment:i,summary:{total:Ge+ke,passed:Ge,failed:ke,...o>1?{iterations:o}:{},...l>1?{concurrency:l}:{},allPassed:ke===0,...eo?{durationMs:eo}:{}}};if((ke>0||p.includes("failedOnly"))&&(It.failedRequests=Oe),p.includes("perRequest")&&(It.results=B),be!==null&&(It.report={uri:`file://${be}`,hint:"Click the URI to open the HTML report in your browser"}),Us!==null&&(It.junitReport={path:Us}),ot.size>0){let k=Math.max(A,1),P=ot.size,K=Array.from(ot).slice(0,5);It.noAssertionExamples=K;let U=e.name;if(P/k>.5)It._suggestions=[`${P}/${k} 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 W=K.map(ue=>`"${ue}"`).join(", ");It._suggestions=[`${P} request(s) have no pm.test() assertions: ${W}. Invoke the "suggest-assertions" prompt (collection="${U}") to generate test coverage for them.`]}}return It}}});var Xi={};Tt(Xi,{runCollection:()=>cn,runFolder:()=>Cb,runRequest:()=>Cc,runSuite:()=>Yi});function Fm(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}=Sc(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 Nm(r,e){if(e.folderPath)return e.folderPath;if(e.folderRef){let{folderPath:t}=xc(r,e.folderRef);return e.onResolve?.({kind:"folder",value:e.folderRef,tier:"name",id:t,path:t}),t}}async function Cc(r){let e=it(r.workspaceFolder),t=r.include??[],n=r.reporters??[],s=n.includes("junit"),i=uc(t,n);try{let o=e.collection,a=Fm(o,r),c=Nm(a,r),l=r.requestId;if(!l){if(!r.requestRef)throw new Error("A request reference is required (requestId or requestRef)");let q=wc(a,r.requestRef,c);l=q.request.id,r.onResolve?.({kind:"request",value:r.requestRef,tier:q.tier,id:l,path:q.folderPath?`${q.folderPath}/${q.request.name}`:q.request.name})}let u=Ki(a,l);if(!u)throw new Error(`Request "${l}" not found in collection "${a.name}"`);let d=o.findRequest(a.id,l)??u.request,m=hc(d.auth,u.folderAuthChain,a.auth),f=r.environment||e.environmentConfig.getSelectedEnvironment(),h=mc(fc({...d,auth:m}),{headers:r.headers,query:r.query,body:r.body,variables:r.variables}),v=await new Mt(e.httpRequest,e.scriptExecutor,e.environmentConfig,e.requestPreparer,f,new $n,a.scripts,u.folderScriptsChain,void 0,a.name,a.auth).execute(h,Ds(r.variables)),y=Os({collectionName:a.name,folderPath:u.folderPath});v.folderPath=u.folderPath,v.collectionName=a.name,v.groupPath=y.groupPath,v.groupType=y.groupType;let x=null,b=null;if(i||s){let q=new Nn(e.config),N=`request-${Bu(a.id)}-${Bu(l)}`,M=`Request: ${u.request.name}`,_=await q.initializeRun(N,M,f,{iterations:1,delayBetweenRequests:0,stopOnError:!0},{targetType:"collection",targetName:a.name,collectionName:a.name,folderPath:u.folderPath||void 0});if(await q.saveResult(1,v),x=await q.finalizeRun("completed",i),s)try{b=await new Lt(q.getBasePath()).generate(N,_)}catch(H){console.warn("[direct-execution] JUnit report generation failed:",H)}}let C=dc(v.response?.headers),R=pc(v.response?.cookies);return{request:u.request.name,status:v.response?.status||0,ok:(v.response?.status??0)>=200&&(v.response?.status??0)<300,duration:`${v.duration}ms`,body:Qi(v.response?.body),allPassed:v.passed,assertions:v.assertions?.map(q=>({name:q.name,passed:q.passed,message:q.message})),...t.includes("headers")?{headers:C}:{},...t.includes("cookies")?{cookies:R}:{},...t.includes("tests")?{tests:v.assertions?.map(q=>({name:q.name,passed:q.passed,...q.message?{message:q.message}:{}}))}:{},...Object.keys(v.modifiedVariables??{}).length?{modifiedVariables:v.modifiedVariables}:{},...t.includes("consoleOutput")&&v.consoleOutput?.length?{consoleOutput:v.consoleOutput}:{},...x!==null?{report:{uri:`file://${x}`,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{lc(e)}}async function cn(r){let e=it(r.workspaceFolder);try{let t=e.collection,n=Fm(t,r),s=Nm(n,r),i=Lu(n),o=Em(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}-${qm(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 Zi(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{lc(e)}}async function Cb(r){return cn({recursive:!0,...r})}async function Yi(r){let e=it(r.workspaceFolder);try{let n=await e.testSuite.getSuite(r.suiteId);if(!n)throw new Error(`Test suite "${r.suiteId}" not found`);return new Zi(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{lc(e)}}var Hs=E(()=>{"use strict";sc();ui();Gi();cc();Hu();Uu();bc();zu();rc();$m()});var Lm={};Tt(Lm,{createMcpRuntime:()=>Db});async function At(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 Bs(r){let e=[r.testSuite,r.collection,r.environmentConfig,r.config,r.console];for(let t of e)try{t?.dispose?.()}catch{}}async function Ab(r,e){let t=Ku.get(r);if(t&&t.expiresAt>Date.now())return t.tools;let n=Gu.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 nc(a,c,i,r)})().then(i=>(Ku.set(r,{tools:i,expiresAt:Date.now()+qb}),i)).finally(()=>Gu.delete(r));return Gu.set(r,s),s}function Pb(r,e){let t=r.config.getMcpConfig().toolPrefix??"";return t&&e.startsWith(t)?e.slice(t.length):e}function kb(r,e,t){return r.replace(/"uri"\s*:\s*"file:\/\/([^"]+)"/g,(n,s)=>`"uri":"http://${e}:${t}/report?path=${encodeURIComponent(s)}"`)}function Mm(r,e,t,n){Tr(r,200,{jsonrpc:"2.0",id:e,error:{code:t,message:n}})}function Ib(r){return r.config.getMcpConfig().toolPageSize??200}async function Tb(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 Ab(r.workspaceFolder,r.container),n=e.params??{},s=typeof n.cursor=="string"?n.cursor:void 0,i=Ib(r.container);if(i<=0||t.length<=i)return{tools:t};let o=tc(s),a=t.slice(o,o+i),c=o+i,l={tools:a};return c<t.length&&(l.nextCursor=ec(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 Qu(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=kb(c,r.host,r.port),u=l.match(/"uri"\s*:\s*"(http:\/\/[^"]+\/report\?[^"]+)"/),p=u?`
1465
1465
 
1466
- [View HTML Report](${u[1]})`:"";return{content:[{type:"text",text:l+d}]}}case"prompts/list":return{prompts:Vi};case"prompts/get":{let t=e.params??{},n=t.name,s=t.arguments??{};if(!n)throw new Error("Missing prompt name");let i=ot(r.workspaceFolder);try{return await Na(n,s,i.collection,r.runStore,r.workspaceFolder)}finally{Ls(i)}}default:throw new Error(`Method not found: ${e.method}`)}}function Pb(r,e,t){let n=!r.container,s=r.container??ot(r.workspaceFolder),i;try{i=s.config.getMcpConfig().cors.allowedOrigins??["http://localhost","http://127.0.0.1"]}finally{n&&Ls(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 kb(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=Nn.resolve(s),o=r.container?.config.getResultsPath(),a=o?Nn.dirname(o):Nn.resolve(r.workspaceFolder,".http-forge",".cache");if(!i.startsWith(a+Nn.sep)||!i.endsWith(".html")){t.statusCode=403,t.end("Forbidden");return}Fm.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 Vu(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 Ib(r){let e=r.workspaceFolder;return{async runRequest(t,n,s){return Pt(()=>xc({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=Q(t).filter(({folderPath:o})=>o===n||o.startsWith(`${n}/`)).length;return s.async===!0?Vu(r.runStore,`${t.name} / ${St(n)}`,i,()=>Pt(()=>cn({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}))):Pt(()=>cn({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=Q(t).length;return n.async===!0?Vu(r.runStore,t.name,s,()=>Pt(()=>cn({workspaceFolder:e,collectionId:t.id,environment:n.environment,variables:n.variables,iterations:n.iterations,stopOnError:n.stopOnError,delay:n.delay,include:n.include}))):Pt(()=>cn({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=ot(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{Ls(i)}return s.async===!0?Vu(r.runStore,n,o,()=>Pt(()=>Qi({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}))):Pt(()=>Qi({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 Ju(r,e,t={}){let n=r.workspaceFolder,s=Cb(r.container,e);if(Object.values(S).includes(s)){let a=ot(n),c=hs();try{let l=await Da(s,t,{collection:a.collection,testSuite:a.testSuite,environmentConfig:a.environmentConfig,workspaceFolder:n,...c?{aiProvider:c}:{}},r.runStore,Ib(r));return Tb.has(s)&&zu.delete(n),l}finally{Ls(a)}}let i=Va(s),o=ot(n);try{let a=o.collection.getAllCollections(),c=a.map(m=>m.id),l=m=>{let f=Sr(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=Q(h).map(y=>y.request.id),v=Sr(f,g);if(!v)throw new Error(`Request not found in collection "${h.name}" for tool: ${e}`);return Pt(()=>xc({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 Pt(()=>cn({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(x=>x.id===h.id),void 0),v=Q(h).map(x=>x.folderPath).filter((x,b,R)=>x&&R.indexOf(x)===b),y=za(f,v);if(!y)throw new Error(`Folder not found in collection "${h.name}" for tool: ${e}`);return Pt(()=>cn({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=Sr(u,d.map(m=>m.id));if(!p)throw new Error(`Test suite not found for tool: ${e}`);return Pt(()=>Qi({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{Ls(o)}}function Pr(r,e,t){r.statusCode=e,r.setHeader("content-type","application/json; charset=utf-8"),r.end(JSON.stringify(t))}function $m(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 Ob(r){return(0,Nm.createServer)(async(e,t)=>{try{if(Pb(r,e,t),e.method==="OPTIONS"){t.statusCode=204,t.end();return}if(e.method==="GET"&&e.url==="/health"){Pr(t,200,{status:"ok",port:r.port});return}if(e.method==="GET"&&e.url?.startsWith("/report?")){kb(r,e,t);return}if(e.method==="POST"&&(e.url==="/"||e.url==="/mcp")){let n;try{n=await $m(e)}catch{Om(t,null,-32700,"Parse error");return}try{let s=await qb(r,n);Pr(t,200,{jsonrpc:"2.0",id:n.id??null,result:s})}catch(s){Om(t,n.id??null,-32603,s.message||"Internal error")}return}if(e.method==="POST"&&e.url==="/tools/execute"){let n=await $m(e);if(!n||typeof n.name!="string"||n.name.trim()===""){Pr(t,400,{error:'Field "name" is required'});return}let s=await Ju(r,n.name,n.args??{});Pr(t,200,{result:s});return}Pr(t,405,{error:"Method not allowed"})}catch(n){Pr(t,500,{error:n.message})}})}function $b(r){if(typeof r.port=="number"&&Number.isFinite(r.port))return Math.min(65535,Math.max(1,Math.floor(r.port)));let t=new Gt(Nn.resolve(r.workspaceFolder)).getMcpConfig().port;return Math.min(65535,Math.max(1,Math.floor(t||3100)))}async function Fb(r){let e=$b(r),t=r.host||"127.0.0.1",n=`${t}:${e}`,s={workspaceFolder:r.workspaceFolder,port:e,host:t,isRunning:!1,runStore:new Ps};return xb.set(n,s),{async start(){if(s.isRunning)return;s.container||(s.container=ot(s.workspaceFolder));let i=Ob(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&&(Ls(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 Ju(s,i,o??{})}}}var Fm,Nm,Nn,xb,wb,zu,Uu,Tb,_m=E(()=>{"use strict";Fm=I(require("fs")),Nm=require("http"),Nn=I(require("path"));Po();oa();js();Xe();Pu();Ma();ku();Tu();Qa();Ne();gc();xb=new Map;wb=3e3,zu=new Map,Uu=new Map;Tb=_a});var lS={};Ot(lS,{AGENTS_MD_BACKUP_FILENAME:()=>Ic,AGENTS_MD_FILENAME:()=>kc,AGENTS_MD_VERSION:()=>Bt,AnthropicProvider:()=>ms,ApiArchitectService:()=>fs,ApiDiscoveryService:()=>br,AwsSecretResolver:()=>fi,AzureKeyVaultResolver:()=>mi,BODY_FILE_MAP:()=>Oc,CACHE_BUSTING_TOOLS:()=>_a,COLLECTION_INPUT_SCHEMA:()=>Ai,CONFIG_FILES:()=>Sn,CollectionLoader:()=>Dn,CollectionLoaderFactory:()=>Yr,CollectionRequestExecutor:()=>_t,CollectionService:()=>Xr,ConfigService:()=>Gt,CookieJar:()=>Fr,CookieService:()=>es,CookieUtils:()=>ie,DEFAULT_CONFIG:()=>re,DEFAULT_REQUEST_SETTINGS:()=>So,DataFileParser:()=>bn,DopplerResolver:()=>vi,EnvironmentConfigService:()=>ns,EnvironmentResolver:()=>$t,ExampleGenerator:()=>Yn,ExpressComponentAnalyzer:()=>Ss,ExpressDiscoveryProvider:()=>dr,FOLDER_INPUT_SCHEMA:()=>qi,FastApiDiscoveryProvider:()=>yr,FastifyComponentAnalyzer:()=>xs,FastifyDiscoveryProvider:()=>pr,FetchHttpClient:()=>Vr,FolderCollectionLoader:()=>Or,FolderCollectionStore:()=>Vt,ForgeContainer:()=>Ao,ForgeEnv:()=>zt,FrameworkDetector:()=>cr,GENERIC_TOOL_NAMES:()=>S,GcpSecretResolver:()=>yi,GraphQLSchemaService:()=>ss,HTTP_METHOD_MAP:()=>nc,HTTP_METHOD_REVERSE:()=>st,HashiCorpVaultResolver:()=>hi,HistoryAnalyzer:()=>Zn,HtmlReportGenerator:()=>xr,HttpForgeParser:()=>vn,HttpRequestService:()=>Ft,InMemoryCookieJar:()=>On,InterceptorChain:()=>Nt,JUnitReportGenerator:()=>Ht,JsonCollectionLoader:()=>Kn,LambdaComponentAnalyzer:()=>ws,LambdaDiscoveryProvider:()=>mr,MCP_PROMPTS:()=>Vi,METADATA_FILES:()=>Oe,McpRunStore:()=>Ps,ModuleLoader:()=>Ys,NestDiscoveryProvider:()=>fr,NodeFileSystem:()=>Jr,NodeHttpClient:()=>gn,OAuth2TokenManager:()=>Kr,OnePasswordResolver:()=>gi,OpenAiProvider:()=>Ci,OpenApiExporter:()=>Qt,OpenApiImporter:()=>Dt,ParserRegistry:()=>$r,PersistentCookieJar:()=>ts,REQUEST_INPUT_SCHEMA:()=>Ei,ROOT_DIRECTORIES:()=>Jt,RefResolver:()=>Xn,RequestExecutor:()=>Jn,RequestHistoryService:()=>os,RequestHistoryStore:()=>Ur,RequestPreparer:()=>rs,RequestPreprocessor:()=>yn,RequestScriptSession:()=>Br,ResultStorageService:()=>Fn,SCHEMA_FILES:()=>Tr,SCRIPTS_DIR:()=>Be,SCRIPT_FILES:()=>Us,SUITE_INPUT_SCHEMA:()=>Pi,SchemaInferenceService:()=>Zt,SchemaInferrer:()=>Kt,ScriptAnalyzer:()=>er,ScriptExecutor:()=>Mt,SecretResolverRegistry:()=>as,ServiceContainer:()=>Rn,ServiceIdentifiers:()=>$,SpringDiscoveryProvider:()=>gr,StatisticsService:()=>Cc,TestSuiteService:()=>cs,TestSuiteStore:()=>Ec,UrlBuilder:()=>lt,VariableInterpolator:()=>hn,VariableResolver:()=>mn,analyzeComponentChainMetadata:()=>vs,analyzeHandlerMetadata:()=>Ti,applyEnvSuggestionsToItems:()=>Xo,applyExtractionPlan:()=>Id,applyFilterChain:()=>jr,applyMcpBodyTruncation:()=>Lt,applyRegenerated:()=>Li,assembleBusinessContext:()=>ds,buildAgentsMdContent:()=>ro,buildArchitectPrompt:()=>ta,buildCollectionBusinessContext:()=>_l,buildCollectionToolDescription:()=>Ga,buildCollectionToolName:()=>Ha,buildDescription:()=>kn,buildExtractionPlan:()=>kd,buildFolderToolDescription:()=>Wa,buildFolderToolName:()=>Ba,buildGenericTools:()=>ki,buildMcpToolList:()=>Xa,buildPromptResult:()=>Na,buildRequestBusinessContext:()=>Wo,buildRequestToolDescription:()=>Ja,buildRequestToolName:()=>La,buildResultFileName:()=>$n,buildRunResultsContext:()=>Dl,buildSuiteToolDescription:()=>Ka,buildSuiteToolName:()=>Ua,cleanupOldBodyFiles:()=>Nc,clearRegisteredKnowledgeSources:()=>up,collectSourceFiles:()=>rt,collectionKnowledgeSource:()=>jt,collectionToEndpoints:()=>ea,combineConfidence:()=>en,computeProjectFreshness:()=>As,concatenateScripts:()=>ni,countRequests:()=>zo,createDefaultKnowledgeSources:()=>jl,createEnvAiProvider:()=>hs,createExpectChain:()=>Vn,createMcpRuntime:()=>Dm,createModuleLoader:()=>fo,createMomentShim:()=>Xs,createNodeContainer:()=>ot,createResponseObject:()=>ei,createTestFunction:()=>ho,decodeCursor:()=>Ya,decodeFolderPath:()=>St,dedupeDiscoveredApiParameters:()=>nn,deleteItemFromTree:()=>Ut,deserializeTypedRecord:()=>Sc,deserializeTypedValue:()=>qr,detectEnvSuggestions:()=>Ri,detectIndexDrift:()=>Su,detectProjectDrift:()=>qs,diffLines:()=>Es,discoverWorkflows:()=>Cn,dispatchGenericTool:()=>Da,encodeCursor:()=>Za,encodeFolderName:()=>Ee,endpointToCreateRequestOptions:()=>vu,endpointToName:()=>qn,endpointToRequestParts:()=>Pn,enhanceCollection:()=>Vm,ensureAgentsMdFile:()=>no,enumerateFolders:()=>Re,evaluateExpression:()=>yt,exportCollectionToRestClient:()=>Rd,extractJsonFromLlm:()=>wt,extractPathParameters:()=>tn,findItemById:()=>xe,flattenRequests:()=>Q,formatConsoleOutput:()=>zn,gatherWorkspaceKnowledge:()=>us,generateFlowFromEndpoints:()=>ar,generateId:()=>oe,generateReleaseNotes:()=>Qu,generateSlug:()=>ct,generateSuiteFromEndpoints:()=>or,getAgentsMdPath:()=>Bs,getAgentsMdStatus:()=>nd,getCompletions:()=>Qm,getRegisteredKnowledgeSources:()=>dp,getServiceContainer:()=>Nl,harToCollection:()=>Xu,hasChanged:()=>Hr,isExpression:()=>fn,isSystemEnvironmentFile:()=>Js,loadEnvironmentsFromFolder:()=>Nr,loadHybridSeedEndpoints:()=>Ii,normalizeFolderInput:()=>tr,normalizeHeaders:()=>go,parseCurlCommand:()=>Um,parseFilterChain:()=>Dr,parseHar:()=>Ac,parseMcpToolName:()=>Va,parsePostmanEnvironment:()=>ko,parseQueryContext:()=>Km,prepareBodyForSave:()=>Fc,proposeSuiteUpdates:()=>ji,readAgentsMdVersion:()=>to,readBodyFromDir:()=>$c,readSchemaFile:()=>Mc,readScriptsFromDir:()=>Vs,redactFullResponse:()=>Oo,redactFullResultDetails:()=>$o,redactHeaders:()=>ut,redactHistoryEntry:()=>To,refreshAgentsMd:()=>rd,registerCoreServices:()=>bi,registerKnowledgeSource:()=>lp,renderArchitectDocs:()=>Vl,renderReleaseNotesMarkdown:()=>Zu,requestKnowledgeSource:()=>et,resolveCollectionRef:()=>yc,resolveFolderRef:()=>vc,resolveFolderToken:()=>za,resolveProjectName:()=>Ql,resolveRegenerated:()=>Oa,resolveRequestRef:()=>bc,resolveResultGrouping:()=>Is,resolveToken:()=>Sr,reviewSuiteRun:()=>Hi,runCollection:()=>Lm,runFolder:()=>Hm,runRequest:()=>jm,runResultsKnowledgeSource:()=>Si,runSuite:()=>Bm,scanCollectionForEnvVarsWithAi:()=>Jm,schemaToExample:()=>vr,searchForItemPath:()=>so,searchForItemPathById:()=>io,serializeTypedValue:()=>Ds,sortItemsByOrder:()=>Dc,suiteIdFromName:()=>ps,threeWayDiff:()=>Ta,toReviewRequestResults:()=>Bi,validateDesignedSpec:()=>Ul,withAiRetry:()=>nt,workspaceKnowledgeSource:()=>tt,writeEnvFile:()=>Wn,writeFolderItems:()=>oi,writeSchemaFiles:()=>_c,writeScriptFile:()=>Zr,writeScriptsToDir:()=>zs});module.exports=_n(lS);var Dn=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()}};oo();dn();function Lc(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(sd),source:{format:"folder",filePath:e,version:r.version}}}function sd(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(sd)};let e=r;return{type:"request",id:e.id,name:e.name,description:e.description,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,...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 dh(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(Hc)}}function Hc(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(Hc)}:{type:"request",id:r.id,name:r.name,description:r.description,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,...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 Or=class{store;constructor(e){this.store=new Vt(e)}loadAll(){return this.store.loadAll().map(t=>Lc(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 Lc(t,this.store.getCollectionPath(t.id))}async create(e,t){let n=await this.store.create(e,t);return Lc(n,this.store.getCollectionPath(n.id))}async save(e){return this.store.save(dh(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,Hc(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 $r=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()}};jn();var Fr=class{cookies=new Map;getCookieKey(e,t,n){return ie.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 ie.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 ie.parseCookieHeaders(e,t)}isExpired(e){return ie.isExpired(e)}domainMatches(e,t){return ie.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)}};co();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})}};Mr();Lr();var zt=class r{envStore;interpolator;urlBuilder;constructor(e,t){this.envStore=e,this.interpolator=t||new hn,this.urlBuilder=new lt}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)}};Lr();Qs();Zs();Mr();si();ri();var Jn=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?[require("path").join(i.forgeRoot,"modules")]:[],a=new Ft(new lt,new Nt,e);this.scriptExecutor=new Mt(a,o,void 0,i?.scriptScope??"shared",i?.scriptTimeout??5e3)}}httpClient;forgeEnv;cookieJar;preprocessor;scriptExecutor;async execute(e,t,n={}){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,x)=>{v==="set"&&y&&x!==void 0?this.forgeEnv.setGlobal(y,x):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 R=b.modifiedRequest;R.url&&(l.url=R.url),R.method&&(l.method=R.method),R.headers&&(l.headers={...l.headers,...R.headers}),R.body!==void 0&&(l.body=R.body?.content||R.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 x=await this.httpClient.send(l);if(!n.skipPostResponse&&p.postResponse.length>0){let b=await f.executePostResponse(p.postResponse,{status:x.status,statusText:x.statusText,headers:x.headers,body:x.body,cookies:yo(x.headers,x.cookies,l.url),responseTime:x.time,responseSize:x.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:x,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=zt.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 Jh(){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 Ur=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=Jh(),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 Vr=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)}}};Qs();Zs();Ro();Co();Mr();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}}};Eo();var Ze=I(require("fs/promises")),Gr=I(require("path")),Jr=class{async readFile(e){return Ze.readFile(e,"utf-8")}async writeFile(e,t){let n=Gr.dirname(e);await this.mkdir(n),await Ze.writeFile(e,t,"utf-8")}async exists(e){try{return await Ze.access(e),!0}catch{return!1}}async mkdir(e){await Ze.mkdir(e,{recursive:!0})}async glob(e,t){let n=t||process.cwd(),s=[];try{await this.walkDirectory(n,i=>{let o=Gr.basename(i);for(let a of e)if(this.matchPattern(o,a)){s.push(i);break}})}catch{}return s}async readDir(e){return Ze.readdir(e)}async isDirectory(e){try{return(await Ze.stat(e)).isDirectory()}catch{return!1}}async walkDirectory(e,t){let n=await Ze.readdir(e,{withFileTypes:!0});for(let s of n){let i=Gr.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)}};si();var Ao=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 hn,this.fileSystem=e.fileSystem||new Jr,this.preprocessor=e.preprocessor||new yn,this.dataFileParser=e.dataFileParser||new bn,this.cookieJar=e.cookieJar||new Fr,e.enableHistory?this.requestHistory=e.requestHistory||new Ur({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 gn(i)}else this.httpClient=new Vr;let t=e.forgeRoot?[require("path").join(e.forgeRoot,"modules")]:[],n=new Ft(new lt,this.interceptorChain,this.httpClient);if(this.scriptExecutor=e.scriptExecutor||new Mt(n,t,void 0,e.scriptScope??"shared",e.scriptTimeout??5e3),this.parserRegistry=new $r,this.parserRegistry.register("http-forge",new vn),(e.storageFormat??"folder")==="folder"&&e.forgeRoot){let i=require("path").join(e.forgeRoot,"collections");this.collectionLoader=new Or(i)}else this.collectionLoader=new Dn(this.fileSystem,this.parserRegistry);this.environmentStore=e.environmentConfig?new $t(e.environmentConfig):$t.fromVariables({}),this.forgeEnv=zt.fromResolver(this.environmentStore),this.requestExecutor=new Jn(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 Dn)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=zt.fromResolver(this.environmentStore),this.requestExecutor=new Jn(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=require("path"),s=n.join(e,"environments"),i,o=Nr(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=require("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})}};Fl();Ml();Jo();Xe();Pu();Ma();ku();Tu();Qa();Ne();ec();async function Dm(r){let{createMcpRuntime:e}=await Promise.resolve().then(()=>(_m(),Mm));return e(r)}async function jm(r){let{runRequest:e}=await Promise.resolve().then(()=>(js(),Zi));return e(r)}async function Lm(r){let{runCollection:e}=await Promise.resolve().then(()=>(js(),Zi));return e(r)}async function Hm(r){let{runFolder:e}=await Promise.resolve().then(()=>(js(),Zi));return e(r)}async function Bm(r){let{runSuite:e}=await Promise.resolve().then(()=>(js(),Zi));return e(r)}gc();al();jn();tc();cl();Qs();Zs();Ro();Co();Mr();zc();Wc();si();ti();ri();is();rl();il();oo();Tc();dn();nl();Yo();function Nb(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 Mb(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 _b(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 Db(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&&Rt(c[2])?i(`${c[1].toUpperCase()}_TOKEN`,c[2]):Rt(o.value)&&i("AUTH_TOKEN",o.value)}else Qo.has(a)&&Rt(o.value)&&i(Xt(o.key),o.value)}for(let o of e)Zo.has(o.key.toLowerCase())&&Rt(o.value)&&i(Xt(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)&&!xi(t)){let c=`${o.protocol}//${o.host}`;i("BASE_URL",c)}}catch{}return n}function Um(r){let e=Nb(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 x=n[++p]??"",b=x.indexOf(":");b>0&&o.push({key:x.slice(0,b).trim(),value:x.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 x=n[++p]??"",b=btoa(x);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 x=n[++p]??"",b=x.indexOf("=");b>0&&u.push({key:x.slice(0,b),value:x.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}=Mb(i),h=null;if(u.length>0)h={type:"raw",format:"text",content:u.map(x=>`${encodeURIComponent(x.key)}=${encodeURIComponent(x.value)}`).join("&")},o.some(x=>x.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(),x=c||y.startsWith("{")||y.startsWith("[");h={type:"raw",format:x?"json":"text",content:a},x&&!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=Db(o,f,m||i);return{name:_b(m||i),method:s.toUpperCase(),url:m||i,headers:g,queryParams:f,body:h,suggestedVars:v}}sr();ir();oa();ir();sr();var wc=10;async function Vm(r,e,t,n){let s=zm(r.items);if(s.length===0)return;let i=Math.ceil(s.length/wc);for(let o=0;o<s.length;o+=wc){let a=s.slice(o,o+wc),c=Math.floor(o/wc)+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:Bb(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 nt(()=>t.complete(jb(l,a))),d=Lb(u);Hb(a,d)}catch{}}await e.saveCollection(r)}function jb(r,e){return`You are an API testing expert. For each HTTP request below, return two improvements:
1466
+ [View HTML Report](${u[1]})`:"";return{content:[{type:"text",text:l+p}]}}case"prompts/list":return{prompts:Ji};case"prompts/get":{let t=e.params??{},n=t.name,s=t.arguments??{};if(!n)throw new Error("Missing prompt name");let i=it(r.workspaceFolder);try{return await Da(n,s,i.collection,r.runStore,r.workspaceFolder)}finally{Bs(i)}}default:throw new Error(`Method not found: ${e.method}`)}}function Ob(r,e,t){let n=!r.container,s=r.container??it(r.workspaceFolder),i;try{i=s.config.getMcpConfig().cors.allowedOrigins??["http://localhost","http://127.0.0.1"]}finally{n&&Bs(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 $b(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=Mn.resolve(s),o=r.container?.config.getResultsPath(),a=o?Mn.dirname(o):Mn.resolve(r.workspaceFolder,".http-forge",".cache");if(!i.startsWith(a+Mn.sep)||!i.endsWith(".html")){t.statusCode=403,t.end("Forbidden");return}Dm.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 Wu(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 Fb(r){let e=r.workspaceFolder;return{async runRequest(t,n,s){return At(()=>Cc({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=Q(t).filter(({folderPath:o})=>o===n||o.startsWith(`${n}/`)).length;return s.async===!0?Wu(r.runStore,`${t.name} / ${bt(n)}`,i,()=>At(()=>cn({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}))):At(()=>cn({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=Q(t).length;return n.async===!0?Wu(r.runStore,t.name,s,()=>At(()=>cn({workspaceFolder:e,collectionId:t.id,environment:n.environment,variables:n.variables,iterations:n.iterations,stopOnError:n.stopOnError,delay:n.delay,include:n.include}))):At(()=>cn({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=it(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{Bs(i)}return s.async===!0?Wu(r.runStore,n,o,()=>At(()=>Yi({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}))):At(()=>Yi({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 Qu(r,e,t={}){let n=r.workspaceFolder,s=Pb(r.container,e);if(Object.values(S).includes(s)){let a=it(n),c=ys();try{let l=await Ha(s,t,{collection:a.collection,testSuite:a.testSuite,environmentConfig:a.environmentConfig,workspaceFolder:n,...c?{aiProvider:c}:{}},r.runStore,Fb(r));return Nb.has(s)&&Ku.delete(n),l}finally{Bs(a)}}let i=Ga(s),o=it(n);try{let a=o.collection.getAllCollections(),c=a.map(m=>m.id),l=m=>{let f=Rr(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=Q(h).map(y=>y.request.id),v=Rr(f,g);if(!v)throw new Error(`Request not found in collection "${h.name}" for tool: ${e}`);return At(()=>Cc({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 At(()=>cn({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(x=>x.id===h.id),void 0),v=Q(h).map(x=>x.folderPath).filter((x,b,C)=>x&&C.indexOf(x)===b),y=Wa(f,v);if(!y)throw new Error(`Folder not found in collection "${h.name}" for tool: ${e}`);return At(()=>cn({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 p=await o.testSuite.getAllSuites(),d=Rr(u,p.map(m=>m.id));if(!d)throw new Error(`Test suite not found for tool: ${e}`);return At(()=>Yi({workspaceFolder:n,suiteId:d,environment:t.environment,variables:t.variables,iterations:t.iterations,stopOnError:t.stopOnError,delay:t.delay,requestFilter:t.requestFilter,include:t.include}))}finally{Bs(o)}}function Tr(r,e,t){r.statusCode=e,r.setHeader("content-type","application/json; charset=utf-8"),r.end(JSON.stringify(t))}function _m(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 Mb(r){return(0,jm.createServer)(async(e,t)=>{try{if(Ob(r,e,t),e.method==="OPTIONS"){t.statusCode=204,t.end();return}if(e.method==="GET"&&e.url==="/health"){Tr(t,200,{status:"ok",port:r.port});return}if(e.method==="GET"&&e.url?.startsWith("/report?")){$b(r,e,t);return}if(e.method==="POST"&&(e.url==="/"||e.url==="/mcp")){let n;try{n=await _m(e)}catch{Mm(t,null,-32700,"Parse error");return}try{let s=await Tb(r,n);Tr(t,200,{jsonrpc:"2.0",id:n.id??null,result:s})}catch(s){Mm(t,n.id??null,-32603,s.message||"Internal error")}return}if(e.method==="POST"&&e.url==="/tools/execute"){let n=await _m(e);if(!n||typeof n.name!="string"||n.name.trim()===""){Tr(t,400,{error:'Field "name" is required'});return}let s=await Qu(r,n.name,n.args??{});Tr(t,200,{result:s});return}Tr(t,405,{error:"Method not allowed"})}catch(n){Tr(t,500,{error:n.message})}})}function _b(r){if(typeof r.port=="number"&&Number.isFinite(r.port))return Math.min(65535,Math.max(1,Math.floor(r.port)));let t=new Jt(Mn.resolve(r.workspaceFolder)).getMcpConfig().port;return Math.min(65535,Math.max(1,Math.floor(t||3100)))}async function Db(r){let e=_b(r),t=r.host||"127.0.0.1",n=`${t}:${e}`,s={workspaceFolder:r.workspaceFolder,port:e,host:t,isRunning:!1,runStore:new Is};return Eb.set(n,s),{async start(){if(s.isRunning)return;s.container||(s.container=it(s.workspaceFolder));let i=Mb(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&&(Bs(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 Qu(s,i,o??{})}}}var Dm,jm,Mn,Eb,qb,Ku,Gu,Nb,Hm=E(()=>{"use strict";Dm=I(require("fs")),jm=require("http"),Mn=I(require("path"));To();la();Hs();Ye();Ou();ja();$u();Nu();Xa();Me();bc();Eb=new Map;qb=3e3,Ku=new Map,Gu=new Map;Nb=La});var fS={};Tt(fS,{AGENTS_MD_BACKUP_FILENAME:()=>Fc,AGENTS_MD_FILENAME:()=>$c,AGENTS_MD_VERSION:()=>Ht,AnthropicProvider:()=>gs,ApiArchitectService:()=>hs,ApiDiscoveryService:()=>wr,AwsSecretResolver:()=>hi,AzureKeyVaultResolver:()=>gi,BODY_FILE_MAP:()=>Mc,CACHE_BUSTING_TOOLS:()=>La,COLLECTION_INPUT_SCHEMA:()=>Pi,CONFIG_FILES:()=>xn,CollectionLoader:()=>Ln,CollectionLoaderFactory:()=>es,CollectionRequestExecutor:()=>Mt,CollectionService:()=>ts,ConfigService:()=>Jt,CookieJar:()=>Mr,CookieService:()=>ns,CookieUtils:()=>oe,DEFAULT_CONFIG:()=>se,DEFAULT_REQUEST_SETTINGS:()=>Ro,DataFileParser:()=>Sn,DopplerResolver:()=>Si,EnvironmentConfigService:()=>ss,EnvironmentResolver:()=>Ot,ExampleGenerator:()=>tr,ExpressComponentAnalyzer:()=>ws,ExpressDiscoveryProvider:()=>mr,FOLDER_INPUT_SCHEMA:()=>ki,FastApiDiscoveryProvider:()=>Sr,FastifyComponentAnalyzer:()=>Rs,FastifyDiscoveryProvider:()=>hr,FetchHttpClient:()=>Jr,FolderCollectionLoader:()=>Fr,FolderCollectionStore:()=>Ut,ForgeContainer:()=>ko,ForgeEnv:()=>Vt,FrameworkDetector:()=>dr,GENERIC_TOOL_NAMES:()=>S,GcpSecretResolver:()=>bi,GraphQLSchemaService:()=>os,HTTP_METHOD_MAP:()=>ic,HTTP_METHOD_REVERSE:()=>rt,HashiCorpVaultResolver:()=>yi,HistoryAnalyzer:()=>er,HtmlReportGenerator:()=>Cr,HttpForgeParser:()=>bn,HttpRequestService:()=>$t,InMemoryCookieJar:()=>$n,InterceptorChain:()=>Ft,JUnitReportGenerator:()=>Lt,JsonCollectionLoader:()=>Yn,LambdaComponentAnalyzer:()=>Cs,LambdaDiscoveryProvider:()=>yr,MCP_PROMPTS:()=>Ji,METADATA_FILES:()=>Ie,McpRunStore:()=>Is,ModuleLoader:()=>ei,NestDiscoveryProvider:()=>gr,NodeFileSystem:()=>Wr,NodeHttpClient:()=>yn,OAuth2TokenManager:()=>Zr,OnePasswordResolver:()=>vi,OpenAiProvider:()=>qi,OpenApiExporter:()=>Kt,OpenApiImporter:()=>_t,ParserRegistry:()=>Nr,PersistentCookieJar:()=>rs,REQUEST_INPUT_SCHEMA:()=>Ai,ROOT_DIRECTORIES:()=>zt,RefResolver:()=>nr,RequestExecutor:()=>Kn,RequestHistoryService:()=>cs,RequestHistoryStore:()=>zr,RequestPreparer:()=>is,RequestPreprocessor:()=>vn,RequestScriptSession:()=>Vr,ResultStorageService:()=>Nn,SCHEMA_FILES:()=>dn,SCRIPTS_DIR:()=>Le,SCRIPT_FILES:()=>zs,SUITE_INPUT_SCHEMA:()=>Ii,SchemaInferenceService:()=>Qt,SchemaInferrer:()=>Wt,ScriptAnalyzer:()=>rr,ScriptExecutor:()=>Nt,SecretResolverRegistry:()=>ls,ServiceContainer:()=>Cn,ServiceIdentifiers:()=>$,SpringDiscoveryProvider:()=>br,StatisticsService:()=>Ac,TestSuiteService:()=>us,TestSuiteStore:()=>Pc,UrlBuilder:()=>ct,VariableInterpolator:()=>gn,VariableResolver:()=>hn,analyzeComponentChainMetadata:()=>Ss,analyzeHandlerMetadata:()=>$i,applyEnvSuggestionsToItems:()=>na,applyExtractionPlan:()=>Fd,applyFilterChain:()=>Hr,applyMcpBodyTruncation:()=>jt,applyRegenerated:()=>Bi,assembleBusinessContext:()=>fs,buildAgentsMdContent:()=>oo,buildArchitectPrompt:()=>sa,buildCollectionBusinessContext:()=>Hl,buildCollectionToolDescription:()=>Qa,buildCollectionToolName:()=>Va,buildDescription:()=>In,buildExtractionPlan:()=>$d,buildFolderToolDescription:()=>Za,buildFolderToolName:()=>za,buildGenericTools:()=>Ti,buildMcpToolList:()=>nc,buildPromptResult:()=>Da,buildRequestBusinessContext:()=>Zo,buildRequestToolDescription:()=>Ka,buildRequestToolName:()=>Ua,buildResultFileName:()=>Fn,buildRunResultsContext:()=>Bl,buildSuiteToolDescription:()=>Ya,buildSuiteToolName:()=>Ja,cleanupOldBodyFiles:()=>jc,clearRegisteredKnowledgeSources:()=>mp,collectSourceFiles:()=>nt,collectionKnowledgeSource:()=>Dt,collectionToEndpoints:()=>ra,combineConfidence:()=>en,computeProjectFreshness:()=>Ps,concatenateScripts:()=>si,countRequests:()=>Wo,createDefaultKnowledgeSources:()=>Ul,createEnvAiProvider:()=>ys,createExpectChain:()=>Gn,createMcpRuntime:()=>Bm,createModuleLoader:()=>go,createMomentShim:()=>ti,createNodeContainer:()=>it,createResponseObject:()=>ni,createTestFunction:()=>vo,decodeCursor:()=>tc,decodeFolderPath:()=>bt,dedupeDiscoveredApiParameters:()=>nn,deleteItemFromTree:()=>Bt,deserializeTypedRecord:()=>Rc,deserializeTypedValue:()=>Ir,detectEnvSuggestions:()=>Ei,detectIndexDrift:()=>Cu,detectProjectDrift:()=>ks,diffLines:()=>As,discoverWorkflows:()=>En,dispatchGenericTool:()=>Ha,encodeCursor:()=>ec,encodeFolderName:()=>qe,endpointToCreateRequestOptions:()=>wu,endpointToName:()=>Pn,endpointToRequestParts:()=>kn,enhanceCollection:()=>Wm,ensureAgentsMdFile:()=>io,enumerateFolders:()=>Ce,evaluateExpression:()=>gt,exportCollectionToRestClient:()=>Ad,extractJsonFromLlm:()=>xt,extractPathParameters:()=>tn,findItemById:()=>Re,flattenRequests:()=>Q,formatConsoleOutput:()=>Wn,gatherWorkspaceKnowledge:()=>ps,generateFlowFromEndpoints:()=>ur,generateId:()=>ae,generateReleaseNotes:()=>ed,generateSlug:()=>at,generateSuiteFromEndpoints:()=>lr,getAgentsMdPath:()=>Vs,getAgentsMdStatus:()=>od,getCompletions:()=>eh,getRegisteredKnowledgeSources:()=>hp,getServiceContainer:()=>jl,harToCollection:()=>rd,hasChanged:()=>Ur,isExpression:()=>mn,isSystemEnvironmentFile:()=>Ws,loadEnvironmentsFromFolder:()=>_r,loadHybridSeedEndpoints:()=>Oi,normalizeFolderInput:()=>sr,normalizeHeaders:()=>bo,parseCurlCommand:()=>Gm,parseFilterChain:()=>Lr,parseHar:()=>kc,parseMcpToolName:()=>Ga,parsePostmanEnvironment:()=>Oo,parseQueryContext:()=>Xm,prepareBodyForSave:()=>Dc,proposeSuiteUpdates:()=>Hi,readAgentsMdVersion:()=>so,readBodyFromDir:()=>_c,readSchemaFile:()=>Lc,readScriptsFromDir:()=>Js,redactFullResponse:()=>No,redactFullResultDetails:()=>Mo,redactHeaders:()=>lt,redactHistoryEntry:()=>Fo,refreshAgentsMd:()=>ad,registerCoreServices:()=>xi,registerKnowledgeSource:()=>fp,renderArchitectDocs:()=>Wl,renderReleaseNotesMarkdown:()=>td,requestKnowledgeSource:()=>Xe,resolveCollectionRef:()=>Sc,resolveFolderRef:()=>xc,resolveFolderToken:()=>Wa,resolveProjectName:()=>eu,resolveRegenerated:()=>Na,resolveRequestRef:()=>wc,resolveResultGrouping:()=>Os,resolveToken:()=>Rr,reviewSuiteRun:()=>Ui,runCollection:()=>Vm,runFolder:()=>zm,runRequest:()=>Um,runResultsKnowledgeSource:()=>wi,runSuite:()=>Jm,scanCollectionForEnvVarsWithAi:()=>Qm,schemaToExample:()=>xr,searchForItemPath:()=>ao,searchForItemPathById:()=>co,serializeTypedValue:()=>Ls,sortItemsByOrder:()=>Bc,suiteIdFromName:()=>ms,threeWayDiff:()=>Fa,toReviewRequestResults:()=>Vi,validateDesignedSpec:()=>Gl,withAiRetry:()=>tt,workspaceKnowledgeSource:()=>et,writeEnvFile:()=>Zn,writeFolderItems:()=>ci,writeSchemaFiles:()=>Hc,writeScriptFile:()=>Xr,writeScriptsToDir:()=>Gs});module.exports=jn(fS);var Ln=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()}};lo();pn();function Vc(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(cd),source:{format:"folder",filePath:e,version:r.version}}}function cd(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(cd)};let e=r;return{type:"request",id:e.id,name:e.name,description:e.description,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,...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 hh(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(zc)}}function zc(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(zc)}:{type:"request",id:r.id,name:r.name,description:r.description,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,...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 Fr=class{store;constructor(e){this.store=new Ut(e)}loadAll(){return this.store.loadAll().map(t=>Vc(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 Vc(t,this.store.getCollectionPath(t.id))}async create(e,t){let n=await this.store.create(e,t);return Vc(n,this.store.getCollectionPath(n.id))}async save(e){return this.store.save(hh(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,zc(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 Nr=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()}};Bn();var Mr=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)}};po();var Ot=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})}};Dr();Br();var Vt=class r{envStore;interpolator;urlBuilder;constructor(e,t){this.envStore=e,this.interpolator=t||new gn,this.urlBuilder=new ct}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=Ot.fromVariables(e);return new r(t)}static fromResolver(e){return new r(e)}};Br();Ys();Xs();Dr();oi();ii();var Kn=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?[require("path").join(i.forgeRoot,"modules")]:[],a=new $t(new ct,new Ft,e);this.scriptExecutor=new Nt(a,o,void 0,i?.scriptScope??"shared",i?.scriptTimeout??5e3)}}httpClient;forgeEnv;cookieJar;preprocessor;scriptExecutor;async execute(e,t,n={}){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,p=this.findFolderPath(t,e.id),d=this.buildScriptChain(e,t,p),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,x)=>{v==="set"&&y&&x!==void 0?this.forgeEnv.setGlobal(y,x):v==="unset"&&y?this.forgeEnv.unsetGlobal(y):v==="clear"&&this.forgeEnv.clearGlobals()}},f=this.scriptExecutor.createRequestSession(m),h,g;try{if(!n.skipPreRequest&&d.preRequest.length>0){let b=await f.executePreRequest(d.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 x=await this.httpClient.send(l);if(!n.skipPostResponse&&d.postResponse.length>0){let b=await f.executePostResponse(d.postResponse,{status:x.status,statusText:x.statusText,headers:x.headers,body:x.body,cookies:So(x.headers,x.cookies,l.url),responseTime:x.time,responseSize:x.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:x,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 p of e.query)p.enabled!==!1&&u.append(p.key,p.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=Vt.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 Qh(){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 zr=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=Qh(),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 Jr=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((p,d)=>{let m=u[d];m!==void 0?u[d]=Array.isArray(m)?[...m,p]:[m,p]:u[d]=p}),{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)}}};Ys();Xs();qo();Ao();Dr();var bn=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}}};Po();var Qe=I(require("fs/promises")),Kr=I(require("path")),Wr=class{async readFile(e){return Qe.readFile(e,"utf-8")}async writeFile(e,t){let n=Kr.dirname(e);await this.mkdir(n),await Qe.writeFile(e,t,"utf-8")}async exists(e){try{return await Qe.access(e),!0}catch{return!1}}async mkdir(e){await Qe.mkdir(e,{recursive:!0})}async glob(e,t){let n=t||process.cwd(),s=[];try{await this.walkDirectory(n,i=>{let o=Kr.basename(i);for(let a of e)if(this.matchPattern(o,a)){s.push(i);break}})}catch{}return s}async readDir(e){return Qe.readdir(e)}async isDirectory(e){try{return(await Qe.stat(e)).isDirectory()}catch{return!1}}async walkDirectory(e,t){let n=await Qe.readdir(e,{withFileTypes:!0});for(let s of n){let i=Kr.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)}};oi();var ko=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 gn,this.fileSystem=e.fileSystem||new Wr,this.preprocessor=e.preprocessor||new vn,this.dataFileParser=e.dataFileParser||new Sn,this.cookieJar=e.cookieJar||new Mr,e.enableHistory?this.requestHistory=e.requestHistory||new zr({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 yn(i)}else this.httpClient=new Jr;let t=e.forgeRoot?[require("path").join(e.forgeRoot,"modules")]:[],n=new $t(new ct,this.interceptorChain,this.httpClient);if(this.scriptExecutor=e.scriptExecutor||new Nt(n,t,void 0,e.scriptScope??"shared",e.scriptTimeout??5e3),this.parserRegistry=new Nr,this.parserRegistry.register("http-forge",new bn),(e.storageFormat??"folder")==="folder"&&e.forgeRoot){let i=require("path").join(e.forgeRoot,"collections");this.collectionLoader=new Fr(i)}else this.collectionLoader=new Ln(this.fileSystem,this.parserRegistry);this.environmentStore=e.environmentConfig?new Ot(e.environmentConfig):Ot.fromVariables({}),this.forgeEnv=Vt.fromResolver(this.environmentStore),this.requestExecutor=new Kn(this.httpClient,this.forgeEnv,this.cookieJar,this.preprocessor,{forgeRoot:e.forgeRoot,scriptExecutor:this.scriptExecutor})}createInterceptorChain(e){let t=new Ft;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 Ln)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 Ot(e),this.forgeEnv=Vt.fromResolver(this.environmentStore),this.requestExecutor=new Kn(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=require("path"),s=n.join(e,"environments"),i,o=_r(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=require("fs"),l=n.join(s,"environments.json");if(c.existsSync(l))try{let u=c.readFileSync(l,"utf-8"),p=JSON.parse(u);if(i={globalVariables:p.globalVariables||{},environments:{},selectedEnvironment:p.selectedEnvironment},p.environments)for(let[d,m]of Object.entries(p.environments)){let f=m;i.environments[d]={name:f.name||d,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})}};Dl();Ll();Ko();Ye();Ou();ja();$u();Nu();Xa();Me();rc();async function Bm(r){let{createMcpRuntime:e}=await Promise.resolve().then(()=>(Hm(),Lm));return e(r)}async function Um(r){let{runRequest:e}=await Promise.resolve().then(()=>(Hs(),Xi));return e(r)}async function Vm(r){let{runCollection:e}=await Promise.resolve().then(()=>(Hs(),Xi));return e(r)}async function zm(r){let{runFolder:e}=await Promise.resolve().then(()=>(Hs(),Xi));return e(r)}async function Jm(r){let{runSuite:e}=await Promise.resolve().then(()=>(Hs(),Xi));return e(r)}bc();dl();Bn();sc();pl();Ys();Xs();qo();Ao();Dr();Kc();Yc();oi();ri();ii();as();al();ll();lo();Nc();pn();ol();ta();function jb(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 Lb(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"),(p,d)=>t[parseInt(d,10)]),c=a(i),l=o.split("&").filter(Boolean).map(u=>{let p=a(u),d=p.indexOf("=");return d===-1?{key:p,value:"",enabled:!0}:{key:decodeURIComponent(p.slice(0,d)),value:decodeURIComponent(p.slice(d+1)),enabled:!0}});return{cleanUrl:c,params:l}}catch{return{cleanUrl:r,params:[]}}}function Hb(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 Bb(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 Xo.has(a)&&wt(o.value)&&i(Yt(o.key),o.value)}for(let o of e)ea.has(o.key.toLowerCase())&&wt(o.value)&&i(Yt(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)&&!Ri(t)){let c=`${o.protocol}//${o.host}`;i("BASE_URL",c)}}catch{}return n}function Gm(r){let e=jb(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=[],p=[],d=0;for(;d<n.length;){let y=n[d];if(y==="-X"||y==="--request")s=n[++d]??"";else if(y==="-H"||y==="--header"){let x=n[++d]??"",b=x.indexOf(":");b>0&&o.push({key:x.slice(0,b).trim(),value:x.slice(b+1).trim()})}else if(y==="-d"||y==="--data"||y==="--data-raw"||y==="--data-binary"||y==="--data-ascii")a=n[++d]??"";else if(y==="--json")a=n[++d]??"",c=!0;else if(y==="-u"||y==="--user"){let x=n[++d]??"",b=btoa(x);o.push({key:"Authorization",value:`Basic ${b}`})}else if(y==="-b"||y==="--cookie")o.push({key:"Cookie",value:n[++d]??""});else if(y==="--url")i=n[++d]??"";else if(y==="-G"||y==="--get")l=!0;else if(y==="-F"||y==="--form"){let x=n[++d]??"",b=x.indexOf("=");b>0&&u.push({key:x.slice(0,b),value:x.slice(b+1)})}else y==="--data-urlencode"?p.push(n[++d]??""):y==="-A"||y==="--user-agent"?o.push({key:"User-Agent",value:n[++d]??""}):y==="-e"||y==="--referer"||y==="--referrer"?o.push({key:"Referer",value:n[++d]??""}):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"?d++:!y.startsWith("-")&&!i&&(i=y));d++}l?s="GET":s||(s=a!==null||u.length>0||p.length>0?"POST":"GET");let{cleanUrl:m,params:f}=Lb(i),h=null;if(u.length>0)h={type:"raw",format:"text",content:u.map(x=>`${encodeURIComponent(x.key)}=${encodeURIComponent(x.value)}`).join("&")},o.some(x=>x.key.toLowerCase()==="content-type")||o.push({key:"Content-Type",value:"multipart/form-data"});else if(p.length>0)h={type:"raw",format:"text",content:p.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(),x=c||y.startsWith("{")||y.startsWith("[");h={type:"raw",format:x?"json":"text",content:a},x&&!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=Bb(o,f,m||i);return{name:Hb(m||i),method:s.toUpperCase(),url:m||i,headers:g,queryParams:f,body:h,suggestedVars:v}}ar();cr();la();cr();ar();var Ec=10;async function Wm(r,e,t,n){let s=Km(r.items);if(s.length===0)return;let i=Math.ceil(s.length/Ec);for(let o=0;o<s.length;o+=Ec){let a=s.slice(o,o+Ec).map(u=>e.getRequestDetail(r.id,u.id)??u),c=Math.floor(o/Ec)+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:Jb(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 tt(()=>t.complete(Ub(l,a))),p=Vb(u);zb(a,p)}catch{}}await e.saveCollection(r)}function Ub(r,e){return`You are an API testing expert. For each HTTP request below, return two improvements:
1467
1467
  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.
1468
1468
  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.
1469
1469
 
1470
1470
  Business context (use this to generate realistic values that match the documented API contract):
1471
- ${ds(e.map(n=>et(n)))||"(none provided \u2014 use generic realistic values)"}
1471
+ ${fs(e.map(n=>Xe(n)))||"(none provided \u2014 use generic realistic values)"}
1472
1472
 
1473
1473
  Input requests (JSON array):
1474
1474
  ${JSON.stringify(r,null,2)}
@@ -1479,26 +1479,26 @@ Return ONLY a valid JSON array matching this shape (no markdown fences, no extra
1479
1479
  Rules:
1480
1480
  - Keep "body" as a valid JSON string (escaped). Use realistic values, not placeholder strings.
1481
1481
  - Keep "testScript" as valid JS. Use pm.test(), pm.response.to.have.status(), pm.expect().
1482
- - One output object per input, same order, same id.`}function Lb(r){let e=wt(r);return Array.isArray(e)?e:[]}function Hb(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 zm(r){let e=[];for(let t of r)t.type==="request"?e.push(t):t.type==="folder"&&t.items&&e.push(...zm(t.items));return e}function Bb(r){if(r.body?.type==="raw"&&typeof r.body.content=="string")return r.body.content.slice(0,300)}Xe();ir();sr();Yo();async function Jm(r,e){let t=Q(r).map(a=>a.request);if(t.length===0)return[];let n=ds(t.slice(0,30).map(a=>et(a))),s=`You are an API testing expert scanning an HTTP collection for hardcoded values.
1482
+ - One output object per input, same order, same id.`}function Vb(r){let e=xt(r);return Array.isArray(e)?e:[]}function zb(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 Km(r){let e=[];for(let t of r)t.type==="request"?e.push(t):t.type==="folder"&&t.items&&e.push(...Km(t.items));return e}function Jb(r){if(r.body?.type==="raw"&&typeof r.body.content=="string")return r.body.content.slice(0,300)}Ye();cr();ar();ta();async function Qm(r,e,t){let n=Q(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=fs(s.map(l=>Xe(l))),o=`You are an API testing expert scanning an HTTP collection for hardcoded values.
1483
1483
  Find all values that should be extracted to environment variables: base URLs, API keys/tokens, tenant or org IDs, user IDs, repeated hostnames.
1484
1484
  Skip: HTTP methods, standard header names (Content-Type, Accept, Authorization key names), empty values, boolean literals, short numeric IDs.
1485
1485
 
1486
1486
  Collection: "${r.name}"
1487
1487
  `+(r.description?.trim()?`Description: ${r.description.trim().slice(0,300)}
1488
1488
  `:"")+`
1489
- ${n}
1489
+ ${i}
1490
1490
 
1491
1491
  Return ONLY a valid JSON array (no markdown fences):
1492
- [{"value":"exact hardcoded string","suggestedName":"UPPER_SNAKE_CASE_NAME","reason":"one sentence","requestIds":["id1","id2"]}]`,i=await nt(()=>e.complete(s)),o=wt(i);return Array.isArray(o)?o.filter(a=>a.value&&a.suggestedName).map(a=>({varName:Xt(a.suggestedName),value:a.value,reason:a.reason??"",occurrences:Ub(t,a.value)})).filter(a=>a.occurrences.length>0).sort((a,c)=>c.occurrences.length-a.occurrences.length):[]}function Ub(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}Ll();Hu();ul();co();Lr();ci();dl();hl();el();function Km(r,e,t){let n=r.slice(0,e),s=n.match(/([a-zA-Z_]\w*)$/),i=s?s[1]:"",o=Zb(n);if(o.trimEnd().endsWith("@")||i&&o.trimEnd().endsWith("@"+i))return{contextType:"directive",fieldPath:[],prefix:i};if(Yb(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&&Gm(o)){let d=Gu(o,t),p=d.length>0?d[d.length-1]:void 0,m=Wm(o);return{contextType:"argument_value",fieldPath:d,parentType:p,prefix:c[2]||"",currentArg:c[1],currentField:m||void 0}}if(Gm(o)){let d=Gu(o,t),p=d.length>0?d[d.length-1]:void 0,m=Wm(o);return{contextType:"argument",fieldPath:d,parentType:p,prefix:i,currentField:m||void 0}}if(Wu(o,"{","}")===0)return{contextType:"root",fieldPath:[],prefix:i};let u=Gu(o,t);return{contextType:"selection_set",fieldPath:u,parentType:u.length>0?u[u.length-1]:void 0,prefix:i}}function Qm(r,e){switch(e.contextType){case"root":return Vb(r,e.prefix);case"selection_set":return zb(r,e);case"argument":return Jb(r,e);case"argument_value":return Gb(r,e);case"directive":return Wb(r,e.prefix);case"fragment_type":return Kb(r,e.prefix);case"variable_def":return Qb(r,e.prefix);default:return[]}}function Vb(r,e){let t=[],n=[{label:"query",detail:"Query operation",insertText:`query \${1:OperationName} {
1492
+ [{"value":"exact hardcoded string","suggestedName":"UPPER_SNAKE_CASE_NAME","reason":"one sentence","requestIds":["id1","id2"]}]`,a=await tt(()=>e.complete(o)),c=xt(a);return Array.isArray(c)?c.filter(l=>l.value&&l.suggestedName).map(l=>({varName:Yt(l.suggestedName),value:l.value,reason:l.reason??"",occurrences:Gb(n,l.value)})).filter(l=>l.occurrences.length>0).sort((l,u)=>u.occurrences.length-l.occurrences.length):[]}function Gb(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}Vl();zu();ml();po();Br();ui();hl();bl();sl();function Xm(r,e,t){let n=r.slice(0,e),s=n.match(/([a-zA-Z_]\w*)$/),i=s?s[1]:"",o=tS(n);if(o.trimEnd().endsWith("@")||i&&o.trimEnd().endsWith("@"+i))return{contextType:"directive",fieldPath:[],prefix:i};if(nS(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&&Zm(o)){let p=Zu(o,t),d=p.length>0?p[p.length-1]:void 0,m=Ym(o);return{contextType:"argument_value",fieldPath:p,parentType:d,prefix:c[2]||"",currentArg:c[1],currentField:m||void 0}}if(Zm(o)){let p=Zu(o,t),d=p.length>0?p[p.length-1]:void 0,m=Ym(o);return{contextType:"argument",fieldPath:p,parentType:d,prefix:i,currentField:m||void 0}}if(Yu(o,"{","}")===0)return{contextType:"root",fieldPath:[],prefix:i};let u=Zu(o,t);return{contextType:"selection_set",fieldPath:u,parentType:u.length>0?u[u.length-1]:void 0,prefix:i}}function eh(r,e){switch(e.contextType){case"root":return Wb(r,e.prefix);case"selection_set":return Kb(r,e);case"argument":return Qb(r,e);case"argument_value":return Zb(r,e);case"directive":return Yb(r,e.prefix);case"fragment_type":return Xb(r,e.prefix);case"variable_def":return eS(r,e.prefix);default:return[]}}function Wb(r,e){let t=[],n=[{label:"query",detail:"Query operation",insertText:`query \${1:OperationName} {
1493
1493
  $0
1494
1494
  }`},{label:"mutation",detail:"Mutation operation",insertText:`mutation \${1:OperationName} {
1495
1495
  $0
1496
1496
  }`},{label:"subscription",detail:"Subscription operation",insertText:`subscription \${1:OperationName} {
1497
1497
  $0
1498
- }`},{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(Zm(i,1,r));return t}function zb(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(Zm(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} {
1498
+ }`},{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(th(i,1,r));return t}function Kb(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(th(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} {
1499
1499
  $0
1500
- }`,sortOrder:5})}return(!e.prefix||"...".startsWith(e.prefix))&&t.push({label:"...",kind:"snippet",detail:"Fragment spread",insertText:"...${1:FragmentName}",sortOrder:8}),t}function Jb(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 Gb(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 Wb(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 Kb(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 Qb(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 Zm(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+=` {
1500
+ }`,sortOrder:5})}return(!e.prefix||"...".startsWith(e.prefix))&&t.push({label:"...",kind:"snippet",detail:"Fragment spread",insertText:"...${1:FragmentName}",sortOrder:8}),t}function Qb(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 Zb(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 Yb(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 Xb(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 eS(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 th(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+=` {
1501
1501
  $0
1502
- }`),{label:r.name,kind:"field",detail:r.type,description:r.description,insertText:i,deprecated:r.isDeprecated,sortOrder:e}}function Zb(r){return r.replace(/"""[\s\S]*?"""/g,'""').replace(/"(?:[^"\\]|\\.)*"/g,'""').replace(/#[^\n]*/g,"")}function Wu(r,e,t){let n=0;for(let s of r)s===e?n++:s===t&&n--;return n}function Gm(r){return Wu(r,"(",")")>0}function Yb(r){if(Wu(r,"(",")")<=0)return!1;let t=r.indexOf("{"),n=t>=0?r.slice(0,t):r;return/\$\w+\s*:\s*\w*$/.test(n)}function Wm(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 Gu(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=Xb(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 Xb(r){let e=[],t=/([a-zA-Z_]\w*|[{}(),:=@!$\[\].]|\.\.\.|"[^"]*"|\d+)/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]);return e}pl();wl();gl();Rl();No();Cl();Bo();jo();Ho();zl();Hl();Bl();Rs();bu();wu();xu();yu();ca();Zl();su();iu();uu();au();ua();En();hu();na();Kl();ia();Cu();var Ku=require("child_process"),eS=/^(feat|fix|perf|docs|refactor|test|build|chore)(?:\(([^)]*)\))?(!?):\s*(.+)$/i,Ym=/BREAKING[- ]CHANGE:/i;function Qu(r){let{projectRoot:e,from:t,to:n="HEAD"}=r,s=t?`${t}..${n}`:n,i=!0,o,a="";try{a=(0,Ku.execSync)(`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=(0,Ku.execSync)("git rev-parse HEAD",{cwd:e,stdio:["ignore","pipe","ignore"],encoding:"utf-8",timeout:3e3}).trim()}catch{i=!1}let c=a.split(`
1503
- `).map(u=>u.trim()).filter(Boolean).map(tS).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 tS(r){let e=r.indexOf(" ");if(e<0)return null;let t=r.slice(0,e),n=r.slice(e+1),s=n.match(eS);if(!s)return{type:"other",subject:n,hash:t,breaking:Ym.test(n)};let[,i,o,a,c]=s;return{type:i.toLowerCase(),scope:o||void 0,subject:c,hash:t,breaking:a==="!"||Ym.test(c)}}function Zu(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(`
1504
- `)}ol();Po();Nu();zi();Ts();ic();function Rc(r,e){if(r.length===0)return 0;let t=Math.ceil(e/100*r.length)-1;return r[Math.max(0,t)]}function Yu(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 Xm(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=Rc(e,50),r.p90=Rc(e,90),r.p95=Rc(e,95),r.p99=Rc(e,99)}var Cc=class{summary;byRequest;overall;errors;startTime=0;constructor(){this.summary=this.createEmptySummary(),this.byRequest=new Map,this.overall=Yu("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=Yu("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,Yu(e,t));let c=this.byRequest.get(e);if(c.name=t,c.count++,s?c.passed++:c.failed++,c.durations.push(n),Xm(c),this.overall.count++,s?this.overall.passed++:this.overall.failed++,this.overall.durations.push(n),Xm(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}}};$l();var kt=I(require("fs")),kr=I(require("path"));dn();var Ec=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=kr.join(this.suiteDir,e,"request.json");if(kt.existsSync(t))try{let n=JSON.parse(kt.readFileSync(t,"utf-8")),s=kr.join(this.suiteDir,e,"scripts"),i=Vs(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=kr.join(this.suiteDir,e);kt.mkdirSync(n,{recursive:!0});let s=t.scripts,i={...t};delete i.scripts;let o=kr.join(n,"request.json"),a=`${o}.tmp-${process.pid}-${Date.now()}`;if(kt.writeFileSync(a,JSON.stringify(i,null,2),"utf-8"),kt.renameSync(a,o),s){let c=kr.join(n,"scripts");zs(c,{preRequest:s.preRequest||void 0,postResponse:s.postResponse||void 0})}}hasEmbeddedRequest(e){return!this.suiteDir||!e?!1:kt.existsSync(kr.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=ct(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=ct(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)}};Ke();function Ac(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(nS(a))}let o=aS(i,e.collectionName??"Imported from HAR");return{requests:i,collection:o}}function Xu(r,e={}){return Ac(r,e).collection}function nS(r){let e=r.request,t=e.method||"GET",n=e.url||"",s=oS(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=rS(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 rS(r,e){if(!r)return null;let t=typeof r.text=="string"?r.text:"",n=r.mimeType||iS(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=sS(t);if(s.length>0)return{type:"x-www-form-urlencoded",content:s}}return{type:"raw",format:"text",content:t}}function sS(r){try{return[...new URLSearchParams(r).entries()].map(([t,n])=>({key:t,value:n,enabled:!0}))}catch{return[]}}function iS(r){return r.find(t=>t.key.toLowerCase()==="content-type")?.value?.split(";")[0].trim()??""}function oS(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 aS(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:oe(`har-${i}`),name:i,items:[]},t.set(i,o),n.push(o)),o.items.push(cS(s))}return{id:oe("har-collection"),name:e,items:n,source:{format:"har",filePath:""},meta:{requestCount:r.length}}}function cS(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:oe(`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}}ll();qo();Eo();El();Al();Il();kl();ql();Pl();Tl();Gs();po();Ke();Bu();0&&(module.exports={AGENTS_MD_BACKUP_FILENAME,AGENTS_MD_FILENAME,AGENTS_MD_VERSION,AnthropicProvider,ApiArchitectService,ApiDiscoveryService,AwsSecretResolver,AzureKeyVaultResolver,BODY_FILE_MAP,CACHE_BUSTING_TOOLS,COLLECTION_INPUT_SCHEMA,CONFIG_FILES,CollectionLoader,CollectionLoaderFactory,CollectionRequestExecutor,CollectionService,ConfigService,CookieJar,CookieService,CookieUtils,DEFAULT_CONFIG,DEFAULT_REQUEST_SETTINGS,DataFileParser,DopplerResolver,EnvironmentConfigService,EnvironmentResolver,ExampleGenerator,ExpressComponentAnalyzer,ExpressDiscoveryProvider,FOLDER_INPUT_SCHEMA,FastApiDiscoveryProvider,FastifyComponentAnalyzer,FastifyDiscoveryProvider,FetchHttpClient,FolderCollectionLoader,FolderCollectionStore,ForgeContainer,ForgeEnv,FrameworkDetector,GENERIC_TOOL_NAMES,GcpSecretResolver,GraphQLSchemaService,HTTP_METHOD_MAP,HTTP_METHOD_REVERSE,HashiCorpVaultResolver,HistoryAnalyzer,HtmlReportGenerator,HttpForgeParser,HttpRequestService,InMemoryCookieJar,InterceptorChain,JUnitReportGenerator,JsonCollectionLoader,LambdaComponentAnalyzer,LambdaDiscoveryProvider,MCP_PROMPTS,METADATA_FILES,McpRunStore,ModuleLoader,NestDiscoveryProvider,NodeFileSystem,NodeHttpClient,OAuth2TokenManager,OnePasswordResolver,OpenAiProvider,OpenApiExporter,OpenApiImporter,ParserRegistry,PersistentCookieJar,REQUEST_INPUT_SCHEMA,ROOT_DIRECTORIES,RefResolver,RequestExecutor,RequestHistoryService,RequestHistoryStore,RequestPreparer,RequestPreprocessor,RequestScriptSession,ResultStorageService,SCHEMA_FILES,SCRIPTS_DIR,SCRIPT_FILES,SUITE_INPUT_SCHEMA,SchemaInferenceService,SchemaInferrer,ScriptAnalyzer,ScriptExecutor,SecretResolverRegistry,ServiceContainer,ServiceIdentifiers,SpringDiscoveryProvider,StatisticsService,TestSuiteService,TestSuiteStore,UrlBuilder,VariableInterpolator,VariableResolver,analyzeComponentChainMetadata,analyzeHandlerMetadata,applyEnvSuggestionsToItems,applyExtractionPlan,applyFilterChain,applyMcpBodyTruncation,applyRegenerated,assembleBusinessContext,buildAgentsMdContent,buildArchitectPrompt,buildCollectionBusinessContext,buildCollectionToolDescription,buildCollectionToolName,buildDescription,buildExtractionPlan,buildFolderToolDescription,buildFolderToolName,buildGenericTools,buildMcpToolList,buildPromptResult,buildRequestBusinessContext,buildRequestToolDescription,buildRequestToolName,buildResultFileName,buildRunResultsContext,buildSuiteToolDescription,buildSuiteToolName,cleanupOldBodyFiles,clearRegisteredKnowledgeSources,collectSourceFiles,collectionKnowledgeSource,collectionToEndpoints,combineConfidence,computeProjectFreshness,concatenateScripts,countRequests,createDefaultKnowledgeSources,createEnvAiProvider,createExpectChain,createMcpRuntime,createModuleLoader,createMomentShim,createNodeContainer,createResponseObject,createTestFunction,decodeCursor,decodeFolderPath,dedupeDiscoveredApiParameters,deleteItemFromTree,deserializeTypedRecord,deserializeTypedValue,detectEnvSuggestions,detectIndexDrift,detectProjectDrift,diffLines,discoverWorkflows,dispatchGenericTool,encodeCursor,encodeFolderName,endpointToCreateRequestOptions,endpointToName,endpointToRequestParts,enhanceCollection,ensureAgentsMdFile,enumerateFolders,evaluateExpression,exportCollectionToRestClient,extractJsonFromLlm,extractPathParameters,findItemById,flattenRequests,formatConsoleOutput,gatherWorkspaceKnowledge,generateFlowFromEndpoints,generateId,generateReleaseNotes,generateSlug,generateSuiteFromEndpoints,getAgentsMdPath,getAgentsMdStatus,getCompletions,getRegisteredKnowledgeSources,getServiceContainer,harToCollection,hasChanged,isExpression,isSystemEnvironmentFile,loadEnvironmentsFromFolder,loadHybridSeedEndpoints,normalizeFolderInput,normalizeHeaders,parseCurlCommand,parseFilterChain,parseHar,parseMcpToolName,parsePostmanEnvironment,parseQueryContext,prepareBodyForSave,proposeSuiteUpdates,readAgentsMdVersion,readBodyFromDir,readSchemaFile,readScriptsFromDir,redactFullResponse,redactFullResultDetails,redactHeaders,redactHistoryEntry,refreshAgentsMd,registerCoreServices,registerKnowledgeSource,renderArchitectDocs,renderReleaseNotesMarkdown,requestKnowledgeSource,resolveCollectionRef,resolveFolderRef,resolveFolderToken,resolveProjectName,resolveRegenerated,resolveRequestRef,resolveResultGrouping,resolveToken,reviewSuiteRun,runCollection,runFolder,runRequest,runResultsKnowledgeSource,runSuite,scanCollectionForEnvVarsWithAi,schemaToExample,searchForItemPath,searchForItemPathById,serializeTypedValue,sortItemsByOrder,suiteIdFromName,threeWayDiff,toReviewRequestResults,validateDesignedSpec,withAiRetry,workspaceKnowledgeSource,writeEnvFile,writeFolderItems,writeSchemaFiles,writeScriptFile,writeScriptsToDir});
1502
+ }`),{label:r.name,kind:"field",detail:r.type,description:r.description,insertText:i,deprecated:r.isDeprecated,sortOrder:e}}function tS(r){return r.replace(/"""[\s\S]*?"""/g,'""').replace(/"(?:[^"\\]|\\.)*"/g,'""').replace(/#[^\n]*/g,"")}function Yu(r,e,t){let n=0;for(let s of r)s===e?n++:s===t&&n--;return n}function Zm(r){return Yu(r,"(",")")>0}function nS(r){if(Yu(r,"(",")")<=0)return!1;let t=r.indexOf("{"),n=t>=0?r.slice(0,t):r;return/\$\w+\s*:\s*\w*$/.test(n)}function Ym(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 Zu(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=rS(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(p=>p.name===c);if(u){let p=u.type.replace(/[!\[\]]/g,"");t.push(p),o=e.types.get(p)}}}}}return t}function rS(r){let e=[],t=/([a-zA-Z_]\w*|[{}(),:=@!$\[\].]|\.\.\.|"[^"]*"|\d+)/g,n;for(;(n=t.exec(r))!==null;)e.push(n[1]);return e}gl();ql();Sl();Al();Do();Pl();zo();Bo();Vo();Kl();zl();Jl();Es();Ru();qu();Eu();xu();da();tu();cu();lu();mu();du();fa();qn();bu();ia();Xl();ca();Pu();var Xu=require("child_process"),sS=/^(feat|fix|perf|docs|refactor|test|build|chore)(?:\(([^)]*)\))?(!?):\s*(.+)$/i,nh=/BREAKING[- ]CHANGE:/i;function ed(r){let{projectRoot:e,from:t,to:n="HEAD"}=r,s=t?`${t}..${n}`:n,i=!0,o,a="";try{a=(0,Xu.execSync)(`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=(0,Xu.execSync)("git rev-parse HEAD",{cwd:e,stdio:["ignore","pipe","ignore"],encoding:"utf-8",timeout:3e3}).trim()}catch{i=!1}let c=a.split(`
1503
+ `).map(u=>u.trim()).filter(Boolean).map(iS).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 iS(r){let e=r.indexOf(" ");if(e<0)return null;let t=r.slice(0,e),n=r.slice(e+1),s=n.match(sS);if(!s)return{type:"other",subject:n,hash:t,breaking:nh.test(n)};let[,i,o,a,c]=s;return{type:i.toLowerCase(),scope:o||void 0,subject:c,hash:t,breaking:a==="!"||nh.test(c)}}function td(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(`
1504
+ `)}ul();To();ju();Gi();$s();cc();function qc(r,e){if(r.length===0)return 0;let t=Math.ceil(e/100*r.length)-1;return r[Math.max(0,t)]}function nd(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 rh(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=qc(e,50),r.p90=qc(e,90),r.p95=qc(e,95),r.p99=qc(e,99)}var Ac=class{summary;byRequest;overall;errors;startTime=0;constructor(){this.summary=this.createEmptySummary(),this.byRequest=new Map,this.overall=nd("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=nd("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,nd(e,t));let c=this.byRequest.get(e);if(c.name=t,c.count++,s?c.passed++:c.failed++,c.durations.push(n),rh(c),this.overall.count++,s?this.overall.passed++:this.overall.failed++,this.overall.durations.push(n),rh(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}}};_l();var Pt=I(require("fs")),Or=I(require("path"));pn();var Pc=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=Or.join(this.suiteDir,e,"request.json");if(Pt.existsSync(t))try{let n=JSON.parse(Pt.readFileSync(t,"utf-8")),s=Or.join(this.suiteDir,e,"scripts"),i=Js(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=Or.join(this.suiteDir,e);Pt.mkdirSync(n,{recursive:!0});let s=t.scripts,i={...t};delete i.scripts;let o=Or.join(n,"request.json"),a=`${o}.tmp-${process.pid}-${Date.now()}`;if(Pt.writeFileSync(a,JSON.stringify(i,null,2),"utf-8"),Pt.renameSync(a,o),s){let c=Or.join(n,"scripts");Gs(c,{preRequest:s.preRequest||void 0,postResponse:s.postResponse||void 0})}}hasEmbeddedRequest(e){return!this.suiteDir||!e?!1:Pt.existsSync(Or.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"),p=i?`${i}/${u}`:u,d=this.searchItems(a.items||[],t,c,l,p);if(d)return d}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=at(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=at(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)}};We();function kc(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(oS(a))}let o=dS(i,e.collectionName??"Imported from HAR");return{requests:i,collection:o}}function rd(r,e={}){return kc(r,e).collection}function oS(r){let e=r.request,t=e.method||"GET",n=e.url||"",s=uS(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=aS(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 aS(r,e){if(!r)return null;let t=typeof r.text=="string"?r.text:"",n=r.mimeType||lS(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=cS(t);if(s.length>0)return{type:"x-www-form-urlencoded",content:s}}return{type:"raw",format:"text",content:t}}function cS(r){try{return[...new URLSearchParams(r).entries()].map(([t,n])=>({key:t,value:n,enabled:!0}))}catch{return[]}}function lS(r){return r.find(t=>t.key.toLowerCase()==="content-type")?.value?.split(";")[0].trim()??""}function uS(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 dS(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:ae(`har-${i}`),name:i,items:[]},t.set(i,o),n.push(o)),o.items.push(pS(s))}return{id:ae("har-collection"),name:e,items:n,source:{format:"har",filePath:""},meta:{requestCount:r.length}}}function pS(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:ae(`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}}fl();Io();Po();kl();Il();Fl();$l();Tl();Ol();Nl();Ks();ho();We();Ju();0&&(module.exports={AGENTS_MD_BACKUP_FILENAME,AGENTS_MD_FILENAME,AGENTS_MD_VERSION,AnthropicProvider,ApiArchitectService,ApiDiscoveryService,AwsSecretResolver,AzureKeyVaultResolver,BODY_FILE_MAP,CACHE_BUSTING_TOOLS,COLLECTION_INPUT_SCHEMA,CONFIG_FILES,CollectionLoader,CollectionLoaderFactory,CollectionRequestExecutor,CollectionService,ConfigService,CookieJar,CookieService,CookieUtils,DEFAULT_CONFIG,DEFAULT_REQUEST_SETTINGS,DataFileParser,DopplerResolver,EnvironmentConfigService,EnvironmentResolver,ExampleGenerator,ExpressComponentAnalyzer,ExpressDiscoveryProvider,FOLDER_INPUT_SCHEMA,FastApiDiscoveryProvider,FastifyComponentAnalyzer,FastifyDiscoveryProvider,FetchHttpClient,FolderCollectionLoader,FolderCollectionStore,ForgeContainer,ForgeEnv,FrameworkDetector,GENERIC_TOOL_NAMES,GcpSecretResolver,GraphQLSchemaService,HTTP_METHOD_MAP,HTTP_METHOD_REVERSE,HashiCorpVaultResolver,HistoryAnalyzer,HtmlReportGenerator,HttpForgeParser,HttpRequestService,InMemoryCookieJar,InterceptorChain,JUnitReportGenerator,JsonCollectionLoader,LambdaComponentAnalyzer,LambdaDiscoveryProvider,MCP_PROMPTS,METADATA_FILES,McpRunStore,ModuleLoader,NestDiscoveryProvider,NodeFileSystem,NodeHttpClient,OAuth2TokenManager,OnePasswordResolver,OpenAiProvider,OpenApiExporter,OpenApiImporter,ParserRegistry,PersistentCookieJar,REQUEST_INPUT_SCHEMA,ROOT_DIRECTORIES,RefResolver,RequestExecutor,RequestHistoryService,RequestHistoryStore,RequestPreparer,RequestPreprocessor,RequestScriptSession,ResultStorageService,SCHEMA_FILES,SCRIPTS_DIR,SCRIPT_FILES,SUITE_INPUT_SCHEMA,SchemaInferenceService,SchemaInferrer,ScriptAnalyzer,ScriptExecutor,SecretResolverRegistry,ServiceContainer,ServiceIdentifiers,SpringDiscoveryProvider,StatisticsService,TestSuiteService,TestSuiteStore,UrlBuilder,VariableInterpolator,VariableResolver,analyzeComponentChainMetadata,analyzeHandlerMetadata,applyEnvSuggestionsToItems,applyExtractionPlan,applyFilterChain,applyMcpBodyTruncation,applyRegenerated,assembleBusinessContext,buildAgentsMdContent,buildArchitectPrompt,buildCollectionBusinessContext,buildCollectionToolDescription,buildCollectionToolName,buildDescription,buildExtractionPlan,buildFolderToolDescription,buildFolderToolName,buildGenericTools,buildMcpToolList,buildPromptResult,buildRequestBusinessContext,buildRequestToolDescription,buildRequestToolName,buildResultFileName,buildRunResultsContext,buildSuiteToolDescription,buildSuiteToolName,cleanupOldBodyFiles,clearRegisteredKnowledgeSources,collectSourceFiles,collectionKnowledgeSource,collectionToEndpoints,combineConfidence,computeProjectFreshness,concatenateScripts,countRequests,createDefaultKnowledgeSources,createEnvAiProvider,createExpectChain,createMcpRuntime,createModuleLoader,createMomentShim,createNodeContainer,createResponseObject,createTestFunction,decodeCursor,decodeFolderPath,dedupeDiscoveredApiParameters,deleteItemFromTree,deserializeTypedRecord,deserializeTypedValue,detectEnvSuggestions,detectIndexDrift,detectProjectDrift,diffLines,discoverWorkflows,dispatchGenericTool,encodeCursor,encodeFolderName,endpointToCreateRequestOptions,endpointToName,endpointToRequestParts,enhanceCollection,ensureAgentsMdFile,enumerateFolders,evaluateExpression,exportCollectionToRestClient,extractJsonFromLlm,extractPathParameters,findItemById,flattenRequests,formatConsoleOutput,gatherWorkspaceKnowledge,generateFlowFromEndpoints,generateId,generateReleaseNotes,generateSlug,generateSuiteFromEndpoints,getAgentsMdPath,getAgentsMdStatus,getCompletions,getRegisteredKnowledgeSources,getServiceContainer,harToCollection,hasChanged,isExpression,isSystemEnvironmentFile,loadEnvironmentsFromFolder,loadHybridSeedEndpoints,normalizeFolderInput,normalizeHeaders,parseCurlCommand,parseFilterChain,parseHar,parseMcpToolName,parsePostmanEnvironment,parseQueryContext,prepareBodyForSave,proposeSuiteUpdates,readAgentsMdVersion,readBodyFromDir,readSchemaFile,readScriptsFromDir,redactFullResponse,redactFullResultDetails,redactHeaders,redactHistoryEntry,refreshAgentsMd,registerCoreServices,registerKnowledgeSource,renderArchitectDocs,renderReleaseNotesMarkdown,requestKnowledgeSource,resolveCollectionRef,resolveFolderRef,resolveFolderToken,resolveProjectName,resolveRegenerated,resolveRequestRef,resolveResultGrouping,resolveToken,reviewSuiteRun,runCollection,runFolder,runRequest,runResultsKnowledgeSource,runSuite,scanCollectionForEnvVarsWithAi,schemaToExample,searchForItemPath,searchForItemPathById,serializeTypedValue,sortItemsByOrder,suiteIdFromName,threeWayDiff,toReviewRequestResults,validateDesignedSpec,withAiRetry,workspaceKnowledgeSource,writeEnvFile,writeFolderItems,writeSchemaFiles,writeScriptFile,writeScriptsToDir});