@curl-runner/cli 1.24.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js DELETED
@@ -1,532 +0,0 @@
1
- #!/usr/bin/env bun
2
- // @bun
3
- var H3=Object.create;var{getPrototypeOf:K3,defineProperty:q9,getOwnPropertyNames:U3}=Object;var B3=Object.prototype.hasOwnProperty;function O3(Z){return this[Z]}var _3,M3,V1=(Z,X,J)=>{var W=Z!=null&&typeof Z==="object";if(W){var $=X?_3??=new WeakMap:M3??=new WeakMap,G=$.get(Z);if(G)return G}J=Z!=null?H3(K3(Z)):{};let Y=X||!Z||!Z.__esModule?q9(J,"default",{value:Z,enumerable:!0}):J;for(let Q of U3(Z))if(!B3.call(Y,Q))q9(Y,Q,{get:O3.bind(Z,Q),enumerable:!0});if(W)$.set(Z,Y);return Y};var x9=(Z,X)=>()=>(X||Z((X={exports:{}}).exports,X),X.exports);var K1=import.meta.require;var G9=x9((z8,$9)=>{var a1=process||{},_4=a1.argv||[],i1=a1.env||{},N2=!(!!i1.NO_COLOR||_4.includes("--no-color"))&&(!!i1.FORCE_COLOR||_4.includes("--color")||a1.platform==="win32"||(a1.stdout||{}).isTTY&&i1.TERM!=="dumb"||!!i1.CI),L2=(Z,X,J=Z)=>(W)=>{let $=""+W,G=$.indexOf(X,Z.length);return~G?Z+I2($,X,J,G)+X:Z+$+X},I2=(Z,X,J,W)=>{let $="",G=0;do $+=Z.substring(G,W)+J,G=W+X.length,W=Z.indexOf(X,G);while(~W);return $+Z.substring(G)},M4=(Z=N2)=>{let X=Z?L2:()=>String;return{isColorSupported:Z,reset:X("\x1B[0m","\x1B[0m"),bold:X("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:X("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:X("\x1B[3m","\x1B[23m"),underline:X("\x1B[4m","\x1B[24m"),inverse:X("\x1B[7m","\x1B[27m"),hidden:X("\x1B[8m","\x1B[28m"),strikethrough:X("\x1B[9m","\x1B[29m"),black:X("\x1B[30m","\x1B[39m"),red:X("\x1B[31m","\x1B[39m"),green:X("\x1B[32m","\x1B[39m"),yellow:X("\x1B[33m","\x1B[39m"),blue:X("\x1B[34m","\x1B[39m"),magenta:X("\x1B[35m","\x1B[39m"),cyan:X("\x1B[36m","\x1B[39m"),white:X("\x1B[37m","\x1B[39m"),gray:X("\x1B[90m","\x1B[39m"),bgBlack:X("\x1B[40m","\x1B[49m"),bgRed:X("\x1B[41m","\x1B[49m"),bgGreen:X("\x1B[42m","\x1B[49m"),bgYellow:X("\x1B[43m","\x1B[49m"),bgBlue:X("\x1B[44m","\x1B[49m"),bgMagenta:X("\x1B[45m","\x1B[49m"),bgCyan:X("\x1B[46m","\x1B[49m"),bgWhite:X("\x1B[47m","\x1B[49m"),blackBright:X("\x1B[90m","\x1B[39m"),redBright:X("\x1B[91m","\x1B[39m"),greenBright:X("\x1B[92m","\x1B[39m"),yellowBright:X("\x1B[93m","\x1B[39m"),blueBright:X("\x1B[94m","\x1B[39m"),magentaBright:X("\x1B[95m","\x1B[39m"),cyanBright:X("\x1B[96m","\x1B[39m"),whiteBright:X("\x1B[97m","\x1B[39m"),bgBlackBright:X("\x1B[100m","\x1B[49m"),bgRedBright:X("\x1B[101m","\x1B[49m"),bgGreenBright:X("\x1B[102m","\x1B[49m"),bgYellowBright:X("\x1B[103m","\x1B[49m"),bgBlueBright:X("\x1B[104m","\x1B[49m"),bgMagentaBright:X("\x1B[105m","\x1B[49m"),bgCyanBright:X("\x1B[106m","\x1B[49m"),bgWhiteBright:X("\x1B[107m","\x1B[49m")}};$9.exports=M4();$9.exports.createColors=M4});var Q9=x9((H8,D4)=>{var Y9={to(Z,X){if(!X)return`\x1B[${Z+1}G`;return`\x1B[${X+1};${Z+1}H`},move(Z,X){let J="";if(Z<0)J+=`\x1B[${-Z}D`;else if(Z>0)J+=`\x1B[${Z}C`;if(X<0)J+=`\x1B[${-X}A`;else if(X>0)J+=`\x1B[${X}B`;return J},up:(Z=1)=>`\x1B[${Z}A`,down:(Z=1)=>`\x1B[${Z}B`,forward:(Z=1)=>`\x1B[${Z}C`,backward:(Z=1)=>`\x1B[${Z}D`,nextLine:(Z=1)=>"\x1B[E".repeat(Z),prevLine:(Z=1)=>"\x1B[F".repeat(Z),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},j2={up:(Z=1)=>"\x1B[S".repeat(Z),down:(Z=1)=>"\x1B[T".repeat(Z)},R2={screen:"\x1B[2J",up:(Z=1)=>"\x1B[1J".repeat(Z),down:(Z=1)=>"\x1B[J".repeat(Z),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(Z){let X="";for(let J=0;J<Z;J++)X+=this.line+(J<Z-1?Y9.up():"");if(Z)X+=Y9.left;return X}};D4.exports={cursor:Y9,scroll:j2,erase:R2,beep:"\x07"}});var{Glob:T7}=globalThis.Bun;var b9={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m"};function F(Z,X){return`${b9[X]}${Z}${b9.reset}`}var D3=[`${process.env.HOME}/.local/bin/curl-runner`,`${process.env.USERPROFILE}\\.local\\bin\\curl-runner.exe`];function v9(){let Z=process.execPath,X=process.argv[0];if(F3(Z))return{source:"bun",path:Z,canAutoUpgrade:!0};if(T3(Z,X))return{source:"npm",path:Z,canAutoUpgrade:!0};if(N3(Z))return{source:"curl",path:Z,canAutoUpgrade:!0};return{source:"standalone",path:Z,canAutoUpgrade:!0}}function F3(Z){if(Z.includes(".bun"))return!0;if(process.env.BUN_INSTALL&&Z.includes(process.env.BUN_INSTALL))return!0;return["/bun/install/","/.bun/bin/","/bun/bin/"].some((J)=>Z.includes(J))}function T3(Z,X){if(Z.includes("node_modules"))return!0;if(X.includes("node_modules"))return!0;if(process.env.npm_config_prefix)return!0;if(process.env.npm_execpath)return!0;return["/lib/node_modules/","/node_modules/.bin/"].some((W)=>Z.includes(W)||X.includes(W))}function N3(Z){return D3.some((X)=>Z===X||Z.startsWith(X))}function y9(Z){switch(Z){case"bun":return"bun install -g @curl-runner/cli@latest";case"npm":return"npm install -g @curl-runner/cli@latest";case"curl":return"curl -fsSL https://www.curl-runner.com/install.sh | bash";case"standalone":return"curl -fsSL https://www.curl-runner.com/install.sh | bash"}}function m9(Z){switch(Z){case"bun":return"bun install -g @curl-runner/cli@latest";case"npm":return"npm install -g @curl-runner/cli@latest";case"curl":case"standalone":return"irm https://www.curl-runner.com/install.ps1 | iex"}}function z0(){return process.platform==="win32"}function o(){if(typeof BUILD_VERSION<"u")return BUILD_VERSION;if(process.env.CURL_RUNNER_VERSION)return process.env.CURL_RUNNER_VERSION;try{let Z=["../package.json","./package.json","../../package.json"];for(let X of Z)try{let J=K1(X);if(J.name==="@curl-runner/cli"&&J.version)return J.version}catch{}return"0.0.0"}catch{return"0.0.0"}}var L3="https://registry.npmjs.org/@curl-runner/cli/latest",I3="https://api.github.com/repos/alexvcasillas/curl-runner/releases/latest";class H0{async run(Z){let X=this.parseArgs(Z);console.log(),console.log(F("curl-runner upgrade","bright")),console.log();let J=v9();console.log(`${F("Installation:","cyan")} ${this.formatSource(J.source)}`),console.log(`${F("Current version:","cyan")} ${o()}`);let W=await this.fetchLatestVersion(J.source);if(!W)console.log(F("Failed to fetch latest version","red")),process.exit(1);console.log(`${F("Latest version:","cyan")} ${W}`),console.log();let $=o();if(!X.force&&!this.isNewerVersion($,W)){console.log(F("Already up to date!","green"));return}let G=z0()?m9(J.source):y9(J.source);if(X.dryRun){console.log(F("Dry run - would execute:","yellow")),console.log(` ${F(G,"cyan")}`);return}console.log(`${F("Upgrading...","yellow")}`),console.log(),await this.executeUpgrade(J,G)}parseArgs(Z){let X={};for(let J of Z)if(J==="--dry-run"||J==="-n")X.dryRun=!0;else if(J==="--force"||J==="-f")X.force=!0;return X}formatSource(Z){switch(Z){case"bun":return"bun (global)";case"npm":return"npm (global)";case"curl":return"curl installer";case"standalone":return"standalone binary"}}async fetchLatestVersion(Z){try{if(Z==="bun"||Z==="npm"){let G=await fetch(L3,{signal:AbortSignal.timeout(5000)});if(!G.ok)return null;return(await G.json()).version}let X=await fetch(I3,{signal:AbortSignal.timeout(5000),headers:{Accept:"application/vnd.github.v3+json"}});if(!X.ok)return null;let W=(await X.json()).tag_name,$=W.match(/(\d+\.\d+\.\d+)/);return $?$[1]:W.replace(/^v/,"")}catch{return null}}isNewerVersion(Z,X){let J=Z.replace(/^v/,""),W=X.replace(/^v/,""),$=J.split(".").map(Number),G=W.split(".").map(Number);for(let Y=0;Y<Math.max($.length,G.length);Y++){let Q=$[Y]||0,z=G[Y]||0;if(z>Q)return!0;if(z<Q)return!1}return!1}async executeUpgrade(Z,X){let{source:J}=Z;try{if(J==="bun")await this.runBunUpgrade();else if(J==="npm")await this.runNpmUpgrade();else await this.runShellUpgrade(X)}catch(W){let $=W instanceof Error?W.message:String(W);if($.includes("EACCES")||$.includes("permission"))console.log(),console.log(F("Permission denied. Try running with sudo:","yellow")),console.log(` ${F(`sudo ${X}`,"cyan")}`),process.exit(1);console.log(F(`Upgrade failed: ${$}`,"red")),console.log(),console.log(F("Manual upgrade:","yellow")),console.log(` ${F(X,"cyan")}`),process.exit(1)}}async runBunUpgrade(){let X=await Bun.spawn(["bun","install","-g","@curl-runner/cli@latest"],{stdout:"inherit",stderr:"inherit"}).exited;if(X!==0)throw Error(`bun install failed with exit code ${X}`);this.showSuccess()}async runNpmUpgrade(){let X=await Bun.spawn(["npm","install","-g","@curl-runner/cli@latest"],{stdout:"inherit",stderr:"inherit"}).exited;if(X!==0)throw Error(`npm install failed with exit code ${X}`);this.showSuccess()}async runShellUpgrade(Z){let X;if(z0())X=Bun.spawn(["powershell","-Command",Z],{stdout:"inherit",stderr:"inherit"});else X=Bun.spawn(["bash","-c",Z],{stdout:"inherit",stderr:"inherit"});let J=await X.exited;if(J!==0)throw Error(`Upgrade script failed with exit code ${J}`);this.showSuccess()}showSuccess(){console.log(),console.log(F("Upgrade complete!","green")),console.log(),console.log("Run `curl-runner --version` to verify.")}}function h9(){console.log(`
4
- ${F("curl-runner upgrade","bright")}
5
-
6
- Automatically upgrade curl-runner to the latest version.
7
- Detects installation source (bun, npm, curl) and uses appropriate method.
8
-
9
- ${F("USAGE:","yellow")}
10
- curl-runner upgrade [options]
11
-
12
- ${F("OPTIONS:","yellow")}
13
- -n, --dry-run Show what would be executed without running
14
- -f, --force Force upgrade even if already on latest version
15
- -h, --help Show this help message
16
-
17
- ${F("EXAMPLES:","yellow")}
18
- curl-runner upgrade # Upgrade to latest
19
- curl-runner upgrade --dry-run # Preview upgrade command
20
- curl-runner upgrade --force # Force reinstall latest
21
- `)}var{Glob:c9}=globalThis.Bun;var j3=["DATE","TIME","UUID","RANDOM"];function U1(Z,X={}){let{variables:J={},storeContext:W,resolveEnv:$=!0}=X;if(typeof Z==="string")return R3(Z,J,W,$);if(Array.isArray(Z))return Z.map((G)=>U1(G,X));if(Z&&typeof Z==="object"){let G={};for(let[Y,Q]of Object.entries(Z))G[Y]=U1(Q,X);return G}return Z}function R3(Z,X,J,W=!0){let $=p9(Z);if($.length===0)return Z;if($.length===1&&$[0].start===0&&$[0].end===Z.length){let Q=B1($[0].name,X,J,W);return Q!==null?Q:Z}let G="",Y=0;for(let Q of $){G+=Z.slice(Y,Q.start);let z=B1(Q.name,X,J,W);G+=z!==null?z:Z.slice(Q.start,Q.end),Y=Q.end}return G+=Z.slice(Y),G}function B1(Z,X,J,W=!0){if(Z.startsWith("store.")&&J){let Q=Z.slice(6);if(Q in J)return J[Q];return null}let $=Z.match(/^([^:]+):(upper|lower)$/);if($){let[,Q,z]=$,H=X[Q]??(W?process.env[Q]:void 0);if(H)return z==="upper"?H.toUpperCase():H.toLowerCase();return null}let G=Z.indexOf(":");if(G!==-1){let Q=Z.slice(0,G),z=Z.slice(G+1);if(!j3.includes(Q)){let H=B1(Q,X,J,W);if(H!==null)return H;if(z.startsWith("${")){let K=z.endsWith("}")?z.slice(2,-1):z.slice(2),B=B1(K,X,J,W);return B!==null?B:z}return z}}let Y=g9(Z);if(Y!==null)return Y;if(Z in X)return X[Z];if(W&&Z in process.env)return process.env[Z];return null}function g9(Z){if(Z==="UUID")return crypto.randomUUID();if(Z==="UUID:short")return crypto.randomUUID().split("-")[0];let X=Z.match(/^RANDOM:(\d+)-(\d+)$/);if(X){let W=Number(X[1]),$=Number(X[2]);return String(Math.floor(Math.random()*($-W+1))+W)}let J=Z.match(/^RANDOM:string:(\d+)$/);if(J){let W=Number(J[1]),$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";return Array.from({length:W},()=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(Math.random()*62))).join("")}if(Z==="CURRENT_TIME"||Z==="TIMESTAMP")return Date.now().toString();if(Z.startsWith("DATE:"))return d9(new Date,Z.slice(5));if(Z.startsWith("TIME:"))return f9(new Date,Z.slice(5));return null}function d9(Z,X){let J=Z.getFullYear(),W=String(Z.getMonth()+1).padStart(2,"0"),$=String(Z.getDate()).padStart(2,"0");return X.replace("YYYY",J.toString()).replace("MM",W).replace("DD",$)}function f9(Z,X){let J=String(Z.getHours()).padStart(2,"0"),W=String(Z.getMinutes()).padStart(2,"0"),$=String(Z.getSeconds()).padStart(2,"0");return X.replace("HH",J).replace("mm",W).replace("ss",$)}function p9(Z){let X=[],J=0;while(J<Z.length)if(Z[J]==="$"&&Z[J+1]==="{"){let W=J;J+=2;let $=1,G=J;while(J<Z.length&&$>0){if(Z[J]==="{")$++;else if(Z[J]==="}")$--;J++}if($===0)X.push({start:W,end:J,name:Z.slice(G,J-1)})}else J++;return X}class v{static async parseFile(Z){let J=await Bun.file(Z).text();return Bun.YAML.parse(J)}static parse(Z){return Bun.YAML.parse(Z)}static interpolateVariables(Z,X,J){return U1(Z,{variables:X,storeContext:J})}static mergeConfigs(Z,X){return{...Z,...X,headers:{...Z.headers,...X.headers},params:{...Z.params,...X.params},variables:{...Z.variables,...X.variables},retry:Z.retry||X.retry?{...Z.retry,...X.retry}:void 0}}}var K0=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],U0=["basic","bearer","digest","ntlm","oauth2"],B0=["sequential","parallel"],O0=["json","pretty","raw"],_0=["minimal","standard","detailed"],M0=["==","!=",">","<",">=","<=","contains","matches","exists","not-exists"],u9=["none","all","failing"],l9=["terminal","json","markdown"],S3={htpp:"http",htps:"https",htp:"http","http:/":"http://","https:/":"https://",locahost:"localhost",localhsot:"localhost",loaclhost:"localhost",localost:"localhost","127.0.0.0":"127.0.0.1"},E3={"content-type":"Content-Type","content-length":"Content-Length","content-encoding":"Content-Encoding","content-language":"Content-Language","content-disposition":"Content-Disposition",accept:"Accept","accept-encoding":"Accept-Encoding","accept-language":"Accept-Language","accept-charset":"Accept-Charset",authorization:"Authorization","cache-control":"Cache-Control",connection:"Connection",cookie:"Cookie","set-cookie":"Set-Cookie",host:"Host",origin:"Origin",referer:"Referer","user-agent":"User-Agent","x-requested-with":"X-Requested-With","x-forwarded-for":"X-Forwarded-For","x-forwarded-proto":"X-Forwarded-Proto","x-api-key":"X-API-Key","x-auth-token":"X-Auth-Token","x-csrf-token":"X-CSRF-Token","x-request-id":"X-Request-ID","x-correlation-id":"X-Correlation-ID",etag:"ETag","if-match":"If-Match","if-none-match":"If-None-Match","if-modified-since":"If-Modified-Since","if-unmodified-since":"If-Unmodified-Since","last-modified":"Last-Modified",location:"Location",pragma:"Pragma","proxy-authorization":"Proxy-Authorization",range:"Range","content-range":"Content-Range",te:"TE",trailer:"Trailer","transfer-encoding":"Transfer-Encoding",upgrade:"Upgrade",vary:"Vary",via:"Via",warning:"Warning","www-authenticate":"WWW-Authenticate","access-control-allow-origin":"Access-Control-Allow-Origin","access-control-allow-methods":"Access-Control-Allow-Methods","access-control-allow-headers":"Access-Control-Allow-Headers","access-control-allow-credentials":"Access-Control-Allow-Credentials","access-control-expose-headers":"Access-Control-Expose-Headers","access-control-max-age":"Access-Control-Max-Age","strict-transport-security":"Strict-Transport-Security","x-content-type-options":"X-Content-Type-Options","x-frame-options":"X-Frame-Options","x-xss-protection":"X-XSS-Protection"},A3=["name","url","method","headers","params","body","formData","timeout","followRedirects","maxRedirects","auth","proxy","insecure","ssl","output","http2","retry","variables","store","when","expect","snapshot","diff","sourceOutputConfig","sourceFile"],V3=["execution","maxConcurrency","continueOnError","dryRun","http2","connectionPool","ci","ssl","watch","profile","snapshot","diff","variables","output","defaults"],P3=["name","description","variables","defaults","requests"],n9=[/^(password|passwd|pwd|secret|api[_-]?key|apikey|token|auth|credential|private[_-]?key)$/i,/Bearer\s+[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+/i,/^[A-Fa-f0-9]{32,}$/,/^sk[-_]live[-_]/i,/^AKIA[0-9A-Z]{16}$/i];class D0{issues=[];currentFile="";definedVariables=new Set;storedVariables=new Set;requestNames=new Set;async run(Z){let X=this.parseArgs(Z),J=Z.filter((Q)=>!Q.startsWith("-"));if(J.length===0)J.push("*.yaml","*.yml");console.log(),console.log(F("curl-runner validate","bright")),console.log();let W=await this.findYamlFiles(J);if(W.length===0){console.log(F("No YAML files found","yellow"));return}console.log(`${F("Files:","cyan")} ${W.length} found`),console.log();let $=0,G=0,Y=0;for(let Q of W){let z=await this.validateFile(Q,X),H=z.issues.filter((O)=>O.severity==="error"),K=z.issues.filter((O)=>O.severity==="warning"),B=z.issues.filter((O)=>O.severity==="info");if(!z.valid||X.strict&&K.length>0){Y++,$+=z.issues.length,console.log(`${F("\u2717","red")} ${Q}`);for(let D of z.issues){let M=D.severity==="error"?F("\u25CF","red"):D.severity==="warning"?F("\u25CF","yellow"):F("\u25CF","blue");if(console.log(` ${M} ${D.path}: ${D.message}`),D.fix&&!X.fix)console.log(` ${F("fix:","cyan")} ${D.fix.description}`)}if(X.fix&&z.fixedContent){await Bun.write(Q,z.fixedContent);let D=z.issues.filter((M)=>M.fix).length;G+=D,console.log(` ${F("\u2713","green")} Fixed ${D} issue(s)`)}let O=[];if(H.length>0)O.push(`${H.length} error(s)`);if(K.length>0)O.push(`${K.length} warning(s)`);if(B.length>0)O.push(`${B.length} info`);if(O.length>0)console.log(` ${F("\u2192","dim")} ${O.join(", ")}`);console.log()}else if(K.length>0||B.length>0){$+=z.issues.length,console.log(`${F("\u2713","green")} ${Q}`);for(let D of z.issues){let M=D.severity==="warning"?F("\u25CF","yellow"):F("\u25CF","blue");if(console.log(` ${M} ${D.path}: ${D.message}`),D.fix&&!X.fix)console.log(` ${F("fix:","cyan")} ${D.fix.description}`)}if(X.fix&&z.fixedContent){await Bun.write(Q,z.fixedContent);let D=z.issues.filter((M)=>M.fix).length;G+=D,console.log(` ${F("\u2713","green")} Fixed ${D} issue(s)`)}let O=[];if(K.length>0)O.push(`${K.length} warning(s)`);if(B.length>0)O.push(`${B.length} info`);if(O.length>0)console.log(` ${F("\u2192","dim")} ${O.join(", ")}`);console.log()}else if(!X.quiet)console.log(`${F("\u2713","green")} ${Q}`)}if(console.log(),Y===0)console.log(F("All files valid!","green"));else{if(console.log(`${F("Summary:","cyan")} ${Y} file(s) with ${$} issue(s)`),X.fix)console.log(`${F("Fixed:","green")} ${G} issue(s)`);process.exit(1)}}parseArgs(Z){let X={};for(let J of Z)if(J==="--fix"||J==="-f")X.fix=!0;else if(J==="--quiet"||J==="-q")X.quiet=!0;else if(J==="--strict"||J==="-s")X.strict=!0;return X}async findYamlFiles(Z){let X=new Set,J=await import("fs/promises");for(let W of Z)try{let $=await J.stat(W);if($.isDirectory()){let G=new c9(`${W}/**/*.{yaml,yml}`);for await(let Y of G.scan("."))X.add(Y)}else if($.isFile()&&(W.endsWith(".yaml")||W.endsWith(".yml")))X.add(W)}catch{let $=W.startsWith("/"),G=new c9($?W.slice(1):W),Y=$?"/":".";for await(let Q of G.scan(Y)){let z=$?`/${Q}`:Q;if(z.endsWith(".yaml")||z.endsWith(".yml"))X.add(z)}}return Array.from(X).sort()}async validateFile(Z,X){this.issues=[],this.currentFile=Z,this.definedVariables=new Set,this.storedVariables=new Set,this.requestNames=new Set;let J;try{J=await v.parseFile(Z)}catch(G){let Y=G instanceof Error?G.message:String(G);return this.addIssue("","error",`Failed to parse YAML: ${Y}`),{file:Z,valid:!1,issues:this.issues}}if(this.collectDefinedVariables(J),this.validateYamlStructure(J),J.global)this.validateGlobalConfig(J.global,"global");if(J.collection)this.validateCollection(J.collection,"collection");if(J.request)this.validateRequest(J.request,"request");if(J.requests)if(!Array.isArray(J.requests))this.addIssue("requests","error","Must be an array");else J.requests.forEach((G,Y)=>{this.validateRequest(G,`requests[${Y}]`)});this.checkDuplicateRequestNames();let W;if(X.fix&&this.issues.some((G)=>G.fix)){let G=JSON.parse(JSON.stringify(J));for(let Y of this.issues)if(Y.fix){let Q=Y.fix.apply();this.applyFix(G,Y.path,Q)}W=this.toYaml(G)}let $=this.issues.filter((G)=>G.severity==="error");return{file:Z,valid:$.length===0,issues:this.issues,fixedContent:W}}collectDefinedVariables(Z){if(Z.global?.variables)for(let J of Object.keys(Z.global.variables))this.definedVariables.add(J);if(Z.collection?.variables)for(let J of Object.keys(Z.collection.variables))this.definedVariables.add(J);this.definedVariables.add("env");let X=[...Z.requests||[],...Z.collection?.requests||[],Z.request].filter(Boolean);for(let J of X){if(J.variables)for(let W of Object.keys(J.variables))this.definedVariables.add(W);if(J.store)for(let W of Object.keys(J.store))this.storedVariables.add(W)}}validateYamlStructure(Z){let X="request"in Z,J="requests"in Z,W="collection"in Z;if(!X&&!J&&!W)this.addIssue("","error",'Missing request(s). Must have "request", "requests", or "collection"');if(X&&J)this.addIssue("","warning",'Both "request" and "requests" defined; both will be executed');if(W&&(X||J))this.addIssue("","warning","Collection mixed with request/requests; may cause confusion");let $=["version","global","collection","requests","request"];for(let G of Object.keys(Z))if(!$.includes(G))this.addIssue(G,"warning",`Unknown top-level key "${G}"`,{description:`Remove unknown key "${G}"`,apply:()=>{return}});if(Z.version!==void 0){if(typeof Z.version!=="string")this.addIssue("version","warning","Version should be a string")}}validateGlobalConfig(Z,X){if(this.checkUnknownKeys(Z,V3,X),Z.execution&&!B0.includes(Z.execution)){let W=this.findClosestMatch(Z.execution,[...B0]);this.addIssue(`${X}.execution`,"error",`Invalid execution mode "${Z.execution}". Must be: ${B0.join(", ")}`,W?{description:`Change to "${W}"`,apply:()=>W}:void 0)}if(Z.maxConcurrency!==void 0){if(typeof Z.maxConcurrency!=="number"||Z.maxConcurrency<1)this.addIssue(`${X}.maxConcurrency`,"error","Must be a positive number");if(Z.execution==="sequential")this.addIssue(`${X}.maxConcurrency`,"warning","maxConcurrency has no effect with sequential execution")}let J=Z;if(this.validateBooleanField(J,"continueOnError",X),this.validateBooleanField(J,"dryRun",X),this.validateBooleanField(J,"http2",X),Z.output)this.validateOutputConfig(Z.output,`${X}.output`);if(Z.connectionPool)this.validateConnectionPool(Z.connectionPool,`${X}.connectionPool`);if(Z.ci)this.validateCIConfig(Z.ci,`${X}.ci`);if(Z.ssl)this.validateSSLConfig(Z.ssl,`${X}.ssl`);if(Z.watch)this.validateWatchConfig(Z.watch,`${X}.watch`);if(Z.profile)this.validateProfileConfig(Z.profile,`${X}.profile`);if(Z.snapshot)this.validateSnapshotConfig(Z.snapshot,`${X}.snapshot`);if(Z.diff)this.validateDiffConfig(Z.diff,`${X}.diff`);if(Z.variables)this.validateVariables(Z.variables,`${X}.variables`);if(Z.defaults)this.validateRequestConfig(Z.defaults,`${X}.defaults`,!0)}validateBooleanField(Z,X,J){if(Z[X]!==void 0&&typeof Z[X]!=="boolean"){let W=String(Z[X]).toLowerCase();if(W==="true"||W==="false")this.addIssue(`${J}.${X}`,"warning",`Should be boolean, not string "${Z[X]}"`,{description:`Convert to ${W}`,apply:()=>W==="true"});else this.addIssue(`${J}.${X}`,"error","Must be a boolean")}}validateVariables(Z,X){if(typeof Z!=="object"||Array.isArray(Z)){this.addIssue(X,"error","Must be an object");return}for(let[J,W]of Object.entries(Z)){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))this.addIssue(`${X}.${J}`,"warning","Variable names should use alphanumeric characters and underscores");if(typeof W==="string"&&this.isSensitiveValue(J,W))this.addIssue(`${X}.${J}`,"warning",'Potentially sensitive value hardcoded. Consider using environment variables like "${env.VAR}"')}}validateOutputConfig(Z,X){let J=["verbose","showHeaders","showBody","showMetrics","format","prettyLevel","saveToFile","dryRun"];if(this.checkUnknownKeys(Z,J,X),Z.format&&!O0.includes(Z.format)){let W=this.findClosestMatch(Z.format,[...O0]);this.addIssue(`${X}.format`,"error",`Invalid format "${Z.format}". Must be: ${O0.join(", ")}`,W?{description:`Change to "${W}"`,apply:()=>W}:void 0)}if(Z.prettyLevel&&!_0.includes(Z.prettyLevel)){let W=this.findClosestMatch(Z.prettyLevel,[..._0]);this.addIssue(`${X}.prettyLevel`,"error",`Invalid prettyLevel "${Z.prettyLevel}". Must be: ${_0.join(", ")}`,W?{description:`Change to "${W}"`,apply:()=>W}:void 0)}this.validateBooleanField(Z,"verbose",X),this.validateBooleanField(Z,"showHeaders",X),this.validateBooleanField(Z,"showBody",X),this.validateBooleanField(Z,"showMetrics",X)}validateConnectionPool(Z,X){let J=["enabled","maxStreamsPerHost","keepaliveTime","connectTimeout"];if(this.checkUnknownKeys(Z,J,X),this.validateBooleanField(Z,"enabled",X),Z.maxStreamsPerHost!==void 0){if(typeof Z.maxStreamsPerHost!=="number"||Z.maxStreamsPerHost<1)this.addIssue(`${X}.maxStreamsPerHost`,"error","Must be a positive number");else if(Z.maxStreamsPerHost>100)this.addIssue(`${X}.maxStreamsPerHost`,"warning","Very high stream count may cause issues with some servers")}if(Z.keepaliveTime!==void 0){if(typeof Z.keepaliveTime!=="number"||Z.keepaliveTime<0)this.addIssue(`${X}.keepaliveTime`,"error","Must be a non-negative number")}if(Z.connectTimeout!==void 0){if(typeof Z.connectTimeout!=="number"||Z.connectTimeout<0)this.addIssue(`${X}.connectTimeout`,"error","Must be a non-negative number")}}validateCIConfig(Z,X){let J=["strictExit","failOn","failOnPercentage"];if(this.checkUnknownKeys(Z,J,X),this.validateBooleanField(Z,"strictExit",X),Z.failOn!==void 0&&(typeof Z.failOn!=="number"||Z.failOn<0))this.addIssue(`${X}.failOn`,"error","Must be a non-negative number");if(Z.failOnPercentage!==void 0){if(typeof Z.failOnPercentage!=="number"||Z.failOnPercentage<0||Z.failOnPercentage>100)this.addIssue(`${X}.failOnPercentage`,"error","Must be a number between 0 and 100")}if(Z.failOn!==void 0&&Z.failOnPercentage!==void 0)this.addIssue(X,"info","Both failOn and failOnPercentage are set; failOn takes precedence")}validateSSLConfig(Z,X){let J=["verify","ca","cert","key"];if(this.checkUnknownKeys(Z,J,X),this.validateBooleanField(Z,"verify",X),Z.ca&&typeof Z.ca!=="string")this.addIssue(`${X}.ca`,"error","Must be a string path");if(Z.cert&&typeof Z.cert!=="string")this.addIssue(`${X}.cert`,"error","Must be a string path");if(Z.key&&typeof Z.key!=="string")this.addIssue(`${X}.key`,"error","Must be a string path");if(Z.cert&&!Z.key)this.addIssue(`${X}`,"warning","cert provided without key; mTLS may fail");if(Z.key&&!Z.cert)this.addIssue(`${X}`,"warning","key provided without cert; mTLS may fail");if(Z.ca&&typeof Z.ca==="string")this.validateFilePath(Z.ca,`${X}.ca`);if(Z.cert&&typeof Z.cert==="string")this.validateFilePath(Z.cert,`${X}.cert`);if(Z.key&&typeof Z.key==="string")this.validateFilePath(Z.key,`${X}.key`)}validateFilePath(Z,X){if(Z.includes("${"))return;if(Z.includes(".."))this.addIssue(X,"info",'Path contains ".."; ensure this is intentional')}validateWatchConfig(Z,X){let J=["enabled","debounce","clear"];if(this.checkUnknownKeys(Z,J,X),Z.debounce!==void 0){if(typeof Z.debounce!=="number"||Z.debounce<0)this.addIssue(`${X}.debounce`,"error","Must be a non-negative number")}this.validateBooleanField(Z,"enabled",X),this.validateBooleanField(Z,"clear",X)}validateProfileConfig(Z,X){let J=["iterations","warmup","concurrency","percentiles"];if(this.checkUnknownKeys(Z,J,X),Z.iterations!==void 0){if(typeof Z.iterations!=="number"||Z.iterations<1)this.addIssue(`${X}.iterations`,"error","Must be a positive number");else if(Z.iterations>1e4)this.addIssue(`${X}.iterations`,"warning","Very high iteration count may take long")}if(Z.warmup!==void 0){if(typeof Z.warmup!=="number"||Z.warmup<0)this.addIssue(`${X}.warmup`,"error","Must be a non-negative number")}if(Z.concurrency!==void 0){if(typeof Z.concurrency!=="number"||Z.concurrency<1)this.addIssue(`${X}.concurrency`,"error","Must be a positive number")}}validateSnapshotConfig(Z,X){let J=["updateMode","dir","ignoreFields","ignoreHeaders"];if(this.checkUnknownKeys(Z,J,X),Z.updateMode&&!u9.includes(Z.updateMode))this.addIssue(`${X}.updateMode`,"error",`Invalid updateMode "${Z.updateMode}". Must be: ${u9.join(", ")}`);if(Z.dir&&typeof Z.dir!=="string")this.addIssue(`${X}.dir`,"error","Must be a string")}validateDiffConfig(Z,X){let J=["outputFormat","dir","ignoreFields","ignoreHeaders","baselineUrl"];if(this.checkUnknownKeys(Z,J,X),Z.outputFormat&&!l9.includes(Z.outputFormat))this.addIssue(`${X}.outputFormat`,"error",`Invalid outputFormat "${Z.outputFormat}". Must be: ${l9.join(", ")}`);if(Z.dir&&typeof Z.dir!=="string")this.addIssue(`${X}.dir`,"error","Must be a string")}validateCollection(Z,X){if(this.checkUnknownKeys(Z,P3,X),!Z.name)this.addIssue(`${X}.name`,"warning","Collection name is recommended");if(!Z.requests||!Array.isArray(Z.requests))this.addIssue(`${X}.requests`,"error","Collection must have a requests array");else{if(Z.requests.length===0)this.addIssue(`${X}.requests`,"warning","Collection has no requests");Z.requests.forEach((J,W)=>{this.validateRequest(J,`${X}.requests[${W}]`)})}if(Z.variables)this.validateVariables(Z.variables,`${X}.variables`);if(Z.defaults)this.validateRequestConfig(Z.defaults,`${X}.defaults`,!0)}validateRequest(Z,X){this.validateRequestConfig(Z,X,!1)}validateRequestConfig(Z,X,J){if(this.checkUnknownKeys(Z,A3,X),Z.name)this.requestNames.add(`${X}:${Z.name}`);if(!J&&!Z.url)this.addIssue(`${X}.url`,"error","URL is required");if(Z.url)this.validateURL(Z.url,`${X}.url`);if(Z.method)this.validateMethod(Z.method,`${X}.method`);if(Z.headers)this.validateHeaders(Z.headers,`${X}.headers`,Z);else if(Z.body!==void 0)this.addIssue(`${X}.headers`,"info","Body present but no Content-Type header; consider adding one");if(Z.params){if(typeof Z.params!=="object"||Array.isArray(Z.params))this.addIssue(`${X}.params`,"error","Params must be an object")}if(Z.body!==void 0&&Z.formData!==void 0)this.addIssue(`${X}`,"error",'Cannot use both "body" and "formData"');if(Z.body!==void 0)this.validateBody(Z.body,`${X}.body`,Z);if(Z.formData)this.validateFormData(Z.formData,`${X}.formData`);if(Z.timeout!==void 0)this.validateTimeout(Z.timeout,`${X}.timeout`);if(Z.auth)this.validateAuth(Z.auth,`${X}.auth`);if(Z.ssl)this.validateSSLConfig(Z.ssl,`${X}.ssl`);if(Z.insecure!==void 0){if(this.validateBooleanField(Z,"insecure",X),Z.insecure===!0)this.addIssue(`${X}.insecure`,"warning","Insecure mode disables SSL verification")}if(Z.proxy)this.validateProxyURL(Z.proxy,`${X}.proxy`);if(Z.retry)this.validateRetry(Z.retry,`${X}.retry`,Z.method);if(Z.when)this.validateWhenCondition(Z.when,`${X}.when`);if(Z.expect)this.validateExpect(Z.expect,`${X}.expect`);if(Z.store)this.validateStore(Z.store,`${X}.store`);if(Z.maxRedirects!==void 0){if(typeof Z.maxRedirects!=="number"||Z.maxRedirects<0)this.addIssue(`${X}.maxRedirects`,"error","Must be a non-negative number");else if(Z.maxRedirects>50)this.addIssue(`${X}.maxRedirects`,"warning","Very high redirect limit")}if(this.validateBooleanField(Z,"followRedirects",X),this.validateBooleanField(Z,"http2",X),Z.snapshot!==void 0&&typeof Z.snapshot==="object")this.validateSnapshotConfig(Z.snapshot,`${X}.snapshot`);if(Z.diff!==void 0&&typeof Z.diff==="object")this.validateDiffConfig(Z.diff,`${X}.diff`)}validateURL(Z,X){if(typeof Z!=="string"){this.addIssue(X,"error","URL must be a string");return}let J=Z.includes("${"),W=Z,$=!1;for(let[G,Y]of Object.entries(S3))if(G==="http:/"||G==="https:/"?new RegExp(G.replace("/","\\/")+"(?!\\/)","i").test(Z):Z.toLowerCase().includes(G)){W=Z.replace(new RegExp(G,"gi"),Y),$=!0,this.addIssue(X,"error",`URL contains typo "${G}"`,{description:`Fix to "${Y}"`,apply:()=>W});break}if(!$&&!Z.startsWith("http")&&!J)this.addIssue(X,"warning","URL should start with http:// or https://",{description:"Prepend https://",apply:()=>`https://${Z}`});if(!J&&Z.match(/https?:\/\/[^/]+\/\/+/)){let G=Z.replace(/(https?:\/\/[^/]+)(\/+)/g,"$1/");this.addIssue(X,"warning","URL contains double slashes in path",{description:"Remove extra slashes",apply:()=>G})}if(Z.includes(" ")){let G=Z.replace(/ /g,"%20");this.addIssue(X,"error","URL contains spaces",{description:"Encode spaces as %20",apply:()=>G})}if(Z.startsWith("http://")&&!Z.includes("localhost")&&!Z.includes("127.0.0.1"))this.addIssue(X,"info","Using HTTP instead of HTTPS; consider using HTTPS for security");if(!J){let G=Z.match(/:(\d+)/);if(G){let Y=parseInt(G[1],10);if(Y<1||Y>65535)this.addIssue(X,"error",`Invalid port number ${Y}. Must be 1-65535`)}}}validateProxyURL(Z,X){if(typeof Z!=="string"){this.addIssue(X,"error","Proxy must be a string URL");return}if(!Z.includes("${")&&!Z.match(/^(https?|socks[45]?):\/\//i))this.addIssue(X,"error","Proxy URL should start with http://, https://, socks4://, or socks5://")}validateMethod(Z,X){let J=Z.toUpperCase();if(!K0.includes(J)){let W=this.findClosestMatch(J,[...K0]);this.addIssue(X,"error",`Invalid method "${Z}". Must be: ${K0.join(", ")}`,W?{description:`Change to "${W}"`,apply:()=>W}:void 0)}else if(Z!==J)this.addIssue(X,"warning",`Method should be uppercase: "${J}"`,{description:`Change to "${J}"`,apply:()=>J})}validateHeaders(Z,X,J){if(typeof Z!=="object"||Array.isArray(Z)){this.addIssue(X,"error","Headers must be an object");return}let W=new Map;for(let[Y,Q]of Object.entries(Z)){let z=Y.toLowerCase(),H=E3[z];if(H&&Y!==H)this.addIssue(`${X}.${Y}`,"info",`Header "${Y}" should be "${H}" for consistency`,{description:`Rename to "${H}"`,apply:()=>({rename:H,value:Q})});if(W.has(z))this.addIssue(`${X}.${Y}`,"warning",`Duplicate header "${Y}" (case-insensitive match with "${W.get(z)}")`);if(W.set(z,Y),typeof Q!=="string"&&typeof Q!=="number")this.addIssue(`${X}.${Y}`,"error","Header value must be a string or number");if(typeof Q==="string"&&this.isSensitiveValue(Y,Q))this.addIssue(`${X}.${Y}`,"warning",'Potentially sensitive header value. Consider using variables like "${env.TOKEN}"')}let $=this.getHeaderValue(Z,"content-type");if(J.body!==void 0&&!$)this.addIssue(X,"info","Body present but no Content-Type header; consider adding one");let G=this.getHeaderValue(Z,"authorization");if(J.auth&&G)this.addIssue(X,"warning","Both auth block and Authorization header present; auth block may be ignored")}getHeaderValue(Z,X){let J=X.toLowerCase();for(let[W,$]of Object.entries(Z))if(W.toLowerCase()===J)return $;return}validateBody(Z,X,J){let W=(J.method||"GET").toUpperCase();if(["GET","HEAD","OPTIONS"].includes(W))this.addIssue(X,"warning",`Body with ${W} method may be ignored by some servers`);if(typeof Z==="string"){let $=Z.trim(),Y=(J.headers?this.getHeaderValue(J.headers,"content-type"):null)?.toLowerCase().includes("json");if($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")||Y)try{JSON.parse($)}catch{this.addIssue(X,"warning","Body looks like JSON but is invalid; check syntax")}}}validateFormData(Z,X){if(typeof Z!=="object"||Array.isArray(Z)){this.addIssue(X,"error","FormData must be an object");return}for(let[J,W]of Object.entries(Z))if(typeof W==="object"&&W!==null&&"file"in W){if(typeof W.file!=="string")this.addIssue(`${X}.${J}.file`,"error","File path must be a string");else this.validateFilePath(W.file,`${X}.${J}.file`);if(W.contentType&&typeof W.contentType!=="string")this.addIssue(`${X}.${J}.contentType`,"error","contentType must be a string");if(W.filename&&typeof W.filename!=="string")this.addIssue(`${X}.${J}.filename`,"error","filename must be a string")}}validateTimeout(Z,X){if(typeof Z!=="number"){if(typeof Z==="string"){let J=parseInt(Z,10);if(!Number.isNaN(J)&&J>0){this.addIssue(X,"warning","Timeout should be a number, not string",{description:`Convert to ${J}`,apply:()=>J});return}}this.addIssue(X,"error","Timeout must be a positive number");return}if(Z<=0)this.addIssue(X,"error","Timeout must be a positive number");else if(Z<100)this.addIssue(X,"warning","Very short timeout (<100ms) may cause failures");else if(Z>300000)this.addIssue(X,"warning","Very long timeout (>5min) - is this intentional?")}validateAuth(Z,X){let J=["type","username","password","token"];if(this.checkUnknownKeys(Z,J,X),!Z.type){this.addIssue(`${X}.type`,"error","Auth type is required");return}if(!U0.includes(Z.type)){let W=this.findClosestMatch(Z.type,[...U0]);this.addIssue(`${X}.type`,"error",`Invalid auth type "${Z.type}". Must be: ${U0.join(", ")}`,W?{description:`Change to "${W}"`,apply:()=>W}:void 0);return}if(Z.type==="basic"){if(!Z.username)this.addIssue(`${X}.username`,"error","Username required for basic auth");if(!Z.password)this.addIssue(`${X}.password`,"warning","Password missing for basic auth");if(Z.password&&typeof Z.password==="string"&&!Z.password.includes("${"))this.addIssue(`${X}.password`,"warning",'Hardcoded password. Consider using "${env.PASSWORD}"')}if(Z.type==="bearer"){if(!Z.token)this.addIssue(`${X}.token`,"error","Token required for bearer auth");if(Z.token&&typeof Z.token==="string"&&!Z.token.includes("${"))this.addIssue(`${X}.token`,"warning",'Hardcoded token. Consider using "${env.TOKEN}"')}}validateRetry(Z,X,J){let W=["count","delay","backoff"];if(this.checkUnknownKeys(Z,W,X),Z.count===void 0)this.addIssue(`${X}.count`,"error","Retry count is required");else if(typeof Z.count!=="number"||Z.count<0)this.addIssue(`${X}.count`,"error","Retry count must be a non-negative number");else if(Z.count>10)this.addIssue(`${X}.count`,"warning","High retry count (>10) may cause long delays");if(Z.delay!==void 0){if(typeof Z.delay!=="number"||Z.delay<0)this.addIssue(`${X}.delay`,"error","Retry delay must be a non-negative number")}if(Z.backoff!==void 0){if(typeof Z.backoff!=="number"||Z.backoff<1)this.addIssue(`${X}.backoff`,"error","Retry backoff must be >= 1");else if(Z.backoff>5)this.addIssue(`${X}.backoff`,"warning","High backoff multiplier may cause very long delays")}if(J&&["POST","PATCH"].includes(J.toUpperCase())&&Z.count&&Z.count>0)this.addIssue(X,"info",`Retrying ${J} requests may cause duplicate operations`)}validateWhenCondition(Z,X){if(typeof Z==="string"){this.validateWhenString(Z,X);return}let J="all"in Z&&Z.all,W="any"in Z&&Z.any,$="left"in Z||"operator"in Z||"right"in Z;if(!J&&!W&&!$){this.addIssue(X,"error",'When condition must have "all", "any", or "left"');return}if(J&&W||J&&$||W&&$)this.addIssue(X,"warning","When condition has multiple forms; behavior may be unexpected");if(J)if(!Array.isArray(Z.all))this.addIssue(`${X}.all`,"error","Must be an array");else{if(Z.all.length===0)this.addIssue(`${X}.all`,"warning",'Empty "all" array - condition always true');Z.all.forEach((G,Y)=>{this.validateConditionExpression(G,`${X}.all[${Y}]`)})}if(W)if(!Array.isArray(Z.any))this.addIssue(`${X}.any`,"error","Must be an array");else{if(Z.any.length===0)this.addIssue(`${X}.any`,"warning",'Empty "any" array - condition always false');Z.any.forEach((G,Y)=>{this.validateConditionExpression(G,`${X}.any[${Y}]`)})}if($)this.validateConditionExpression(Z,X)}validateWhenString(Z,X){if(!Z.includes("store.")&&!Z.includes("env."))this.addIssue(X,"warning","When string should reference store.* or env.* values");if(!/\s*(==|!=|>=|<=|>|<|contains|matches|exists|not-exists)\s*/.test(Z))this.addIssue(X,"warning","When string should contain a valid operator (==, !=, >, <, >=, <=, contains, matches, exists)")}validateConditionExpression(Z,X){if(!Z.left)this.addIssue(`${X}.left`,"error","Left operand is required");else if(!Z.left.startsWith("store.")&&!Z.left.startsWith("env."))this.addIssue(`${X}.left`,"warning",'Left operand should start with "store." or "env."');if(!Z.operator)this.addIssue(`${X}.operator`,"error","Operator is required");else if(!M0.includes(Z.operator)){let J=this.findClosestMatch(Z.operator,[...M0]);this.addIssue(`${X}.operator`,"error",`Invalid operator "${Z.operator}". Must be: ${M0.join(", ")}`,J?{description:`Change to "${J}"`,apply:()=>J}:void 0)}if(Z.operator!=="exists"&&Z.operator!=="not-exists"){if(Z.right===void 0)this.addIssue(`${X}.right`,"error","Right operand is required")}}validateExpect(Z,X){let J=["failure","status","headers","body","responseTime"];if(this.checkUnknownKeys(Z,J,X),this.validateBooleanField(Z,"failure",X),Z.status!==void 0)this.validateExpectStatus(Z.status,`${X}.status`);if(Z.headers){if(typeof Z.headers!=="object"||Array.isArray(Z.headers))this.addIssue(`${X}.headers`,"error","Expected headers must be an object")}if(Z.responseTime!==void 0)this.validateResponseTime(Z.responseTime,`${X}.responseTime`)}validateExpectStatus(Z,X){if(Array.isArray(Z)){if(Z.length===0)this.addIssue(X,"warning","Empty status array - no status will match");for(let J of Z)if(typeof J!=="number"||J<100||J>599){this.addIssue(X,"error","Status codes must be numbers between 100-599");break}}else if(typeof Z==="string"){let J=parseInt(Z,10);if(!Number.isNaN(J)&&J>=100&&J<=599)this.addIssue(X,"warning","Status should be a number, not string",{description:`Convert to ${J}`,apply:()=>J});else this.addIssue(X,"error","Status code must be a number between 100-599")}else if(typeof Z!=="number"||Z<100||Z>599)this.addIssue(X,"error","Status code must be a number between 100-599")}validateResponseTime(Z,X){if(typeof Z!=="string"){this.addIssue(X,"error",'Response time must be a string (e.g., "< 1000")');return}let J=/^[<>]=?\s*(\d+|\$\{[^}]+\})(\s*,\s*[<>]=?\s*(\d+|\$\{[^}]+\}))?$/;if(!Z.match(J))this.addIssue(X,"warning",'Response time should be like "< 1000", "> 500, < 2000"')}validateStore(Z,X){if(typeof Z!=="object"||Array.isArray(Z)){this.addIssue(X,"error","Store must be an object");return}for(let[J,W]of Object.entries(Z)){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))this.addIssue(`${X}.${J}`,"warning","Store variable names should use alphanumeric characters and underscores");if(typeof W!=="string")this.addIssue(`${X}.${J}`,"error","Store path must be a string");else{let $=["body","status","headers","responseTime"],G=W.split(".")[0];if(!$.includes(G))this.addIssue(`${X}.${J}`,"warning",`Store path should start with: ${$.join(", ")}`)}}}checkDuplicateRequestNames(){let Z=new Map;for(let X of this.requestNames){let[J,W]=X.split(":");if(!Z.has(W))Z.set(W,[]);Z.get(W).push(J)}for(let[X,J]of Z)if(J.length>1)this.addIssue(J[1],"warning",`Duplicate request name "${X}" (also at ${J[0]})`)}checkUnknownKeys(Z,X,J){for(let W of Object.keys(Z))if(!X.includes(W)){let $=this.findClosestMatch(W,X);this.addIssue(`${J}.${W}`,"warning",$?`Unknown key "${W}" (did you mean "${$}"?)`:`Unknown key "${W}"`,$?{description:`Rename to "${$}"`,apply:()=>({rename:$})}:void 0)}}findClosestMatch(Z,X){let J=Z.toLowerCase(),W=null,$=3;for(let G of X){let Y=G.toLowerCase();if(J===Y)return G;if(Y.startsWith(J)||J.startsWith(Y))return G;let Q=this.editDistance(J,Y);if(Q<$)$=Q,W=G}return W}editDistance(Z,X){if(Z.length===0)return X.length;if(X.length===0)return Z.length;let J=[];for(let W=0;W<=X.length;W++)J[W]=[W];for(let W=0;W<=Z.length;W++)J[0][W]=W;for(let W=1;W<=X.length;W++)for(let $=1;$<=Z.length;$++)if(X.charAt(W-1)===Z.charAt($-1))J[W][$]=J[W-1][$-1];else J[W][$]=Math.min(J[W-1][$-1]+1,J[W][$-1]+1,J[W-1][$]+1);return J[X.length][Z.length]}isSensitiveValue(Z,X){if(X.includes("${"))return!1;for(let J of n9)if(J.test(Z))return!0;for(let J of n9)if(J.test(X))return!0;return!1}addIssue(Z,X,J,W){this.issues.push({file:this.currentFile,path:Z||"(root)",severity:X,message:J,fix:W})}applyFix(Z,X,J){if(!X||X==="(root)")return;let W=X.split(".").flatMap((G)=>{let Y=G.match(/^(\w+)\[(\d+)\]$/);return Y?[Y[1],Number(Y[2])]:G}),$=Z;for(let G=0;G<W.length-1;G++){let Y=W[G];if(typeof $==="object"&&$!==null)$=$[Y]}if(typeof $==="object"&&$!==null){let G=W[W.length-1];if(typeof J==="object"&&J!==null&&"rename"in J){let Y=J,Q=Y.value??$[G];delete $[G],$[Y.rename]=Q}else if(J===void 0)delete $[G];else $[G]=J}}toYaml(Z){return this.serializeYaml(Z)}serializeYaml(Z,X=0){let J=" ".repeat(X);if(Z===null||Z===void 0)return"null";if(typeof Z==="string"){if(Z.includes(`
22
- `)||Z.includes(":")||Z.includes("#")||Z.startsWith("$")||Z.match(/^[0-9]/)||Z===""||Z==="true"||Z==="false"||Z==="null")return JSON.stringify(Z);return Z}if(typeof Z==="number"||typeof Z==="boolean")return String(Z);if(Array.isArray(Z)){if(Z.length===0)return"[]";return Z.map((W)=>{if(typeof W==="object"&&W!==null){let G=this.serializeYaml(W,X+1).split(`
23
- `);return`${J}- ${G[0]}
24
- ${G.slice(1).map((Y)=>`${J} ${Y}`).join(`
25
- `)}`.trimEnd()}return`${J}- ${this.serializeYaml(W,X)}`}).join(`
26
- `)}if(typeof Z==="object"){let W=Object.entries(Z).filter(([,$])=>$!==void 0);if(W.length===0)return"{}";return W.map(([$,G])=>{if(typeof G==="object"&&G!==null&&!Array.isArray(G)){let Y=this.serializeYaml(G,X+1);return`${J}${$}:
27
- ${Y.split(`
28
- `).map((Q)=>` ${Q}`).join(`
29
- `)}`}if(Array.isArray(G))return`${J}${$}:
30
- ${this.serializeYaml(G,X+1)}`;return`${J}${$}: ${this.serializeYaml(G,X)}`}).join(`
31
- `)}return String(Z)}}function o9(){console.log(`
32
- ${F("curl-runner validate","bright")}
33
-
34
- Validate YAML files against curl-runner schema and curl options.
35
- Discovers issues and proposes fixes, or auto-fixes with --fix.
36
-
37
- ${F("USAGE:","yellow")}
38
- curl-runner validate [files...] [options]
39
-
40
- ${F("OPTIONS:","yellow")}
41
- -f, --fix Auto-fix issues where possible
42
- -q, --quiet Only show files with issues
43
- -s, --strict Treat warnings as errors
44
- -h, --help Show this help message
45
-
46
- ${F("ARGUMENTS:","yellow")}
47
- files File paths or glob patterns (default: *.yaml, *.yml)
48
-
49
- ${F("EXAMPLES:","yellow")}
50
- curl-runner validate # Validate all YAML in current dir
51
- curl-runner validate api.yaml # Validate single file
52
- curl-runner validate "tests/**/*.yaml" # Validate with glob pattern
53
- curl-runner validate --fix # Validate and auto-fix issues
54
- curl-runner validate -fq # Fix quietly (only show errors)
55
- curl-runner validate --strict # Fail on warnings too
56
-
57
- ${F("VALIDATION CATEGORIES:","yellow")}
58
-
59
- ${F("Structure","cyan")}
60
- \u2022 YAML syntax and parsing
61
- \u2022 Required fields (url, auth.type, etc.)
62
- \u2022 Unknown/misspelled keys with suggestions
63
- \u2022 Duplicate request names
64
-
65
- ${F("URLs","cyan")}
66
- \u2022 Valid URL syntax
67
- \u2022 Common typos (htpp, localhsot, etc.)
68
- \u2022 Double slashes in paths
69
- \u2022 Missing protocol (http/https)
70
- \u2022 Valid port numbers (1-65535)
71
- \u2022 Spaces in URLs
72
-
73
- ${F("HTTP","cyan")}
74
- \u2022 Valid methods (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS)
75
- \u2022 Method casing (lowercase \u2192 UPPERCASE)
76
- \u2022 Headers casing (content-type \u2192 Content-Type)
77
- \u2022 Content-Type consistency with body
78
- \u2022 Duplicate headers
79
-
80
- ${F("Auth & Security","cyan")}
81
- \u2022 Valid auth types (basic, bearer)
82
- \u2022 Required auth fields (username, password, token)
83
- \u2022 Hardcoded credentials warning
84
- \u2022 Insecure mode warnings
85
- \u2022 HTTP vs HTTPS warnings
86
-
87
- ${F("Configuration","cyan")}
88
- \u2022 Boolean string values ("true" \u2192 true)
89
- \u2022 Numeric string values
90
- \u2022 Valid execution modes
91
- \u2022 Valid output formats
92
- \u2022 SSL certificate consistency
93
-
94
- ${F("Timeouts & Retries","cyan")}
95
- \u2022 Positive timeout values
96
- \u2022 Reasonable timeout ranges
97
- \u2022 Retry count limits
98
- \u2022 Non-idempotent retry warnings
99
-
100
- ${F("Conditions & Expectations","cyan")}
101
- \u2022 When condition operators
102
- \u2022 Store path references
103
- \u2022 Status code ranges (100-599)
104
- \u2022 Response time format
105
-
106
- ${F("AUTO-FIXABLE ISSUES:","yellow")}
107
- \u2022 Lowercase HTTP methods \u2192 UPPERCASE
108
- \u2022 Missing https:// prefix on URLs
109
- \u2022 URL typos (htpp \u2192 http, localhsot \u2192 localhost)
110
- \u2022 Double slashes in URL paths
111
- \u2022 Spaces in URLs (\u2192 %20)
112
- \u2022 Header casing (content-type \u2192 Content-Type)
113
- \u2022 Boolean strings ("true" \u2192 true)
114
- \u2022 Numeric strings (timeout: "5000" \u2192 5000)
115
- \u2022 Status code strings ("200" \u2192 200)
116
- \u2022 Execution mode typos
117
- \u2022 Unknown keys (with suggestions)
118
- `)}function F0(Z){let X=[],J=Z.split(`
119
- `),W=0;while(W<J.length){let $=J[W].trim();if(!$||$.startsWith("#")||$.startsWith("//")){W++;continue}let G=k3($);if(G>=0){let Y=$.slice(G);while(Y.endsWith("\\")&&W+1<J.length)Y=Y.slice(0,-1),W++,Y+=` ${J[W].trim()}`;let Q=C3(Y);if(Q>0)Y=Y.slice(0,Q).trim();if(Y=Y.replace(/;\s*$/,"").trim(),Y.length>4)X.push(Y)}W++}return X}function k3(Z){if(Z.startsWith("curl ")||Z==="curl")return 0;let X=[/(?:^|&&\s*|;\s*|\|\|\s*|\$\(\s*|`\s*)curl\s/];for(let J of X){let W=J.exec(Z);if(W){let $=Z.indexOf("curl",W.index);if($>=0)return $}}return-1}function C3(Z){let X=!1,J=!1;for(let W=0;W<Z.length;W++){let $=Z[W];if($==="\\"&&!X){W++;continue}if($==="'"&&!J){X=!X;continue}if($==='"'&&!X){J=!J;continue}if($==="|"&&!X&&!J)return W}return-1}function T0(Z){let X=["curl"];if(Z.method!=="GET"||Z.body||Z.formData)X.push(`-X ${Z.method}`);for(let[W,$]of Object.entries(Z.headers))X.push(`-H ${x(`${W}: ${$}`)}`);if(Z.auth){if(Z.auth.type==="basic")X.push(`-u ${x(`${Z.auth.username||""}:${Z.auth.password||""}`)}`);else if(Z.auth.type==="bearer")X.push(`-H ${x(`Authorization: Bearer ${Z.auth.token||""}`)}`)}if(Z.formData)for(let[W,$]of Object.entries(Z.formData))if(typeof $==="string")X.push(`--form-string ${x(`${W}=${$}`)}`);else{let G=`@${$.file}`;if($.filename)G+=`;filename=${$.filename}`;if($.contentType)G+=`;type=${$.contentType}`;X.push(`-F ${x(`${W}=${G}`)}`)}else if(Z.body)if(Z.body.type==="json"){if(X.push(`-d ${x(JSON.stringify(Z.body.content))}`),!Z.headers["Content-Type"])X.push(`-H ${x("Content-Type: application/json")}`)}else if(Z.body.type==="urlencoded")X.push(`--data-urlencode ${x(String(Z.body.content))}`);else if(Z.body.type==="binary")X.push(`--data-binary ${x(String(Z.body.content))}`);else X.push(`-d ${x(String(Z.body.content))}`);if(Z.timeout!==void 0)X.push(`--max-time ${Math.ceil(Z.timeout/1000)}`);if(Z.followRedirects)X.push("-L");if(Z.maxRedirects!==void 0)X.push(`--max-redirs ${Z.maxRedirects}`);if(Z.proxy)X.push(`-x ${x(Z.proxy)}`);if(Z.insecure)X.push("-k");if(Z.http2)X.push("--http2");if(Z.output)X.push(`-o ${x(Z.output)}`);if(Z.ssl){if(Z.ssl.ca)X.push(`--cacert ${x(Z.ssl.ca)}`);if(Z.ssl.cert)X.push(`--cert ${x(Z.ssl.cert)}`);if(Z.ssl.key)X.push(`--key ${x(Z.ssl.key)}`)}let J=Z.url;if(Z.params&&Object.keys(Z.params).length>0){let W=new URLSearchParams(Z.params).toString();J+=(J.includes("?")?"&":"?")+W}return X.push(x(J)),X.join(" \\\n ")}function x(Z){if(Z.includes("'"))return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\$/g,"\\$").replace(/`/g,"\\`")}"`;if(/[^a-zA-Z0-9_./:@=,+%-]/.test(Z))return`'${Z}'`;return Z}function O1(Z){let X=[],J="",W=0,$=Z.length;while(W<$){let G=Z[W];if(G==="\\"&&W+1<$&&(Z[W+1]===`
120
- `||Z[W+1]==="\r")){if(W+=2,W<$&&Z[W]===`
121
- `)W++;while(W<$&&(Z[W]===" "||Z[W]==="\t"))W++;continue}if(G===" "||G==="\t"||G===`
122
- `||G==="\r"){if(J.length>0)X.push(J),J="";W++;continue}if(G==="'"){W++;while(W<$&&Z[W]!=="'")J+=Z[W],W++;if(W<$)W++;continue}if(G==='"'){W++;while(W<$&&Z[W]!=='"'){if(Z[W]==="\\"&&W+1<$){let Y=Z[W+1];if(Y==='"'||Y==="\\"||Y==="$"||Y==="`"||Y===`
123
- `){if(Y===`
124
- `){W+=2;continue}J+=Y,W+=2;continue}}J+=Z[W],W++}if(W<$)W++;continue}if(G==="\\"&&W+1<$){J+=Z[W+1],W+=2;continue}J+=G,W++}if(J.length>0)X.push(J);return X}var N0=new Set(["-X","--request","-H","--header","-d","--data","--data-raw","--data-binary","--data-ascii","--data-urlencode","-F","--form","--form-string","-u","--user","-o","--output","-x","--proxy","--max-time","-m","--max-redirs","--cacert","--cert","--key","-b","--cookie","-c","--cookie-jar","-A","--user-agent","-e","--referer","--connect-timeout","--retry","--retry-delay","-w","--write-out","--resolve","--interface","--local-port","--limit-rate","--ciphers","--proto","--tlsv1.2","--tlsv1.3"]),i9=new Set(["-G","--get","-I","--head","-L","--location","-k","--insecure","-s","--silent","-S","--show-error","-v","--verbose","--compressed","--http2","--http2-prior-knowledge","--http1.1","-N","--no-buffer","--raw","-f","--fail","--fail-early","--globoff","-#","--progress-bar","--tr-encoding","--tcp-nodelay","--tcp-fastopen"]);function k1(Z){let X=O1(Z.trim());return a9(X)}function a9(Z){let X={url:"",headers:[],unsupportedFlags:[]},J=[],W=[],$=[],G=[],Y=[],Q=[],z=0;if(Z.length>0&&Z[0]==="curl")z=1;while(z<Z.length){let H=Z[z];if(!H.startsWith("-")){if(!X.url)X.url=H;z++;continue}if(H.startsWith("-")&&!H.startsWith("--")&&H.length>2){let K=`-${H[1]}`;if(N0.has(K)){let O=H.slice(2);z=P1(K,O,Z,z,X,J,W,$,G,Y,Q);continue}let B=!0;for(let O=1;O<H.length;O++){let D=`-${H[O]}`;if(!i9.has(D)){B=!1;break}}if(B){for(let O=1;O<H.length;O++)z=P1(`-${H[O]}`,void 0,Z,z,X,J,W,$,G,Y,Q);z++;continue}}if(N0.has(H)){let K=Z[z+1];z=P1(H,K,Z,z,X,J,W,$,G,Y,Q);continue}if(i9.has(H)){z=P1(H,void 0,Z,z,X,J,W,$,G,Y,Q);continue}if(H.startsWith("-")){let K=Z[z+1];if(K&&!K.startsWith("-"))X.unsupportedFlags.push({flag:H,value:K}),z+=2;else X.unsupportedFlags.push({flag:H}),z++;continue}z++}if(J.length>0)X.data=J;if(W.length>0)X.dataRaw=W;if($.length>0)X.dataBinary=$;if(G.length>0)X.dataUrlencode=G;if(Y.length>0)X.form=Y;if(Q.length>0)X.formString=Q;return X}function P1(Z,X,J,W,$,G,Y,Q,z,H,K){switch(Z){case"-X":case"--request":return $.method=X?.toUpperCase(),W+2;case"-H":case"--header":{if(X){let B=X.indexOf(":");if(B>0)$.headers.push({key:X.slice(0,B).trim(),value:X.slice(B+1).trim()})}return W+2}case"-d":case"--data":case"--data-ascii":if(X!==void 0)G.push(X);return W+2;case"--data-raw":if(X!==void 0)Y.push(X);return W+2;case"--data-binary":if(X!==void 0)Q.push(X);return W+2;case"--data-urlencode":if(X!==void 0)z.push(X);return W+2;case"-F":case"--form":if(X!==void 0)H.push(X);return W+2;case"--form-string":if(X!==void 0)K.push(X);return W+2;case"-u":case"--user":return $.user=X,W+2;case"-o":case"--output":return $.output=X,W+2;case"-x":case"--proxy":return $.proxy=X,W+2;case"--max-time":case"-m":if(X)$.maxTime=Number(X);return W+2;case"--max-redirs":if(X)$.maxRedirs=Number(X);return W+2;case"--cacert":return $.cacert=X,W+2;case"--cert":return $.cert=X,W+2;case"--key":return $.key=X,W+2;case"-b":case"--cookie":return $.cookie=X,W+2;case"-c":case"--cookie-jar":return $.cookieJar=X,W+2;case"-A":case"--user-agent":return $.userAgent=X,W+2;case"-e":case"--referer":return $.referer=X,W+2;case"-G":case"--get":return $.get=!0,W+1;case"-I":case"--head":return $.head=!0,W+1;case"-L":case"--location":return $.location=!0,W+1;case"-k":case"--insecure":return $.insecure=!0,W+1;case"--compressed":return $.compressed=!0,W+1;case"--http2":return $.http2=!0,W+1;case"-s":case"--silent":return $.silent=!0,W+1;case"-v":case"--verbose":return $.verbose=!0,W+1;default:if(N0.has(Z))return W+2;return W+1}}function C1(Z){let X=[],{url:J,params:W}=w3(Z.url),$=q3(Z),G=b3(Z,$),{body:Y,formData:Q}=v3(Z,X),z=h3(Z,Y,Q),H=g3(Z);for(let B of Z.unsupportedFlags)X.push(`Unsupported curl flag: ${B.flag}${B.value?` ${B.value}`:""}`);if(Z.compressed)X.push("Flag --compressed has no YAML equivalent; curl handles decompression natively");if(Z.cookie)X.push(`Cookie flag (-b ${Z.cookie}) stored as header; manual review recommended`),$.Cookie=Z.cookie;if(Z.cookieJar)X.push(`Cookie jar flag (-c ${Z.cookieJar}) has no YAML equivalent`);if(Z.userAgent&&!$["User-Agent"])$["User-Agent"]=Z.userAgent;if(Z.referer&&!$.Referer)$.Referer=Z.referer;let K={method:z,url:J,headers:$,metadata:{source:"curl",warnings:X,unsupportedFlags:Z.unsupportedFlags.length>0?Z.unsupportedFlags:void 0}};if(Object.keys(W).length>0)K.params=W;if(Y)K.body=Y;if(Q)K.formData=Q;if(G)K.auth=G;if(Z.insecure)K.insecure=!0;if(Z.location)K.followRedirects=!0;if(Z.maxRedirs!==void 0)K.maxRedirects=Z.maxRedirs;if(Z.maxTime!==void 0)K.timeout=Z.maxTime*1000;if(Z.proxy)K.proxy=Z.proxy;if(Z.output)K.output=Z.output;if(Z.http2)K.http2=!0;if(H)K.ssl=H;return K}function w3(Z){let X={};if(!Z)return{url:"",params:X};let J=Z.indexOf("?");if(J===-1)return{url:Z,params:X};let W=Z.slice(0,J),$=Z.slice(J+1);for(let G of $.split("&")){let Y=G.indexOf("=");if(Y>0){let Q=decodeURIComponent(G.slice(0,Y)),z=decodeURIComponent(G.slice(Y+1));X[Q]=z}else if(G.length>0)X[decodeURIComponent(G)]=""}return{url:W,params:X}}function q3(Z){let X={};for(let J of Z.headers){if(J.key.toLowerCase()==="authorization")continue;X[x3(J.key)]=J.value}return X}function x3(Z){return Z.split("-").map((X)=>X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()).join("-")}function b3(Z,X){if(Z.user){let J=Z.user.indexOf(":");if(J>0)return{type:"basic",username:Z.user.slice(0,J),password:Z.user.slice(J+1)};return{type:"basic",username:Z.user,password:""}}for(let J of Z.headers)if(J.key.toLowerCase()==="authorization"){let W=J.value.trim();if(W.toLowerCase().startsWith("bearer "))return{type:"bearer",token:W.slice(7).trim()};if(W.toLowerCase().startsWith("basic "))try{let $=atob(W.slice(6).trim()),G=$.indexOf(":");if(G>0)return{type:"basic",username:$.slice(0,G),password:$.slice(G+1)}}catch{X.Authorization=W}else X.Authorization=W}return}function v3(Z,X){if(Z.form&&Z.form.length>0){let W={};for(let $ of Z.form)y3($,W);if(Z.formString)for(let $ of Z.formString){let G=$.indexOf("=");if(G>0)W[$.slice(0,G)]=$.slice(G+1)}return{formData:W}}if(Z.dataUrlencode&&Z.dataUrlencode.length>0)return{body:{type:"urlencoded",content:Z.dataUrlencode.map(($)=>encodeURIComponent($)).join("&")}};if(Z.dataBinary&&Z.dataBinary.length>0){if(Z.dataBinary[0].startsWith("@"))return{body:{type:"binary",content:Z.dataBinary[0]}};return{body:{type:"raw",content:Z.dataBinary.join("")}}}let J=[...Z.data||[],...Z.dataRaw||[]];if(J.length>0){let W=J.join("&");try{return{body:{type:"json",content:JSON.parse(W)}}}catch{if(m3(W))return{body:{type:"urlencoded",content:W}};return{body:{type:"raw",content:W}}}}return{}}function y3(Z,X){let J=Z.indexOf("=");if(J<=0)return;let W=Z.slice(0,J),$=Z.slice(J+1);if($.startsWith("@")){let G=$.slice(1).split(";"),Y={file:G[0]};for(let Q=1;Q<G.length;Q++){let[z,H]=G[Q].split("=");if(z==="filename")Y.filename=H;else if(z==="type")Y.contentType=H}X[W]=Y}else X[W]=$}function m3(Z){return/^[^=&]+=[^&]*(&[^=&]+=[^&]*)*$/.test(Z)}function h3(Z,X,J){if(Z.method)return Z.method;if(Z.head)return"HEAD";if(Z.get)return"GET";if(X||J)return"POST";return"GET"}function g3(Z){if(!Z.cacert&&!Z.cert&&!Z.key)return;let X={};if(Z.cacert)X.ca=Z.cacert;if(Z.cert)X.cert=Z.cert;if(Z.key)X.key=Z.key;return X}function w1(Z,X){let J=[],W=X?.pretty??!0;if((X?.lossReport??!0)&&Z.metadata.warnings.length>0){for(let G of Z.metadata.warnings)J.push(`# Warning: ${G}`);J.push("")}if(J.push("request:"),Z.name)J.push(` name: ${E(Z.name)}`);if(J.push(` method: ${Z.method}`),J.push(` url: ${E(Z.url)}`),Z.params&&Object.keys(Z.params).length>0){J.push(" params:");for(let[G,Y]of Q1(Z.params))J.push(` ${d(G)}: ${E(Y)}`)}if(Object.keys(Z.headers).length>0){J.push(" headers:");for(let[G,Y]of Q1(Z.headers))J.push(` ${d(G)}: ${E(Y)}`)}if(Z.auth){if(J.push(" auth:"),J.push(` type: ${Z.auth.type}`),Z.auth.type==="basic")J.push(` username: ${E(Z.auth.username||"")}`),J.push(` password: ${E(Z.auth.password||"")}`);else if(Z.auth.type==="bearer")J.push(` token: ${E(Z.auth.token||"")}`)}if(Z.body)if(J.push(" body:"),Z.body.type==="json")if(W){let G=r9(Z.body.content,4);J.push(...G)}else J.push(` json: ${JSON.stringify(Z.body.content)}`);else if(Z.body.type==="urlencoded")J.push(` form: ${E(String(Z.body.content))}`);else if(Z.body.type==="binary")J.push(` binary: ${E(String(Z.body.content))}`);else J.push(` raw: ${E(String(Z.body.content))}`);if(Z.formData&&Object.keys(Z.formData).length>0){J.push(" formData:");for(let[G,Y]of Q1(Z.formData))if(typeof Y==="string")J.push(` ${d(G)}: ${E(Y)}`);else{if(J.push(` ${d(G)}:`),J.push(` file: ${E(Y.file)}`),Y.filename)J.push(` filename: ${E(Y.filename)}`);if(Y.contentType)J.push(` contentType: ${E(Y.contentType)}`)}}if(Z.timeout!==void 0)J.push(` timeout: ${Z.timeout}`);if(Z.followRedirects)J.push(" followRedirects: true");if(Z.maxRedirects!==void 0)J.push(` maxRedirects: ${Z.maxRedirects}`);if(Z.proxy)J.push(` proxy: ${E(Z.proxy)}`);if(Z.insecure)J.push(" insecure: true");if(Z.http2)J.push(" http2: true");if(Z.output)J.push(` output: ${E(Z.output)}`);if(Z.ssl){if(J.push(" ssl:"),Z.ssl.ca)J.push(` ca: ${E(Z.ssl.ca)}`);if(Z.ssl.cert)J.push(` cert: ${E(Z.ssl.cert)}`);if(Z.ssl.key)J.push(` key: ${E(Z.ssl.key)}`)}return`${J.join(`
125
- `)}
126
- `}function L0(Z,X){let J=[],W=X?.pretty??!0;if(X?.lossReport??!0){let G=Z.flatMap((Y)=>Y.metadata.warnings);if(G.length>0){for(let Y of G)J.push(`# Warning: ${Y}`);J.push("")}}J.push("requests:");for(let G=0;G<Z.length;G++){let Y=Z[G];if(G>0)J.push("");if(Y.name)J.push(` - name: ${E(Y.name)}`);else J.push(` - name: request_${G+1}`);if(J.push(` method: ${Y.method}`),J.push(` url: ${E(Y.url)}`),Y.params&&Object.keys(Y.params).length>0){J.push(" params:");for(let[Q,z]of Q1(Y.params))J.push(` ${d(Q)}: ${E(z)}`)}if(Object.keys(Y.headers).length>0){J.push(" headers:");for(let[Q,z]of Q1(Y.headers))J.push(` ${d(Q)}: ${E(z)}`)}if(Y.auth){if(J.push(" auth:"),J.push(` type: ${Y.auth.type}`),Y.auth.type==="basic")J.push(` username: ${E(Y.auth.username||"")}`),J.push(` password: ${E(Y.auth.password||"")}`);else if(Y.auth.type==="bearer")J.push(` token: ${E(Y.auth.token||"")}`)}if(Y.body)if(J.push(" body:"),Y.body.type==="json")if(W){let Q=r9(Y.body.content,6);J.push(...Q)}else J.push(` json: ${JSON.stringify(Y.body.content)}`);else if(Y.body.type==="urlencoded")J.push(` form: ${E(String(Y.body.content))}`);else if(Y.body.type==="binary")J.push(` binary: ${E(String(Y.body.content))}`);else J.push(` raw: ${E(String(Y.body.content))}`);if(Y.formData&&Object.keys(Y.formData).length>0){J.push(" formData:");for(let[Q,z]of Q1(Y.formData))if(typeof z==="string")J.push(` ${d(Q)}: ${E(z)}`);else{if(J.push(` ${d(Q)}:`),J.push(` file: ${E(z.file)}`),z.filename)J.push(` filename: ${E(z.filename)}`);if(z.contentType)J.push(` contentType: ${E(z.contentType)}`)}}if(Y.timeout!==void 0)J.push(` timeout: ${Y.timeout}`);if(Y.followRedirects)J.push(" followRedirects: true");if(Y.maxRedirects!==void 0)J.push(` maxRedirects: ${Y.maxRedirects}`);if(Y.proxy)J.push(` proxy: ${E(Y.proxy)}`);if(Y.insecure)J.push(" insecure: true");if(Y.http2)J.push(" http2: true");if(Y.output)J.push(` output: ${E(Y.output)}`);if(Y.ssl){if(J.push(" ssl:"),Y.ssl.ca)J.push(` ca: ${E(Y.ssl.ca)}`);if(Y.ssl.cert)J.push(` cert: ${E(Y.ssl.cert)}`);if(Y.ssl.key)J.push(` key: ${E(Y.ssl.key)}`)}}return`${J.join(`
127
- `)}
128
- `}function r9(Z,X){let J=" ".repeat(X);if(Z===null||Z===void 0)return[`${J}json: null`];if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")return[`${J}json: ${JSON.stringify(Z)}`];if(Array.isArray(Z)){if(Z.length===0)return[`${J}json: []`];if(Z.every((W)=>typeof W!=="object"||W===null))return[`${J}json: [${Z.map((W)=>JSON.stringify(W)).join(", ")}]`];return[`${J}json: ${JSON.stringify(Z)}`]}if(typeof Z==="object"){let W=Z,$=Object.keys(W);if($.length===0)return[`${J}json: {}`];let G=[];G.push(`${J}json:`);for(let Y of $){let Q=W[Y];if(Q===null)G.push(`${J} ${d(Y)}: null`);else if(typeof Q==="object"&&!Array.isArray(Q))G.push(`${J} ${d(Y)}: ${JSON.stringify(Q)}`);else if(Array.isArray(Q))G.push(`${J} ${d(Y)}: ${JSON.stringify(Q)}`);else G.push(`${J} ${d(Y)}: ${d3(Q)}`)}return G}return[`${J}json: ${JSON.stringify(Z)}`]}function E(Z){if(Z==="")return'""';if(f3(Z))return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return Z}function d(Z){if(/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(Z))return Z;return`"${Z.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function d3(Z){if(typeof Z==="string")return E(Z);if(typeof Z==="number"||typeof Z==="boolean")return String(Z);return JSON.stringify(Z)}function f3(Z){if(/[{}[\],&*?|>!%#@`]/.test(Z))return!0;if(/: /.test(Z)||Z.endsWith(":"))return!0;if(Z.startsWith("'")||Z.startsWith('"'))return!0;let X=Z.toLowerCase();if(["true","false","null","yes","no","on","off"].includes(X))return!0;if(/^-?\d+(\.\d+)?$/.test(Z))return!0;if(Z.startsWith(" ")||Z.endsWith(" "))return!0;return!1}function Q1(Z){return Object.entries(Z).sort(([X],[J])=>X.localeCompare(J))}function I0(Z){let X=[],J={};if(Z.headers)for(let[$,G]of Object.entries(Z.headers))J[$]=G;let W={method:Z.method||"GET",url:Z.url,headers:J,metadata:{source:"yaml",warnings:X}};if(Z.name)W.name=Z.name;if(Z.params)W.params={...Z.params};if(Z.auth)W.auth={type:Z.auth.type,username:Z.auth.username,password:Z.auth.password,token:Z.auth.token};if(Z.body!==void 0)if(typeof Z.body==="object"&&Z.body!==null&&!Array.isArray(Z.body)){let $=Z.body;if("json"in $)W.body={type:"json",content:$.json};else if("form"in $)W.body={type:"urlencoded",content:String($.form)};else if("raw"in $)W.body={type:"raw",content:String($.raw)};else if("binary"in $)W.body={type:"binary",content:String($.binary)};else W.body={type:"json",content:Z.body}}else W.body={type:"json",content:Z.body};if(Z.formData){let $={};for(let[G,Y]of Object.entries(Z.formData))if(typeof Y==="object"&&Y!==null&&"file"in Y)$[G]={file:Y.file,filename:Y.filename,contentType:Y.contentType};else $[G]=String(Y);W.formData=$}if(Z.timeout)W.timeout=Z.timeout;if(Z.followRedirects!==void 0)W.followRedirects=Z.followRedirects;if(Z.maxRedirects)W.maxRedirects=Z.maxRedirects;if(Z.proxy)W.proxy=Z.proxy;if(Z.insecure)W.insecure=!0;if(Z.http2)W.http2=!0;if(Z.output)W.output=Z.output;if(Z.ssl){if(W.ssl={},Z.ssl.ca)W.ssl.ca=Z.ssl.ca;if(Z.ssl.cert)W.ssl.cert=Z.ssl.cert;if(Z.ssl.key)W.ssl.key=Z.ssl.key}if(Z.expect)X.push("expect block has no curl equivalent");if(Z.store)X.push("store block has no curl equivalent");if(Z.when)X.push("when condition has no curl equivalent");if(Z.retry)X.push("retry config simplified in curl output");if(Z.snapshot)X.push("snapshot config has no curl equivalent");if(Z.diff)X.push("diff config has no curl equivalent");return W}function j0(Z,X){let J=k1(Z),W=C1(J),G={output:w1(W,{pretty:X?.pretty??!0,lossReport:X?.lossReport??!0}),warnings:W.metadata.warnings};if(X?.debug)G.debug={tokens:O1(Z.trim()),ast:J,ir:W};return G}async function R0(Z,X){let J=await Bun.file(Z).text(),W=F0(J);if(W.length===0)return{output:"",warnings:["No curl commands found in file"]};let $=[],G=[];for(let z=0;z<W.length;z++){let H=k1(W[z]),K=C1(H);K.name=`request_${z+1}`,$.push(K),G.push(...K.metadata.warnings)}if($.length===1){let H={output:w1($[0],{pretty:X?.pretty??!0,lossReport:X?.lossReport??!0}),warnings:G};if(X?.debug)H.debug={ir:$[0]};return H}let Q={output:L0($,{pretty:X?.pretty??!0,lossReport:X?.lossReport??!0}),warnings:G};if(X?.debug)Q.debug={ir:$};return Q}async function S0(Z,X){let J=await Bun.file(Z).text(),W=Bun.YAML.parse(J),$=[];if(W.request)$.push(W.request);if(W.requests)$.push(...W.requests);if(W.collection?.requests)$.push(...W.collection.requests);if($.length===0)return{output:"",warnings:["No requests found in YAML file"]};let G=[],Y=[];for(let z of $){let H=I0(z);G.push(...H.metadata.warnings),Y.push(T0(H))}return{output:Y.join(`
129
-
130
- `),warnings:G}}function E0(Z){if(Z.length<3)return null;let X=Z[1];if(X!=="curl"&&X!=="file"&&X!=="yaml")return null;let J=Z[2],W={};for(let $=3;$<Z.length;$++)switch(Z[$]){case"--output":case"-o":W.output=Z[++$];break;case"--pretty":W.pretty=!0;break;case"--normalize":W.normalize=!0;break;case"--loss-report":W.lossReport=!0;break;case"--batch":W.batch=!0;break;case"--env-detect":W.envDetect=!0;break;case"--debug":W.debug=!0;break}return{subcommand:X,input:J,options:W}}function A0(Z){let X={files:[]};for(let J=0;J<Z.length;J++){let W=Z[J],$=Z[J+1],G=$!==void 0&&!$.startsWith("-");if(W.startsWith("--"))J+=p3(W.slice(2),$,G,X);else if(W.startsWith("-"))J+=c3(W.slice(1),$,G,X);else X.files.push(W)}return X}function p3(Z,X,J,W){switch(Z){case"help":return W.help=!0,0;case"version":return W.version=!0,0;case"all":return W.all=!0,0;case"dry-run":return W.dryRun=!0,0;case"http2":return W.http2=!0,0;case"connection-pool":return W.connectionPool=!0,0;case"quiet":return W.quiet=!0,0;case"show-headers":return W.showHeaders=!0,0;case"show-body":return W.showBody=!0,0;case"show-metrics":return W.showMetrics=!0,0;case"no-retry":return W.noRetry=!0,0;case"watch":return W.watch=!0,0;case"watch-clear":return W.watchClear=!0,0;case"no-watch-clear":return W.watchClear=!1,0;case"profile-histogram":return W.profileHistogram=!0,0;case"snapshot":return W.snapshot=!0,0;case"update-snapshots":return W.snapshotUpdate="all",0;case"update-failing":return W.snapshotUpdate="failing",0;case"ci-snapshot":return W.snapshotCi=!0,0;case"diff":return W.diff=!0,0;case"diff-save":return W.diffSave=!0,0;case"strict-exit":return W.strictExit=!0,0;case"no-redact":return W.noRedact=!0,0}if(!J){if(Z==="verbose")return W.verbose=!0,0;if(Z==="continue-on-error")return W.continueOnError=!0,0;return 0}switch(Z){case"env":return W.env=X,1;case"execution":if(X==="sequential"||X==="parallel")W.execution=X;return 1;case"max-concurrent":{let $=Number.parseInt(X,10);if($>0)W.maxConcurrency=$;return 1}case"max-streams":{let $=Number.parseInt(X,10);if($>0)W.maxStreams=$;return 1}case"keepalive-time":return W.keepaliveTime=Number.parseInt(X,10),1;case"connect-timeout":return W.connectTimeout=Number.parseInt(X,10),1;case"verbose":return W.verbose=X==="true",1;case"output":return W.output=X,1;case"output-format":if(["json","pretty","raw"].includes(X))W.outputFormat=X;return 1;case"pretty-level":if(["minimal","standard","detailed"].includes(X))W.prettyLevel=X;return 1;case"timeout":return W.timeout=Number.parseInt(X,10),1;case"retries":return W.retries=Number.parseInt(X,10),1;case"retry-delay":return W.retryDelay=Number.parseInt(X,10),1;case"continue-on-error":return W.continueOnError=X==="true",1;case"watch-debounce":return W.watchDebounce=Number.parseInt(X,10),1;case"profile":return W.profile=Number.parseInt(X,10),1;case"profile-warmup":return W.profileWarmup=Number.parseInt(X,10),1;case"profile-concurrency":return W.profileConcurrency=Number.parseInt(X,10),1;case"profile-export":return W.profileExport=X,1;case"snapshot-dir":return W.snapshotDir=X,1;case"diff-label":return W.diffLabel=X,1;case"diff-compare":return W.diffCompare=X,1;case"diff-dir":return W.diffDir=X,1;case"diff-output":if(["terminal","json","markdown"].includes(X))W.diffOutput=X;return 1;case"fail-on":return W.failOn=Number.parseInt(X,10),1;case"fail-on-percentage":{let $=Number.parseFloat(X);if($>=0&&$<=100)W.failOnPercentage=$;return 1}default:return 1}}function c3(Z,X,J,W){let $=0;for(let G of Z)switch(G){case"h":W.help=!0;break;case"v":W.verbose=!0;break;case"p":W.execution="parallel";break;case"c":break;case"q":W.quiet=!0;break;case"w":W.watch=!0;break;case"s":W.snapshot=!0;break;case"u":W.snapshotUpdate="all";break;case"d":W.diff=!0;break;case"n":W.dryRun=!0;break;case"o":if(J)W.output=X,$=1;break;case"P":if(J)W.profile=Number.parseInt(X,10),$=1;break;case"e":if(J)W.env=X,$=1;break}return $}function V0(Z){if(Z[0]==="upgrade")return"upgrade";if(Z[0]==="validate")return"validate";if(Z[0]==="convert")return"convert";if(Z[0]==="diff"&&Z.length>=3)return"diff-subcommand";if(Z[0]==="init")return"init";if(Z[0]==="edit")return"edit";return null}function P0(Z){let X={};for(let J=1;J<Z.length;J++){let W=Z[J],$=Z[J+1];if(W==="--wizard"||W==="-w")X.wizard=!0;else if(W==="-o"||W==="--output"){if($&&!$.startsWith("-"))X.outputPath=$,J++}else if(!W.startsWith("-")&&!X.url)X.url=W}return X}function k0(Z){let X={file:""};for(let J=1;J<Z.length;J++){let W=Z[J],$=Z[J+1];if(W==="-o"||W==="--output"){if($&&!$.startsWith("-"))X.outputPath=$,J++}else if(!W.startsWith("-")&&!X.file)X.file=W}return X}function C0(Z){if(Z.help)return"help";if(Z.version)return"version";return null}import{join as q1}from"path";function u3(Z){let X={},J=Z.split(`
131
- `);for(let W of J){let $=W.trim();if(!$||$.startsWith("#"))continue;let G=$.indexOf("=");if(G===-1)continue;let Y=$.slice(0,G).trim(),Q=$.slice(G+1).trim();if(Q.startsWith('"')&&Q.endsWith('"')||Q.startsWith("'")&&Q.endsWith("'"))Q=Q.slice(1,-1);if($.slice(G+1).trim().startsWith('"'))Q=Q.replace(/\\n/g,`
132
- `).replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\\\/g,"\\");if(Y)X[Y]=Q}return X}async function l3(Z){let X=Bun.file(Z);if(!await X.exists())return{};try{let J=await X.text();return u3(J)}catch{return{}}}function n3(Z){return Object.keys(Z).filter((X)=>X.startsWith("SECRET_"))}async function w0(Z=process.cwd(),X){let J=[q1(Z,".env"),q1(Z,".env.local")];if(X)J.push(q1(Z,`.env.${X}`),q1(Z,`.env.${X}.local`));let W={};for(let $ of J){let G=await l3($);W={...W,...G}}return{variables:W,secretKeys:n3(W)}}function q0(){let Z={};return o3(Z),i3(Z),a3(Z),r3(Z),s3(Z),t3(Z),e3(Z),Z2(Z),X2(Z),Z}function o3(Z){if(process.env.CURL_RUNNER_EXECUTION)Z.execution=process.env.CURL_RUNNER_EXECUTION;if(process.env.CURL_RUNNER_CONTINUE_ON_ERROR)Z.continueOnError=process.env.CURL_RUNNER_CONTINUE_ON_ERROR.toLowerCase()==="true";if(process.env.CURL_RUNNER_DRY_RUN)Z.dryRun=process.env.CURL_RUNNER_DRY_RUN.toLowerCase()==="true";if(process.env.CURL_RUNNER_HTTP2)Z.http2=process.env.CURL_RUNNER_HTTP2.toLowerCase()==="true";if(process.env.CURL_RUNNER_MAX_CONCURRENCY){let X=Number.parseInt(process.env.CURL_RUNNER_MAX_CONCURRENCY,10);if(X>0)Z.maxConcurrency=X}}function i3(Z){if(process.env.CURL_RUNNER_CONNECTION_POOL)Z.connectionPool={...Z.connectionPool,enabled:process.env.CURL_RUNNER_CONNECTION_POOL.toLowerCase()==="true"};if(process.env.CURL_RUNNER_MAX_STREAMS_PER_HOST)Z.connectionPool={...Z.connectionPool,maxStreamsPerHost:Number.parseInt(process.env.CURL_RUNNER_MAX_STREAMS_PER_HOST,10)};if(process.env.CURL_RUNNER_KEEPALIVE_TIME)Z.connectionPool={...Z.connectionPool,keepaliveTime:Number.parseInt(process.env.CURL_RUNNER_KEEPALIVE_TIME,10)};if(process.env.CURL_RUNNER_CONNECT_TIMEOUT)Z.connectionPool={...Z.connectionPool,connectTimeout:Number.parseInt(process.env.CURL_RUNNER_CONNECT_TIMEOUT,10)}}function a3(Z){if(process.env.CURL_RUNNER_VERBOSE)Z.output={...Z.output,verbose:process.env.CURL_RUNNER_VERBOSE.toLowerCase()==="true"};if(process.env.CURL_RUNNER_OUTPUT_FORMAT){let X=process.env.CURL_RUNNER_OUTPUT_FORMAT;if(["json","pretty","raw"].includes(X))Z.output={...Z.output,format:X}}if(process.env.CURL_RUNNER_PRETTY_LEVEL){let X=process.env.CURL_RUNNER_PRETTY_LEVEL;if(["minimal","standard","detailed"].includes(X))Z.output={...Z.output,prettyLevel:X}}if(process.env.CURL_RUNNER_OUTPUT_FILE)Z.output={...Z.output,saveToFile:process.env.CURL_RUNNER_OUTPUT_FILE}}function r3(Z){if(process.env.CURL_RUNNER_STRICT_EXIT)Z.ci={...Z.ci,strictExit:process.env.CURL_RUNNER_STRICT_EXIT.toLowerCase()==="true"};if(process.env.CURL_RUNNER_FAIL_ON)Z.ci={...Z.ci,failOn:Number.parseInt(process.env.CURL_RUNNER_FAIL_ON,10)};if(process.env.CURL_RUNNER_FAIL_ON_PERCENTAGE){let X=Number.parseFloat(process.env.CURL_RUNNER_FAIL_ON_PERCENTAGE);if(X>=0&&X<=100)Z.ci={...Z.ci,failOnPercentage:X}}}function s3(Z){if(process.env.CURL_RUNNER_WATCH)Z.watch={...Z.watch,enabled:process.env.CURL_RUNNER_WATCH.toLowerCase()==="true"};if(process.env.CURL_RUNNER_WATCH_DEBOUNCE)Z.watch={...Z.watch,debounce:Number.parseInt(process.env.CURL_RUNNER_WATCH_DEBOUNCE,10)};if(process.env.CURL_RUNNER_WATCH_CLEAR)Z.watch={...Z.watch,clear:process.env.CURL_RUNNER_WATCH_CLEAR.toLowerCase()!=="false"}}function t3(Z){if(process.env.CURL_RUNNER_PROFILE){let X=Number.parseInt(process.env.CURL_RUNNER_PROFILE,10);if(X>0)Z.profile={...Z.profile,iterations:X}}if(process.env.CURL_RUNNER_PROFILE_WARMUP)Z.profile={...Z.profile,iterations:Z.profile?.iterations??10,warmup:Number.parseInt(process.env.CURL_RUNNER_PROFILE_WARMUP,10)};if(process.env.CURL_RUNNER_PROFILE_CONCURRENCY)Z.profile={...Z.profile,iterations:Z.profile?.iterations??10,concurrency:Number.parseInt(process.env.CURL_RUNNER_PROFILE_CONCURRENCY,10)};if(process.env.CURL_RUNNER_PROFILE_HISTOGRAM)Z.profile={...Z.profile,iterations:Z.profile?.iterations??10,histogram:process.env.CURL_RUNNER_PROFILE_HISTOGRAM.toLowerCase()==="true"};if(process.env.CURL_RUNNER_PROFILE_EXPORT)Z.profile={...Z.profile,iterations:Z.profile?.iterations??10,exportFile:process.env.CURL_RUNNER_PROFILE_EXPORT}}function e3(Z){if(process.env.CURL_RUNNER_SNAPSHOT)Z.snapshot={...Z.snapshot,enabled:process.env.CURL_RUNNER_SNAPSHOT.toLowerCase()==="true"};if(process.env.CURL_RUNNER_SNAPSHOT_UPDATE){let X=process.env.CURL_RUNNER_SNAPSHOT_UPDATE.toLowerCase();if(["none","all","failing"].includes(X))Z.snapshot={...Z.snapshot,updateMode:X}}if(process.env.CURL_RUNNER_SNAPSHOT_DIR)Z.snapshot={...Z.snapshot,dir:process.env.CURL_RUNNER_SNAPSHOT_DIR};if(process.env.CURL_RUNNER_SNAPSHOT_CI)Z.snapshot={...Z.snapshot,ci:process.env.CURL_RUNNER_SNAPSHOT_CI.toLowerCase()==="true"}}function Z2(Z){if(process.env.CURL_RUNNER_DIFF)Z.diff={...Z.diff,enabled:process.env.CURL_RUNNER_DIFF.toLowerCase()==="true"};if(process.env.CURL_RUNNER_DIFF_SAVE)Z.diff={...Z.diff,save:process.env.CURL_RUNNER_DIFF_SAVE.toLowerCase()==="true"};if(process.env.CURL_RUNNER_DIFF_LABEL)Z.diff={...Z.diff,label:process.env.CURL_RUNNER_DIFF_LABEL};if(process.env.CURL_RUNNER_DIFF_COMPARE)Z.diff={...Z.diff,compareWith:process.env.CURL_RUNNER_DIFF_COMPARE};if(process.env.CURL_RUNNER_DIFF_DIR)Z.diff={...Z.diff,dir:process.env.CURL_RUNNER_DIFF_DIR};if(process.env.CURL_RUNNER_DIFF_OUTPUT){let X=process.env.CURL_RUNNER_DIFF_OUTPUT.toLowerCase();if(["terminal","json","markdown"].includes(X))Z.diff={...Z.diff,outputFormat:X}}}function X2(Z){if(process.env.CURL_RUNNER_TIMEOUT)Z.defaults={...Z.defaults,timeout:Number.parseInt(process.env.CURL_RUNNER_TIMEOUT,10)};if(process.env.CURL_RUNNER_RETRIES)Z.defaults={...Z.defaults,retry:{...Z.defaults?.retry,count:Number.parseInt(process.env.CURL_RUNNER_RETRIES,10)}};if(process.env.CURL_RUNNER_RETRY_DELAY)Z.defaults={...Z.defaults,retry:{...Z.defaults?.retry,delay:Number.parseInt(process.env.CURL_RUNNER_RETRY_DELAY,10)}}}var s9=["curl-runner.yaml","curl-runner.yml",".curl-runner.yaml",".curl-runner.yml"];async function x0(Z,X){for(let J of s9)try{if(await Bun.file(J).exists()){let G=(await v.parseFile(J)).global||{};return Z?.(`Loaded configuration from ${J}`),{config:G,path:J}}}catch(W){X?.(`Failed to load configuration from ${J}: ${W}`)}return{config:{},path:null}}var J2=[/sk_live_[a-zA-Z0-9]{24,}/g,/sk_test_[a-zA-Z0-9]{24,}/g,/pk_live_[a-zA-Z0-9]{24,}/g,/pk_test_[a-zA-Z0-9]{24,}/g,/rk_live_[a-zA-Z0-9]{24,}/g,/rk_test_[a-zA-Z0-9]{24,}/g,/AKIA[0-9A-Z]{16}/g,/ghp_[a-zA-Z0-9]{36,}/g,/gho_[a-zA-Z0-9]{36,}/g,/ghu_[a-zA-Z0-9]{36,}/g,/ghs_[a-zA-Z0-9]{36,}/g,/ghr_[a-zA-Z0-9]{36,}/g,/npm_[a-zA-Z0-9]{36,}/g,/xox[baprs]-[a-zA-Z0-9-]{10,}/g,/pdl_[a-zA-Z0-9]{20,}/g,/sk-[a-zA-Z0-9]{48,}/g,/sk-ant-[a-zA-Z0-9-]{40,}/g,/Bearer [a-zA-Z0-9_-]{40,}/g];class t9{secrets=new Map;sortedSecrets=[];patternRedaction=!0;addSecrets(Z){for(let[X,J]of Object.entries(Z))if(J&&J.length>0)this.secrets.set(X,J);this.updateSortedSecrets()}addSecret(Z,X){if(X&&X.length>0)this.secrets.set(Z,X),this.updateSortedSecrets()}setPatternRedaction(Z){this.patternRedaction=Z}clear(){this.secrets.clear(),this.sortedSecrets=[]}updateSortedSecrets(){this.sortedSecrets=Array.from(this.secrets.values()).filter((Z)=>Z.length>0).sort((Z,X)=>X.length-Z.length)}redact(Z){let X=Z;for(let J of this.sortedSecrets)X=X.split(J).join("[REDACTED]");if(this.patternRedaction)for(let J of J2)J.lastIndex=0,X=X.replace(J,"[REDACTED]");return X}hasSecrets(){return this.secrets.size>0}get secretCount(){return this.secrets.size}}var b0=null;function x1(){if(!b0)b0=new t9;return b0}async function v0(Z,X){let J=V0(Z);if(J==="upgrade")return{config:{},cliOptions:{files:[]},files:[],mode:"upgrade",rawArgs:Z,secretKeys:[]};if(J==="init")return{config:{},cliOptions:{files:[]},files:[],mode:"init",rawArgs:Z,secretKeys:[]};if(J==="edit")return{config:{},cliOptions:{files:[]},files:[],mode:"edit",rawArgs:Z,secretKeys:[]};if(J==="validate")return{config:{},cliOptions:{files:[]},files:[],mode:"validate",rawArgs:Z,secretKeys:[]};if(J==="convert")return{config:{},cliOptions:{files:[]},files:[],mode:"convert",rawArgs:Z,secretKeys:[]};let W=A0(Z),$=C0(W);if($)return{config:{},cliOptions:W,files:W.files,mode:$,rawArgs:Z,secretKeys:[]};if(J==="diff-subcommand")return{config:{},cliOptions:W,files:Z.slice(1),mode:"diff-subcommand",rawArgs:Z,secretKeys:[]};let G=q0(),{config:Y}=await x0(X?.onInfo,X?.onWarning),Q=b1(Y,G);Q=W2(Q,W);let z=W.env??Q.env?.environment,{variables:H,secretKeys:K}=await w0(process.cwd(),z);if(Q.variables={...H,...Q.variables},!W.noRedact&&Q.env?.redactSecrets!==!1&&K.length>0){let D=x1(),M={};for(let _ of K)if(Q.variables?.[_])M[_]=Q.variables[_];D.addSecrets(M)}let O=$2(W,Q);return{config:Q,cliOptions:W,files:W.files,mode:O,rawArgs:Z,secretKeys:K}}function b1(Z,X){return{...Z,...X,env:{...Z.env,...X.env},variables:{...Z.variables,...X.variables},output:{...Z.output,...X.output},defaults:{...Z.defaults,...X.defaults,retry:Z.defaults?.retry||X.defaults?.retry?{...Z.defaults?.retry,...X.defaults?.retry}:void 0},ci:{...Z.ci,...X.ci},watch:{...Z.watch,...X.watch},snapshot:{...Z.snapshot,...X.snapshot},diff:{...Z.diff,...X.diff},connectionPool:{...Z.connectionPool,...X.connectionPool}}}function W2(Z,X){let J={...Z};if(X.env)J.env={...J.env,environment:X.env};if(X.noRedact)J.env={...J.env,redactSecrets:!1};if(X.execution)J.execution=X.execution;if(X.maxConcurrency!==void 0)J.maxConcurrency=X.maxConcurrency;if(X.continueOnError!==void 0)J.continueOnError=X.continueOnError;if(X.dryRun!==void 0)J.dryRun=X.dryRun,J.output={...J.output,dryRun:X.dryRun};if(X.http2!==void 0)J.http2=X.http2,J.defaults={...J.defaults,http2:X.http2};if(X.connectionPool!==void 0)J.connectionPool={...J.connectionPool,enabled:X.connectionPool};if(X.maxStreams!==void 0)J.connectionPool={...J.connectionPool,enabled:!0,maxStreamsPerHost:X.maxStreams};if(X.keepaliveTime!==void 0)J.connectionPool={...J.connectionPool,enabled:!0,keepaliveTime:X.keepaliveTime};if(X.connectTimeout!==void 0)J.connectionPool={...J.connectionPool,enabled:!0,connectTimeout:X.connectTimeout};if(X.verbose!==void 0)J.output={...J.output,verbose:X.verbose};if(X.quiet)J.output={...J.output,verbose:!1,quiet:!0};if(X.output)J.output={...J.output,saveToFile:X.output};if(X.outputFormat)J.output={...J.output,format:X.outputFormat};if(X.prettyLevel)J.output={...J.output,prettyLevel:X.prettyLevel};if(X.showHeaders!==void 0)J.output={...J.output,showHeaders:X.showHeaders};if(X.showBody!==void 0)J.output={...J.output,showBody:X.showBody};if(X.showMetrics!==void 0)J.output={...J.output,showMetrics:X.showMetrics};if(X.timeout)J.defaults={...J.defaults,timeout:X.timeout};if(X.retries||X.noRetry){let W=X.noRetry?0:X.retries||0;J.defaults={...J.defaults,retry:{...J.defaults?.retry,count:W}}}if(X.retryDelay)J.defaults={...J.defaults,retry:{...J.defaults?.retry,delay:X.retryDelay}};if(X.strictExit!==void 0)J.ci={...J.ci,strictExit:X.strictExit};if(X.failOn!==void 0)J.ci={...J.ci,failOn:X.failOn};if(X.failOnPercentage!==void 0)J.ci={...J.ci,failOnPercentage:X.failOnPercentage};if(X.snapshot!==void 0)J.snapshot={...J.snapshot,enabled:X.snapshot};if(X.snapshotUpdate!==void 0)J.snapshot={...J.snapshot,enabled:!0,updateMode:X.snapshotUpdate};if(X.snapshotDir!==void 0)J.snapshot={...J.snapshot,dir:X.snapshotDir};if(X.snapshotCi!==void 0)J.snapshot={...J.snapshot,ci:X.snapshotCi};if(X.diff!==void 0)J.diff={...J.diff,enabled:X.diff};if(X.diffSave!==void 0)J.diff={...J.diff,enabled:!0,save:X.diffSave};if(X.diffLabel!==void 0)J.diff={...J.diff,label:X.diffLabel};if(X.diffCompare!==void 0)J.diff={...J.diff,enabled:!0,compareWith:X.diffCompare};if(X.diffDir!==void 0)J.diff={...J.diff,dir:X.diffDir};if(X.diffOutput!==void 0)J.diff={...J.diff,outputFormat:X.diffOutput};return J}function $2(Z,X){let J=Z.watch||X.watch?.enabled,W=Z.profile??X.profile?.iterations;if(W&&W>0)return"profile";if(J)return"watch";return"normal"}function y0(Z,X){return{iterations:Z.profile??X.profile?.iterations??10,warmup:Z.profileWarmup??X.profile?.warmup??1,concurrency:Z.profileConcurrency??X.profile?.concurrency??1,histogram:Z.profileHistogram??X.profile?.histogram??!1,exportFile:Z.profileExport??X.profile?.exportFile}}function m0(Z,X){return{enabled:!0,debounce:Z.watchDebounce??X.watch?.debounce??300,clear:Z.watchClear??X.watch?.clear??!0}}import*as i from"fs/promises";import*as y from"path";var G2=1,Y2="__baselines__";class z1{baselineDir;writeLocks=new Map;constructor(Z={}){this.baselineDir=Z.dir||Y2}getBaselinePath(Z,X){let J=y.dirname(Z),W=y.basename(Z,y.extname(Z));return y.join(J,this.baselineDir,`${W}.${X}.baseline.json`)}getBaselineDir(Z){return y.join(y.dirname(Z),this.baselineDir)}async load(Z,X){let J=this.getBaselinePath(Z,X);try{let W=Bun.file(J);if(!await W.exists())return null;let $=await W.text();return JSON.parse($)}catch{return null}}async save(Z,X,J){let W=this.getBaselinePath(Z,X),$=this.writeLocks.get(W),G=(async()=>{if($)await $;let Y=y.dirname(W);await i.mkdir(Y,{recursive:!0});let Q=JSON.stringify(J,null,2);await Bun.write(W,Q)})();this.writeLocks.set(W,G),await G,this.writeLocks.delete(W)}async get(Z,X,J){return(await this.load(Z,X))?.baselines[J]||null}async listLabels(Z){let X=this.getBaselineDir(Z),J=y.basename(Z,y.extname(Z));try{let W=await i.readdir(X),$=[];for(let G of W){let Y=G.match(new RegExp(`^${J}\\.(.+)\\.baseline\\.json$`));if(Y)$.push(Y[1])}return $.sort()}catch{return[]}}createBaseline(Z,X){let J={hash:"",capturedAt:new Date().toISOString()};if(Z.status!==void 0)J.status=Z.status;if(Z.headers)J.headers=this.normalizeHeaders(Z.headers);if(Z.body!==void 0)J.body=Z.body;if(X.includeTimings&&Z.metrics?.duration!==void 0)J.timing=Z.metrics.duration;return J.hash=this.hash(J),J}normalizeHeaders(Z){let X={},J=Object.keys(Z).sort();for(let W of J){let $=Z[W];X[W.toLowerCase()]=Array.isArray($)?$.join(", "):$}return X}hash(Z){let X=JSON.stringify(Z),J=new Bun.CryptoHasher("md5");return J.update(X),J.digest("hex").slice(0,8)}async saveBaseline(Z,X,J,W){let $={};for(let Y of J){if(Y.skipped||!Y.success)continue;let Q=Y.request.name||Y.request.url;$[Q]=this.createBaseline(Y,W)}let G={version:G2,label:X,capturedAt:new Date().toISOString(),baselines:$};await this.save(Z,X,G)}async cleanOldBaselines(Z,X){let J=this.getBaselineDir(Z),W=Date.now()-X*24*60*60*1000,$=0;try{let G=await i.readdir(J);for(let Y of G){if(!Y.endsWith(".baseline.json"))continue;let Q=y.join(J,Y);if((await i.stat(Q)).mtimeMs<W)await i.unlink(Q),$++}}catch{}return $}static mergeConfig(Z,X){if(!X&&!Z?.enabled)return null;if(X===!0)return{enabled:!0,exclude:Z?.exclude||[],match:Z?.match||{},includeTimings:Z?.includeTimings||!1};if(typeof X==="object"&&X.enabled!==!1)return{enabled:!0,exclude:[...Z?.exclude||[],...X.exclude||[]],match:{...Z?.match||{},...X.match||{}},includeTimings:X.includeTimings??Z?.includeTimings??!1};if(Z?.enabled&&X===void 0)return{enabled:!0,exclude:Z.exclude||[],match:Z.match||{},includeTimings:Z.includeTimings||!1};return null}}var _1={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m"};function a(Z,X){return`${_1[X]}${Z}${_1.reset}`}function u(Z){if(Z<1000)return`${Z.toFixed(0)}ms`;return`${(Z/1000).toFixed(2)}s`}function e(Z){if(Z<1)return`${(Z*1000).toFixed(0)}\xB5s`;if(Z<1000)return`${Z.toFixed(1)}ms`;return`${(Z/1000).toFixed(2)}s`}function v1(Z){if(!Z)return"0 B";let X=["B","KB","MB","GB"],J=Math.floor(Math.log(Z)/Math.log(1024));return`${(Z/1024**J).toFixed(2)} ${X[J]}`}function y1(Z,X="pretty"){if(X==="raw")return typeof Z==="string"?Z:JSON.stringify(Z);if(X==="json")return JSON.stringify(Z);return JSON.stringify(Z,null,2)}function h0(Z){return Z.replace(/.*\//,"").replace(".yaml","")}class H1{color(Z,X){if(!X||!(X in _1))return Z;return a(Z,X)}render(Z,X=" "){Z.forEach((J,W)=>{let $=W===Z.length-1,G=$?`${X}\u2514\u2500`:`${X}\u251C\u2500`;if(J.label&&J.value){let Y=J.color?this.color(J.value,J.color):J.value,Q=Y.split(`
133
- `);if(Q.length===1)console.log(`${G} ${J.label}: ${Y}`);else{console.log(`${G} ${J.label}:`);let z=$?`${X} `:`${X}\u2502 `;for(let H of Q)console.log(`${z}${H}`)}}else if(J.label&&!J.value)console.log(`${G} ${J.label}:`);else if(!J.label&&J.value){let Y=$?`${X} `:`${X}\u2502 `;console.log(`${Y}${J.value}`)}if(J.children&&J.children.length>0){let Y=$?`${X} `:`${X}\u2502 `;this.render(J.children,Y)}})}}class M1{outputFormat;constructor(Z="terminal"){this.outputFormat=Z}color(Z,X){if(this.outputFormat!=="terminal")return Z;return a(Z,X)}formatSummary(Z,X,J){switch(this.outputFormat){case"json":return this.formatSummaryJson(Z);case"markdown":return this.formatSummaryMarkdown(Z,X,J);default:return this.formatSummaryTerminal(Z,X,J)}}formatSummaryTerminal(Z,X,J){let W=[];W.push(""),W.push(`${this.color("Response Diff:","bright")} ${this.color(X,"cyan")} \u2192 ${this.color(J,"cyan")}`),W.push("");for(let $ of Z.results)W.push(this.formatResultTerminal($)),W.push("");return W.push(this.formatStatsSummary(Z)),W.join(`
134
- `)}formatSummaryJson(Z){return JSON.stringify({summary:{total:Z.totalRequests,unchanged:Z.unchanged,changed:Z.changed,newBaselines:Z.newBaselines},results:Z.results.map((X)=>({request:X.requestName,status:X.hasDifferences?"changed":X.isNewBaseline?"new":"unchanged",differences:X.differences,timingDiff:X.timingDiff}))},null,2)}formatSummaryMarkdown(Z,X,J){let W=[];if(W.push(`# Response Diff: ${X} \u2192 ${J}`),W.push(""),W.push("| Metric | Count |"),W.push("|--------|-------|"),W.push(`| Total Requests | ${Z.totalRequests} |`),W.push(`| Unchanged | ${Z.unchanged} |`),W.push(`| Changed | ${Z.changed} |`),W.push(`| New Baselines | ${Z.newBaselines} |`),W.push(""),Z.changed>0){W.push("## Changes"),W.push("");for(let $ of Z.results)if($.hasDifferences)W.push(this.formatResultMarkdown($))}if(Z.newBaselines>0){W.push("## New Requests"),W.push("");for(let $ of Z.results)if($.isNewBaseline)W.push(`- \`${$.requestName}\``);W.push("")}return W.join(`
135
- `)}formatResultTerminal(Z){let X=[];if(Z.isNewBaseline)return X.push(` ${this.color("NEW","cyan")} ${this.color(Z.requestName,"bright")}`),X.join(`
136
- `);if(!Z.hasDifferences)return X.push(` ${this.color("\u2713","green")} ${this.color(Z.requestName,"bright")} ${this.color("(no changes)","dim")}`),X.join(`
137
- `);X.push(` ${this.color("\u2717","red")} ${this.color(Z.requestName,"bright")}`);for(let J of Z.differences)X.push(this.formatDifferenceTerminal(J));if(Z.timingDiff){let{baseline:J,current:W,changePercent:$}=Z.timingDiff,G=$>=0?"+":"",Y=$>20?"red":$<-20?"green":"yellow";X.push(` ${this.color("timing:","cyan")} ${J}ms \u2192 ${W}ms ${this.color(`(${G}${$.toFixed(0)}%)`,Y)}`)}return X.join(`
138
- `)}formatDifferenceTerminal(Z){let X=[],J=Z.path||"(root)";switch(Z.type){case"added":X.push(` ${this.color(J,"cyan")}:`),X.push(` ${this.color(`+ ${this.stringify(Z.current)}`,"green")}`);break;case"removed":X.push(` ${this.color(J,"cyan")}:`),X.push(` ${this.color(`- ${this.stringify(Z.baseline)}`,"red")}`);break;case"changed":X.push(` ${this.color(J,"cyan")}:`),X.push(` ${this.color(`- ${this.stringify(Z.baseline)}`,"red")}`),X.push(` ${this.color(`+ ${this.stringify(Z.current)}`,"green")}`);break;case"type_mismatch":X.push(` ${this.color(J,"cyan")} (type mismatch):`),X.push(` ${this.color(`- ${this.stringify(Z.baseline)} (${typeof Z.baseline})`,"red")}`),X.push(` ${this.color(`+ ${this.stringify(Z.current)} (${typeof Z.current})`,"green")}`);break}return X.join(`
139
- `)}formatResultMarkdown(Z){let X=[];X.push(`### \`${Z.requestName}\``),X.push(""),X.push("```diff");for(let J of Z.differences)X.push(this.formatDifferenceMarkdown(J));if(X.push("```"),Z.timingDiff){let{baseline:J,current:W,changePercent:$}=Z.timingDiff,G=$>=0?"+":"";X.push(""),X.push(`**Timing:** ${J}ms \u2192 ${W}ms (${G}${$.toFixed(0)}%)`)}return X.push(""),X.join(`
140
- `)}formatDifferenceMarkdown(Z){let X=[],J=Z.path||"(root)";switch(Z.type){case"added":X.push(`# ${J}:`),X.push(`+ ${this.stringify(Z.current)}`);break;case"removed":X.push(`# ${J}:`),X.push(`- ${this.stringify(Z.baseline)}`);break;case"changed":X.push(`# ${J}:`),X.push(`- ${this.stringify(Z.baseline)}`),X.push(`+ ${this.stringify(Z.current)}`);break;case"type_mismatch":X.push(`# ${J} (type mismatch):`),X.push(`- ${this.stringify(Z.baseline)} (${typeof Z.baseline})`),X.push(`+ ${this.stringify(Z.current)} (${typeof Z.current})`);break}return X.join(`
141
- `)}formatStatsSummary(Z){let X=[];if(Z.unchanged>0)X.push(this.color(`${Z.unchanged} unchanged`,"green"));if(Z.changed>0)X.push(this.color(`${Z.changed} changed`,"red"));if(Z.newBaselines>0)X.push(this.color(`${Z.newBaselines} new`,"cyan"));return`Summary: ${X.join(", ")} (${Z.totalRequests} total)`}stringify(Z){if(Z===void 0)return"undefined";if(Z===null)return"null";if(typeof Z==="string")return`"${Z}"`;if(typeof Z==="object"){let X=JSON.stringify(Z);if(X.length>80)return`${X.slice(0,77)}...`;return X}return String(Z)}}class m1{excludePaths;matchRules;includeTimings;constructor(Z){this.excludePaths=new Set(Z.exclude||[]),this.matchRules=new Map(Object.entries(Z.match||{})),this.includeTimings=Z.includeTimings||!1}compare(Z,X,J,W,$){let G=[];if(Z.status!==void 0||X.status!==void 0){if(Z.status!==X.status&&!this.isExcluded("status"))G.push({path:"status",baseline:Z.status,current:X.status,type:"changed"})}if(Z.headers||X.headers){let Q=this.compareObjects(Z.headers||{},X.headers||{},"headers");G.push(...Q)}if(Z.body!==void 0||X.body!==void 0){let Q=this.deepCompare(Z.body,X.body,"body");G.push(...Q)}let Y={requestName:$,hasDifferences:G.length>0,isNewBaseline:!1,baselineLabel:J,currentLabel:W,differences:G};if(this.includeTimings&&Z.timing!==void 0&&X.timing!==void 0){let Q=(X.timing-Z.timing)/Z.timing*100;Y.timingDiff={baseline:Z.timing,current:X.timing,changePercent:Q}}return Y}deepCompare(Z,X,J){if(this.isExcluded(J))return[];if(this.matchesRule(J,X))return[];if(Z===null&&X===null)return[];if(Z===void 0&&X===void 0)return[];let W=this.getType(Z),$=this.getType(X);if(W!==$)return[{path:J,baseline:Z,current:X,type:"type_mismatch"}];if(W!=="object"&&W!=="array"){if(Z!==X)return[{path:J,baseline:Z,current:X,type:"changed"}];return[]}if(W==="array")return this.compareArrays(Z,X,J);return this.compareObjects(Z,X,J)}compareArrays(Z,X,J){let W=[],$=Math.max(Z.length,X.length);for(let G=0;G<$;G++){let Y=`${J}[${G}]`;if(G>=Z.length){if(!this.isExcluded(Y))W.push({path:Y,baseline:void 0,current:X[G],type:"added"})}else if(G>=X.length){if(!this.isExcluded(Y))W.push({path:Y,baseline:Z[G],current:void 0,type:"removed"})}else{let Q=this.deepCompare(Z[G],X[G],Y);W.push(...Q)}}return W}compareObjects(Z,X,J){let W=[],$=new Set([...Object.keys(Z),...Object.keys(X)]);for(let G of $){let Y=J?`${J}.${G}`:G,Q=G in Z,z=G in X;if(!Q&&z){if(!this.isExcluded(Y))W.push({path:Y,baseline:void 0,current:X[G],type:"added"})}else if(Q&&!z){if(!this.isExcluded(Y))W.push({path:Y,baseline:Z[G],current:void 0,type:"removed"})}else{let H=this.deepCompare(Z[G],X[G],Y);W.push(...H)}}return W}isExcluded(Z){if(this.excludePaths.has(Z))return!0;for(let X of this.excludePaths){if(X.startsWith("*.")){let J=X.slice(2);if(Z.endsWith(`.${J}`))return!0;if(Z.split(".").pop()===J)return!0}if(X.includes("[*]")){if(new RegExp(`^${X.replace(/\[\*\]/g,"\\[\\d+\\]").replace(/\./g,"\\.")}$`).test(Z))return!0}}return!1}matchesRule(Z,X){let J=this.matchRules.get(Z);if(!J)return!1;if(J==="*")return!0;if(J.startsWith("regex:")){let W=J.slice(6);try{return new RegExp(W).test(String(X))}catch{return!1}}return!1}getType(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";if(Array.isArray(Z))return"array";return typeof Z}}class D1{manager;constructor(Z={}){this.manager=new z1(Z)}async compareWithBaseline(Z,X,J,W,$){let G=await this.manager.load(Z,W),Y=[];for(let Q of X){if(Q.skipped||!Q.success)continue;let z=Q.request.name||Q.request.url,H=this.manager.createBaseline(Q,$);if(!G){Y.push({requestName:z,hasDifferences:!1,isNewBaseline:!0,baselineLabel:W,currentLabel:J,differences:[]});continue}let K=G.baselines[z];if(!K){Y.push({requestName:z,hasDifferences:!1,isNewBaseline:!0,baselineLabel:W,currentLabel:J,differences:[]});continue}let O=new m1($).compare(K,H,W,J,z);Y.push(O)}return{totalRequests:Y.length,unchanged:Y.filter((Q)=>!Q.hasDifferences&&!Q.isNewBaseline).length,changed:Y.filter((Q)=>Q.hasDifferences).length,newBaselines:Y.filter((Q)=>Q.isNewBaseline).length,results:Y}}async compareTwoBaselines(Z,X,J,W){let $=await this.manager.load(Z,X),G=await this.manager.load(Z,J);if(!$)throw Error(`Baseline '${X}' not found`);if(!G)throw Error(`Baseline '${J}' not found`);let Y=new Set([...Object.keys($.baselines),...Object.keys(G.baselines)]),Q=[],z=new m1(W);for(let H of Y){let K=$.baselines[H],B=G.baselines[H];if(!K){Q.push({requestName:H,hasDifferences:!0,isNewBaseline:!1,baselineLabel:X,currentLabel:J,differences:[{path:"",baseline:void 0,current:"exists",type:"added"}]});continue}if(!B){Q.push({requestName:H,hasDifferences:!0,isNewBaseline:!1,baselineLabel:X,currentLabel:J,differences:[{path:"",baseline:"exists",current:void 0,type:"removed"}]});continue}let O=z.compare(K,B,X,J,H);Q.push(O)}return{totalRequests:Q.length,unchanged:Q.filter((H)=>!H.hasDifferences).length,changed:Q.filter((H)=>H.hasDifferences).length,newBaselines:0,results:Q}}async saveBaseline(Z,X,J,W){await this.manager.saveBaseline(Z,X,J,W)}async listLabels(Z){return this.manager.listLabels(Z)}getManager(){return this.manager}}function g0(Z){return typeof Z==="object"&&Z!==null&&"file"in Z}var Q2=`
142
- __CURL_METRICS_START__%{json}__CURL_METRICS_END__`;function F1(Z,X={}){let{writeOutMarker:J=Q2,includeSilentFlags:W=!0,includeHttp2Flag:$=!0,includeOutputFlag:G=!0}=X,Y=[];if(Y.push("-X",Z.method||"GET"),Y.push("-w",J),Y.push("-D","-"),Z.headers)for(let[z,H]of Object.entries(Z.headers))Y.push("-H",`${z}: ${H}`);if(Z.auth){if(Z.auth.type==="basic"&&Z.auth.username&&Z.auth.password)Y.push("-u",`${Z.auth.username}:${Z.auth.password}`);else if(Z.auth.type==="bearer"&&Z.auth.token)Y.push("-H",`Authorization: Bearer ${Z.auth.token}`)}if(Z.formData)for(let[z,H]of Object.entries(Z.formData))if(g0(H)){let K=`@${H.file}`;if(H.filename)K+=`;filename=${H.filename}`;if(H.contentType)K+=`;type=${H.contentType}`;Y.push("-F",`${z}=${K}`)}else{let K=String(H);Y.push("--form-string",`${z}=${K}`)}else if(Z.body){let z=typeof Z.body==="string"?Z.body:JSON.stringify(Z.body);if(Y.push("-d",z),!Z.headers?.["Content-Type"])Y.push("-H","Content-Type: application/json")}if(Z.timeout)Y.push("--max-time",Z.timeout.toString());if(Z.followRedirects!==!1){if(Y.push("-L"),Z.maxRedirects)Y.push("--max-redirs",Z.maxRedirects.toString())}if(Z.proxy)Y.push("-x",Z.proxy);if(Z.insecure||Z.ssl?.verify===!1)Y.push("-k");if(Z.ssl){if(Z.ssl.ca)Y.push("--cacert",Z.ssl.ca);if(Z.ssl.cert)Y.push("--cert",Z.ssl.cert);if(Z.ssl.key)Y.push("--key",Z.ssl.key)}if(G&&Z.output)Y.push("-o",Z.output);if($&&Z.http2)Y.push("--http2");if(W)Y.push("-s","-S");let Q=Z.url;if(Z.params&&Object.keys(Z.params).length>0){let z=new URLSearchParams(Z.params).toString();Q+=(Q.includes("?")?"&":"?")+z}return{args:Y,url:Q}}function T1(Z){return["curl",...Z].map((X)=>X.includes(" ")||X.includes('"')||X.includes("'")?`'${X.replace(/'/g,"'\\''")}'`:X).join(" ")}function d0(Z){return`
143
- __CURL_BATCH_${Z}_START__%{json}__CURL_BATCH_${Z}_END__
144
- `}var h1="__CURL_METRICS_START__",g1="__CURL_METRICS_END__";function $1(Z,X){if(!Z)return Z;try{let J=X?.includes("application/json"),W=Z.trim().startsWith("{")||Z.trim().startsWith("[");if(J||W)return JSON.parse(Z)}catch{}return Z}function N1(Z){return{duration:(Z.time_total||0)*1000,size:Z.size_download,dnsLookup:(Z.time_namelookup||0)*1000,tcpConnection:(Z.time_connect||0)*1000,tlsHandshake:(Z.time_appconnect||0)*1000,firstByte:(Z.time_starttransfer||0)*1000,download:(Z.time_total||0)*1000}}function e9(Z){let X=Z.match(new RegExp(`${h1}(.+?)${g1}`));if(!X)return{body:Z,metrics:{}};let J=Z.replace(new RegExp(`${h1}.+?${g1}`),"").trim(),W={};try{W=JSON.parse(X[1])}catch{}return{body:J,metrics:W}}function f0(Z,X){let J=`__CURL_BATCH_${X}_START__`,W=`__CURL_BATCH_${X}_END__`,$=Z.indexOf(J),G=Z.indexOf(W);if($===-1||G===-1)return{found:!1,metricsJson:"",startIdx:-1,endIdx:-1};return{found:!0,metricsJson:Z.substring($+J.length,G),startIdx:$,endIdx:G}}var z2=/^HTTP\/[\d.]+\s+(\d{3})/;function d1(Z){let X=[],J=0;while(J<Z.length){while(J<Z.length){let O=Z.charCodeAt(J);if(O===13||O===10||O===32||O===9)J++;else break}if(J>=Z.length)break;let W=Z.slice(J).match(z2);if(!W)break;let $=Number(W[1]),G=Z.indexOf(`\r
145
- \r
146
- `,J),Y=Z.indexOf(`
147
-
148
- `,J),Q,z;if(G!==-1&&(Y===-1||G<=Y))Q=G,z=4;else if(Y!==-1)Q=Y,z=2;else break;let K=Z.indexOf(`
149
- `,J)+1,B={};if(K>0&&K<Q)for(let O of Z.slice(K,Q).split(/\r?\n/)){if(!O)continue;let D=O.indexOf(":");if(D===-1)continue;let M=O.slice(0,D).trim().toLowerCase();if(!M)continue;let _=O.slice(D+1).trim(),N=B[M];if(N===void 0)B[M]=_;else if(Array.isArray(N))N.push(_);else B[M]=[N,_]}X.push({status:$,headers:B}),J=Q+z}return{blocks:X,bodyOffset:J}}function p0(Z){let{blocks:X,bodyOffset:J}=d1(Z),W;for(let Y=X.length-1;Y>=0;Y--)if(X[Y].status>=200){W=X[Y];break}let{body:$,metrics:G}=e9(Z.slice(J));return{headers:W?.headers??{},status:W?.status,headerHistory:X,body:$,metrics:G}}function L1(Z){return Z.response_code||Z.http_code}function c0(Z){if(Z===void 0)return!1;return Z>=200&&Z<400}class Z1{static buildCommand(Z){let{args:X,url:J}=F1(Z,{includeSilentFlags:!0,includeHttp2Flag:!0,includeOutputFlag:!0});return X.push(J),X}static formatCommandForDisplay(Z){return T1(Z)}static async executeCurl(Z){try{let X=Bun.spawn(["curl",...Z],{stdout:"pipe",stderr:"pipe"}),J=await new Response(X.stdout).text(),W=await new Response(X.stderr).text();if(await X.exited,X.exitCode!==0&&!J)return{success:!1,error:W||`Command failed with exit code ${X.exitCode}`};let{headers:$,status:G,headerHistory:Y,body:Q,metrics:z}=p0(J),H=L1(z)??G,K=N1(z);return{success:!0,status:H,headers:$,headerHistory:Y,body:Q,metrics:K}}catch(X){return{success:!1,error:X instanceof Error?X.message:String(X)}}}}class u0{color(Z,X){return a(Z,X)}formatResult(Z,X){let J=[];if(X.isNew&&X.updated)return J.push(` ${this.color("NEW","cyan")} Snapshot created for "${this.color(Z,"bright")}"`),J.join(`
150
- `);if(X.updated)return J.push(` ${this.color("UPDATED","yellow")} Snapshot updated for "${this.color(Z,"bright")}"`),J.join(`
151
- `);if(X.match)return J.push(` ${this.color("PASS","green")} Snapshot matches for "${this.color(Z,"bright")}"`),J.join(`
152
- `);return J.push(` ${this.color("FAIL","red")} Snapshot mismatch for "${this.color(Z,"bright")}"`),J.push(""),J.push(this.formatDiff(X.differences)),J.push(""),J.push(this.color(" Run with --update-snapshots (-u) to update","dim")),J.join(`
153
- `)}formatDiff(Z){let X=[];X.push(` ${this.color("- Expected","red")}`),X.push(` ${this.color("+ Received","green")}`),X.push("");for(let J of Z)X.push(this.formatDifference(J));return X.join(`
154
- `)}formatDifference(Z){let X=[],J=Z.path||"(root)";switch(Z.type){case"added":X.push(` ${this.color(J,"cyan")}:`),X.push(` ${this.color(`+ ${this.stringify(Z.received)}`,"green")}`);break;case"removed":X.push(` ${this.color(J,"cyan")}:`),X.push(` ${this.color(`- ${this.stringify(Z.expected)}`,"red")}`);break;case"changed":X.push(` ${this.color(J,"cyan")}:`),X.push(` ${this.color(`- ${this.stringify(Z.expected)}`,"red")}`),X.push(` ${this.color(`+ ${this.stringify(Z.received)}`,"green")}`);break;case"type_mismatch":X.push(` ${this.color(J,"cyan")} (type mismatch):`),X.push(` ${this.color(`- ${this.stringify(Z.expected)} (${typeof Z.expected})`,"red")}`),X.push(` ${this.color(`+ ${this.stringify(Z.received)} (${typeof Z.received})`,"green")}`);break}return X.join(`
155
- `)}stringify(Z){if(Z===void 0)return"undefined";if(Z===null)return"null";if(typeof Z==="string")return`"${Z}"`;if(typeof Z==="object"){let X=JSON.stringify(Z);if(X.length>80)return`${X.slice(0,77)}...`;return X}return String(Z)}formatSummary(Z){let X=[];if(Z.passed>0)X.push(this.color(`${Z.passed} passed`,"green"));if(Z.failed>0)X.push(this.color(`${Z.failed} failed`,"red"));if(Z.updated>0)X.push(this.color(`${Z.updated} updated`,"yellow"));if(Z.created>0)X.push(this.color(`${Z.created} created`,"cyan"));if(X.length===0)return"";return`Snapshots: ${X.join(", ")}`}}function f1(Z,X){if(Z.length===0)return 0;if(Z.length===1)return Z[0];let J=X/100*(Z.length-1),W=Math.floor(J),$=Math.ceil(J),G=J-W;if(W===$)return Z[W];return Z[W]*(1-G)+Z[$]*G}function H2(Z){if(Z.length===0)return 0;return Z.reduce((X,J)=>X+J,0)/Z.length}function K2(Z,X){if(Z.length<=1)return 0;let W=Z.map(($)=>($-X)**2).reduce(($,G)=>$+G,0)/Z.length;return Math.sqrt(W)}function Z4(Z,X,J){let W=Z.slice(X),$=[...W].sort((z,H)=>z-H),G=H2($),Y=Z.length;return{iterations:W.length,warmup:X,min:$.length>0?$[0]:0,max:$.length>0?$[$.length-1]:0,mean:Math.round(G*100)/100,median:Math.round(f1($,50)*100)/100,p50:Math.round(f1($,50)*100)/100,p95:Math.round(f1($,95)*100)/100,p99:Math.round(f1($,99)*100)/100,stdDev:Math.round(K2($,G)*100)/100,failures:J,failureRate:Y>0?Math.round(J/Y*1e4)/100:0,timings:W}}function X4(Z,X=10,J=40){if(Z.length===0)return["No data"];let W=Math.min(...Z),Y=(Math.max(...Z)-W||1)/X,Q=Array(X).fill(0);for(let K of Z){let B=Math.min(Math.floor((K-W)/Y),X-1);Q[B]++}let z=Math.max(...Q),H=[];for(let K=0;K<X;K++){let B=W+K*Y,O=W+(K+1)*Y,D=z>0?Math.round(Q[K]/z*J):0,M="\u2588".repeat(D),_=`${B.toFixed(0).padStart(6)}ms - ${O.toFixed(0).padStart(6)}ms`;H.push(`${_} \u2502${M} ${Q[K]}`)}return H}function J4(Z,X){let J=["iteration","latency_ms"],W=Z.timings.map(($,G)=>`${G+1},${$}`);return[J.join(","),...W].join(`
156
- `)}function W4(Z,X){return JSON.stringify({request:X,summary:{iterations:Z.iterations,warmup:Z.warmup,failures:Z.failures,failureRate:Z.failureRate,min:Z.min,max:Z.max,mean:Z.mean,median:Z.median,p50:Z.p50,p95:Z.p95,p99:Z.p99,stdDev:Z.stdDev},timings:Z.timings},null,2)}class l{config;redactor=x1();constructor(Z={}){this.config={verbose:!1,showHeaders:!1,showBody:!0,showMetrics:!1,format:"pretty",prettyLevel:"minimal",...Z}}redact(Z){return this.redactor.redact(Z)}color(Z,X){return a(Z,X)}shouldShowOutput(){if(this.config.quiet)return!1;if(this.config.format==="raw")return!1;if(this.config.format==="pretty")return!0;return this.config.verbose!==!1}shouldShowHeaders(){if(this.config.format!=="pretty")return this.config.showHeaders||!1;switch(this.config.prettyLevel||"standard"){case"minimal":return!1;case"standard":return this.config.showHeaders||!1;case"detailed":return!0;default:return this.config.showHeaders||!1}}shouldShowBody(){if(this.config.format!=="pretty")return this.config.showBody!==!1;switch(this.config.prettyLevel||"standard"){case"minimal":return!1;case"standard":return this.config.showBody!==!1;case"detailed":return!0;default:return this.config.showBody!==!1}}shouldShowMetrics(){if(this.config.format!=="pretty")return this.config.showMetrics||!1;switch(this.config.prettyLevel||"standard"){case"minimal":return!1;case"standard":return this.config.showMetrics||!1;case"detailed":return!0;default:return this.config.showMetrics||!1}}shouldShowRequestDetails(){if(this.config.format!=="pretty")return this.config.verbose||!1;switch(this.config.prettyLevel||"standard"){case"minimal":return!1;case"standard":return this.config.verbose||!1;case"detailed":return!0;default:return this.config.verbose||!1}}shouldShowSeparators(){if(this.config.format!=="pretty")return!0;switch(this.config.prettyLevel||"standard"){case"minimal":return!1;case"standard":return!0;case"detailed":return!0;default:return!0}}colorStatusCode(Z){return this.color(Z,"yellow")}logValidationErrors(Z){let X=Z.split("; ");if(X.length===1){let J=X[0].trim(),W=J.match(/^Expected status (.+?), got (.+)$/);if(W){let[,$,G]=W,Y=this.colorStatusCode($.replace(" or ","|")),Q=this.color(G,"red");console.log(` ${this.color("\u2717","red")} ${this.color("Error:","red")} Expected ${this.color("status","yellow")} ${Y}, got ${Q}`)}else console.log(` ${this.color("\u2717","red")} ${this.color("Error:","red")} ${J}`)}else{console.log(` ${this.color("\u2717","red")} ${this.color("Validation Errors:","red")}`);for(let J of X){let W=J.trim();if(W)if(W.startsWith("Expected ")){let $=W.match(/^Expected status (.+?), got (.+)$/);if($){let[,G,Y]=$,Q=this.colorStatusCode(G.replace(" or ","|")),z=this.color(Y,"red");console.log(` ${this.color("\u2022","red")} ${this.color("status","yellow")}: expected ${Q}, got ${z}`)}else{let G=W.match(/^Expected (.+?) to be (.+?), got (.+)$/);if(G){let[,Y,Q,z]=G;console.log(` ${this.color("\u2022","red")} ${this.color(Y,"yellow")}: expected ${this.color(Q,"green")}, got ${this.color(z,"red")}`)}else console.log(` ${this.color("\u2022","red")} ${W}`)}}else console.log(` ${this.color("\u2022","red")} ${W}`)}}}logExecutionStart(Z,X){if(!this.shouldShowOutput())return;if(this.shouldShowSeparators())console.log(),console.log(this.color(`Executing ${Z} request(s) in ${X} mode`,"dim")),console.log();else console.log()}logRequestStart(Z,X){return}logCommand(Z){if(this.config.dryRun||this.shouldShowRequestDetails())console.log(this.color(" Command:","dim")),console.log(this.color(` ${this.redact(Z)}`,"dim"))}logRetry(Z,X){if(!this.shouldShowOutput())return;console.log(this.color(` \u21BB Retry ${Z}/${X}...`,"yellow"))}logRequestComplete(Z){if(this.config.quiet)return;if(this.config.format==="raw"){if(Z.success&&this.config.showBody&&Z.body){let Q=y1(Z.body,this.config.format);console.log(Q)}return}if(this.config.format==="json"){let Q={request:{name:Z.request.name,url:this.redact(Z.request.url),method:Z.request.method||"GET"},success:Z.success,...Z.dryRun?{dryRun:!0}:{status:Z.status},...this.shouldShowHeaders()&&Z.headers?{headers:Z.headers}:{},...this.shouldShowBody()&&Z.body?{body:Z.body}:{},...Z.error?{error:Z.error}:{},...this.shouldShowMetrics()&&Z.metrics?{metrics:Z.metrics}:{}};console.log(JSON.stringify(Q,null,2));return}if(!this.shouldShowOutput())return;let X=this.config.prettyLevel||"minimal",J=Z.success?"green":"red",W=Z.success?"\u2713":"x",$=Z.request.name||"Request";if(X==="minimal"){let Q=Z.request.sourceFile?h0(Z.request.sourceFile):"inline";console.log(`${this.color(W,J)} ${this.color($,"bright")} [${Q}]`);let z=[],H=new H1;z.push({label:Z.request.method||"GET",value:this.redact(Z.request.url),color:"blue"});let K=Z.dryRun?"DRY-RUN":Z.status?`${Z.status}`:"ERROR";if(z.push({label:`${W} Status`,value:K,color:Z.dryRun?"cyan":J}),Z.metrics){let B=`${u(Z.metrics.duration)} | ${v1(Z.metrics.size)}`;z.push({label:"Duration",value:B,color:"cyan"})}if(H.render(z),Z.error)console.log(),this.logValidationErrors(Z.error);if(Z.snapshotResult)console.log(),this.logSnapshotResult(Z.request.name||"Request",Z.snapshotResult);console.log();return}console.log(`${this.color(W,J)} ${this.color($,"bright")}`);let G=[],Y=new H1;if(G.push({label:"URL",value:this.redact(Z.request.url),color:"blue"}),G.push({label:"Method",value:Z.request.method||"GET",color:"yellow"}),G.push({label:"Status",value:Z.dryRun?"DRY-RUN":String(Z.status||"ERROR"),color:Z.dryRun?"cyan":J}),Z.metrics)G.push({label:"Duration",value:u(Z.metrics.duration),color:"cyan"});if(this.shouldShowHeaders()&&Z.headers&&Object.keys(Z.headers).length>0){let Q=Object.entries(Z.headers).map(([z,H])=>({label:this.color(z,"dim"),value:String(H)}));G.push({label:"Headers",children:Q})}if(this.shouldShowBody()&&Z.body){let z=y1(Z.body,this.config.format).split(`
157
- `),H=this.shouldShowRequestDetails()?1/0:10,K=z.slice(0,H);if(z.length>H)K.push(this.color(`... (${z.length-H} more lines)`,"dim"));G.push({label:"Response Body",value:K.join(`
158
- `)})}if(this.shouldShowMetrics()&&Z.metrics&&X==="detailed"){let Q=Z.metrics,z=[];if(z.push({label:"Request Duration",value:u(Q.duration),color:"cyan"}),Q.size!==void 0)z.push({label:"Response Size",value:v1(Q.size),color:"cyan"});if(Q.dnsLookup)z.push({label:"DNS Lookup",value:u(Q.dnsLookup),color:"cyan"});if(Q.tcpConnection)z.push({label:"TCP Connection",value:u(Q.tcpConnection),color:"cyan"});if(Q.tlsHandshake)z.push({label:"TLS Handshake",value:u(Q.tlsHandshake),color:"cyan"});if(Q.firstByte)z.push({label:"Time to First Byte",value:u(Q.firstByte),color:"cyan"});G.push({label:"Metrics",children:z})}if(Y.render(G),Z.error)console.log(),this.logValidationErrors(Z.error);if(Z.snapshotResult)console.log(),this.logSnapshotResult(Z.request.name||"Request",Z.snapshotResult);console.log()}logSnapshotResult(Z,X){if(!X)return;let J=new u0;console.log(J.formatResult(Z,X))}logSummary(Z,X=!1){if(this.config.quiet)return;if(this.config.format==="raw")return;if(this.config.format==="json"){let z={summary:{total:Z.total,successful:Z.successful,failed:Z.failed,skipped:Z.skipped,duration:Z.duration},results:Z.results.map((H)=>({request:{name:H.request.name,url:this.redact(H.request.url),method:H.request.method||"GET"},success:H.success,...H.dryRun?{dryRun:!0}:{status:H.status},...this.shouldShowHeaders()&&H.headers?{headers:H.headers}:{},...this.shouldShowBody()&&H.body?{body:H.body}:{},...H.error?{error:H.error}:{},...this.shouldShowMetrics()&&H.metrics?{metrics:H.metrics}:{}}))};console.log(JSON.stringify(z,null,2));return}if(!this.shouldShowOutput())return;let J=this.config.prettyLevel||"minimal";if(X)console.log();if(J==="minimal"){let z=Z.failed===0?"green":"red",H=Z.skipped>0?`, ${Z.skipped} skipped`:"",K=Z.failed===0?`${Z.total} request${Z.total===1?"":"s"} completed successfully${H}`:`${Z.successful}/${Z.total} request${Z.total===1?"":"s"} completed, ${Z.failed} failed${H}`;console.log(`${X?"\u25C6 Global Summary":"Summary"}: ${this.color(K,z)}`);return}let W=(Z.successful/Z.total*100).toFixed(1),$=Z.failed===0?"green":"red",G=Z.skipped>0?`, ${Z.skipped} skipped`:"",Y=Z.failed===0?`${Z.total} request${Z.total===1?"":"s"} completed successfully${G}`:`${Z.successful}/${Z.total} request${Z.total===1?"":"s"} completed, ${Z.failed} failed${G}`,Q=X?"\u25C6 Global Summary":"Summary";if(console.log(),console.log(`${Q}: ${this.color(Y,$)} (${this.color(u(Z.duration),"cyan")})`),Z.failed>0&&this.shouldShowRequestDetails())Z.results.filter((z)=>!z.success).forEach((z)=>{let H=z.request.name||this.redact(z.request.url);console.log(` ${this.color("\u2022","red")} ${H}: ${z.error||""}`)})}logError(Z){console.error(this.color(`\u2717 ${Z}`,"red"))}logWarning(Z){if(!this.shouldShowOutput())return;console.warn(this.color(`\u26A0 ${Z}`,"yellow"))}logInfo(Z){if(!this.shouldShowOutput())return;console.log(this.color(`\u2139 ${Z}`,"blue"))}logSuccess(Z){if(!this.shouldShowOutput())return;console.log(this.color(`\u2713 ${Z}`,"green"))}logSkipped(Z,X,J){if(!this.shouldShowOutput())return;let W=Z.name||`Request ${X}`;if(this.config.format==="json"){let $={request:{name:Z.name,url:this.redact(Z.url),method:Z.method||"GET"},skipped:!0,reason:J||"condition not met"};console.log(JSON.stringify($,null,2));return}if(console.log(`${this.color("\u2298","yellow")} ${this.color(W,"bright")} ${this.color("[SKIP]","yellow")}`),J){let $=[{label:"Reason",value:J,color:"yellow"}];new H1().render($)}console.log()}logFileHeader(Z,X){if(!this.shouldShowOutput()||this.config.format!=="pretty")return;let J=Z.replace(/.*\//,"").replace(".yaml","");console.log(),console.log(this.color(`\u25B6 ${J}.yaml`,"bright")+this.color(` (${X} request${X===1?"":"s"})`,"dim"))}logWatch(Z){if(!this.shouldShowOutput())return;console.log(),console.log(`${this.color("Watching for changes...","cyan")} ${this.color("(press Ctrl+C to stop)","dim")}`);let X=Z.length<=3?Z.join(", "):`${Z.length} files`;console.log(this.color(` Files: ${X}`,"dim")),console.log()}logWatchReady(){if(!this.shouldShowOutput())return;console.log(),console.log(this.color("Watching for changes...","cyan"))}logFileChanged(Z){if(!this.shouldShowOutput())return;let X=new Date().toLocaleTimeString("en-US",{hour12:!1});console.log(this.color("-".repeat(50),"dim")),console.log(`${this.color(`[${X}]`,"dim")} File changed: ${this.color(Z,"yellow")}`),console.log()}logProfileStart(Z,X,J,W){if(!this.shouldShowOutput())return;console.log(),console.log(`${this.color("\u26A1 PROFILING","magenta")} ${this.color(Z,"bright")}`),console.log(this.color(` ${X} iterations, ${J} warmup, concurrency: ${W}`,"dim"))}logProfileResult(Z,X){let{stats:J,request:W}=Z,$=W.name||W.url;if(this.config.format==="json"){console.log(JSON.stringify({request:{name:$,url:W.url,method:W.method||"GET"},stats:{iterations:J.iterations,warmup:J.warmup,failures:J.failures,failureRate:J.failureRate,min:J.min,max:J.max,mean:J.mean,median:J.median,p50:J.p50,p95:J.p95,p99:J.p99,stdDev:J.stdDev}}));return}if(this.config.format==="raw"){console.log(`${J.p50} ${J.p95} ${J.p99} ${J.mean}`);return}console.log();let G=J.failures===0?this.color("\u2713","green"):this.color("\u26A0","yellow");if(console.log(`${G} ${this.color($,"bright")}`),console.log(this.color(" \u250C\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\u2510","dim")),console.log(` \u2502 ${this.color("p50","cyan")} ${e(J.p50).padStart(10)} \u2502 ${this.color("min","dim")} ${e(J.min).padStart(10)} \u2502`),console.log(` \u2502 ${this.color("p95","yellow")} ${e(J.p95).padStart(10)} \u2502 ${this.color("max","dim")} ${e(J.max).padStart(10)} \u2502`),console.log(` \u2502 ${this.color("p99","red")} ${e(J.p99).padStart(10)} \u2502 ${this.color("mean","dim")} ${e(J.mean).padStart(10)} \u2502`),console.log(this.color(" \u2514\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\u2518","dim")),console.log(this.color(` \u03C3 ${J.stdDev.toFixed(2)}ms | ${J.iterations} samples | ${J.failures} failures (${J.failureRate}%)`,"dim")),X&&J.timings.length>0){console.log(),console.log(this.color(" Distribution:","dim"));let Y=X4(J.timings,8,30);for(let Q of Y)console.log(` ${this.color(Q,"dim")}`)}}logProfileSummary(Z){if(!this.shouldShowOutput())return;let X=Z.reduce((W,$)=>W+$.stats.iterations,0),J=Z.reduce((W,$)=>W+$.stats.failures,0);if(console.log(),console.log(this.color("\u2500".repeat(50),"dim")),console.log(`${this.color("\u26A1 Profile Summary:","magenta")} ${Z.length} request${Z.length===1?"":"s"}, ${X} total iterations`),J>0)console.log(this.color(` ${J} total failures`,"yellow"))}}class l0{logger;profileConfig;constructor(Z,X){this.profileConfig=X,this.logger=new l(Z.output)}async executeSingleIteration(Z){let X=performance.now(),J=Z1.buildCommand(Z),W=await Z1.executeCurl(J);if(W.success){let $=W.headers?.["content-type"],G=Array.isArray($)?$[0]:$;return{request:Z,success:!0,status:W.status,headers:W.headers,body:$1(W.body,G),metrics:{...W.metrics,duration:performance.now()-X}}}return{request:Z,success:!1,error:W.error,metrics:{duration:performance.now()-X}}}async executeWithConcurrency(Z,X,J){let W=[];for(let $=0;$<X;$+=J){let G=Math.min(J,X-$),Y=await Promise.all(Array.from({length:G},()=>this.executeSingleIteration(Z)));W.push(...Y)}return W}async profileRequest(Z,X=0){let J=this.profileConfig.iterations,W=this.profileConfig.warmup??1,$=this.profileConfig.concurrency??1,G=Z.name||`Request ${X+1}`;this.logger.logProfileStart(G,J,W,$);let Y=$===1?await this.executeSequentially(Z,J):await this.executeWithConcurrency(Z,J,$),Q=[],z=0;for(let B of Y)if(B.success&&B.metrics?.duration!==void 0)Q.push(B.metrics.duration);else z++,Q.push(0);let H=Q.map((B,O)=>Y[O].success?B:-1).filter((B)=>B>=0),K=Z4(H,Math.min(W,H.length),z);return{request:Z,stats:K,iterations:Y}}async executeSequentially(Z,X){let J=[];for(let W=0;W<X;W++){let $=await this.executeSingleIteration(Z);J.push($)}return J}async profileRequests(Z){let X=[];for(let J=0;J<Z.length;J++){let W=await this.profileRequest(Z[J],J);X.push(W),this.logger.logProfileResult(W,this.profileConfig.histogram??!1)}return X}}function a0(Z,X){if(!X)return{success:!0};let J=[];if(X.status!==void 0){let $=$4(Z.status,X.status);J.push(...$)}if(X.headers){let $=G4(Z.headers,X.headers);J.push(...$)}if(X.body!==void 0){let $=p1(Z.body,X.body,"");J.push(...$)}if(X.responseTime!==void 0&&Z.metrics){let $=Z.metrics.duration;if(!c1($,X.responseTime))J.push(`Expected response time to match ${X.responseTime}ms, got ${$.toFixed(2)}ms`)}let W=J.length>0;if(X.failure===!0){if(W)return{success:!1,error:J.join("; ")};let $=Z.status||0;if($>=400)return{success:!0};return{success:!1,error:`Expected request to fail (4xx/5xx) but got status ${$}`}}if(W)return{success:!1,error:J.join("; ")};return{success:!0}}function $4(Z,X){let J=Array.isArray(X)?X:[X];if(!J.includes(Z||0))return[`Expected status ${J.join(" or ")}, got ${Z}`];return[]}function G4(Z,X){let J=[];for(let[W,$]of Object.entries(X)){let G=Z?.[W.toLowerCase()];if(!(Array.isArray(G)?G.includes($)||G.join(", ")===$:G===$)){let Q=Array.isArray(G)?`[${G.map((z)=>`"${z}"`).join(", ")}]`:`"${G}"`;J.push(`Expected header ${W}="${$}", got ${Q}`)}}return J}function p1(Z,X,J){let W=[];if(typeof X!=="object"||X===null){let $=I1(Z,X,J||"body");if(!$.isValid)W.push($.error);return W}if(Array.isArray(X)){if(Array.isArray(Z)){for(let G=0;G<X.length;G++){let Y=X[G],Q=`${J||"body"}[${G}]`;if(typeof Y==="object"&&Y!==null){if(!Z.some((H)=>{return p1(H,Y,Q).length===0}))W.push(`Expected ${J||"body"} to contain item matching ${JSON.stringify(Y)}, but no match found`)}else if(!Z.some((H)=>{return I1(H,Y,Q).isValid}))W.push(`Expected ${J||"body"} to contain item matching ${JSON.stringify(Y)}, but no match found`)}return W}let $=I1(Z,X,J||"body");if(!$.isValid)W.push($.error);return W}for(let[$,G]of Object.entries(X)){let Y=J?`${J}.${$}`:$,Q;if(Array.isArray(Z)&&Y4($))Q=Q4(Z,$);else Q=Z?.[$];if(typeof G==="object"&&G!==null){let z=p1(Q,G,Y);W.push(...z)}else{let z=I1(Q,G,Y);if(!z.isValid)W.push(z.error)}}return W}function I1(Z,X,J){if(X==="$absent"){if(Z!==void 0)return{isValid:!1,error:`Expected ${J} to be absent, got ${JSON.stringify(Z)}`};return{isValid:!0}}if(X==="$exists"){if(Z===void 0)return{isValid:!1,error:`Expected ${J} to exist, but it was absent`};return{isValid:!0}}if(X==="*")return{isValid:!0};if(Array.isArray(X)){if(!X.some(($)=>{if($==="*")return!0;if(typeof $==="string"&&n0($))return o0(Z,$);if(typeof $==="string"&&i0($))return c1(Z,$);return Z===$}))return{isValid:!1,error:`Expected ${J} to match one of ${JSON.stringify(X)}, got ${JSON.stringify(Z)}`};return{isValid:!0}}if(typeof X==="string"&&n0(X)){if(!o0(Z,X))return{isValid:!1,error:`Expected ${J} to match pattern ${X}, got ${JSON.stringify(Z)}`};return{isValid:!0}}if(typeof X==="string"&&i0(X)){if(!c1(Z,X))return{isValid:!1,error:`Expected ${J} to match range ${X}, got ${JSON.stringify(Z)}`};return{isValid:!0}}if(X==="null"||X===null){if(Z!==null)return{isValid:!1,error:`Expected ${J} to be null, got ${JSON.stringify(Z)}`};return{isValid:!0}}if(Z!==X)return{isValid:!1,error:`Expected ${J} to be ${JSON.stringify(X)}, got ${JSON.stringify(Z)}`};return{isValid:!0}}function n0(Z){return Z.startsWith("^")||Z.endsWith("$")||Z.includes("\\d")||Z.includes("\\w")||Z.includes("\\s")}function o0(Z,X){let J=String(Z);try{return new RegExp(X).test(J)}catch{return!1}}function i0(Z){return/^(>=?|<=?|>|<)\s*[\d.-]+(\s*,\s*(>=?|<=?|>|<)\s*[\d.-]+)*$/.test(Z)}function c1(Z,X){let J=Number(Z);if(Number.isNaN(J))return!1;let W=X.match(/^([\d.-]+)\s*-\s*([\d.-]+)$/);if(W){let G=Number(W[1]),Y=Number(W[2]);return J>=G&&J<=Y}return X.split(",").map((G)=>G.trim()).every((G)=>{let Y=G.match(/^(>=?|<=?|>|<)\s*([\d.-]+)$/);if(!Y)return!1;let Q=Y[1],z=Number(Y[2]);switch(Q){case">":return J>z;case">=":return J>=z;case"<":return J<z;case"<=":return J<=z;default:return!1}})}function Y4(Z){return/^\[.*\]$/.test(Z)||Z==="*"||Z.startsWith("slice(")}function Q4(Z,X){if(X==="*")return Z;if(X.startsWith("[")&&X.endsWith("]")){let J=X.slice(1,-1);if(J==="*")return Z;let W=Number(J);if(!Number.isNaN(W))return W>=0?Z[W]:Z[Z.length+W]}if(X.startsWith("slice(")){let J=X.match(/slice\((\d+)(?:,(\d+))?\)/);if(J){let W=Number(J[1]),$=J[2]?Number(J[2]):void 0;return Z.slice(W,$)}}return}async function u1(Z,X,J={}){if(Z.success&&X.expect){let G=a0(Z,X.expect);if(!G.success)Z.success=!1,Z.error=G.error}let{snapshotManager:W,snapshotConfig:$}=J;if(W&&$&&X.sourceFile&&Z.success){let G=await W.compareAndUpdate(X.sourceFile,X.name||"Request",Z,$);if(Z.snapshotResult=G,!G.match&&!G.updated){if(Z.success=!1,!Z.error)Z.error="Snapshot mismatch"}}return Z}function z4(Z,X,J){return X*J**(Z-1)}async function r0(Z,X={}){let{config:J,shouldRetry:W,onRetry:$,getDelay:G}=X,Y=(J?.count??0)+1,Q=J?.delay??0,z=J?.backoff??1,H=0,K,B;while(H<Y){if(H>0&&$)$(H,J?.count??0);if(H>0){let D=G?.(H,B)??(Q>0?z4(H,Q,z):0);if(D>0)await Bun.sleep(D)}H++;try{let O=await Z();if(B=O,W?.(O)){K="Operation returned retriable result";continue}return{value:O,success:!0,attempts:H}}catch(O){K=O instanceof Error?O.message:String(O)}}return{value:B,success:!1,attempts:H,error:K}}var s0=[429,500,502,503,504];import*as r from"path";class t0{excludePaths;matchRules;constructor(Z){this.excludePaths=new Set(Z.exclude||[]),this.matchRules=new Map(Object.entries(Z.match||{}))}compare(Z,X){let J=[];if(Z.status!==void 0||X.status!==void 0){if(Z.status!==X.status&&!this.isExcluded("status"))J.push({path:"status",expected:Z.status,received:X.status,type:"changed"})}if(Z.headers||X.headers){let W=this.compareObjects(Z.headers||{},X.headers||{},"headers");J.push(...W)}if(Z.body!==void 0||X.body!==void 0){let W=this.deepCompare(Z.body,X.body,"body");J.push(...W)}return{match:J.length===0,differences:J}}deepCompare(Z,X,J){if(this.isExcluded(J))return[];if(this.matchesRule(J,X))return[];if(Z===null&&X===null)return[];if(Z===void 0&&X===void 0)return[];let W=this.getType(Z),$=this.getType(X);if(W!==$)return[{path:J,expected:Z,received:X,type:"type_mismatch"}];if(W!=="object"&&W!=="array"){if(Z!==X)return[{path:J,expected:Z,received:X,type:"changed"}];return[]}if(W==="array")return this.compareArrays(Z,X,J);return this.compareObjects(Z,X,J)}compareArrays(Z,X,J){let W=[],$=Math.max(Z.length,X.length);for(let G=0;G<$;G++){let Y=`${J}[${G}]`;if(G>=Z.length){if(!this.isExcluded(Y))W.push({path:Y,expected:void 0,received:X[G],type:"added"})}else if(G>=X.length){if(!this.isExcluded(Y))W.push({path:Y,expected:Z[G],received:void 0,type:"removed"})}else{let Q=this.deepCompare(Z[G],X[G],Y);W.push(...Q)}}return W}compareObjects(Z,X,J){let W=[],$=new Set([...Object.keys(Z),...Object.keys(X)]);for(let G of $){let Y=J?`${J}.${G}`:G,Q=G in Z,z=G in X;if(!Q&&z){if(!this.isExcluded(Y))W.push({path:Y,expected:void 0,received:X[G],type:"added"})}else if(Q&&!z){if(!this.isExcluded(Y))W.push({path:Y,expected:Z[G],received:void 0,type:"removed"})}else{let H=this.deepCompare(Z[G],X[G],Y);W.push(...H)}}return W}isExcluded(Z){if(this.excludePaths.has(Z))return!0;for(let X of this.excludePaths){if(X.startsWith("*.")){let J=X.slice(2);if(Z.endsWith(`.${J}`))return!0;if(Z.split(".").pop()===J)return!0}if(X.includes("[*]")){if(new RegExp(`^${X.replace(/\[\*\]/g,"\\[\\d+\\]").replace(/\./g,"\\.")}$`).test(Z))return!0}}return!1}matchesRule(Z,X){let J=this.matchRules.get(Z);if(!J)return!1;if(J==="*")return!0;if(J.startsWith("regex:")){let W=J.slice(6);try{return new RegExp(W).test(String(X))}catch{return!1}}return!1}getType(Z){if(Z===null)return"null";if(Z===void 0)return"undefined";if(Array.isArray(Z))return"array";return typeof Z}}var U2=1,B2="__snapshots__";class l1{snapshotDir;globalConfig;writeLocks=new Map;constructor(Z={}){this.globalConfig=Z,this.snapshotDir=Z.dir||B2}getSnapshotPath(Z){let X=r.dirname(Z),J=r.basename(Z,r.extname(Z));return r.join(X,this.snapshotDir,`${J}.snap.json`)}async load(Z){let X=this.getSnapshotPath(Z);try{let J=Bun.file(X);if(!await J.exists())return null;let W=await J.text();return JSON.parse(W)}catch{return null}}async save(Z,X){let J=this.getSnapshotPath(Z),W=this.writeLocks.get(J),$=(async()=>{if(W)await W;let G=r.dirname(J);await(await import("fs/promises")).mkdir(G,{recursive:!0});let Q=JSON.stringify(X,null,2);await Bun.write(J,Q)})();this.writeLocks.set(J,$),await $,this.writeLocks.delete(J)}async get(Z,X){return(await this.load(Z))?.snapshots[X]||null}createSnapshot(Z,X){let J=X.include||["body"],W={hash:"",updatedAt:new Date().toISOString()};if(J.includes("status")&&Z.status!==void 0)W.status=Z.status;if(J.includes("headers")&&Z.headers)W.headers=this.normalizeHeaders(Z.headers);if(J.includes("body")&&Z.body!==void 0)W.body=Z.body;return W.hash=this.hash(W),W}normalizeHeaders(Z){let X={},J=Object.keys(Z).sort();for(let W of J){let $=Z[W];X[W.toLowerCase()]=Array.isArray($)?$.join(", "):$}return X}hash(Z){let X=JSON.stringify(Z),J=new Bun.CryptoHasher("md5");return J.update(X),J.digest("hex").slice(0,8)}async compareAndUpdate(Z,X,J,W){let $=W.name||X,G=await this.get(Z,$),Y=this.createSnapshot(J,W);if(!G){if(this.globalConfig.ci)return{match:!1,isNew:!0,updated:!1,differences:[{path:"",expected:"snapshot",received:"none",type:"removed"}]};return await this.updateSnapshot(Z,$,Y),{match:!0,isNew:!0,updated:!0,differences:[]}}let z=new t0(W).compare(G,Y);if(z.match)return{match:!0,isNew:!1,updated:!1,differences:[]};let H=this.globalConfig.updateMode||"none";if(H==="all"||H==="failing")return await this.updateSnapshot(Z,$,Y),{match:!0,isNew:!1,updated:!0,differences:z.differences};return{match:!1,isNew:!1,updated:!1,differences:z.differences}}async updateSnapshot(Z,X,J){let W=await this.load(Z);if(!W)W={version:U2,snapshots:{}};W.snapshots[X]=J,await this.save(Z,W)}static mergeConfig(Z,X){if(!X&&!Z?.enabled)return null;if(X===!0)return{enabled:!0,include:Z?.include||["body"],exclude:Z?.exclude||[],match:Z?.match||{}};if(typeof X==="object"&&X.enabled!==!1)return{enabled:!0,name:X.name,include:X.include||Z?.include||["body"],exclude:[...Z?.exclude||[],...X.exclude||[]],match:{...Z?.match||{},...X.match||{}}};if(Z?.enabled&&X===void 0)return{enabled:!0,include:Z.include||["body"],exclude:Z.exclude||[],match:Z.match||{}};return null}}function e0(Z,X){let J=X.split("."),W=Z;for(let $ of J){if(W===null||W===void 0)return;if(typeof W!=="object")return;let G=$.match(/^(\w+)\[(\d+)\]$/);if(G){let[,Y,Q]=G,z=Number.parseInt(Q,10);if(W=W[Y],Array.isArray(W))W=W[z];else return}else if(/^\d+$/.test($)&&Array.isArray(W))W=W[Number.parseInt($,10)];else W=W[$]}return W}function n1(Z){if(Z===void 0||Z===null)return"";if(typeof Z==="string")return Z;if(typeof Z==="number"||typeof Z==="boolean")return String(Z);return JSON.stringify(Z)}function H4(Z,X){let J={},W={status:Z.status,headers:Z.headers||{},body:Z.body,metrics:Z.metrics};for(let[$,G]of Object.entries(X)){let Y=e0(W,G);J[$]=n1(Y)}return J}function K4(){return{}}function O2(Z){let X=Z.trim(),J=X.match(/^(.+?)\s+(exists|not-exists)$/i);if(J)return{left:J[1].trim(),operator:J[2].toLowerCase()};let W=/^(.+?)\s*(==|!=|>=|<=|>|<|contains|matches)\s*(.+)$/i,$=X.match(W);if(!$)return null;let[,G,Y,Q]=$,z=_2(Q.trim());return{left:G.trim(),operator:Y.toLowerCase(),right:z}}function _2(Z){if(Z==="true")return!0;if(Z==="false")return!1;let X=Number(Z);if(!Number.isNaN(X)&&Z!=="")return X;if(Z.startsWith('"')&&Z.endsWith('"')||Z.startsWith("'")&&Z.endsWith("'"))return Z.slice(1,-1);return Z}function M2(Z,X){let J=Z.startsWith("store.")?Z.slice(6):Z;if(J in X){let G=X[J];if(G.startsWith("{")||G.startsWith("["))try{return JSON.parse(G)}catch{return G}let Y=Number(G);if(!Number.isNaN(Y)&&G!=="")return Y;if(G==="true")return!0;if(G==="false")return!1;return G}let W=J.split("."),$=W[0];if($ in X){let G=X[$];try{let Y=JSON.parse(G);return e0(Y,W.slice(1).join("."))}catch{return}}return}function U4(Z,X,J){if(J)return Z===X;return Z.toLowerCase()===X.toLowerCase()}function o1(Z,X){let J=M2(Z.left,X),W=Z.caseSensitive??!1,$=(Y)=>{if(Y===void 0)return"undefined";if(Y===null)return"null";if(typeof Y==="string")return`"${Y}"`;return String(Y)},G=`${Z.left} ${Z.operator}${Z.right!==void 0?` ${$(Z.right)}`:""}`;switch(Z.operator){case"exists":return{passed:J!==void 0&&J!==null&&J!=="",description:G};case"not-exists":return{passed:J===void 0||J===null||J==="",description:G};case"==":{let Y;if(typeof J==="string"&&typeof Z.right==="string")Y=U4(J,Z.right,W);else Y=J==Z.right;return{passed:Y,description:G}}case"!=":{let Y;if(typeof J==="string"&&typeof Z.right==="string")Y=!U4(J,Z.right,W);else Y=J!=Z.right;return{passed:Y,description:G}}case">":return{passed:Number(J)>Number(Z.right),description:G};case"<":return{passed:Number(J)<Number(Z.right),description:G};case">=":return{passed:Number(J)>=Number(Z.right),description:G};case"<=":return{passed:Number(J)<=Number(Z.right),description:G};case"contains":{let Y=n1(J),Q=String(Z.right??"");return{passed:W?Y.includes(Q):Y.toLowerCase().includes(Q.toLowerCase()),description:G}}case"matches":{let Y=n1(J),Q=String(Z.right??"");try{return{passed:new RegExp(Q,W?"":"i").test(Y),description:G}}catch{return{passed:!1,description:`${G} (invalid regex)`}}}default:return{passed:!1,description:`unknown operator: ${Z.operator}`}}}function B4(Z,X){if(typeof Z==="string"){let J=O2(Z);if(!J)return{shouldRun:!1,reason:`invalid condition syntax: "${Z}"`};let W=o1(J,X);return{shouldRun:W.passed,reason:W.passed?void 0:`condition not met: ${W.description}`}}if(Z.all&&Z.all.length>0){for(let J of Z.all){let W=o1(J,X);if(!W.passed)return{shouldRun:!1,reason:`condition not met: ${W.description}`}}return{shouldRun:!0}}if(Z.any&&Z.any.length>0){let J=[];for(let W of Z.any){let $=o1(W,X);if($.passed)return{shouldRun:!0};J.push($.description)}return{shouldRun:!1,reason:`no conditions met: ${J.join(", ")}`}}if(Z.left&&Z.operator){let J={left:Z.left,operator:Z.operator,right:Z.right,caseSensitive:Z.caseSensitive},W=o1(J,X);return{shouldRun:W.passed,reason:W.passed?void 0:`condition not met: ${W.description}`}}return{shouldRun:!0}}class Z9{poolConfig;constructor(Z={}){this.poolConfig={enabled:!0,maxStreamsPerHost:10,keepaliveTime:60,connectTimeout:30,...Z}}getHostKey(Z){try{let X=new URL(Z);return`${X.protocol}//${X.host}`}catch{return Z}}groupRequestsByHost(Z){let X=new Map;return Z.forEach((J,W)=>{let $=this.getHostKey(J.url),G=X.get($)||[];G.push({index:W,config:J}),X.set($,G)}),Array.from(X.entries()).map(([J,W])=>({host:J,requests:W}))}buildRequestArgs(Z,X){let{args:J,url:W}=F1(Z,{writeOutMarker:d0(X),includeSilentFlags:!1,includeHttp2Flag:!1,includeOutputFlag:!1});return J.push(W),J}buildBatchedCommand(Z){let X=[];return X.push("-Z"),X.push("--parallel-max",this.poolConfig.maxStreamsPerHost.toString()),X.push("--http2"),X.push("--keepalive-time",this.poolConfig.keepaliveTime.toString()),X.push("--connect-timeout",this.poolConfig.connectTimeout.toString()),X.push("-s","-S"),Z.requests.forEach((J,W)=>{if(W>0)X.push("--next");let $=this.buildRequestArgs(J.config,J.index);X.push(...$)}),X}parseBatchedOutput(Z,X,J,W){let $=new Map;for(let G of J.requests){let{found:Y,metricsJson:Q,startIdx:z}=f0(Z,G.index);if(!Y){$.set(G.index,{request:G.config,success:!1,error:X||`Request failed (exit code: ${W})`,metrics:{duration:0}});continue}let H={};try{H=JSON.parse(Q)}catch{}let K=z,B=0;for(let S of J.requests){if(S.index===G.index)continue;let V=`__CURL_BATCH_${S.index}_END__`,k=Z.indexOf(V);if(k!==-1&&k<K&&k+V.length>B)B=k+V.length}let O=Z.substring(B,K),{blocks:D,bodyOffset:M}=d1(O),_;for(let S=D.length-1;S>=0;S--)if(D[S].status>=200){_=D[S];break}let N=O.slice(M).trim(),I=L1(H)??_?.status,j=N1(H);$.set(G.index,{request:G.config,success:c0(I),status:I,headers:_?.headers??{},headerHistory:D,body:$1(N),metrics:j})}return $}async executeBatch(Z){let X=this.buildBatchedCommand(Z);try{let J=Bun.spawn(["curl",...X],{stdout:"pipe",stderr:"pipe"}),W=await new Response(J.stdout).text(),$=await new Response(J.stderr).text();return await J.exited,this.parseBatchedOutput(W,$,Z,J.exitCode||0)}catch(J){let W=new Map;for(let $ of Z.requests)W.set($.index,{request:$.config,success:!1,error:J instanceof Error?J.message:String(J),metrics:{duration:0}});return W}}async executeAll(Z){let X=this.groupRequestsByHost(Z),J=new Map,W=X.map((G)=>this.executeBatch(G)),$=await Promise.all(W);for(let G of $)for(let[Y,Q]of G)J.set(Y,Q);return Z.map((G,Y)=>{return J.get(Y)||{request:Z[Y],success:!1,error:"Request not executed",metrics:{duration:0}}})}formatBatchedCommandForDisplay(Z){let X=this.buildBatchedCommand(Z);return T1(X)}}class X9{logger;globalConfig;snapshotManager;pooledExecutor=null;constructor(Z={}){if(this.globalConfig=Z,this.logger=new l(Z.output),this.snapshotManager=new l1(Z.snapshot),Z.connectionPool?.enabled)this.pooledExecutor=new Z9(Z.connectionPool)}mergeOutputConfig(Z){return{...this.globalConfig.output,...Z.sourceOutputConfig}}getSnapshotConfig(Z){return l1.mergeConfig(this.globalConfig.snapshot,Z.snapshot)}isFileAttachment(Z){return typeof Z==="object"&&Z!==null&&"file"in Z}async validateFileAttachments(Z){if(!Z.formData)return;let X=[];for(let[J,W]of Object.entries(Z.formData))if(this.isFileAttachment(W)){let $=W.file;if(!await Bun.file($).exists())X.push(`${J}: ${$}`)}if(X.length>0)return`File(s) not found: ${X.join(", ")}`;return}async executeRequest(Z,X=0){let J=performance.now(),W=this.mergeOutputConfig(Z),$=new l(W);$.logRequestStart(Z,X);let G=await this.validateFileAttachments(Z);if(G){let D={request:Z,success:!1,error:G,metrics:{duration:performance.now()-J}};return $.logRequestComplete(D),D}let Y=Z1.buildCommand(Z);if($.logCommand(Z1.formatCommandForDisplay(Y)),this.globalConfig.dryRun){let D={request:Z,success:!0,dryRun:!0,metrics:{duration:0}};return $.logRequestComplete(D),D}let Q=Z.retry?.retryableStatuses??[...s0],z=(Z.retry?.count??0)>0,H=await r0(()=>Z1.executeCurl(Y),{config:Z.retry,shouldRetry:(D)=>{if(!D.success)return!0;if(z&&D.status!==void 0)return Q.includes(D.status);return!1},onRetry:(D,M)=>$.logRetry(D,M),getDelay:(D,M)=>{if(M?.status===429&&M.headers){let _=M.headers["retry-after"],N=Array.isArray(_)?_[0]:_;if(N){let I=Number(N);if(!Number.isNaN(I))return I*1000}}return}}),K=z&&H.value?.status!==void 0&&Q.includes(H.value.status);if(!H.success||!H.value?.success||K){let D={request:Z,success:!1,status:H.value?.status,error:H.error||H.value?.error||`Request failed with status ${H.value?.status}`,metrics:{duration:performance.now()-J}};return $.logRequestComplete(D),D}let B=H.value,O=this.processCurlResult(Z,B,J);return await u1(O,Z,{snapshotManager:this.snapshotManager,snapshotConfig:this.getSnapshotConfig(Z)}),$.logRequestComplete(O),O}processCurlResult(Z,X,J){let W=X.headers?.["content-type"],$=Array.isArray(W)?W[0]:W,G=$1(X.body,$);return{request:Z,success:!0,status:X.status,headers:X.headers,headerHistory:X.headerHistory,body:G,metrics:{...X.metrics,duration:performance.now()-J}}}async executeSequential(Z){let X=performance.now(),J=[],W=K4();for(let $=0;$<Z.length;$++){let G=this.interpolateStoreVariables(Z[$],W);if(G.when){let Q=B4(G.when,W);if(!Q.shouldRun){let z={request:G,success:!0,skipped:!0,skipReason:Q.reason};J.push(z),this.logger.logSkipped(G,$+1,Q.reason);continue}}let Y=await this.executeRequest(G,$+1);if(J.push(Y),Y.success&&G.store){let Q=H4(Y,G.store);Object.assign(W,Q),this.logStoredValues(Q)}if(!Y.success&&!this.globalConfig.continueOnError){this.logger.logError("Stopping execution due to error");break}}return this.createSummary(J,performance.now()-X)}interpolateStoreVariables(Z,X){if(Object.keys(X).length===0)return Z;return v.interpolateVariables(Z,{},X)}logStoredValues(Z){if(Object.keys(Z).length===0)return;let X=Object.entries(Z);for(let[J,W]of X){let $=W.length>50?`${W.substring(0,50)}...`:W;this.logger.logInfo(`Stored: ${J} = "${$}"`)}}async executeParallel(Z){let X=performance.now();if(this.pooledExecutor&&!this.globalConfig.dryRun)return this.executePooled(Z,X);let J=this.globalConfig.maxConcurrency;if(!J||J>=Z.length){let $=Z.map((Y,Q)=>this.executeRequest(Y,Q+1)),G=await Promise.all($);return this.createSummary(G,performance.now()-X)}let W=[];for(let $=0;$<Z.length;$+=J){let Y=Z.slice($,$+J).map((H,K)=>this.executeRequest(H,$+K+1)),Q=await Promise.all(Y);if(W.push(...Q),Q.some((H)=>!H.success)&&!this.globalConfig.continueOnError){this.logger.logError("Stopping execution due to error");break}}return this.createSummary(W,performance.now()-X)}async executePooled(Z,X){this.logger.logInfo(`Using connection pooling (HTTP/2 multiplexing) for ${Z.length} requests`);let J=this.pooledExecutor.groupRequestsByHost(Z);for(let G of J)this.logger.logInfo(` ${G.host}: ${G.requests.length} request(s) batched`);let W=await this.pooledExecutor.executeAll(Z),$=[];for(let G=0;G<W.length;G++){let Y=W[G],Q=Z[G],z=this.mergeOutputConfig(Q),H=new l(z);if(H.logRequestStart(Q,G+1),await u1(Y,Q,{snapshotManager:this.snapshotManager,snapshotConfig:this.getSnapshotConfig(Q)}),H.logRequestComplete(Y),$.push(Y),!Y.success&&!this.globalConfig.continueOnError){this.logger.logError("Stopping execution due to error");break}}return this.createSummary($,performance.now()-X)}async execute(Z){this.logger.logExecutionStart(Z.length,this.globalConfig.execution||"sequential");let X=this.globalConfig.execution==="parallel"?await this.executeParallel(Z):await this.executeSequential(Z);if(this.logger.logSummary(X),this.globalConfig.output?.saveToFile)await this.saveSummaryToFile(X);return X}createSummary(Z,X){let J=Z.filter((G)=>G.skipped).length,W=Z.filter((G)=>G.success&&!G.skipped).length,$=Z.filter((G)=>!G.success).length;return{total:Z.length,successful:W,failed:$,skipped:J,duration:X,results:Z}}async saveSummaryToFile(Z){let X=this.globalConfig.output?.saveToFile;if(!X)return;let J=JSON.stringify(Z,null,2);await Bun.write(X,J),this.logger.logInfo(`Results saved to ${X}`)}}var O4=`${process.env.HOME}/.curl-runner-version-cache.json`,D2=86400000,F2="https://registry.npmjs.org/@curl-runner/cli/latest";class J9{async checkForUpdates(Z=!1){try{if(process.env.CI)return;let X=o();if(X==="0.0.0")return;if(!Z){let W=await this.getCachedVersion();if(W&&Date.now()-W.lastCheck<D2){this.compareVersions(X,W.latestVersion);return}}let J=await this.fetchLatestVersion();if(J)await this.setCachedVersion(J),this.compareVersions(X,J)}catch{}}async fetchLatestVersion(){try{let Z=await fetch(F2,{signal:AbortSignal.timeout(3000)});if(!Z.ok)return null;return(await Z.json()).version}catch{return null}}compareVersions(Z,X){if(this.isNewerVersion(Z,X))console.log(),console.log(F("\u256D\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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E","yellow")),console.log(F("\u2502","yellow")+" "+F("\u2502","yellow")),console.log(F("\u2502","yellow")+" "+F("Update available!","bright")+` ${F(Z,"red")} \u2192 ${F(X,"green")} `+F("\u2502","yellow")),console.log(F("\u2502","yellow")+" "+F("\u2502","yellow")),console.log(F("\u2502","yellow")+" Run "+F("curl-runner upgrade","cyan")+" to update "+F("\u2502","yellow")),console.log(F("\u2502","yellow")+" "+F("\u2502","yellow")),console.log(F("\u2570\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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F","yellow")),console.log()}isNewerVersion(Z,X){try{let J=Z.replace(/^v/,""),W=X.replace(/^v/,""),$=J.split(".").map(Number),G=W.split(".").map(Number);for(let Y=0;Y<Math.max($.length,G.length);Y++){let Q=$[Y]||0,z=G[Y]||0;if(z>Q)return!0;if(z<Q)return!1}return!1}catch{return!1}}async getCachedVersion(){try{let Z=Bun.file(O4);if(await Z.exists())return JSON.parse(await Z.text())}catch{}return null}async setCachedVersion(Z){try{let X={lastCheck:Date.now(),latestVersion:Z};await Bun.write(O4,JSON.stringify(X))}catch{}}}import{watch as T2}from"fs";class W9{watchers=[];debounceTimer=null;isRunning=!1;pendingRun=!1;options;constructor(Z){this.options=Z}async start(){let{files:Z,logger:X}=this.options;await this.runRequests();for(let J of Z)try{let W=T2(J,($)=>{if($==="change")this.handleFileChange(J)});W.on("error",($)=>{X.logWarning(`Watch error on ${J}: ${$.message}`)}),this.watchers.push(W)}catch(W){X.logWarning(`Failed to watch ${J}: ${W instanceof Error?W.message:String(W)}`)}X.logWatch(Z),this.setupSignalHandlers(),await this.keepAlive()}handleFileChange(Z){let{config:X,logger:J}=this.options,W=X.debounce??300;if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(async()=>{if(this.isRunning){this.pendingRun=!0;return}if(X.clear!==!1)console.clear();J.logFileChanged(Z),await this.runRequests()},W)}async runRequests(){let{onRun:Z,logger:X}=this.options;this.isRunning=!0;try{await Z()}catch(J){X.logError(J instanceof Error?J.message:String(J))}if(this.isRunning=!1,this.pendingRun){this.pendingRun=!1;let{config:J}=this.options;if(J.clear!==!1)console.clear();X.logFileChanged("(queued change)"),await this.runRequests()}else X.logWatchReady()}setupSignalHandlers(){let Z=()=>{this.stop(),process.exit(0)};process.on("SIGINT",Z),process.on("SIGTERM",Z)}async keepAlive(){while(!0)await Bun.sleep(1000)}stop(){for(let Z of this.watchers)Z.close();if(this.watchers=[],this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null}}var X1=V1(G9(),1);import{stdout as L4,stdin as S2}from"process";var h=V1(Q9(),1);import E2 from"readline";var A2=(Z)=>Z===161||Z===164||Z===167||Z===168||Z===170||Z===173||Z===174||Z>=176&&Z<=180||Z>=182&&Z<=186||Z>=188&&Z<=191||Z===198||Z===208||Z===215||Z===216||Z>=222&&Z<=225||Z===230||Z>=232&&Z<=234||Z===236||Z===237||Z===240||Z===242||Z===243||Z>=247&&Z<=250||Z===252||Z===254||Z===257||Z===273||Z===275||Z===283||Z===294||Z===295||Z===299||Z>=305&&Z<=307||Z===312||Z>=319&&Z<=322||Z===324||Z>=328&&Z<=331||Z===333||Z===338||Z===339||Z===358||Z===359||Z===363||Z===462||Z===464||Z===466||Z===468||Z===470||Z===472||Z===474||Z===476||Z===593||Z===609||Z===708||Z===711||Z>=713&&Z<=715||Z===717||Z===720||Z>=728&&Z<=731||Z===733||Z===735||Z>=768&&Z<=879||Z>=913&&Z<=929||Z>=931&&Z<=937||Z>=945&&Z<=961||Z>=963&&Z<=969||Z===1025||Z>=1040&&Z<=1103||Z===1105||Z===8208||Z>=8211&&Z<=8214||Z===8216||Z===8217||Z===8220||Z===8221||Z>=8224&&Z<=8226||Z>=8228&&Z<=8231||Z===8240||Z===8242||Z===8243||Z===8245||Z===8251||Z===8254||Z===8308||Z===8319||Z>=8321&&Z<=8324||Z===8364||Z===8451||Z===8453||Z===8457||Z===8467||Z===8470||Z===8481||Z===8482||Z===8486||Z===8491||Z===8531||Z===8532||Z>=8539&&Z<=8542||Z>=8544&&Z<=8555||Z>=8560&&Z<=8569||Z===8585||Z>=8592&&Z<=8601||Z===8632||Z===8633||Z===8658||Z===8660||Z===8679||Z===8704||Z===8706||Z===8707||Z===8711||Z===8712||Z===8715||Z===8719||Z===8721||Z===8725||Z===8730||Z>=8733&&Z<=8736||Z===8739||Z===8741||Z>=8743&&Z<=8748||Z===8750||Z>=8756&&Z<=8759||Z===8764||Z===8765||Z===8776||Z===8780||Z===8786||Z===8800||Z===8801||Z>=8804&&Z<=8807||Z===8810||Z===8811||Z===8814||Z===8815||Z===8834||Z===8835||Z===8838||Z===8839||Z===8853||Z===8857||Z===8869||Z===8895||Z===8978||Z>=9312&&Z<=9449||Z>=9451&&Z<=9547||Z>=9552&&Z<=9587||Z>=9600&&Z<=9615||Z>=9618&&Z<=9621||Z===9632||Z===9633||Z>=9635&&Z<=9641||Z===9650||Z===9651||Z===9654||Z===9655||Z===9660||Z===9661||Z===9664||Z===9665||Z>=9670&&Z<=9672||Z===9675||Z>=9678&&Z<=9681||Z>=9698&&Z<=9701||Z===9711||Z===9733||Z===9734||Z===9737||Z===9742||Z===9743||Z===9756||Z===9758||Z===9792||Z===9794||Z===9824||Z===9825||Z>=9827&&Z<=9829||Z>=9831&&Z<=9834||Z===9836||Z===9837||Z===9839||Z===9886||Z===9887||Z===9919||Z>=9926&&Z<=9933||Z>=9935&&Z<=9939||Z>=9941&&Z<=9953||Z===9955||Z===9960||Z===9961||Z>=9963&&Z<=9969||Z===9972||Z>=9974&&Z<=9977||Z===9979||Z===9980||Z===9982||Z===9983||Z===10045||Z>=10102&&Z<=10111||Z>=11094&&Z<=11097||Z>=12872&&Z<=12879||Z>=57344&&Z<=63743||Z>=65024&&Z<=65039||Z===65533||Z>=127232&&Z<=127242||Z>=127248&&Z<=127277||Z>=127280&&Z<=127337||Z>=127344&&Z<=127373||Z===127375||Z===127376||Z>=127387&&Z<=127404||Z>=917760&&Z<=917999||Z>=983040&&Z<=1048573||Z>=1048576&&Z<=1114109,V2=(Z)=>Z===12288||Z>=65281&&Z<=65376||Z>=65504&&Z<=65510,P2=(Z)=>Z>=4352&&Z<=4447||Z===8986||Z===8987||Z===9001||Z===9002||Z>=9193&&Z<=9196||Z===9200||Z===9203||Z===9725||Z===9726||Z===9748||Z===9749||Z>=9800&&Z<=9811||Z===9855||Z===9875||Z===9889||Z===9898||Z===9899||Z===9917||Z===9918||Z===9924||Z===9925||Z===9934||Z===9940||Z===9962||Z===9970||Z===9971||Z===9973||Z===9978||Z===9981||Z===9989||Z===9994||Z===9995||Z===10024||Z===10060||Z===10062||Z>=10067&&Z<=10069||Z===10071||Z>=10133&&Z<=10135||Z===10160||Z===10175||Z===11035||Z===11036||Z===11088||Z===11093||Z>=11904&&Z<=11929||Z>=11931&&Z<=12019||Z>=12032&&Z<=12245||Z>=12272&&Z<=12287||Z>=12289&&Z<=12350||Z>=12353&&Z<=12438||Z>=12441&&Z<=12543||Z>=12549&&Z<=12591||Z>=12593&&Z<=12686||Z>=12688&&Z<=12771||Z>=12783&&Z<=12830||Z>=12832&&Z<=12871||Z>=12880&&Z<=19903||Z>=19968&&Z<=42124||Z>=42128&&Z<=42182||Z>=43360&&Z<=43388||Z>=44032&&Z<=55203||Z>=63744&&Z<=64255||Z>=65040&&Z<=65049||Z>=65072&&Z<=65106||Z>=65108&&Z<=65126||Z>=65128&&Z<=65131||Z>=94176&&Z<=94180||Z===94192||Z===94193||Z>=94208&&Z<=100343||Z>=100352&&Z<=101589||Z>=101632&&Z<=101640||Z>=110576&&Z<=110579||Z>=110581&&Z<=110587||Z===110589||Z===110590||Z>=110592&&Z<=110882||Z===110898||Z>=110928&&Z<=110930||Z===110933||Z>=110948&&Z<=110951||Z>=110960&&Z<=111355||Z===126980||Z===127183||Z===127374||Z>=127377&&Z<=127386||Z>=127488&&Z<=127490||Z>=127504&&Z<=127547||Z>=127552&&Z<=127560||Z===127568||Z===127569||Z>=127584&&Z<=127589||Z>=127744&&Z<=127776||Z>=127789&&Z<=127797||Z>=127799&&Z<=127868||Z>=127870&&Z<=127891||Z>=127904&&Z<=127946||Z>=127951&&Z<=127955||Z>=127968&&Z<=127984||Z===127988||Z>=127992&&Z<=128062||Z===128064||Z>=128066&&Z<=128252||Z>=128255&&Z<=128317||Z>=128331&&Z<=128334||Z>=128336&&Z<=128359||Z===128378||Z===128405||Z===128406||Z===128420||Z>=128507&&Z<=128591||Z>=128640&&Z<=128709||Z===128716||Z>=128720&&Z<=128722||Z>=128725&&Z<=128727||Z>=128732&&Z<=128735||Z===128747||Z===128748||Z>=128756&&Z<=128764||Z>=128992&&Z<=129003||Z===129008||Z>=129292&&Z<=129338||Z>=129340&&Z<=129349||Z>=129351&&Z<=129535||Z>=129648&&Z<=129660||Z>=129664&&Z<=129672||Z>=129680&&Z<=129725||Z>=129727&&Z<=129733||Z>=129742&&Z<=129755||Z>=129760&&Z<=129768||Z>=129776&&Z<=129784||Z>=131072&&Z<=196605||Z>=196608&&Z<=262141,z9=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,r1=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,s1=/\t{1,1000}/y,H9=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,t1=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,k2=/\p{M}+/gu,C2={limit:1/0,ellipsis:""},I4=(Z,X={},J={})=>{let W=X.limit??1/0,$=X.ellipsis??"",G=X?.ellipsisWidth??($?I4($,C2,J).width:0),Y=J.ansiWidth??0,Q=J.controlWidth??0,z=J.tabWidth??8,H=J.ambiguousWidth??1,K=J.emojiWidth??2,B=J.fullWidthWidth??2,O=J.regularWidth??1,D=J.wideWidth??2,M=0,_=0,N=Z.length,I=0,j=!1,S=N,V=Math.max(0,W-G),k=0,w=0,T=0,L=0;Z:for(;;){if(w>k||_>=N&&_>M){let f=Z.slice(k,w)||Z.slice(M,_);I=0;for(let c of f.replaceAll(k2,"")){let g=c.codePointAt(0)||0;if(V2(g)?L=B:P2(g)?L=D:H!==O&&A2(g)?L=H:L=O,T+L>V&&(S=Math.min(S,Math.max(k,M)+I)),T+L>W){j=!0;break Z}I+=c.length,T+=L}k=w=0}if(_>=N)break;if(t1.lastIndex=_,t1.test(Z)){if(I=t1.lastIndex-_,L=I*O,T+L>V&&(S=Math.min(S,_+Math.floor((V-T)/O))),T+L>W){j=!0;break}T+=L,k=M,w=_,_=M=t1.lastIndex;continue}if(z9.lastIndex=_,z9.test(Z)){if(T+Y>V&&(S=Math.min(S,_)),T+Y>W){j=!0;break}T+=Y,k=M,w=_,_=M=z9.lastIndex;continue}if(r1.lastIndex=_,r1.test(Z)){if(I=r1.lastIndex-_,L=I*Q,T+L>V&&(S=Math.min(S,_+Math.floor((V-T)/Q))),T+L>W){j=!0;break}T+=L,k=M,w=_,_=M=r1.lastIndex;continue}if(s1.lastIndex=_,s1.test(Z)){if(I=s1.lastIndex-_,L=I*z,T+L>V&&(S=Math.min(S,_+Math.floor((V-T)/z))),T+L>W){j=!0;break}T+=L,k=M,w=_,_=M=s1.lastIndex;continue}if(H9.lastIndex=_,H9.test(Z)){if(T+K>V&&(S=Math.min(S,_)),T+K>W){j=!0;break}T+=K,k=M,w=_,_=M=H9.lastIndex;continue}_+=1}return{width:j?V:T,index:j?S:N,truncated:j,ellipsed:j&&W>=G}},w2={limit:1/0,ellipsis:"",ellipsisWidth:0},j1=(Z,X={})=>I4(Z,w2,X).width,Z0="\x1B",j4="\x9B",q2=39,O9="\x07",R4="[",x2="]",S4="m",_9=`${x2}8;;`,F4=new RegExp(`(?:\\${R4}(?<code>\\d+)m|\\${_9}(?<uri>.*)${O9})`,"y"),b2=(Z)=>{if(Z>=30&&Z<=37||Z>=90&&Z<=97)return 39;if(Z>=40&&Z<=47||Z>=100&&Z<=107)return 49;if(Z===1||Z===2)return 22;if(Z===3)return 23;if(Z===4)return 24;if(Z===7)return 27;if(Z===8)return 28;if(Z===9)return 29;if(Z===0)return 0},T4=(Z)=>`${Z0}${R4}${Z}${S4}`,N4=(Z)=>`${Z0}${_9}${Z}${O9}`,v2=(Z)=>Z.map((X)=>j1(X)),K9=(Z,X,J)=>{let W=X[Symbol.iterator](),$=!1,G=!1,Y=Z.at(-1),Q=Y===void 0?0:j1(Y),z=W.next(),H=W.next(),K=0;for(;!z.done;){let B=z.value,O=j1(B);Q+O<=J?Z[Z.length-1]+=B:(Z.push(B),Q=0),(B===Z0||B===j4)&&($=!0,G=X.startsWith(_9,K+1)),$?G?B===O9&&($=!1,G=!1):B===S4&&($=!1):(Q+=O,Q===J&&!H.done&&(Z.push(""),Q=0)),z=H,H=W.next(),K+=B.length}Y=Z.at(-1),!Q&&Y!==void 0&&Y.length>0&&Z.length>1&&(Z[Z.length-2]+=Z.pop())},y2=(Z)=>{let X=Z.split(" "),J=X.length;for(;J>0&&!(j1(X[J-1])>0);)J--;return J===X.length?Z:X.slice(0,J).join(" ")+X.slice(J).join("")},m2=(Z,X,J={})=>{if(J.trim!==!1&&Z.trim()==="")return"";let W="",$,G,Y=Z.split(" "),Q=v2(Y),z=[""];for(let[M,_]of Y.entries()){J.trim!==!1&&(z[z.length-1]=(z.at(-1)??"").trimStart());let N=j1(z.at(-1)??"");if(M!==0&&(N>=X&&(J.wordWrap===!1||J.trim===!1)&&(z.push(""),N=0),(N>0||J.trim===!1)&&(z[z.length-1]+=" ",N++)),J.hard&&Q[M]>X){let I=X-N,j=1+Math.floor((Q[M]-I-1)/X);Math.floor((Q[M]-1)/X)<j&&z.push(""),K9(z,_,X);continue}if(N+Q[M]>X&&N>0&&Q[M]>0){if(J.wordWrap===!1&&N<X){K9(z,_,X);continue}z.push("")}if(N+Q[M]>X&&J.wordWrap===!1){K9(z,_,X);continue}z[z.length-1]+=_}J.trim!==!1&&(z=z.map((M)=>y2(M)));let H=z.join(`
159
- `),K=H[Symbol.iterator](),B=K.next(),O=K.next(),D=0;for(;!B.done;){let M=B.value,_=O.value;if(W+=M,M===Z0||M===j4){F4.lastIndex=D+1;let I=F4.exec(H)?.groups;if(I?.code!==void 0){let j=Number.parseFloat(I.code);$=j===q2?void 0:j}else I?.uri!==void 0&&(G=I.uri.length===0?void 0:I.uri)}let N=$?b2($):void 0;_===`
160
- `?(G&&(W+=N4("")),$&&N&&(W+=T4(N))):M===`
161
- `&&($&&N&&(W+=T4($)),G&&(W+=N4(G))),D+=M.length,B=O,O=K.next()}return W};function U9(Z,X,J){return String(Z).normalize().replaceAll(`\r
162
- `,`
163
- `).split(`
164
- `).map((W)=>m2(W,X,J)).join(`
165
- `)}var h2=["up","down","left","right","space","enter","cancel"],J1={actions:new Set(h2),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0};function E4(Z,X){if(typeof Z=="string")return J1.aliases.get(Z)===X;for(let J of Z)if(J!==void 0&&E4(J,X))return!0;return!1}function g2(Z,X){if(Z===X)return;let J=Z.split(`
166
- `),W=X.split(`
167
- `),$=Math.max(J.length,W.length),G=[];for(let Y=0;Y<$;Y++)J[Y]!==W[Y]&&G.push(Y);return{lines:G,numLinesBefore:J.length,numLinesAfter:W.length,numLines:$}}var B8=globalThis.process.platform.startsWith("win"),B9=Symbol("clack:cancel");function R(Z){return Z===B9}function e1(Z,X){let J=Z;J.isTTY&&J.setRawMode(X)}var M9=(Z)=>("columns"in Z)&&typeof Z.columns=="number"?Z.columns:80,D9=(Z)=>("rows"in Z)&&typeof Z.rows=="number"?Z.rows:20;function Y1(Z,X,J,W=J){let $=M9(Z??L4);return U9(X,$-J.length,{hard:!0,trim:!1}).split(`
168
- `).map((G,Y)=>`${Y===0?W:J}${G}`).join(`
169
- `)}class W1{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(Z,X=!0){let{input:J=S2,output:W=L4,render:$,signal:G,...Y}=Z;this.opts=Y,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=$.bind(this),this._track=X,this._abortSignal=G,this.input=J,this.output=W}unsubscribe(){this._subscribers.clear()}setSubscriber(Z,X){let J=this._subscribers.get(Z)??[];J.push(X),this._subscribers.set(Z,J)}on(Z,X){this.setSubscriber(Z,{cb:X})}once(Z,X){this.setSubscriber(Z,{cb:X,once:!0})}emit(Z,...X){let J=this._subscribers.get(Z)??[],W=[];for(let $ of J)$.cb(...X),$.once&&W.push(()=>J.splice(J.indexOf($),1));for(let $ of W)$()}prompt(){return new Promise((Z)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),Z(B9);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=E2.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),e1(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(h.cursor.show),this.output.off("resize",this.render),e1(this.input,!1),Z(this.value)}),this.once("cancel",()=>{this.output.write(h.cursor.show),this.output.off("resize",this.render),e1(this.input,!1),Z(B9)})})}_isActionKey(Z,X){return Z==="\t"}_setValue(Z){this.value=Z,this.emit("value",this.value)}_setUserInput(Z,X){this.userInput=Z??"",this.emit("userInput",this.userInput),X&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(Z,X){if(this._track&&X.name!=="return"&&(X.name&&this._isActionKey(Z,X)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),X?.name&&(!this._track&&J1.aliases.has(X.name)&&this.emit("cursor",J1.aliases.get(X.name)),J1.actions.has(X.name)&&this.emit("cursor",X.name)),Z&&(Z.toLowerCase()==="y"||Z.toLowerCase()==="n")&&this.emit("confirm",Z.toLowerCase()==="y"),this.emit("key",Z?.toLowerCase(),X),X?.name==="return"){if(this.opts.validate){let J=this.opts.validate(this.value);J&&(this.error=J instanceof Error?J.message:J,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}E4([Z,X?.name,X?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
170
- `),e1(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let Z=U9(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
171
- `).length-1;this.output.write(h.cursor.move(-999,Z*-1))}render(){let Z=U9(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(Z!==this._prevFrame){if(this.state==="initial")this.output.write(h.cursor.hide);else{let X=g2(this._prevFrame,Z),J=D9(this.output);if(this.restoreCursor(),X){let W=Math.max(0,X.numLinesAfter-J),$=Math.max(0,X.numLinesBefore-J),G=X.lines.find((Y)=>Y>=W);if(G===void 0){this._prevFrame=Z;return}if(X.lines.length===1){this.output.write(h.cursor.move(0,G-$)),this.output.write(h.erase.lines(1));let Y=Z.split(`
172
- `);this.output.write(Y[G]),this._prevFrame=Z,this.output.write(h.cursor.move(0,Y.length-G-1));return}else if(X.lines.length>1){if(W<$)G=W;else{let Q=G-$;Q>0&&this.output.write(h.cursor.move(0,Q))}this.output.write(h.erase.down());let Y=Z.split(`
173
- `).slice(G);this.output.write(Y.join(`
174
- `)),this._prevFrame=Z;return}}this.output.write(h.erase.down())}this.output.write(Z),this.state==="initial"&&(this.state="active"),this._prevFrame=Z}}}function d2(Z,X){if(Z===void 0||X.length===0)return 0;let J=X.findIndex((W)=>W.value===Z);return J!==-1?J:0}function f2(Z,X){return(X.label??String(X.value)).toLowerCase().includes(Z.toLowerCase())}function p2(Z,X){if(X)return Z?X:X[0]}class A4 extends W1{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#Z=0;#J="";#W;#X;get cursor(){return this.#Z}get userInputWithCursor(){if(!this.userInput)return X1.default.inverse(X1.default.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let Z=this.userInput.slice(0,this._cursor),[X,...J]=this.userInput.slice(this._cursor);return`${Z}${X1.default.inverse(X)}${J.join("")}`}get options(){return typeof this.#X=="function"?this.#X():this.#X}constructor(Z){super(Z),this.#X=Z.options;let X=this.options;this.filteredOptions=[...X],this.multiple=Z.multiple===!0,this.#W=Z.filter??f2;let J;if(Z.initialValue&&Array.isArray(Z.initialValue)?this.multiple?J=Z.initialValue:J=Z.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(J=[this.options[0].value]),J)for(let W of J){let $=X.findIndex((G)=>G.value===W);$!==-1&&(this.toggleSelected(W),this.#Z=$)}this.focusedValue=this.options[this.#Z]?.value,this.on("key",(W,$)=>this.#$(W,$)),this.on("userInput",(W)=>this.#G(W))}_isActionKey(Z,X){return Z==="\t"||this.multiple&&this.isNavigating&&X.name==="space"&&Z!==void 0&&Z!==""}#$(Z,X){let J=X.name==="up",W=X.name==="down",$=X.name==="return";J||W?(this.#Z=Math.max(0,Math.min(this.#Z+(J?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#Z]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):$?this.value=p2(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(X.name==="tab"||this.isNavigating&&X.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(Z){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(Z)?this.selectedValues=this.selectedValues.filter((X)=>X!==Z):this.selectedValues=[...this.selectedValues,Z]:this.selectedValues=[Z])}#G(Z){if(Z!==this.#J){this.#J=Z;let X=this.options;Z?this.filteredOptions=X.filter((J)=>this.#W(Z,J)):this.filteredOptions=[...X],this.#Z=d2(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#Z]?.value,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}}class F9 extends W1{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(Z){super(Z,!1),this.value=!!Z.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(X)=>{this.output.write(h.cursor.move(0,-1)),this.value=X,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}class V4 extends W1{options;cursor=0;#Z;getGroupItems(Z){return this.options.filter((X)=>X.group===Z)}isGroupSelected(Z){let X=this.getGroupItems(Z),J=this.value;return J===void 0?!1:X.every((W)=>J.includes(W.value))}toggleValue(){let Z=this.options[this.cursor];if(this.value===void 0&&(this.value=[]),Z.group===!0){let X=Z.value,J=this.getGroupItems(X);this.isGroupSelected(X)?this.value=this.value.filter((W)=>J.findIndex(($)=>$.value===W)===-1):this.value=[...this.value,...J.map((W)=>W.value)],this.value=Array.from(new Set(this.value))}else{let X=this.value.includes(Z.value);this.value=X?this.value.filter((J)=>J!==Z.value):[...this.value,Z.value]}}constructor(Z){super(Z,!1);let{options:X}=Z;this.#Z=Z.selectableGroups!==!1,this.options=Object.entries(X).flatMap(([J,W])=>[{value:J,group:!0,label:J},...W.map(($)=>({...$,group:J}))]),this.value=[...Z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:J})=>J===Z.cursorAt),this.#Z?0:1),this.on("cursor",(J)=>{switch(J){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let W=this.options[this.cursor]?.group===!0;!this.#Z&&W&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let W=this.options[this.cursor]?.group===!0;!this.#Z&&W&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}}function G1(Z,X,J){let W=Z+X,$=Math.max(J.length-1,0),G=W<0?$:W>$?0:W;return J[G].disabled?G1(G,X<0?-1:1,J):G}class T9 extends W1{options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter((Z)=>Z.disabled!==!0)}toggleAll(){let Z=this._enabledOptions,X=this.value!==void 0&&this.value.length===Z.length;this.value=X?[]:Z.map((J)=>J.value)}toggleInvert(){let Z=this.value;if(!Z)return;let X=this._enabledOptions.filter((J)=>!Z.includes(J.value));this.value=X.map((J)=>J.value)}toggleValue(){this.value===void 0&&(this.value=[]);let Z=this.value.includes(this._value);this.value=Z?this.value.filter((X)=>X!==this._value):[...this.value,this._value]}constructor(Z){super(Z,!1),this.options=Z.options,this.value=[...Z.initialValues??[]];let X=Math.max(this.options.findIndex(({value:J})=>J===Z.cursorAt),0);this.cursor=this.options[X].disabled?G1(X,1,this.options):X,this.on("key",(J)=>{J==="a"&&this.toggleAll(),J==="i"&&this.toggleInvert()}),this.on("cursor",(J)=>{switch(J){case"left":case"up":this.cursor=G1(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=G1(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}var P4=class extends W1{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let Z=this.userInput;if(this.cursor>=Z.length)return`${this.masked}${X1.default.inverse(X1.default.hidden("_"))}`;let X=this.masked,J=X.slice(0,this.cursor),W=X.slice(this.cursor);return`${J}${X1.default.inverse(W[0])}${W.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:Z,...X}){super(X),this._mask=Z??"\u2022",this.on("userInput",(J)=>{this._setValue(J)})}};class N9 extends W1{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(Z){super(Z,!1),this.options=Z.options;let X=this.options.findIndex(({value:W})=>W===Z.initialValue),J=X===-1?0:X;this.cursor=this.options[J].disabled?G1(J,1,this.options):J,this.changeValue(),this.on("cursor",(W)=>{switch(W){case"left":case"up":this.cursor=G1(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=G1(this.cursor,1,this.options);break}this.changeValue()})}}class L9 extends W1{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let Z=this.userInput;if(this.cursor>=Z.length)return`${this.userInput}\u2588`;let X=Z.slice(0,this.cursor),[J,...W]=Z.slice(this.cursor);return`${X}${X1.default.inverse(J)}${W.join("")}`}get cursor(){return this._cursor}constructor(Z){super({...Z,initialUserInput:Z.initialUserInput??Z.initialValue}),this.on("userInput",(X)=>{this._setValue(X)}),this.on("finalize",()=>{this.value||(this.value=Z.defaultValue),this.value===void 0&&(this.value="")})}}var U=V1(G9(),1);import p from"process";var b4=V1(Q9(),1);function c2(){return p.platform!=="win32"?p.env.TERM!=="linux":!!p.env.CI||!!p.env.WT_SESSION||!!p.env.TERMINUS_SUBLIME||p.env.ConEmuTask==="{cmd::Cmder}"||p.env.TERM_PROGRAM==="Terminus-Sublime"||p.env.TERM_PROGRAM==="vscode"||p.env.TERM==="xterm-256color"||p.env.TERM==="alacritty"||p.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var u2=c2();var P=(Z,X)=>u2?Z:X,l2=P("\u25C6","*"),n2=P("\u25A0","x"),o2=P("\u25B2","x"),v4=P("\u25C7","o"),i2=P("\u250C","T"),A=P("\u2502","|"),n=P("\u2514","\u2014"),L8=P("\u2510","T"),I8=P("\u2518","\u2014"),S9=P("\u25CF",">"),G0=P("\u25CB"," "),a2=P("\u25FB","[\u2022]"),k4=P("\u25FC","[+]"),C4=P("\u25FB","[ ]"),r2=P("\u25AA","\u2022"),j8=P("\u2500","-"),R8=P("\u256E","+"),S8=P("\u251C","+"),E8=P("\u256F","+"),A8=P("\u2570","+"),V8=P("\u256D","+"),s2=P("\u25CF","\u2022"),t2=P("\u25C6","*"),e2=P("\u25B2","!"),Z7=P("\u25A0","x"),E1=(Z)=>{switch(Z){case"initial":case"active":return U.default.cyan(l2);case"cancel":return U.default.red(n2);case"error":return U.default.yellow(o2);case"submit":return U.default.green(v4)}},y4=(Z)=>{switch(Z){case"initial":case"active":return U.default.cyan(A);case"cancel":return U.default.red(A);case"error":return U.default.yellow(A);case"submit":return U.default.green(A)}},X7=(Z)=>Z===161||Z===164||Z===167||Z===168||Z===170||Z===173||Z===174||Z>=176&&Z<=180||Z>=182&&Z<=186||Z>=188&&Z<=191||Z===198||Z===208||Z===215||Z===216||Z>=222&&Z<=225||Z===230||Z>=232&&Z<=234||Z===236||Z===237||Z===240||Z===242||Z===243||Z>=247&&Z<=250||Z===252||Z===254||Z===257||Z===273||Z===275||Z===283||Z===294||Z===295||Z===299||Z>=305&&Z<=307||Z===312||Z>=319&&Z<=322||Z===324||Z>=328&&Z<=331||Z===333||Z===338||Z===339||Z===358||Z===359||Z===363||Z===462||Z===464||Z===466||Z===468||Z===470||Z===472||Z===474||Z===476||Z===593||Z===609||Z===708||Z===711||Z>=713&&Z<=715||Z===717||Z===720||Z>=728&&Z<=731||Z===733||Z===735||Z>=768&&Z<=879||Z>=913&&Z<=929||Z>=931&&Z<=937||Z>=945&&Z<=961||Z>=963&&Z<=969||Z===1025||Z>=1040&&Z<=1103||Z===1105||Z===8208||Z>=8211&&Z<=8214||Z===8216||Z===8217||Z===8220||Z===8221||Z>=8224&&Z<=8226||Z>=8228&&Z<=8231||Z===8240||Z===8242||Z===8243||Z===8245||Z===8251||Z===8254||Z===8308||Z===8319||Z>=8321&&Z<=8324||Z===8364||Z===8451||Z===8453||Z===8457||Z===8467||Z===8470||Z===8481||Z===8482||Z===8486||Z===8491||Z===8531||Z===8532||Z>=8539&&Z<=8542||Z>=8544&&Z<=8555||Z>=8560&&Z<=8569||Z===8585||Z>=8592&&Z<=8601||Z===8632||Z===8633||Z===8658||Z===8660||Z===8679||Z===8704||Z===8706||Z===8707||Z===8711||Z===8712||Z===8715||Z===8719||Z===8721||Z===8725||Z===8730||Z>=8733&&Z<=8736||Z===8739||Z===8741||Z>=8743&&Z<=8748||Z===8750||Z>=8756&&Z<=8759||Z===8764||Z===8765||Z===8776||Z===8780||Z===8786||Z===8800||Z===8801||Z>=8804&&Z<=8807||Z===8810||Z===8811||Z===8814||Z===8815||Z===8834||Z===8835||Z===8838||Z===8839||Z===8853||Z===8857||Z===8869||Z===8895||Z===8978||Z>=9312&&Z<=9449||Z>=9451&&Z<=9547||Z>=9552&&Z<=9587||Z>=9600&&Z<=9615||Z>=9618&&Z<=9621||Z===9632||Z===9633||Z>=9635&&Z<=9641||Z===9650||Z===9651||Z===9654||Z===9655||Z===9660||Z===9661||Z===9664||Z===9665||Z>=9670&&Z<=9672||Z===9675||Z>=9678&&Z<=9681||Z>=9698&&Z<=9701||Z===9711||Z===9733||Z===9734||Z===9737||Z===9742||Z===9743||Z===9756||Z===9758||Z===9792||Z===9794||Z===9824||Z===9825||Z>=9827&&Z<=9829||Z>=9831&&Z<=9834||Z===9836||Z===9837||Z===9839||Z===9886||Z===9887||Z===9919||Z>=9926&&Z<=9933||Z>=9935&&Z<=9939||Z>=9941&&Z<=9953||Z===9955||Z===9960||Z===9961||Z>=9963&&Z<=9969||Z===9972||Z>=9974&&Z<=9977||Z===9979||Z===9980||Z===9982||Z===9983||Z===10045||Z>=10102&&Z<=10111||Z>=11094&&Z<=11097||Z>=12872&&Z<=12879||Z>=57344&&Z<=63743||Z>=65024&&Z<=65039||Z===65533||Z>=127232&&Z<=127242||Z>=127248&&Z<=127277||Z>=127280&&Z<=127337||Z>=127344&&Z<=127373||Z===127375||Z===127376||Z>=127387&&Z<=127404||Z>=917760&&Z<=917999||Z>=983040&&Z<=1048573||Z>=1048576&&Z<=1114109,J7=(Z)=>Z===12288||Z>=65281&&Z<=65376||Z>=65504&&Z<=65510,W7=(Z)=>Z>=4352&&Z<=4447||Z===8986||Z===8987||Z===9001||Z===9002||Z>=9193&&Z<=9196||Z===9200||Z===9203||Z===9725||Z===9726||Z===9748||Z===9749||Z>=9800&&Z<=9811||Z===9855||Z===9875||Z===9889||Z===9898||Z===9899||Z===9917||Z===9918||Z===9924||Z===9925||Z===9934||Z===9940||Z===9962||Z===9970||Z===9971||Z===9973||Z===9978||Z===9981||Z===9989||Z===9994||Z===9995||Z===10024||Z===10060||Z===10062||Z>=10067&&Z<=10069||Z===10071||Z>=10133&&Z<=10135||Z===10160||Z===10175||Z===11035||Z===11036||Z===11088||Z===11093||Z>=11904&&Z<=11929||Z>=11931&&Z<=12019||Z>=12032&&Z<=12245||Z>=12272&&Z<=12287||Z>=12289&&Z<=12350||Z>=12353&&Z<=12438||Z>=12441&&Z<=12543||Z>=12549&&Z<=12591||Z>=12593&&Z<=12686||Z>=12688&&Z<=12771||Z>=12783&&Z<=12830||Z>=12832&&Z<=12871||Z>=12880&&Z<=19903||Z>=19968&&Z<=42124||Z>=42128&&Z<=42182||Z>=43360&&Z<=43388||Z>=44032&&Z<=55203||Z>=63744&&Z<=64255||Z>=65040&&Z<=65049||Z>=65072&&Z<=65106||Z>=65108&&Z<=65126||Z>=65128&&Z<=65131||Z>=94176&&Z<=94180||Z===94192||Z===94193||Z>=94208&&Z<=100343||Z>=100352&&Z<=101589||Z>=101632&&Z<=101640||Z>=110576&&Z<=110579||Z>=110581&&Z<=110587||Z===110589||Z===110590||Z>=110592&&Z<=110882||Z===110898||Z>=110928&&Z<=110930||Z===110933||Z>=110948&&Z<=110951||Z>=110960&&Z<=111355||Z===126980||Z===127183||Z===127374||Z>=127377&&Z<=127386||Z>=127488&&Z<=127490||Z>=127504&&Z<=127547||Z>=127552&&Z<=127560||Z===127568||Z===127569||Z>=127584&&Z<=127589||Z>=127744&&Z<=127776||Z>=127789&&Z<=127797||Z>=127799&&Z<=127868||Z>=127870&&Z<=127891||Z>=127904&&Z<=127946||Z>=127951&&Z<=127955||Z>=127968&&Z<=127984||Z===127988||Z>=127992&&Z<=128062||Z===128064||Z>=128066&&Z<=128252||Z>=128255&&Z<=128317||Z>=128331&&Z<=128334||Z>=128336&&Z<=128359||Z===128378||Z===128405||Z===128406||Z===128420||Z>=128507&&Z<=128591||Z>=128640&&Z<=128709||Z===128716||Z>=128720&&Z<=128722||Z>=128725&&Z<=128727||Z>=128732&&Z<=128735||Z===128747||Z===128748||Z>=128756&&Z<=128764||Z>=128992&&Z<=129003||Z===129008||Z>=129292&&Z<=129338||Z>=129340&&Z<=129349||Z>=129351&&Z<=129535||Z>=129648&&Z<=129660||Z>=129664&&Z<=129672||Z>=129680&&Z<=129725||Z>=129727&&Z<=129733||Z>=129742&&Z<=129755||Z>=129760&&Z<=129768||Z>=129776&&Z<=129784||Z>=131072&&Z<=196605||Z>=196608&&Z<=262141,I9=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,X0=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,J0=/\t{1,1000}/y,j9=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,W0=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,$7=/\p{M}+/gu,G7={limit:1/0,ellipsis:""},m4=(Z,X={},J={})=>{let W=X.limit??1/0,$=X.ellipsis??"",G=X?.ellipsisWidth??($?m4($,G7,J).width:0),Y=J.ansiWidth??0,Q=J.controlWidth??0,z=J.tabWidth??8,H=J.ambiguousWidth??1,K=J.emojiWidth??2,B=J.fullWidthWidth??2,O=J.regularWidth??1,D=J.wideWidth??2,M=0,_=0,N=Z.length,I=0,j=!1,S=N,V=Math.max(0,W-G),k=0,w=0,T=0,L=0;Z:for(;;){if(w>k||_>=N&&_>M){let f=Z.slice(k,w)||Z.slice(M,_);I=0;for(let c of f.replaceAll($7,"")){let g=c.codePointAt(0)||0;if(J7(g)?L=B:W7(g)?L=D:H!==O&&X7(g)?L=H:L=O,T+L>V&&(S=Math.min(S,Math.max(k,M)+I)),T+L>W){j=!0;break Z}I+=c.length,T+=L}k=w=0}if(_>=N)break;if(W0.lastIndex=_,W0.test(Z)){if(I=W0.lastIndex-_,L=I*O,T+L>V&&(S=Math.min(S,_+Math.floor((V-T)/O))),T+L>W){j=!0;break}T+=L,k=M,w=_,_=M=W0.lastIndex;continue}if(I9.lastIndex=_,I9.test(Z)){if(T+Y>V&&(S=Math.min(S,_)),T+Y>W){j=!0;break}T+=Y,k=M,w=_,_=M=I9.lastIndex;continue}if(X0.lastIndex=_,X0.test(Z)){if(I=X0.lastIndex-_,L=I*Q,T+L>V&&(S=Math.min(S,_+Math.floor((V-T)/Q))),T+L>W){j=!0;break}T+=L,k=M,w=_,_=M=X0.lastIndex;continue}if(J0.lastIndex=_,J0.test(Z)){if(I=J0.lastIndex-_,L=I*z,T+L>V&&(S=Math.min(S,_+Math.floor((V-T)/z))),T+L>W){j=!0;break}T+=L,k=M,w=_,_=M=J0.lastIndex;continue}if(j9.lastIndex=_,j9.test(Z)){if(T+K>V&&(S=Math.min(S,_)),T+K>W){j=!0;break}T+=K,k=M,w=_,_=M=j9.lastIndex;continue}_+=1}return{width:j?V:T,index:j?S:N,truncated:j,ellipsed:j&&W>=G}},Y7={limit:1/0,ellipsis:"",ellipsisWidth:0},S1=(Z,X={})=>m4(Z,Y7,X).width,Y0="\x1B",h4="\x9B",Q7=39,A9="\x07",g4="[",z7="]",d4="m",V9=`${z7}8;;`,w4=new RegExp(`(?:\\${g4}(?<code>\\d+)m|\\${V9}(?<uri>.*)${A9})`,"y"),H7=(Z)=>{if(Z>=30&&Z<=37||Z>=90&&Z<=97)return 39;if(Z>=40&&Z<=47||Z>=100&&Z<=107)return 49;if(Z===1||Z===2)return 22;if(Z===3)return 23;if(Z===4)return 24;if(Z===7)return 27;if(Z===8)return 28;if(Z===9)return 29;if(Z===0)return 0},q4=(Z)=>`${Y0}${g4}${Z}${d4}`,x4=(Z)=>`${Y0}${V9}${Z}${A9}`,K7=(Z)=>Z.map((X)=>S1(X)),R9=(Z,X,J)=>{let W=X[Symbol.iterator](),$=!1,G=!1,Y=Z.at(-1),Q=Y===void 0?0:S1(Y),z=W.next(),H=W.next(),K=0;for(;!z.done;){let B=z.value,O=S1(B);Q+O<=J?Z[Z.length-1]+=B:(Z.push(B),Q=0),(B===Y0||B===h4)&&($=!0,G=X.startsWith(V9,K+1)),$?G?B===A9&&($=!1,G=!1):B===d4&&($=!1):(Q+=O,Q===J&&!H.done&&(Z.push(""),Q=0)),z=H,H=W.next(),K+=B.length}Y=Z.at(-1),!Q&&Y!==void 0&&Y.length>0&&Z.length>1&&(Z[Z.length-2]+=Z.pop())},U7=(Z)=>{let X=Z.split(" "),J=X.length;for(;J>0&&!(S1(X[J-1])>0);)J--;return J===X.length?Z:X.slice(0,J).join(" ")+X.slice(J).join("")},B7=(Z,X,J={})=>{if(J.trim!==!1&&Z.trim()==="")return"";let W="",$,G,Y=Z.split(" "),Q=K7(Y),z=[""];for(let[M,_]of Y.entries()){J.trim!==!1&&(z[z.length-1]=(z.at(-1)??"").trimStart());let N=S1(z.at(-1)??"");if(M!==0&&(N>=X&&(J.wordWrap===!1||J.trim===!1)&&(z.push(""),N=0),(N>0||J.trim===!1)&&(z[z.length-1]+=" ",N++)),J.hard&&Q[M]>X){let I=X-N,j=1+Math.floor((Q[M]-I-1)/X);Math.floor((Q[M]-1)/X)<j&&z.push(""),R9(z,_,X);continue}if(N+Q[M]>X&&N>0&&Q[M]>0){if(J.wordWrap===!1&&N<X){R9(z,_,X);continue}z.push("")}if(N+Q[M]>X&&J.wordWrap===!1){R9(z,_,X);continue}z[z.length-1]+=_}J.trim!==!1&&(z=z.map((M)=>U7(M)));let H=z.join(`
175
- `),K=H[Symbol.iterator](),B=K.next(),O=K.next(),D=0;for(;!B.done;){let M=B.value,_=O.value;if(W+=M,M===Y0||M===h4){w4.lastIndex=D+1;let I=w4.exec(H)?.groups;if(I?.code!==void 0){let j=Number.parseFloat(I.code);$=j===Q7?void 0:j}else I?.uri!==void 0&&(G=I.uri.length===0?void 0:I.uri)}let N=$?H7($):void 0;_===`
176
- `?(G&&(W+=x4("")),$&&N&&(W+=q4(N))):M===`
177
- `&&($&&N&&(W+=q4($)),G&&(W+=x4(G))),D+=M.length,B=O,O=K.next()}return W};function O7(Z,X,J){return String(Z).normalize().replaceAll(`\r
178
- `,`
179
- `).split(`
180
- `).map((W)=>B7(W,X,J)).join(`
181
- `)}var _7=(Z,X,J,W,$)=>{let G=X,Y=0;for(let Q=J;Q<W;Q++){let z=Z[Q];if(G=G-z.length,Y++,G<=$)break}return{lineCount:G,removals:Y}},E9=(Z)=>{let{cursor:X,options:J,style:W}=Z,$=Z.output??process.stdout,G=M9($),Y=Z.columnPadding??0,Q=Z.rowPadding??4,z=G-Y,H=D9($),K=U.default.dim("..."),B=Z.maxItems??Number.POSITIVE_INFINITY,O=Math.max(H-Q,0),D=Math.max(Math.min(B,O),5),M=0;X>=D-3&&(M=Math.max(Math.min(X-D+3,J.length-D),0));let _=D<J.length&&M>0,N=D<J.length&&M+D<J.length,I=Math.min(M+D,J.length),j=[],S=0;_&&S++,N&&S++;let V=M+(_?1:0),k=I-(N?1:0);for(let T=V;T<k;T++){let L=O7(W(J[T],T===X),z,{hard:!0,trim:!1}).split(`
182
- `);j.push(L),S+=L.length}if(S>O){let T=0,L=0,f=S,c=X-V,g=(Q3,z3)=>_7(j,f,Q3,z3,O);_?({lineCount:f,removals:T}=g(0,c),f>O&&({lineCount:f,removals:L}=g(c+1,j.length))):({lineCount:f,removals:L}=g(c+1,j.length),f>O&&({lineCount:f,removals:T}=g(0,c))),T>0&&(_=!0,j.splice(0,T)),L>0&&(N=!0,j.splice(j.length-L,L))}let w=[];_&&w.push(K);for(let T of j)for(let L of T)w.push(L);return N&&w.push(K),w};var b=(Z)=>{let X=Z.active??"Yes",J=Z.inactive??"No";return new F9({active:X,inactive:J,signal:Z.signal,input:Z.input,output:Z.output,initialValue:Z.initialValue??!0,render(){let W=`${U.default.gray(A)}
183
- ${E1(this.state)} ${Z.message}
184
- `,$=this.value?X:J;switch(this.state){case"submit":return`${W}${U.default.gray(A)} ${U.default.dim($)}`;case"cancel":return`${W}${U.default.gray(A)} ${U.default.strikethrough(U.default.dim($))}
185
- ${U.default.gray(A)}`;default:return`${W}${U.default.cyan(A)} ${this.value?`${U.default.green(S9)} ${X}`:`${U.default.dim(G0)} ${U.default.dim(X)}`} ${U.default.dim("/")} ${this.value?`${U.default.dim(G0)} ${U.default.dim(J)}`:`${U.default.green(S9)} ${J}`}
186
- ${U.default.cyan(n)}
187
- `}}}).prompt()},s=async(Z,X)=>{let J={},W=Object.keys(Z);for(let $ of W){let G=Z[$],Y=await G({results:J})?.catch((Q)=>{throw Q});if(typeof X?.onCancel=="function"&&R(Y)){J[$]="canceled",X.onCancel({results:J});continue}J[$]=Y}return J};var m={message:(Z=[],{symbol:X=U.default.gray(A),secondarySymbol:J=U.default.gray(A),output:W=process.stdout,spacing:$=1,withGuide:G}={})=>{let Y=[],Q=(G??J1.withGuide)!==!1,z=Q?J:"",H=Q?`${X} `:"",K=Q?`${J} `:"";for(let O=0;O<$;O++)Y.push(z);let B=Array.isArray(Z)?Z:Z.split(`
188
- `);if(B.length>0){let[O,...D]=B;O.length>0?Y.push(`${H}${O}`):Y.push(Q?X:"");for(let M of D)M.length>0?Y.push(`${K}${M}`):Y.push(Q?J:"")}W.write(`${Y.join(`
189
- `)}
190
- `)},info:(Z,X)=>{m.message(Z,{...X,symbol:U.default.blue(s2)})},success:(Z,X)=>{m.message(Z,{...X,symbol:U.default.green(t2)})},step:(Z,X)=>{m.message(Z,{...X,symbol:U.default.green(v4)})},warn:(Z,X)=>{m.message(Z,{...X,symbol:U.default.yellow(e2)})},warning:(Z,X)=>{m.warn(Z,X)},error:(Z,X)=>{m.message(Z,{...X,symbol:U.default.red(Z7)})}},q=(Z="",X)=>{(X?.output??process.stdout).write(`${U.default.gray(n)} ${U.default.red(Z)}
191
-
192
- `)},P9=(Z="",X)=>{(X?.output??process.stdout).write(`${U.default.gray(i2)} ${Z}
193
- `)},Q0=(Z="",X)=>{(X?.output??process.stdout).write(`${U.default.gray(A)}
194
- ${U.default.gray(n)} ${Z}
195
-
196
- `)},R1=(Z,X)=>Z.split(`
197
- `).map((J)=>X(J)).join(`
198
- `),f4=(Z)=>{let X=(W,$)=>{let G=W.label??String(W.value);return $==="disabled"?`${U.default.gray(C4)} ${R1(G,(Y)=>U.default.strikethrough(U.default.gray(Y)))}${W.hint?` ${U.default.dim(`(${W.hint??"disabled"})`)}`:""}`:$==="active"?`${U.default.cyan(a2)} ${G}${W.hint?` ${U.default.dim(`(${W.hint})`)}`:""}`:$==="selected"?`${U.default.green(k4)} ${R1(G,U.default.dim)}${W.hint?` ${U.default.dim(`(${W.hint})`)}`:""}`:$==="cancelled"?`${R1(G,(Y)=>U.default.strikethrough(U.default.dim(Y)))}`:$==="active-selected"?`${U.default.green(k4)} ${G}${W.hint?` ${U.default.dim(`(${W.hint})`)}`:""}`:$==="submitted"?`${R1(G,U.default.dim)}`:`${U.default.dim(C4)} ${R1(G,U.default.dim)}`},J=Z.required??!0;return new T9({options:Z.options,signal:Z.signal,input:Z.input,output:Z.output,initialValues:Z.initialValues,required:J,cursorAt:Z.cursorAt,validate(W){if(J&&(W===void 0||W.length===0))return`Please select at least one option.
199
- ${U.default.reset(U.default.dim(`Press ${U.default.gray(U.default.bgWhite(U.default.inverse(" space ")))} to select, ${U.default.gray(U.default.bgWhite(U.default.inverse(" enter ")))} to submit`))}`},render(){let W=Y1(Z.output,Z.message,`${y4(this.state)} `,`${E1(this.state)} `),$=`${U.default.gray(A)}
200
- ${W}
201
- `,G=this.value??[],Y=(Q,z)=>{if(Q.disabled)return X(Q,"disabled");let H=G.includes(Q.value);return z&&H?X(Q,"active-selected"):H?X(Q,"selected"):X(Q,z?"active":"inactive")};switch(this.state){case"submit":{let Q=this.options.filter(({value:H})=>G.includes(H)).map((H)=>X(H,"submitted")).join(U.default.dim(", "))||U.default.dim("none"),z=Y1(Z.output,Q,`${U.default.gray(A)} `);return`${$}${z}`}case"cancel":{let Q=this.options.filter(({value:H})=>G.includes(H)).map((H)=>X(H,"cancelled")).join(U.default.dim(", "));if(Q.trim()==="")return`${$}${U.default.gray(A)}`;let z=Y1(Z.output,Q,`${U.default.gray(A)} `);return`${$}${z}
202
- ${U.default.gray(A)}`}case"error":{let Q=`${U.default.yellow(A)} `,z=this.error.split(`
203
- `).map((B,O)=>O===0?`${U.default.yellow(n)} ${U.default.yellow(B)}`:` ${B}`).join(`
204
- `),H=$.split(`
205
- `).length,K=z.split(`
206
- `).length+1;return`${$}${Q}${E9({output:Z.output,options:this.options,cursor:this.cursor,maxItems:Z.maxItems,columnPadding:Q.length,rowPadding:H+K,style:Y}).join(`
207
- ${Q}`)}
208
- ${z}
209
- `}default:{let Q=`${U.default.cyan(A)} `,z=$.split(`
210
- `).length;return`${$}${Q}${E9({output:Z.output,options:this.options,cursor:this.cursor,maxItems:Z.maxItems,columnPadding:Q.length,rowPadding:z+2,style:Y}).join(`
211
- ${Q}`)}
212
- ${U.default.cyan(n)}
213
- `}}}}).prompt()};var p4=(Z)=>new P4({validate:Z.validate,mask:Z.mask??r2,signal:Z.signal,input:Z.input,output:Z.output,render(){let X=`${U.default.gray(A)}
214
- ${E1(this.state)} ${Z.message}
215
- `,J=this.userInputWithCursor,W=this.masked;switch(this.state){case"error":{let $=W?` ${W}`:"";return Z.clearOnError&&this.clear(),`${X.trim()}
216
- ${U.default.yellow(A)}${$}
217
- ${U.default.yellow(n)} ${U.default.yellow(this.error)}
218
- `}case"submit":{let $=W?` ${U.default.dim(W)}`:"";return`${X}${U.default.gray(A)}${$}`}case"cancel":{let $=W?` ${U.default.strikethrough(U.default.dim(W))}`:"";return`${X}${U.default.gray(A)}${$}${W?`
219
- ${U.default.gray(A)}`:""}`}default:return`${X}${U.default.cyan(A)} ${J}
220
- ${U.default.cyan(n)}
221
- `}}}).prompt();var P8=U.default.magenta;var k8={light:P("\u2500","-"),heavy:P("\u2501","="),block:P("\u2588","#")};var $0=(Z,X)=>Z.includes(`
222
- `)?Z.split(`
223
- `).map((J)=>X(J)).join(`
224
- `):X(Z),t=(Z)=>{let X=(J,W)=>{let $=J.label??String(J.value);switch(W){case"disabled":return`${U.default.gray(G0)} ${$0($,U.default.gray)}${J.hint?` ${U.default.dim(`(${J.hint??"disabled"})`)}`:""}`;case"selected":return`${$0($,U.default.dim)}`;case"active":return`${U.default.green(S9)} ${$}${J.hint?` ${U.default.dim(`(${J.hint})`)}`:""}`;case"cancelled":return`${$0($,(G)=>U.default.strikethrough(U.default.dim(G)))}`;default:return`${U.default.dim(G0)} ${$0($,U.default.dim)}`}};return new N9({options:Z.options,signal:Z.signal,input:Z.input,output:Z.output,initialValue:Z.initialValue,render(){let J=`${E1(this.state)} `,W=`${y4(this.state)} `,$=Y1(Z.output,Z.message,W,J),G=`${U.default.gray(A)}
225
- ${$}
226
- `;switch(this.state){case"submit":{let Y=`${U.default.gray(A)} `,Q=Y1(Z.output,X(this.options[this.cursor],"selected"),Y);return`${G}${Q}`}case"cancel":{let Y=`${U.default.gray(A)} `,Q=Y1(Z.output,X(this.options[this.cursor],"cancelled"),Y);return`${G}${Q}
227
- ${U.default.gray(A)}`}default:{let Y=`${U.default.cyan(A)} `,Q=G.split(`
228
- `).length;return`${G}${Y}${E9({output:Z.output,cursor:this.cursor,options:this.options,maxItems:Z.maxItems,columnPadding:Y.length,rowPadding:Q+2,style:(z,H)=>X(z,z.disabled?"disabled":H?"active":"inactive")}).join(`
229
- ${Y}`)}
230
- ${U.default.cyan(n)}
231
- `}}}}).prompt()};var C8=`${U.default.gray(A)} `;var C=(Z)=>new L9({validate:Z.validate,placeholder:Z.placeholder,defaultValue:Z.defaultValue,initialValue:Z.initialValue,output:Z.output,signal:Z.signal,input:Z.input,render(){let X=(Z?.withGuide??J1.withGuide)!==!1,J=`${`${X?`${U.default.gray(A)}
232
- `:""}${E1(this.state)} `}${Z.message}
233
- `,W=Z.placeholder?U.default.inverse(Z.placeholder[0])+U.default.dim(Z.placeholder.slice(1)):U.default.inverse(U.default.hidden("_")),$=this.userInput?this.userInputWithCursor:W,G=this.value??"";switch(this.state){case"error":{let Y=this.error?` ${U.default.yellow(this.error)}`:"",Q=X?`${U.default.yellow(A)} `:"",z=X?U.default.yellow(n):"";return`${J.trim()}
234
- ${Q}${$}
235
- ${z}${Y}
236
- `}case"submit":{let Y=G?` ${U.default.dim(G)}`:"",Q=X?U.default.gray(A):"";return`${J}${Q}${Y}`}case"cancel":{let Y=G?` ${U.default.strikethrough(U.default.dim(G))}`:"",Q=X?U.default.gray(A):"";return`${J}${Q}${Y}${G.trim()?`
237
- ${Q}`:""}`}default:{let Y=X?`${U.default.cyan(A)} `:"",Q=X?U.default.cyan(n):"";return`${J}${Y}${$}
238
- ${Q}
239
- `}}}}).prompt();async function u4(Z){let X=await v.parseFile(Z),J;if(X.request)J=X.request;else if(X.requests&&X.requests.length>0)J=X.requests[0];else if(X.collection?.requests&&X.collection.requests.length>0)J=X.collection.requests[0];if(!J)throw Error("No request found in YAML file");return M7(J)}function M7(Z){let X={url:Z.url,method:Z.method||"GET"};if(Z.name)X.name=Z.name;if(Z.headers&&Object.keys(Z.headers).length>0)X.headers=Z.headers;if(Z.params&&Object.keys(Z.params).length>0)X.params=Z.params;if(Z.body!==void 0)if(typeof Z.body==="object"&&Z.body!==null)X.bodyType="json",X.body=Z.body;else X.bodyType="raw",X.body=Z.body;else if(Z.formData)X.bodyType="form",X.formData=Z.formData;else X.bodyType="none";if(Z.auth){if(Z.auth.type==="bearer")X.authType="bearer",X.token=Z.auth.token;else if(Z.auth.type==="basic")X.authType="basic",X.username=Z.auth.username,X.password=Z.auth.password}else X.authType="none";if(Z.timeout)X.timeout=Z.timeout;if(Z.followRedirects!==void 0)X.followRedirects=Z.followRedirects;if(Z.maxRedirects)X.maxRedirects=Z.maxRedirects;if(Z.insecure)X.insecure=Z.insecure;if(Z.http2)X.http2=Z.http2;if(Z.retry)X.retryEnabled=!0,X.retryCount=Z.retry.count,X.retryDelay=Z.retry.delay,X.retryBackoff=Z.retry.backoff;if(Z.expect){if(Z.expect.status)X.expectStatus=Z.expect.status;if(Z.expect.responseTime)X.expectResponseTime=Z.expect.responseTime}if(Z.output)X.outputFile=Z.output;return X}async function l4(Z){try{return await Bun.file(Z).exists()}catch{return!1}}var n4={"basic-get":{name:"Basic GET Request",description:"Simple GET request to fetch data",defaults:{method:"GET",followRedirects:!0}},"basic-post":{name:"Basic POST Request",description:"POST request with JSON body",defaults:{method:"POST",bodyType:"json",headers:{"Content-Type":"application/json"}}},"api-test":{name:"API Test",description:"Request with validation and response time check",defaults:{method:"GET",expectStatus:200,expectResponseTime:"< 2000",verbose:!0,showHeaders:!0}},"file-upload":{name:"File Upload",description:"Multipart form upload request",defaults:{method:"POST",bodyType:"form"}},"auth-flow":{name:"Auth Flow",description:"Request with authentication",defaults:{method:"POST",authType:"bearer",headers:{"Content-Type":"application/json"}}}};function o4(Z){return n4[Z]}function i4(){return Object.entries(n4).map(([Z,X])=>({value:Z,label:X.name,hint:X.description}))}var D7=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"];async function a4(){let Z=[{value:"blank",label:"Blank",hint:"Start from scratch"},...i4()];return t({message:"Start from a template?",options:Z})}async function r4(Z){return await s({url:()=>C({message:"Request URL",placeholder:"https://api.example.com/endpoint",initialValue:Z?.url||"",validate:(J)=>{if(!J)return"URL is required";try{new URL(J)}catch{return"Invalid URL format"}}}),method:()=>t({message:"HTTP method",initialValue:Z?.method||"GET",options:D7.map((J)=>({value:J,label:J}))}),name:()=>C({message:"Request name (optional)",placeholder:"My API Request",initialValue:Z?.name||""})},{onCancel:()=>{q("Wizard cancelled"),process.exit(0)}})}async function s4(Z){let X=await b({message:"Add headers?",initialValue:Z?Object.keys(Z).length>0:!1});if(R(X)||!X)return R(X)?X:Z;let J={...Z},W=!0,$=await f4({message:"Add common headers (space to select)",options:[{value:"content-type-json",label:"Content-Type: application/json"},{value:"accept-json",label:"Accept: application/json"},{value:"user-agent",label:"User-Agent: curl-runner"}],required:!1});if(R($))return $;if(Array.isArray($))for(let G of $){if(G==="content-type-json")J["Content-Type"]="application/json";if(G==="accept-json")J.Accept="application/json";if(G==="user-agent")J["User-Agent"]="curl-runner"}while(W){let G=await b({message:"Add custom header?",initialValue:!1});if(R(G))return G;if(!G)break;let Y=await s({key:()=>C({message:"Header name",placeholder:"X-Custom-Header",validate:(Q)=>!Q?"Header name required":void 0}),value:()=>C({message:"Header value",placeholder:"value",validate:(Q)=>!Q?"Header value required":void 0})});if(Y.key&&Y.value)J[Y.key]=Y.value;W=!0}return Object.keys(J).length>0?J:void 0}async function t4(Z){let X=await t({message:"Request body type",initialValue:Z?.bodyType||"none",options:[{value:"none",label:"None",hint:"No request body"},{value:"json",label:"JSON",hint:"JSON object"},{value:"form",label:"Form Data",hint:"Multipart form / file upload"},{value:"raw",label:"Raw",hint:"Plain text or other"}]});if(R(X))return X;if(X==="none")return{bodyType:"none"};if(X==="json"){let W=await C({message:"JSON body (or press enter for interactive)",placeholder:'{"key": "value"}',initialValue:Z?.body?JSON.stringify(Z.body):""});if(R(W))return W;if(W)try{return{bodyType:"json",body:JSON.parse(W)}}catch{return m.warn("Invalid JSON, storing as raw string"),{bodyType:"raw",body:W}}let $={},G=!0;while(G){let Y=await s({key:()=>C({message:"Field name",placeholder:"key"}),value:()=>C({message:"Field value",placeholder:"value"}),type:()=>t({message:"Value type",options:[{value:"string",label:"String"},{value:"number",label:"Number"},{value:"boolean",label:"Boolean"}]})});if(Y.key)if(Y.type==="number")$[Y.key]=Number(Y.value);else if(Y.type==="boolean")$[Y.key]=Y.value==="true";else $[Y.key]=Y.value;let Q=await b({message:"Add another field?",initialValue:!1});if(R(Q))return Q;G=Q}return{bodyType:"json",body:$}}if(X==="form"){let W={},$=!0;while($){let G=await t({message:"Field type",options:[{value:"text",label:"Text field"},{value:"file",label:"File upload"}]});if(R(G))return G;let Y=await C({message:"Field name",placeholder:G==="file"?"file":"field",validate:(z)=>!z?"Field name required":void 0});if(R(Y))return Y;if(G==="file"){let z=await C({message:"File path",placeholder:"./upload.txt",validate:(H)=>!H?"File path required":void 0});if(R(z))return z;W[Y]={file:z}}else{let z=await C({message:"Field value",placeholder:"value"});if(R(z))return z;W[Y]=z}let Q=await b({message:"Add another field?",initialValue:!1});if(R(Q))return Q;$=Q}return{bodyType:"form",formData:W}}let J=await C({message:"Raw body content",placeholder:"Your content here",initialValue:Z?.body||""});if(R(J))return J;return{bodyType:"raw",body:J}}async function e4(Z){let X=await t({message:"Authentication",initialValue:Z?.authType||"none",options:[{value:"none",label:"None"},{value:"bearer",label:"Bearer Token",hint:"Authorization: Bearer <token>"},{value:"basic",label:"Basic Auth",hint:"Username/password"}]});if(R(X))return X;if(X==="none")return{authType:"none"};if(X==="bearer"){let W=await C({message:"Bearer token",placeholder:"your-token-here",initialValue:Z?.token||"",validate:($)=>!$?"Token required":void 0});if(R(W))return W;return{authType:"bearer",token:W}}let J=await s({username:()=>C({message:"Username",initialValue:Z?.username||"",validate:(W)=>!W?"Username required":void 0}),password:()=>p4({message:"Password",validate:(W)=>!W?"Password required":void 0})});if(R(J.username)||R(J.password))return Symbol("cancel");return{authType:"basic",username:J.username,password:J.password}}async function Z3(Z){let X=await b({message:"Configure advanced options?",initialValue:!1});if(R(X)||!X)return R(X)?X:{};let J=await s({timeout:()=>C({message:"Timeout (ms)",placeholder:"30000",initialValue:Z?.timeout?.toString()||"",validate:($)=>{if(!$)return;let G=Number($);if(Number.isNaN(G)||G<0)return"Must be a positive number"}}),followRedirects:()=>b({message:"Follow redirects?",initialValue:Z?.followRedirects??!0}),insecure:()=>b({message:"Skip SSL verification? (insecure)",initialValue:Z?.insecure??!1}),http2:()=>b({message:"Use HTTP/2?",initialValue:Z?.http2??!1})}),W={};if(J.timeout)W.timeout=Number(J.timeout);if(J.followRedirects===!1)W.followRedirects=!1;if(J.insecure)W.insecure=!0;if(J.http2)W.http2=!0;return W}async function X3(Z){let X=await b({message:"Configure retry strategy?",initialValue:Z?.retryEnabled??!1});if(R(X)||!X)return R(X)?X:{};let J=await s({count:()=>C({message:"Max retry attempts",placeholder:"3",initialValue:Z?.retryCount?.toString()||"3",validate:(W)=>{let $=Number(W);if(Number.isNaN($)||$<1)return"Must be at least 1"}}),delay:()=>C({message:"Retry delay (ms)",placeholder:"1000",initialValue:Z?.retryDelay?.toString()||"1000",validate:(W)=>{if(!W)return;let $=Number(W);if(Number.isNaN($)||$<0)return"Must be a positive number"}}),backoff:()=>C({message:"Backoff multiplier",placeholder:"2 (exponential)",initialValue:Z?.retryBackoff?.toString()||"",validate:(W)=>{if(!W)return;let $=Number(W);if(Number.isNaN($)||$<1)return"Must be at least 1"}})});return{retryEnabled:!0,retryCount:Number(J.count),retryDelay:J.delay?Number(J.delay):void 0,retryBackoff:J.backoff?Number(J.backoff):void 0}}async function J3(Z){let X=await b({message:"Add response validation?",initialValue:!!(Z?.expectStatus||Z?.expectResponseTime)});if(R(X)||!X)return R(X)?X:{};let J=await s({status:()=>C({message:"Expected status code(s)",placeholder:"200 or 200,201",initialValue:Z?.expectStatus?Array.isArray(Z.expectStatus)?Z.expectStatus.join(","):String(Z.expectStatus):""}),responseTime:()=>C({message:"Response time constraint",placeholder:"< 2000 (ms)",initialValue:Z?.expectResponseTime||""})}),W={};if(J.status){let $=J.status.split(",").map((G)=>Number(G.trim()));W.expectStatus=$.length===1?$[0]:$}if(J.responseTime)W.expectResponseTime=J.responseTime;return W}async function W3(Z){return await s({outputPath:()=>C({message:"Save to file",placeholder:"api-request.yaml",initialValue:Z?.outputFile||"request.yaml",validate:(J)=>{if(!J)return"File path required";if(!J.endsWith(".yaml")&&!J.endsWith(".yml"))return"File must end with .yaml or .yml"}}),runAfter:()=>b({message:"Run request after creating?",initialValue:!0})})}function F7(Z){let X={url:Z.url};if(Z.name)X.name=Z.name;if(Z.method&&Z.method!=="GET")X.method=Z.method;if(Z.headers&&Object.keys(Z.headers).length>0)X.headers=Z.headers;if(Z.params&&Object.keys(Z.params).length>0)X.params=Z.params;if(Z.bodyType==="json"&&Z.body)X.body=Z.body;else if(Z.bodyType==="form"&&Z.formData)X.formData=Z.formData;else if(Z.bodyType==="raw"&&Z.body)X.body=Z.body;if(Z.authType==="basic"&&Z.username)X.auth={type:"basic",username:Z.username,password:Z.password||""};else if(Z.authType==="bearer"&&Z.token)X.auth={type:"bearer",token:Z.token};if(Z.timeout)X.timeout=Z.timeout;if(Z.followRedirects===!1)X.followRedirects=!1;if(Z.maxRedirects)X.maxRedirects=Z.maxRedirects;if(Z.insecure)X.insecure=!0;if(Z.http2)X.http2=!0;if(Z.retryEnabled&&Z.retryCount){if(X.retry={count:Z.retryCount},Z.retryDelay)X.retry.delay=Z.retryDelay;if(Z.retryBackoff)X.retry.backoff=Z.retryBackoff}if(Z.expectStatus||Z.expectResponseTime){if(X.expect={},Z.expectStatus)X.expect.status=Z.expectStatus;if(Z.expectResponseTime)X.expect.responseTime=Z.expectResponseTime}if(Z.outputFile)X.output=Z.outputFile;return X}function k9(Z){return{request:F7(Z)}}function C9(Z){return A1(Z)}function A1(Z,X=0){let J=" ".repeat(X);if(Z===null||Z===void 0)return"null";if(typeof Z==="string"){if(Z.includes(":")||Z.includes("#")||Z.includes(`
240
- `)||Z.startsWith(" ")||Z.endsWith(" ")||/^[0-9]/.test(Z)||["true","false","null","yes","no"].includes(Z.toLowerCase()))return JSON.stringify(Z);return Z}if(typeof Z==="number"||typeof Z==="boolean")return String(Z);if(Array.isArray(Z)){if(Z.length===0)return"[]";if(Z.every((W)=>typeof W!=="object"||W===null))return`[${Z.map((W)=>A1(W,0)).join(", ")}]`;return Z.map((W)=>`${J}- ${A1(W,X+1).trimStart()}`).join(`
241
- `)}if(typeof Z==="object"){let W=Object.entries(Z);if(W.length===0)return"{}";let $=[];for(let[G,Y]of W){if(Y===void 0)continue;if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y)){$.push(`${J}${G}:`);let Q=A1(Y,X+1);$.push(Q)}else{let Q=A1(Y,X+1);if(Q.includes(`
242
- `))$.push(`${J}${G}:`),$.push(Q);else $.push(`${J}${G}: ${Q}`)}}return $.join(`
243
- `)}return String(Z)}async function w9(Z={}){P9(`curl-runner wizard v${o()}`);let X;if(Z.editFile){if(!await l4(Z.editFile))q(`File not found: ${Z.editFile}`),process.exit(1);m.info(`Editing: ${Z.editFile}`);let Y=await u4(Z.editFile);X=await $3(Y),Z.outputPath=Z.outputPath||Z.editFile}else{let Y=await a4();if(R(Y))q("Wizard cancelled"),process.exit(0);let Q=Y==="blank"?void 0:o4(Y).defaults;X=await $3(Q)}let J=await W3({outputFile:Z.outputPath});if(R(J))q("Wizard cancelled"),process.exit(0);let W=k9(X),$=C9(W);m.step("Preview:"),console.log(),console.log($),console.log();let G=await b({message:`Save to ${J.outputPath}?`,initialValue:!0});if(R(G)||!G)q("Wizard cancelled"),process.exit(0);if(await Bun.write(J.outputPath,$),m.success(`Saved to ${J.outputPath}`),J.runAfter)m.step("Running request..."),console.log(),await Bun.spawn(["bun","run",process.argv[1],J.outputPath],{stdout:"inherit",stderr:"inherit"}).exited;Q0("Done!")}async function $3(Z){let X=await r4(Z);if(R(X))q("Wizard cancelled"),process.exit(0);let J={...Z,...X},W=await s4(Z?.headers);if(R(W))q("Wizard cancelled"),process.exit(0);if(W)J.headers=W;if(!["GET","HEAD","OPTIONS"].includes(J.method)){let z=await t4(Z);if(R(z))q("Wizard cancelled"),process.exit(0);J={...J,...z}}let $=await e4(Z);if(R($))q("Wizard cancelled"),process.exit(0);J={...J,...$};let G=await Z3(Z);if(R(G))q("Wizard cancelled"),process.exit(0);J={...J,...G};let Y=await X3(Z);if(R(Y))q("Wizard cancelled"),process.exit(0);J={...J,...Y};let Q=await J3(Z);if(R(Q))q("Wizard cancelled"),process.exit(0);return J={...J,...Q},J}async function G3(Z){P9("curl-runner quick init");let X=Z||await C({message:"Request URL",placeholder:"https://api.example.com/endpoint",validate:(Q)=>{if(!Q)return"URL is required";try{new URL(Q)}catch{return"Invalid URL format"}}});if(R(X))q("Cancelled"),process.exit(0);let J=await t({message:"HTTP method",initialValue:"GET",options:[{value:"GET",label:"GET"},{value:"POST",label:"POST"},{value:"PUT",label:"PUT"},{value:"DELETE",label:"DELETE"}]});if(R(J))q("Cancelled"),process.exit(0);let W=await C({message:"Save to",placeholder:"request.yaml",initialValue:"request.yaml",validate:(Q)=>{if(!Q)return"Filename required";if(!Q.endsWith(".yaml")&&!Q.endsWith(".yml"))return"Must end with .yaml or .yml"}});if(R(W))q("Cancelled"),process.exit(0);let $=k9({url:X,method:J}),G=C9($);await Bun.write(W,G),m.success(`Created ${W}`);let Y=await b({message:"Run now?",initialValue:!0});if(R(Y)){Q0("Done!");return}if(Y)console.log(),await Bun.spawn(["bun","run",process.argv[1],W],{stdout:"inherit",stderr:"inherit"}).exited;Q0("Done!")}class Y3{logger=new l;async run(Z){try{let X=Z.includes("--quiet")||Z.includes("-q"),J=await v0(Z,{onInfo:X?void 0:(Q)=>this.logger.logInfo(Q),onWarning:X?void 0:(Q)=>this.logger.logWarning(Q)}),{config:W,cliOptions:$,mode:G,rawArgs:Y}=J;if(this.logger=new l(W.output),G!=="version"&&G!=="help")new J9().checkForUpdates().catch(()=>{});switch(G){case"help":this.showHelp();return;case"version":console.log(`curl-runner v${o()}`);return;case"upgrade":if(Y.includes("--help")||Y.includes("-h")){h9();return}await new H0().run(Y.slice(1));return;case"validate":if(Y.includes("--help")||Y.includes("-h")){o9();return}await new D0().run(Y.slice(1));return;case"diff-subcommand":await this.executeDiffSubcommand(Y.slice(1),$);return;case"convert":await this.executeConvert(Y);return;case"init":await this.executeInit(Y);return;case"edit":await this.executeEdit(Y);return;case"profile":case"watch":case"normal":await this.executeMain($,W,G);return}}catch(X){this.logger.logError(X instanceof Error?X.message:String(X)),process.exit(1)}}async executeMain(Z,X,J){let W=await this.findYamlFiles(Z.files,Z.all);if(W.length===0)this.logger.logError("No YAML files found"),process.exit(1);this.logger.logInfo(`Found ${W.length} YAML file(s)`);let $=[],G=X;for(let Y of W){this.logger.logInfo(`Processing: ${Y}`);let{requests:Q,config:z}=await this.processYamlFile(Y,G.defaults),H=z?.output||{},K=Q.map((B)=>({...B,sourceOutputConfig:H,sourceFile:Y}));if(z)G=b1(G,z);$.push(...K)}if($.length===0)this.logger.logError("No requests found in YAML files"),process.exit(1);if(J==="profile"){let Y=y0(Z,G);await this.executeProfileMode($,G,Y)}else if(J==="watch"){let Y=m0(Z,G);await new W9({files:W,config:Y,logger:this.logger,onRun:async()=>{await this.executeRequests(W,G)}}).start()}else{let Y=await this.executeRequests(W,G),Q=this.determineExitCode(Y,G);process.exit(Q)}}async executeProfileMode(Z,X,J){let $=await new l0(X,J).profileRequests(Z);if(this.logger.logProfileSummary($),J.exportFile){let Q=[],z=J.exportFile.endsWith(".csv");for(let K of $){let B=K.request.name||K.request.url;Q.push(z?J4(K.stats,B):W4(K.stats,B))}let H=z?Q.join(`
244
-
245
- `):`[${Q.join(`,
246
- `)}]`;await Bun.write(J.exportFile,H),this.logger.logInfo(`Profile results exported to ${J.exportFile}`)}let G=$.reduce((Q,z)=>Q+z.stats.failures,0),Y=$.reduce((Q,z)=>Q+z.stats.iterations+z.stats.warmup,0);process.exit(G>0&&G/Y>0.5?1:0)}async executeRequests(Z,X){let J=[],W=[];for(let Y of Z){let{requests:Q,config:z}=await this.processYamlFile(Y,X.defaults),H=z?.output||{},K=Q.map((B)=>({...B,sourceOutputConfig:H,sourceFile:Y}));J.push({file:Y,requests:K,config:z}),W.push(...K)}let $=new X9(X),G;if(J.length>1){let Y=[],Q=0;for(let B=0;B<J.length;B++){let O=J[B];this.logger.logFileHeader(O.file,O.requests.length);let D=await $.execute(O.requests);if(Y.push(...D.results),Q+=D.duration,B<J.length-1&&!X.output?.quiet)console.log()}let z=Y.filter((B)=>B.success&&!B.skipped).length,H=Y.filter((B)=>!B.success&&!B.skipped).length,K=Y.filter((B)=>B.skipped).length;G={total:Y.length,successful:z,failed:H,skipped:K,duration:Q,results:Y},this.logger.logSummary(G,!0)}else G=await $.execute(W);if(X.diff?.enabled||X.diff?.save||X.diff?.compareWith)await this.handleDiffMode(Z[0],G.results,X.diff);return G}async handleDiffMode(Z,X,J){let W=new D1(J),$=new M1(J.outputFormat||"terminal"),G=z1.mergeConfig(J,!0)||{},Y=J.label||"current",Q=J.compareWith;if(J.save)await W.saveBaseline(Z,Y,X,G),this.logger.logInfo(`Baseline saved as '${Y}'`);if(Q){let z=await W.compareWithBaseline(Z,X,Y,Q,G);if(z.newBaselines===z.totalRequests){this.logger.logWarning(`No baseline '${Q}' found. Saving current run as baseline.`),await W.saveBaseline(Z,Q,X,G);return}if(console.log($.formatSummary(z,Q,Y)),J.save)await W.saveBaseline(Z,Y,X,G)}else if(J.enabled&&!J.save){let z=await W.listLabels(Z);if(z.length===0)await W.saveBaseline(Z,"baseline",X,G),this.logger.logInfo("No baselines found. Saved current run as 'baseline'.");else if(z.length===1){let H=await W.compareWithBaseline(Z,X,Y,z[0],G);console.log($.formatSummary(H,z[0],Y))}else this.logger.logInfo(`Available baselines: ${z.join(", ")}`),this.logger.logInfo("Use --diff-compare <label> to compare against a specific baseline.")}}async executeConvert(Z){if(Z.includes("--help")||Z.includes("-h")){this.showConvertHelp();return}let X=E0(Z);if(!X)this.showConvertHelp(),process.exit(1);let J;switch(X.subcommand){case"curl":J=j0(X.input,X.options);break;case"file":J=await R0(X.input,X.options);break;case"yaml":J=await S0(X.input,X.options);break}if(X.options.debug&&J.debug)console.log(this.logger.color("DEBUG:","yellow")),console.log(JSON.stringify(J.debug,null,2)),console.log();if(J.warnings.length>0&&!X.options.output)for(let W of J.warnings)this.logger.logWarning(W);if(X.options.output)await Bun.write(X.options.output,J.output),this.logger.logInfo(`Written to ${X.options.output}`);else console.log(J.output)}async executeInit(Z){let X=P0(Z);if(Z.includes("--help")||Z.includes("-h")){this.showInitHelp();return}if(X.wizard)await w9({outputPath:X.outputPath});else await G3(X.url)}async executeEdit(Z){let X=k0(Z);if(Z.includes("--help")||Z.includes("-h")){this.showEditHelp();return}if(!X.file)this.logger.logError("Usage: curl-runner edit <file.yaml>"),process.exit(1);await w9({editFile:X.file,outputPath:X.outputPath})}async executeDiffSubcommand(Z,X){let J=Z[0],W=Z[1],$=Z[2];if(!$){let H=await this.findYamlFiles([],X.all);if(H.length===0)this.logger.logError("No YAML files found. Specify a file: curl-runner diff <label1> <label2> <file.yaml>"),process.exit(1);if(H.length>1)this.logger.logError("Multiple YAML files found. Specify which file to use."),process.exit(1);$=H[0]}let G={dir:X.diffDir||"__baselines__",outputFormat:X.diffOutput||"terminal"},Y=new D1(G),Q=new M1(G.outputFormat||"terminal"),z={exclude:[],match:{}};try{let H=await Y.compareTwoBaselines($,J,W,z);console.log(Q.formatSummary(H,J,W)),process.exit(H.changed>0?1:0)}catch(H){this.logger.logError(H instanceof Error?H.message:String(H)),process.exit(1)}}async findYamlFiles(Z,X){let J=new Set,W=[];if(Z.length===0)W=X?["**/*.yaml","**/*.yml"]:["*.yaml","*.yml"];else for(let $ of Z)try{let Y=await(await import("fs/promises")).stat($);if(Y.isDirectory()){if(W.push(`${$}/*.yaml`,`${$}/*.yml`),X)W.push(`${$}/**/*.yaml`,`${$}/**/*.yml`)}else if(Y.isFile())W.push($)}catch{W.push($)}for(let $ of W){let G=new T7($);for await(let Y of G.scan("."))if(Y.endsWith(".yaml")||Y.endsWith(".yml"))J.add(Y)}return Array.from(J).sort()}async processYamlFile(Z,X={}){let J=await v.parseFile(Z),W=[],$;if(J.global)$=J.global;let G={...J.global?.variables,...J.collection?.variables},Y={...X,...J.global?.defaults,...J.collection?.defaults};if(J.request)W.push(this.prepareRequest(J.request,G,Y));if(J.requests)for(let Q of J.requests)W.push(this.prepareRequest(Q,G,Y));if(J.collection?.requests)for(let Q of J.collection.requests)W.push(this.prepareRequest(Q,G,Y));return{requests:W,config:$}}prepareRequest(Z,X,J){let W=v.interpolateVariables(Z,X);return v.mergeConfigs(J,W)}determineExitCode(Z,X){let{failed:J,total:W}=Z,$=X.ci;if(J===0)return 0;if($){if($.strictExit)return 1;if($.failOn!==void 0&&J>$.failOn)return 1;if($.failOnPercentage!==void 0&&W>0){if(J/W*100>$.failOnPercentage)return 1}if($.failOn!==void 0||$.failOnPercentage!==void 0)return 0}return!X.continueOnError?1:0}showInitHelp(){console.log(`
247
- ${this.logger.color("\uD83D\uDE80 CURL RUNNER - INIT","bright")}
248
-
249
- ${this.logger.color("USAGE:","yellow")}
250
- curl-runner init [url] [options]
251
-
252
- ${this.logger.color("OPTIONS:","yellow")}
253
- -w, --wizard Launch full interactive wizard
254
- -o, --output <file> Output file path (default: request.yaml)
255
- -h, --help Show this help
256
-
257
- ${this.logger.color("EXAMPLES:","yellow")}
258
- # Quick init with prompts
259
- curl-runner init
260
-
261
- # Quick init with URL
262
- curl-runner init https://api.example.com/users
263
-
264
- # Full wizard mode
265
- curl-runner init --wizard
266
-
267
- # Wizard with custom output
268
- curl-runner init -w -o api-test.yaml
269
- `)}showEditHelp(){console.log(`
270
- ${this.logger.color("\uD83D\uDE80 CURL RUNNER - EDIT","bright")}
271
-
272
- ${this.logger.color("USAGE:","yellow")}
273
- curl-runner edit <file.yaml> [options]
274
-
275
- ${this.logger.color("OPTIONS:","yellow")}
276
- -o, --output <file> Save to different file (default: overwrite original)
277
- -h, --help Show this help
278
-
279
- ${this.logger.color("EXAMPLES:","yellow")}
280
- # Edit existing file
281
- curl-runner edit api-test.yaml
282
-
283
- # Edit and save to new file
284
- curl-runner edit api-test.yaml -o api-test-v2.yaml
285
- `)}showConvertHelp(){console.log(`
286
- ${this.logger.color("CURL RUNNER - CONVERT","bright")}
287
-
288
- ${this.logger.color("USAGE:","yellow")}
289
- curl-runner convert curl "<curl command>" Convert curl \u2192 YAML
290
- curl-runner convert file <script.sh> Convert shell script \u2192 YAML
291
- curl-runner convert yaml <test.yaml> Convert YAML \u2192 curl
292
-
293
- ${this.logger.color("OPTIONS:","yellow")}
294
- -o, --output <file> Write output to file
295
- --pretty Pretty-print output (default for YAML)
296
- --loss-report Show warnings for unsupported features (default)
297
- --debug Show token stream, AST, and IR
298
- -h, --help Show this help
299
-
300
- ${this.logger.color("EXAMPLES:","yellow")}
301
- # Convert inline curl to YAML
302
- curl-runner convert curl "curl -X POST https://api.example.com -d '{"name":"Alex"}'"
303
-
304
- # Convert and save to file
305
- curl-runner convert curl "curl https://api.example.com" -o test.yaml
306
-
307
- # Convert shell script (batch)
308
- curl-runner convert file scripts/api-tests.sh
309
-
310
- # Convert YAML back to curl
311
- curl-runner convert yaml test.yaml
312
-
313
- # Debug mode
314
- curl-runner convert curl "curl https://example.com" --debug
315
- `)}showHelp(){console.log(`
316
- ${this.logger.color("\uD83D\uDE80 CURL RUNNER","bright")}
317
-
318
- ${this.logger.color("USAGE:","yellow")}
319
- curl-runner [files...] [options]
320
-
321
- ${this.logger.color("OPTIONS:","yellow")}
322
- -h, --help Show this help message
323
- -n, --dry-run Show curl commands without executing
324
- --http2 Use HTTP/2 protocol with multiplexing
325
- --connection-pool Enable TCP connection pooling with HTTP/2 multiplexing
326
- --max-streams <n> Max concurrent streams per host (default: 10)
327
- --keepalive-time <sec> TCP keepalive time in seconds (default: 60)
328
- --connect-timeout <sec> Connection timeout in seconds (default: 30)
329
- -v, --verbose Enable verbose output
330
- -q, --quiet Suppress non-error output
331
- -p, --execution parallel Execute requests in parallel
332
- --max-concurrent <n> Limit concurrent requests in parallel mode
333
- -c, --continue-on-error Continue execution on errors
334
- -o, --output <file> Save results to file
335
- --all Find all YAML files recursively
336
- --timeout <ms> Set request timeout in milliseconds
337
- --retries <count> Set maximum retry attempts
338
- --retry-delay <ms> Set delay between retries in milliseconds
339
- --no-retry Disable retry mechanism
340
- --output-format <format> Set output format (json|pretty|raw)
341
- --pretty-level <level> Set pretty format level (minimal|standard|detailed)
342
- --show-headers Include response headers in output
343
- --show-body Include response body in output
344
- --show-metrics Include performance metrics in output
345
- --version Show version
346
-
347
- ${this.logger.color("WATCH MODE:","yellow")}
348
- -w, --watch Watch files and re-run on changes
349
- --watch-debounce <ms> Debounce delay for watch mode (default: 300)
350
- --no-watch-clear Don't clear screen between watch runs
351
-
352
- ${this.logger.color("PROFILE MODE:","yellow")}
353
- -P, --profile <n> Run each request N times for latency stats
354
- --profile-warmup <n> Warmup iterations to exclude from stats (default: 1)
355
- --profile-concurrency <n> Concurrent iterations (default: 1 = sequential)
356
- --profile-histogram Show ASCII histogram of latency distribution
357
- --profile-export <file> Export raw timings to file (.json or .csv)
358
-
359
- ${this.logger.color("CI/CD OPTIONS:","yellow")}
360
- --strict-exit Exit with code 1 if any validation fails (for CI/CD)
361
- --fail-on <count> Exit with code 1 if failures exceed this count
362
- --fail-on-percentage <pct> Exit with code 1 if failure percentage exceeds this value
363
-
364
- ${this.logger.color("SNAPSHOT OPTIONS:","yellow")}
365
- -s, --snapshot Enable snapshot testing
366
- -u, --update-snapshots Update all snapshots
367
- --update-failing Update only failing snapshots
368
- --snapshot-dir <dir> Custom snapshot directory (default: __snapshots__)
369
- --ci-snapshot Fail if snapshot is missing (CI mode)
370
-
371
- ${this.logger.color("DIFF OPTIONS:","yellow")}
372
- -d, --diff Enable response diffing (compare with baseline)
373
- --diff-save Save current run as baseline
374
- --diff-label <name> Label for current run (e.g., 'staging', 'v1.0')
375
- --diff-compare <label> Compare against this baseline label
376
- --diff-dir <dir> Baseline storage directory (default: __baselines__)
377
- --diff-output <format> Output format (terminal|json|markdown)
378
-
379
- ${this.logger.color("DIFF SUBCOMMAND:","yellow")}
380
- curl-runner diff <label1> <label2> [file.yaml]
381
- Compare two stored baselines without making requests
382
-
383
- ${this.logger.color("UPGRADE:","yellow")}
384
- curl-runner upgrade Upgrade to latest version (auto-detects install method)
385
- curl-runner upgrade --dry-run Preview upgrade command without executing
386
- curl-runner upgrade --force Force reinstall even if up to date
387
-
388
- ${this.logger.color("VALIDATE:","yellow")}
389
- curl-runner validate Validate YAML files against curl-runner schema
390
- curl-runner validate --fix Validate and auto-fix issues where possible
391
- curl-runner validate -q Only show files with issues
392
-
393
- ${this.logger.color("CONVERT:","yellow")}
394
- curl-runner convert curl "<cmd>" Convert curl command to YAML
395
- curl-runner convert file <sh> Convert shell script to YAML (batch)
396
- curl-runner convert yaml <yaml> Convert YAML to curl command(s)
397
-
398
- ${this.logger.color("WIZARD:","yellow")}
399
- curl-runner init Quick create a new YAML file
400
- curl-runner init --wizard Full interactive wizard
401
- curl-runner init <url> Quick create with URL
402
- curl-runner edit <file.yaml> Edit existing YAML file
403
-
404
- ${this.logger.color("EXAMPLES:","yellow")}
405
- # Run all YAML files in current directory
406
- curl-runner
407
-
408
- # Run specific file
409
- curl-runner api-tests.yaml
410
-
411
- # Run all files in a directory
412
- curl-runner examples/
413
-
414
- # Run all files in multiple directories
415
- curl-runner tests/ examples/
416
-
417
- # Run all files recursively in parallel
418
- curl-runner --all -p
419
-
420
- # Run in parallel with max 5 concurrent requests
421
- curl-runner -p --max-concurrent 5 tests.yaml
422
-
423
- # Run directory recursively
424
- curl-runner --all examples/
425
-
426
- # Run with verbose output and continue on errors
427
- curl-runner tests/*.yaml -vc
428
-
429
- # Dry run - show curl commands without executing
430
- curl-runner api.yaml --dry-run
431
-
432
- # Use HTTP/2 for all requests
433
- curl-runner api.yaml --http2
434
-
435
- # Enable connection pooling with HTTP/2 multiplexing
436
- curl-runner api.yaml -p --connection-pool
437
-
438
- # Connection pooling with custom settings
439
- curl-runner api.yaml -p --connection-pool --max-streams 20
440
-
441
- # Run with minimal pretty output (only status and errors)
442
- curl-runner --output-format pretty --pretty-level minimal test.yaml
443
-
444
- # Run with detailed pretty output (show all information)
445
- curl-runner --output-format pretty --pretty-level detailed test.yaml
446
-
447
- # CI/CD: Fail if any validation fails (strict mode)
448
- curl-runner tests/ --strict-exit
449
-
450
- # CI/CD: Run all tests but fail if any validation fails
451
- curl-runner tests/ --continue-on-error --strict-exit
452
-
453
- # CI/CD: Allow up to 2 failures
454
- curl-runner tests/ --fail-on 2
455
-
456
- # CI/CD: Allow up to 10% failures
457
- curl-runner tests/ --fail-on-percentage 10
458
-
459
- # Watch mode - re-run on file changes
460
- curl-runner api.yaml --watch
461
-
462
- # Watch with custom debounce
463
- curl-runner tests/ -w --watch-debounce 500
464
-
465
- # Profile mode - run request 100 times for latency stats
466
- curl-runner api.yaml -P 100
467
-
468
- # Profile with 5 warmup iterations and histogram
469
- curl-runner api.yaml --profile 50 --profile-warmup 5 --profile-histogram
470
-
471
- # Profile with concurrent iterations and export
472
- curl-runner api.yaml -P 100 --profile-concurrency 10 --profile-export results.json
473
-
474
- # Snapshot testing - save and compare responses
475
- curl-runner api.yaml --snapshot
476
-
477
- # Update all snapshots
478
- curl-runner api.yaml -su
479
-
480
- # CI mode - fail if snapshot missing
481
- curl-runner api.yaml --snapshot --ci-snapshot
482
-
483
- # Response diffing - save baseline for staging
484
- curl-runner api.yaml --diff-save --diff-label staging
485
-
486
- # Compare current run against staging baseline
487
- curl-runner api.yaml --diff --diff-compare staging
488
-
489
- # Compare staging vs production baselines (offline)
490
- curl-runner diff staging production api.yaml
491
-
492
- # Auto-diff: creates baseline on first run, compares on subsequent runs
493
- curl-runner api.yaml --diff
494
-
495
- # Diff with JSON output for CI
496
- curl-runner api.yaml --diff --diff-compare staging --diff-output json
497
-
498
- # Create new YAML file with wizard
499
- curl-runner init --wizard
500
-
501
- # Quick create with URL
502
- curl-runner init https://api.example.com/users
503
-
504
- # Edit existing YAML file
505
- curl-runner edit api-test.yaml
506
-
507
- ${this.logger.color("YAML STRUCTURE:","yellow")}
508
- Single request:
509
- request:
510
- url: https://api.example.com
511
- method: GET
512
-
513
- Multiple requests:
514
- requests:
515
- - url: https://api.example.com/users
516
- method: GET
517
- - url: https://api.example.com/posts
518
- method: POST
519
- body: { title: "Test" }
520
-
521
- With global config:
522
- global:
523
- execution: parallel
524
- variables:
525
- BASE_URL: https://api.example.com
526
- requests:
527
- - url: \${BASE_URL}/users
528
- method: GET
529
- `)}}var N7=new Y3;N7.run(process.argv.slice(2));
530
-
531
- //# debugId=A4D5B3CA459B43C964756E2164756E21
532
- //# sourceMappingURL=cli.js.map