stably 4.3.7 → 4.3.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var e=require("commander"),t=require("buffer"),n=require("path"),r=require("child_process"),o=require("process"),s=require("url"),i=require("os"),a=require("fs");require("timers/promises");var c=require("util"),l=require("@anthropic-ai/claude-agent-sdk"),d=require("dotenv"),u=require("picocolors"),p=require("simple-git"),f=require("crypto"),h=require("fs/promises"),m=require("@clack/prompts"),g=require("readline/promises"),_=require("zod"),y=require("open"),E=require("http"),b=require("react"),I=require("react/jsx-runtime"),w=require("zod/v3"),v=require("@stablyhq/runner-sdk");function T(e){return e&&e.__esModule?e:{default:e}}var R=T(n),S=T(r),C=T(o),x=T(i),A=T(a),U=T(u),P=T(f),L=T(_),O=T(y),B=T(E),N=Object.create,D=Object.defineProperty,j=Object.getOwnPropertyDescriptor,k=Object.getOwnPropertyNames,$=Object.getPrototypeOf,M=Object.prototype.hasOwnProperty,H=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),G=(e,t)=>function(){return t||(0,e[k(e)[0]])((t={exports:{}}).exports,t),t.exports},F=(e,t,n)=>(n=null!=e?N($(e)):{},((e,t,n,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of k(t))M.call(e,n)||void 0===n||D(e,n,{get:()=>t[n],enumerable:!(r=j(t,n))||r.enumerable});return e})(D(n,"default",{value:e,enumerable:!0}),e)),Y=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(e,t){t.exports=o,o.sync=function(e,t){return r(n.statSync(e),e,t)};var n=H("fs");function r(e,t,n){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var n=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!n)return!0;if(-1!==(n=n.split(";")).indexOf(""))return!0;for(var r=0;r<n.length;r++){var o=n[r].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}(t,n)}function o(e,t,o){n.stat(e,function(n,s){o(n,!n&&r(s,e,t))})}}}),z=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(e,t){t.exports=r,r.sync=function(e,t){return o(n.statSync(e),t)};var n=H("fs");function r(e,t,r){n.stat(e,function(e,n){r(e,!e&&o(n,t))})}function o(e,t){return e.isFile()&&function(e,t){var n=e.mode,r=e.uid,o=e.gid,s=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),i=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8);return n&parseInt("001",8)||n&c&&o===i||n&a&&r===s||n&(a|c)&&0===s}(e,t)}}}),W=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(e,t){var n;function r(e,t,o){if("function"==typeof t&&(o=t,t={}),!o){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(n,o){r(e,t||{},function(e,t){e?o(e):n(t)})})}n(e,t||{},function(e,n){e&&("EACCES"===e.code||t&&t.ignoreErrors)&&(e=null,n=!1),o(e,n)})}H("fs"),n="win32"===process.platform||global.TESTING_WINDOWS?Y():z(),t.exports=r,r.sync=function(e,t){try{return n.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||"EACCES"===e.code)return!1;throw e}}}}),K=G({"node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(e,t){var n="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,r=H("path"),o=n?";":":",s=W(),i=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),a=(e,t)=>{const r=t.colon||o,s=e.match(/\//)||n&&e.match(/\\/)?[""]:[...n?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],i=n?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=n?i.split(r):[""];return n&&-1!==e.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:s,pathExt:a,pathExtExe:i}},c=(e,t,n)=>{"function"==typeof t&&(n=t,t={}),t||(t={});const{pathEnv:o,pathExt:c,pathExtExe:l}=a(e,t),d=[],u=n=>new Promise((s,a)=>{if(n===o.length)return t.all&&d.length?s(d):a(i(e));const c=o[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=r.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;s(p(f,n,0))}),p=(e,n,r)=>new Promise((o,i)=>{if(r===c.length)return o(u(n+1));const a=c[r];s(e+a,{pathExt:l},(s,i)=>{if(!s&&i){if(!t.all)return o(e+a);d.push(e+a)}return o(p(e,n,r+1))})});return n?u(0).then(e=>n(null,e),n):u(0)};t.exports=c,c.sync=(e,t)=>{t=t||{};const{pathEnv:n,pathExt:o,pathExtExe:c}=a(e,t),l=[];for(let i=0;i<n.length;i++){const a=n[i],d=/^".*"$/.test(a)?a.slice(1,-1):a,u=r.join(d,e),p=!d&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let e=0;e<o.length;e++){const n=p+o[e];try{if(s.sync(n,{pathExt:c})){if(!t.all)return n;l.push(n)}}catch(e){}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw i(e)}}}),V=G({"node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(e,t){var n=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};t.exports=n,t.exports.default=n}}),q=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){var n=H("path"),r=K(),o=V();function s(e,t){const s=e.options.env||process.env,i=process.cwd(),a=null!=e.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch(e){}let l;try{l=r.sync(e.command,{path:s[o({env:s})],pathExt:t?n.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=n.resolve(a?e.options.cwd:"",l)),l}t.exports=function(e){return s(e)||s(e,!0)}}}),J=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(e,t){var n=/([()\][%!^"`<>&|;, *?])/g;t.exports.command=function(e){return e.replace(n,"^$1")},t.exports.argument=function(e,t){return e=(e=`"${e=(e=(e=`${e}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(n,"^$1"),t&&(e=e.replace(n,"^$1")),e}}}),X=G({"node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(e,t){t.exports=/^#!(.*)/}}),Q=G({"node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(e,t){var n=X();t.exports=(e="")=>{const t=e.match(n);if(!t)return null;const[r,o]=t[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return"env"===s?o:o?`${s} ${o}`:s}}}),Z=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(e,t){var n=H("fs"),r=Q();t.exports=function(e){const t=Buffer.alloc(150);let o;try{o=n.openSync(e,"r"),n.readSync(o,t,0,150,0),n.closeSync(o)}catch(e){}return r(t.toString())}}}),ee=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(e,t){var n=H("path"),r=q(),o=J(),s=Z(),i="win32"===process.platform,a=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;t.exports=function(e,t,l){t&&!Array.isArray(t)&&(l=t,t=null);const d={command:e,args:t=t?t.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:e,args:t}};return l.shell?d:function(e){if(!i)return e;const t=function(e){e.file=r(e);const t=e.file&&s(e.file);return t?(e.args.unshift(e.file),e.command=t,r(e)):e.file}(e),l=!a.test(t);if(e.options.forceShell||l){const r=c.test(t);e.command=n.normalize(e.command),e.command=o.command(e.command),e.args=e.args.map(e=>o.argument(e,r));const s=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${s}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}(d)}}}),te=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(e,t){var n="win32"===process.platform;function r(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function o(e,t){return n&&1===e&&!t.file?r(t.original,"spawn"):null}t.exports={hookChildProcess:function(e,t){if(!n)return;const r=e.emit;e.emit=function(n,s){if("exit"===n){const n=o(s,t);if(n)return r.call(e,"error",n)}return r.apply(e,arguments)}},verifyENOENT:o,verifyENOENTSync:function(e,t){return n&&1===e&&!t.file?r(t.original,"spawnSync"):null},notFoundError:r}}}),ne=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(e,t){var n=H("child_process"),r=ee(),o=te();function s(e,t,s){const i=r(e,t,s),a=n.spawn(i.command,i.args,i.options);return o.hookChildProcess(a,i),a}t.exports=s,t.exports.spawn=s,t.exports.sync=function(e,t,s){const i=r(e,t,s),a=n.spawnSync(i.command,i.args,i.options);return a.error=a.error||o.verifyENOENTSync(a.status,i),a},t.exports._parse=r,t.exports._enoent=o}}),re=G({"node_modules/.pnpm/merge-stream@2.0.0/node_modules/merge-stream/index.js"(e,t){var{PassThrough:n}=H("stream");t.exports=function(){var e=[],t=new n({objectMode:!0});return t.setMaxListeners(0),t.add=r,t.isEmpty=function(){return 0==e.length},t.on("unpipe",o),Array.prototype.slice.call(arguments).forEach(r),t;function r(n){return Array.isArray(n)?(n.forEach(r),this):(e.push(n),n.once("end",o.bind(null,n)),n.once("error",t.emit.bind(t,"error")),n.pipe(t,{end:!1}),this)}function o(n){!(e=e.filter(function(e){return e!==n})).length&&t.readable&&t.end()}}}}),oe=G({"node_modules/.pnpm/java-properties@1.0.2/node_modules/java-properties/dist-node/index.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.of=e.PropertiesFile=void 0;var t,n=(t=H("fs"))&&t.__esModule?t:{default:t},r=class{constructor(...e){this.objs={},e.length&&this.of.apply(this,e)}makeKeys(e){if(e&&0!==e.indexOf("#")){let t=["=",":"].map(t=>e.indexOf(t)).filter(e=>e>-1),n=Math.min(...t),r=e.substring(0,n).trim(),o=e.substring(n+1).trim();if(this.objs.hasOwnProperty(r))if(Array.isArray(this.objs[r]))this.objs[r].push(o);else{let e=this.objs[r];this.objs[r]=[e,o]}else{const e=o.replace(/"/g,'\\"').replace(/\\:/g,":").replace(/\\=/g,"=");this.objs[r]=unescape(JSON.parse('"'+e+'"'))}}}addFile(e){let t=n.default.readFileSync(e,"utf-8").split(/\r?\n/),r=this;for(let e=0;e<t.length;e++){let n=t[e];for(;"\\"===n.substring(n.length-1);)n=n.slice(0,-1),n+=t[e+1].trim(),e++;r.makeKeys(n)}}of(...e){for(let t=0;t<e.length;t++)this.addFile(e[t])}get(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){let t=[];for(let n=0;n<this.objs[e].length;n++)t[n]=this.interpolate(this.objs[e][n]);return t}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getLast(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){var n=this.objs[e].length;return this.interpolate(this.objs[e][n-1])}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getFirst(e,t){return this.objs.hasOwnProperty(e)?Array.isArray(this.objs[e])?this.interpolate(this.objs[e][0]):void 0===this.objs[e]?"":this.interpolate(this.objs[e]):t}getInt(e,t){let n=this.getLast(e);return n?parseInt(n,10):t}getFloat(e,t){let n=this.getLast(e);return n?parseFloat(n):t}getBoolean(e,t){let n=this.getLast(e);return n?!/^(false|0)$/i.test(r=n)&&!!r:t||!1;var r}set(e,t){this.objs[e]=t}interpolate(e){let t=this;return e.replace(/\\\\/g,"\\").replace(/\$\{([A-Za-z0-9\.\-\_]*)\}/g,function(e){return t.getLast(e.substring(2,e.length-1))})}getKeys(){let e=[];for(let t in this.objs)e.push(t);return e}getMatchingKeys(e){let t=[];for(let n in this.objs)-1!==n.search(e)&&t.push(n);return t}reset(){this.objs={}}};e.PropertiesFile=r,e.of=function(...e){let t=new r;return t.of.apply(t,e),t}}}),se={detect:({env:e})=>Boolean(e.APPVEYOR),configuration({env:e}){const t=e.APPVEYOR_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Appveyor",service:"appveyor",commit:e.APPVEYOR_REPO_COMMIT,tag:e.APPVEYOR_REPO_TAG_NAME,build:e.APPVEYOR_BUILD_NUMBER,buildUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/${e.APPVEYOR_BUILD_VERSION}`,branch:e.APPVEYOR_REPO_BRANCH,job:e.APPVEYOR_JOB_NUMBER,jobUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/job/${e.APPVEYOR_JOB_ID}`,pr:t,isPr:n,prBranch:e.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH,slug:e.APPVEYOR_REPO_NAME,root:e.APPVEYOR_BUILD_FOLDER}}};function ie(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function ae(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var ce={detect:({env:e})=>Boolean(e.BUILD_BUILDURI),configuration({env:e}){const t=e.SYSTEM_PULLREQUEST_PULLREQUESTID,n=Boolean(t);return{name:"Azure Pipelines",service:"azurePipelines",commit:e.BUILD_SOURCEVERSION,build:e.BUILD_BUILDNUMBER,branch:ae(n?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:n,prBranch:ae(n?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},le={detect:({env:e})=>Boolean(e.bamboo_agentId),configuration:({env:e})=>({name:"Bamboo",service:"bamboo",commit:e.bamboo_planRepository_1_revision,build:e.bamboo_buildNumber,buildUrl:e.bamboo_buildResultsUrl,branch:e.bamboo_planRepository_1_branchName,job:e.bamboo_buildKey,root:e.bamboo_build_working_directory})},de={detect:({env:e})=>Boolean(e.BITBUCKET_BUILD_NUMBER),configuration:({env:e})=>({name:"Bitbucket Pipelines",service:"bitbucket",commit:e.BITBUCKET_COMMIT,tag:e.BITBUCKET_TAG,build:e.BITBUCKET_BUILD_NUMBER,buildUrl:`https://bitbucket.org/${e.BITBUCKET_REPO_FULL_NAME}/addon/pipelines/home#!/results/${e.BITBUCKET_BUILD_NUMBER}`,branch:e.BITBUCKET_BRANCH,slug:e.BITBUCKET_REPO_FULL_NAME,root:e.BITBUCKET_CLONE_DIR})},ue={detect:({env:e})=>Boolean(e.BITRISE_IO),configuration({env:e}){const t="false"===e.BITRISE_PULL_REQUEST?void 0:e.BITRISE_PULL_REQUEST,n=Boolean(t);return{name:"Bitrise",service:"bitrise",commit:e.BITRISE_GIT_COMMIT,tag:e.BITRISE_GIT_TAG,build:e.BITRISE_BUILD_NUMBER,buildUrl:e.BITRISE_BUILD_URL,branch:n?e.BITRISEIO_GIT_BRANCH_DEST:e.BITRISE_GIT_BRANCH,pr:t,isPr:n,prBranch:n?e.BITRISE_GIT_BRANCH:void 0,slug:e.BITRISE_APP_SLUG}}},pe={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=ie(e.BUDDY_EXECUTION_PULL_REQUEST_ID),n=Boolean(t);return{name:"Buddy",service:"buddy",commit:e.BUDDY_EXECUTION_REVISION,tag:e.BUDDY_EXECUTION_TAG,build:e.BUDDY_EXECUTION_ID,buildUrl:e.BUDDY_EXECUTION_URL,branch:n?e.BUDDY_EXECUTION_PULL_REQUEST_HEAD_BRANCH:e.BUDDY_EXECUTION_BRANCH,pr:t,isPr:n,slug:e.BUDDY_REPO_SLUG}}},fe=F(ne());function he(e={}){const{env:t=process.env,platform:n=process.platform}=e;return"win32"!==n?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"}var me=(e,t)=>({name:`SIGRT${t+1}`,number:ge+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),ge=34,_e=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],ye=()=>{const e=(()=>{const e=64-ge+1;return Array.from({length:e},me)})();return[..._e,...e].map(Ee)},Ee=({name:e,number:t,description:n,action:r,forced:o=!1,standard:s})=>{const{signals:{[e]:a}}=i.constants,c=void 0!==a;return{name:e,number:c?a:t,description:n,supported:c,action:r,forced:o,standard:s}},be=({name:e,number:t,description:n,supported:r,action:o,forced:s,standard:i})=>[e,{name:e,number:t,description:n,supported:r,action:o,forced:s,standard:i}],Ie=(()=>{const e=ye();return Object.fromEntries(e.map(be))})();(()=>{const e=ye(),t=Array.from({length:65},(t,n)=>((e,t)=>{const n=((e,t)=>{const n=t.find(({name:t})=>i.constants.signals[t]===e);return void 0!==n?n:t.find(t=>t.number===e)})(e,t);if(void 0===n)return{};const{name:r,description:o,supported:s,action:a,forced:c,standard:l}=n;return{[e]:{name:r,number:e,description:o,supported:s,action:a,forced:c,standard:l}}})(n,e));Object.assign({},...t)})();var we=({stdout:e,stderr:t,all:n,error:r,signal:o,exitCode:s,command:i,escapedCommand:a,timedOut:c,isCanceled:l,killed:d,parsed:{options:{timeout:u,cwd:p=C.default.cwd()}}})=>{s=null===s?void 0:s;const f=void 0===(o=null===o?void 0:o)?void 0:Ie[o].description,h=(({timedOut:e,timeout:t,errorCode:n,signal:r,signalDescription:o,exitCode:s,isCanceled:i})=>e?`timed out after ${t} milliseconds`:void 0!==n?`failed with ${n}`:void 0!==r?`was killed with ${r} (${o})`:void 0!==s?`failed with exit code ${s}`:"failed")({timedOut:c,timeout:u,errorCode:r&&r.code,signal:o,signalDescription:f,exitCode:s,isCanceled:l}),m=`Command ${h}: ${i}`,g="[object Error]"===Object.prototype.toString.call(r),_=g?`${m}\n${r.message}`:m,y=[_,t,e].filter(Boolean).join("\n");return g?(r.originalMessage=r.message,r.message=y):r=new Error(y),r.shortMessage=_,r.command=i,r.escapedCommand=a,r.exitCode=s,r.signal=o,r.signalDescription=f,r.stdout=e,r.stderr=t,r.cwd=p,void 0!==n&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=Boolean(c),r.isCanceled=l,r.killed=d&&!c,r},ve=["stdin","stdout","stderr"],Te=[];Te.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&Te.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&Te.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Re=e=>!!e&&"object"==typeof e&&"function"==typeof e.removeListener&&"function"==typeof e.emit&&"function"==typeof e.reallyExit&&"function"==typeof e.listeners&&"function"==typeof e.kill&&"number"==typeof e.pid&&"function"==typeof e.on,Se=Symbol.for("signal-exit emitter"),Ce=globalThis,xe=Object.defineProperty.bind(Object),Ae=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ce[Se])return Ce[Se];xe(Ce,Se,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const n=this.listeners[e],r=n.indexOf(t);-1!==r&&(0===r&&1===n.length?n.length=0:n.splice(r,1))}emit(e,t,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let r=!1;for(const o of this.listeners[e])r=!0===o(t,n)||r;return"exit"===e&&(r=this.emit("afterExit",t,n)||r),r}},Ue=class{},Pe=globalThis.process;Re(Pe)?new class extends Ue{#e="win32"===Pe.platform?"SIGINT":"SIGHUP";#t=new Ae;#n;#r;#o;#s={};#i=!1;constructor(e){super(),this.#n=e,this.#s={};for(const t of Te)this.#s[t]=()=>{const n=this.#n.listeners(t);let{count:r}=this.#t;const o=e;if("object"==typeof o.__signal_exit_emitter__&&"number"==typeof o.__signal_exit_emitter__.count&&(r+=o.__signal_exit_emitter__.count),n.length===r){this.unload();const n=this.#t.emit("exit",null,t),r="SIGHUP"===t?this.#e:t;n||e.kill(e.pid,r)}};this.#o=e.reallyExit,this.#r=e.emit}onExit(e,t){if(!Re(this.#n))return()=>{};!1===this.#i&&this.load();const n=t?.alwaysLast?"afterExit":"exit";return this.#t.on(n,e),()=>{this.#t.removeListener(n,e),0===this.#t.listeners.exit.length&&0===this.#t.listeners.afterExit.length&&this.unload()}}load(){if(!this.#i){this.#i=!0,this.#t.count+=1;for(const e of Te)try{const t=this.#s[e];t&&this.#n.on(e,t)}catch(e){}this.#n.emit=(e,...t)=>this.#a(e,...t),this.#n.reallyExit=e=>this.#c(e)}}unload(){this.#i&&(this.#i=!1,Te.forEach(e=>{const t=this.#s[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#n.removeListener(e,t)}catch(e){}}),this.#n.emit=this.#r,this.#n.reallyExit=this.#o,this.#t.count-=1)}#c(e){return Re(this.#n)?(this.#n.exitCode=e||0,this.#t.emit("exit",this.#n.exitCode,null),this.#o.call(this.#n,this.#n.exitCode)):0}#a(e,...t){const n=this.#r;if("exit"===e&&Re(this.#n)){"number"==typeof t[0]&&(this.#n.exitCode=t[0]);const r=n.call(this.#n,e,...t);return this.#t.emit("exit",this.#n.exitCode,null),r}return n.call(this.#n,e,...t)}}(Pe):new class extends Ue{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,F(re());var Le=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Le,e)]);var Oe=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Be=/^[\w.-]+$/,Ne=c.debuglog("execa").enabled,De=(e,t)=>String(e).padStart(t,"0"),je=(e,t,n={})=>{const r=fe.default._parse(e,t,n);return e=r.command,t=r.args,(n={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(n=r.options).cwd||C.default.cwd(),execPath:C.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ne,...n}).env=(({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:o})=>{const i=t?{...C.default.env,...e}:e;return n?(({env:e=C.default.env,...t}={})=>{const n=he({env:e={...e}});return t.path=e[n],e[n]=(({cwd:e=C.default.cwd(),path:t=C.default.env[he()],preferLocal:n=!0,execPath:r=C.default.execPath,addExecPath:o=!0}={})=>{const i=e instanceof URL?s.fileURLToPath(e):e,a=R.default.resolve(i),c=[];return n&&((e,t)=>{let n;for(;n!==t;)e.push(R.default.join(t,"node_modules/.bin")),n=t,t=R.default.resolve(t,"..")})(c,a),o&&((e,t,n)=>{const r=t instanceof URL?s.fileURLToPath(t):t;e.push(R.default.resolve(n,r,".."))})(c,r,a),[...c,t].join(R.default.delimiter)})(t),e})({env:i,cwd:r,execPath:o}):i})(n),n.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return ve.map(t=>e[t]);if((e=>ve.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${ve.map(e=>`\`${e}\``).join(", ")}`);if("string"==typeof t)return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const n=Math.max(t.length,ve.length);return Array.from({length:n},(e,n)=>t[n])})(n),"win32"===C.default.platform&&"cmd"===R.default.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},ke=(e,n,r)=>"string"==typeof n||t.Buffer.isBuffer(n)?e.stripFinalNewline?function(e){const t="string"==typeof e?"\n":"\n".charCodeAt(),n="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===n&&(e=e.slice(0,-1)),e}(n):n:void 0===r?void 0:"";function $e(e,t,n){const r=je(e,t,n),o=((e,t)=>Oe(e,t).join(" "))(e,t),s=((e,t)=>Oe(e,t).map(e=>(e=>"string"!=typeof e||Be.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&C.default.stderr.write(`[${(()=>{const e=new Date;return`${De(e.getHours(),2)}:${De(e.getMinutes(),2)}:${De(e.getSeconds(),2)}.${De(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(s,r.options);const i=(e=>{const t=(({input:e,inputFile:t})=>"string"!=typeof t?e:((e=>{if(void 0!==e)throw new TypeError("The `input` and `inputFile` options cannot be both set.")})(e),a.readFileSync(t)))(e);if(null!==(n=t)&&"object"==typeof n&&"function"==typeof n.pipe)throw new TypeError("The `input` option cannot be a stream in sync mode");var n;return t})(r.options);let c;try{c=S.default.spawnSync(r.file,r.args,{...r.options,input:i})}catch(e){throw we({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1})}const l=ke(r.options,c.stdout,c.error),d=ke(r.options,c.stderr,c.error);if(c.error||0!==c.status||null!==c.signal){const e=we({stdout:l,stderr:d,error:c.error,signal:c.signal,exitCode:c.status,command:o,escapedCommand:s,parsed:r,timedOut:c.error&&"ETIMEDOUT"===c.error.code,isCanceled:!1,killed:null!==c.signal});if(!r.options.reject)return e;throw e}return{command:o,escapedCommand:s,exitCode:0,stdout:l,stderr:d,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function Me(e){try{return $e("git",["rev-parse","HEAD"],e).stdout}catch{return}}function He(e){try{const t=$e("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=$e("git",["show","-s","--pretty=%d","HEAD"],e).stdout.replace(/^\(|\)$/g,"").split(", ").find(e=>e.startsWith("origin/"));return t?t.match(/^origin\/(?<branch>.+)/)[1]:void 0}return t}catch{return}}var Ge=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Fe=/^\/(.*)\.git$/;function Ye(e){if(e){if(e.match(Ge))return e.replace(Ge,"$1");try{return new URL(e).pathname.replace(Fe,"$1")}catch{return}}}var ze={detect:({env:e})=>Boolean(e.BUILDKITE),configuration({env:e}){const t="false"===e.BUILDKITE_PULL_REQUEST?void 0:e.BUILDKITE_PULL_REQUEST,n=Boolean(t);return{name:"Buildkite",service:"buildkite",build:e.BUILDKITE_BUILD_NUMBER,buildUrl:e.BUILDKITE_BUILD_URL,commit:e.BUILDKITE_COMMIT,tag:e.BUILDKITE_TAG,branch:n?e.BUILDKITE_PULL_REQUEST_BASE_BRANCH:e.BUILDKITE_BRANCH,slug:Ye(e.BUILDKITE_REPO),pr:t,isPr:n,prBranch:n?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},We={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||ie(e.CIRCLE_PULL_REQUEST||e.CI_PULL_REQUEST),n=Boolean(t);return{name:"CircleCI",service:"circleci",build:e.CIRCLE_BUILD_NUM,buildUrl:e.CIRCLE_BUILD_URL,job:`${e.CIRCLE_BUILD_NUM}.${e.CIRCLE_NODE_INDEX}`,commit:e.CIRCLE_SHA1,tag:e.CIRCLE_TAG,branch:n?void 0:e.CIRCLE_BRANCH,pr:t,isPr:n,prBranch:n?e.CIRCLE_BRANCH:void 0,slug:`${e.CIRCLE_PROJECT_USERNAME}/${e.CIRCLE_PROJECT_REPONAME}`}}},Ke="https://cirrus-ci.com",Ve={detect:({env:e})=>Boolean(e.CIRRUS_CI),configuration({env:e}){const t=e.CIRRUS_PR,n=Boolean(t);return{name:"Cirrus CI",service:"cirrus",commit:e.CIRRUS_CHANGE_IN_REPO,tag:e.CIRRUS_TAG,build:e.CIRRUS_BUILD_ID,buildUrl:`${Ke}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${Ke}/task/${e.CIRRUS_TASK_ID}`,branch:n?e.CIRRUS_BASE_BRANCH:e.CIRRUS_BRANCH,pr:t,isPr:n,prBranch:n?e.CIRRUS_BRANCH:void 0,slug:e.CIRRUS_REPO_FULL_NAME,root:e.CIRRUS_WORKING_DIR}}},qe={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:Me({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:He({env:e,cwd:t}),buildUrl:`https://console.aws.amazon.com/codebuild/home?region=${e.AWS_REGION}#/builds/${e.CODEBUILD_BUILD_ID}/view/new`,root:e.PWD})},Je={detect:({env:e})=>Boolean(e.CF_BUILD_ID),configuration({env:e}){const t=e.CF_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Codefresh",service:"codefresh",commit:e.CF_REVISION,build:e.CF_BUILD_ID,buildUrl:e.CF_BUILD_URL,branch:n?e.CF_PULL_REQUEST_TARGET:e.CF_BRANCH,pr:t,isPr:n,prBranch:n?e.CF_BRANCH:void 0,slug:`${e.CF_REPO_OWNER}/${e.CF_REPO_NAME}`,root:e.CF_VOLUME_PATH}}},Xe={detect:({env:e})=>Boolean(e.DRONE),configuration({env:e}){const t="pull_request"===e.DRONE_BUILD_EVENT;return{name:"Drone",service:"drone",commit:e.DRONE_COMMIT_SHA,tag:e.DRONE_TAG,build:e.DRONE_BUILD_NUMBER,buildUrl:e.DRONE_BUILD_LINK,branch:t?e.DRONE_TARGET_BRANCH:e.DRONE_BRANCH,job:e.DRONE_JOB_NUMBER,jobUrl:e.DRONE_BUILD_LINK,pr:e.DRONE_PULL_REQUEST,isPr:t,prBranch:t?e.DRONE_SOURCE_BRANCH:void 0,slug:`${e.DRONE_REPO_OWNER}/${e.DRONE_REPO_NAME}`,root:e.DRONE_WORKSPACE}}},Qe=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(a.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?ae(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},Ze={detect:({env:e})=>Boolean(e.GITHUB_ACTIONS),configuration({env:e,cwd:t}){const n="pull_request"===e.GITHUB_EVENT_NAME||"pull_request_target"===e.GITHUB_EVENT_NAME,r=ae("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(a.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;return t&&t.pull_request?t.pull_request.number:void 0})(e)}/merge`:e.GITHUB_REF);return{name:"GitHub Actions",service:"github",commit:e.GITHUB_SHA,build:e.GITHUB_RUN_ID,buildUrl:`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`,isPr:n,branch:r,prBranch:n?r:void 0,slug:e.GITHUB_REPOSITORY,root:e.GITHUB_WORKSPACE,...n?Qe({env:e}):void 0}}},et={detect:({env:e})=>Boolean(e.GITLAB_CI),configuration({env:e}){const t=e.CI_MERGE_REQUEST_ID,n=Boolean(t);return{name:"GitLab CI/CD",service:"gitlab",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_ID,buildUrl:`${e.CI_PROJECT_URL}/pipelines/${e.CI_PIPELINE_ID}`,job:e.CI_JOB_ID,jobUrl:`${e.CI_PROJECT_URL}/-/jobs/${e.CI_JOB_ID}`,branch:n?e.CI_MERGE_REQUEST_TARGET_BRANCH_NAME:e.CI_COMMIT_REF_NAME,pr:t,isPr:n,prBranch:e.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,slug:e.CI_PROJECT_PATH,root:e.CI_PROJECT_DIR}}},tt={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const n=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,r=Boolean(n),o=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||Me({env:e,cwd:t}),branch:r?e.ghprbTargetBranch||e.gitlabTargetBranch:o,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,root:e.WORKSPACE,pr:n,isPr:r,prBranch:r?e.ghprbSourceBranch||e.gitlabSourceBranch||o:void 0}}},nt={detect:({env:e})=>"true"===e.NETLIFY,configuration({env:e}){const t="true"===e.PULL_REQUEST;return{name:"Netlify",service:"netlify",commit:e.COMMIT_REF,build:e.DEPLOY_ID,buildUrl:`https://app.netlify.com/sites/${e.SITE_NAME}/deploys/${e.DEPLOY_ID}`,branch:t?void 0:e.HEAD,pr:e.REVIEW_ID,isPr:t,prBranch:t?e.HEAD:void 0,slug:e.REPOSITORY_URL.match(/[^/:]+\/[^/]+?$/)[0],root:e.PWD}}},rt={detect:({env:e})=>Boolean(e.DISTELLI_APPNAME),configuration:({env:e})=>({name:"Puppet",service:"puppet",build:e.DISTELLI_BUILDNUM,buildUrl:e.DISTELLI_RELEASE,commit:e.DISTELLI_RELREVISION,branch:e.DISTELLI_RELBRANCH,root:e.DISTELLI_INSTALLHOME})},ot={detect:({env:e})=>Boolean(e.SAILCI),configuration({env:e}){const t=e.SAIL_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Sail CI",service:"sail",commit:e.SAIL_COMMIT_SHA,branch:n?void 0:e.SAIL_COMMIT_BRANCH,pr:t,isPr:n,slug:`${e.SAIL_REPO_OWNER}/${e.SAIL_REPO_NAME}`,root:e.SAIL_CLONE_DIR}}},st={detect:({env:e})=>Boolean(e.SCREWDRIVER),configuration({env:e}){const t=e.SD_PULL_REQUEST,n=Boolean(t);return{name:"Screwdriver.cd",service:"screwdriver",branch:n?e.PR_BASE_BRANCH_NAME:e.GIT_BRANCH,prBranch:n?e.PR_BRANCH_NAME:void 0,commit:e.SD_BUILD_SHA,build:e.SD_BUILD_ID,buildUrl:e.SD_UI_BUILD_URL,job:e.SD_JOB_ID,pr:t,isPr:n,slug:e.SD_PIPELINE_NAME,root:e.SD_ROOT_DIR}}},it={detect:({env:e})=>Boolean(e.SCRUTINIZER),configuration({env:e}){const t=e.SCRUTINIZER_PR_NUMBER,n=Boolean(t);return{name:"Scrutinizer",service:"scrutinizer",commit:e.SCRUTINIZER_SHA1,build:e.SCRUTINIZER_INSPECTION_UUID,branch:e.SCRUTINIZER_BRANCH,pr:t,isPr:n,prBranch:e.SCRUTINIZER_PR_SOURCE_BRANCH}}},at={detect:({env:e})=>Boolean(e.SEMAPHORE),configuration({env:e,cwd:t}){const n=e.SEMAPHORE_GIT_PR_NUMBER||e.PULL_REQUEST_NUMBER,r=Boolean(n);return{name:"Semaphore",service:"semaphore",commit:e.SEMAPHORE_GIT_SHA||Me({env:e,cwd:t}),tag:e.SEMAPHORE_GIT_TAG_NAME,build:e.SEMAPHORE_JOB_ID||e.SEMAPHORE_BUILD_NUMBER,branch:e.SEMAPHORE_GIT_BRANCH||(r?void 0:e.BRANCH_NAME),pr:n,isPr:r,prBranch:e.SEMAPHORE_GIT_PR_BRANCH||(r?e.BRANCH_NAME:void 0),slug:e.SEMAPHORE_GIT_REPO_SLUG||e.SEMAPHORE_REPO_SLUG,root:e.SEMAPHORE_GIT_DIR||e.SEMAPHORE_PROJECT_DIR}}},ct={detect:({env:e})=>Boolean(e.SHIPPABLE),configuration({env:e}){const t="true"===e.IS_PULL_REQUEST?e.PULL_REQUEST:void 0,n=Boolean(t);return{name:"Shippable",service:"shippable",commit:e.COMMIT,tag:e.GIT_TAG_NAME,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,branch:n?e.BASE_BRANCH:e.BRANCH,job:e.JOB_NUMBER,pr:t,isPr:n,prBranch:n?e.HEAD_BRANCH:void 0,slug:e.SHIPPABLE_REPO_SLUG,root:e.SHIPPABLE_BUILD_DIR}}},lt=F(oe()),dt={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},ut=e=>{try{return lt.default.of(e)}catch{return}},pt=({env:e,cwd:t})=>{const n=e.TEAMCITY_BUILD_PROPERTIES_FILE?ut(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,r=n?n.get("teamcity.configuration.properties.file"):void 0,o=r?ut(r):r;return Object.fromEntries(Object.keys(dt).map(r=>[r,(n?n.get(dt[r]):void 0)||(o?o.get(dt[r]):void 0)||("branch"===r?He({env:e,cwd:t}):void 0)]))},ft={appveyor:se,azurePipelines:ce,bamboo:le,bitbucket:de,bitrise:ue,buddy:pe,buildkite:ze,circleci:We,cirrus:Ve,cloudflarePages:{detect:({env:e})=>"1"===e.CF_PAGES,configuration:({env:e})=>({name:"Cloudflare Pages",service:"cloudflarePages",commit:e.CF_PAGES_COMMIT_SHA,branch:e.CF_PAGES_BRANCH,root:e.PWD})},codebuild:qe,codefresh:Je,codeship:{detect:({env:e})=>e.CI_NAME&&"codeship"===e.CI_NAME,configuration:({env:e})=>({name:"Codeship",service:"codeship",build:e.CI_BUILD_NUMBER,buildUrl:e.CI_BUILD_URL,commit:e.CI_COMMIT_ID,branch:e.CI_BRANCH,slug:e.CI_REPO_NAME})},drone:Xe,github:Ze,gitlab:et,jenkins:tt,netlify:nt,puppet:rt,sail:ot,screwdriver:st,scrutinizer:it,semaphore:at,shippable:ct,teamcity:{detect:({env:e})=>Boolean(e.TEAMCITY_VERSION),configuration:({env:e,cwd:t})=>({name:"TeamCity",service:"teamcity",commit:e.BUILD_VCS_NUMBER,build:e.BUILD_NUMBER,slug:e.TEAMCITY_BUILDCONF_NAME,...pt({env:e,cwd:t})})},travis:{detect:({env:e})=>Boolean(e.TRAVIS),configuration({env:e}){const t="false"===e.TRAVIS_PULL_REQUEST?void 0:e.TRAVIS_PULL_REQUEST,n=Boolean(t);return{name:"Travis CI",service:"travis",commit:e.TRAVIS_COMMIT,tag:e.TRAVIS_TAG,build:e.TRAVIS_BUILD_NUMBER,buildUrl:e.TRAVIS_BUILD_WEB_URL,branch:e.TRAVIS_BRANCH,job:e.TRAVIS_JOB_NUMBER,jobUrl:e.TRAVIS_JOB_WEB_URL,pr:t,isPr:n,prBranch:e.TRAVIS_PULL_REQUEST_BRANCH,slug:e.TRAVIS_REPO_SLUG,root:e.TRAVIS_BUILD_DIR}}},vela:{detect:({env:e})=>Boolean(e.VELA),configuration({env:e}){const t="pull_request"===e.VELA_BUILD_EVENT;return{name:"Vela",service:"vela",branch:t?e.VELA_PULL_REQUEST_TARGET:e.VELA_BUILD_BRANCH,commit:e.VELA_BUILD_COMMIT,tag:e.VELA_BUILD_TAG,build:e.VELA_BUILD_NUMBER,buildUrl:e.VELA_BUILD_LINK,job:void 0,jobUrl:void 0,isPr:t,pr:e.VELA_BUILD_PULL_REQUEST,prBranch:e.VELA_PULL_REQUEST_SOURCE,slug:e.VELA_REPO_FULL_NAME,root:e.VELA_BUILD_WORKSPACE}}},vercel:{detect:({env:e})=>Boolean(e.VERCEL)||Boolean(e.NOW_GITHUB_DEPLOYMENT),configuration({env:e}){const t="Vercel",n="vercel";return e.VERCEL?{name:t,service:n,commit:e.VERCEL_GIT_COMMIT_SHA,branch:e.VERCEL_GIT_COMMIT_REF,slug:`${e.VERCEL_GIT_REPO_OWNER}/${e.VERCEL_GIT_REPO_SLUG}`}:{name:t,service:n,commit:e.NOW_GITHUB_COMMIT_SHA,branch:e.NOW_GITHUB_COMMIT_REF,slug:`${e.NOW_GITHUB_ORG}/${e.NOW_GITHUB_REPO}`}}},wercker:{detect:({env:e})=>Boolean(e.WERCKER_MAIN_PIPELINE_STARTED),configuration:({env:e})=>({name:"Wercker",service:"wercker",commit:e.WERCKER_GIT_COMMIT,build:e.WERCKER_MAIN_PIPELINE_STARTED,buildUrl:e.WERCKER_RUN_URL,branch:e.WERCKER_GIT_BRANCH,slug:`${e.WERCKER_GIT_OWNER}/${e.WERCKER_GIT_REPOSITORY}`,root:e.WERCKER_ROOT})},woodpecker:{detect:({env:e})=>e.CI&&"woodpecker"===e.CI,configuration({env:e}){const t="pull_request"===e.CI_PIPELINE_EVENT;return{name:"Woodpecker CI",service:"woodpecker",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_NUMBER,buildUrl:e.CI_PIPELINE_URL,branch:t?e.CI_COMMIT_TARGET_BRANCH:e.CI_COMMIT_BRANCH,job:e.CI_STEP_NUMBER,jobUrl:e.CI_STEP_URL,pr:e.CI_COMMIT_PULL_REQUEST,isPr:t,prBranch:t?e.CI_COMMIT_SOURCE_BRANCH:void 0,slug:`${e.CI_REPO_OWNER}/${e.CI_REPO_NAME}`,root:e.CI_WORKSPACE}}},jetbrainsSpace:{detect:({env:e})=>Boolean(e.JB_SPACE_EXECUTION_NUMBER),configuration({env:e}){const t=e.JB_SPACE_PROJECT_KEY,n=e.JB_SPACE_GIT_REPOSITORY_NAME;return{name:"JetBrains Space",service:"jetbrainsSpace",commit:e.JB_SPACE_GIT_REVISION,build:e.JB_SPACE_EXECUTION_NUMBER,branch:ae(e.JB_SPACE_GIT_BRANCH),slug:t&&n?`${t.toLowerCase()}/${n}`:void 0}}}},ht=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=p.simpleGit({baseDir:e.workingDir,maxConcurrentProcesses:1})}static createLocal({workingDir:t}){return new e({mode:"local",workingDir:t})}static createCloud({workingDir:t,baseBranch:n}){return new e({mode:"cloud",workingDir:t,baseBranch:n})}async captureSnapshot(){if("local"!==this.config.mode)return;this.snapshotIndexPath=n.join(i.tmpdir(),`git-diff-tracker-${f.randomUUID()}.index`),await this.git.env("GIT_INDEX_FILE",this.snapshotIndexPath).add(["-A"]);const e=await this.git.env("GIT_INDEX_FILE",this.snapshotIndexPath).raw(["write-tree"]);this.snapshotTreeHash=e.trim()}async computeDiff(){return"local"===this.config.mode?this.computeLocalDiff():this.computeCloudDiff()}async computeLocalDiff(){if(!this.snapshotTreeHash)throw new Error("No snapshot captured. Call captureSnapshot() first.");const e=n.join(i.tmpdir(),`git-diff-tracker-${f.randomUUID()}.index`);try{await this.git.env("GIT_INDEX_FILE",e).add(["-A"]);const t=(await this.git.env("GIT_INDEX_FILE",e).raw(["write-tree"])).trim();return await this.git.raw(["diff-tree","-p","--no-color",this.snapshotTreeHash,t])}finally{await mt(e)}}async computeCloudDiff(){if("cloud"!==this.config.mode)throw new Error("computeCloudDiff called but mode is not cloud");const{baseBranch:e}=this.config;return await this.git.revparse([`origin/${e}`]).then(()=>!0).catch(()=>!1)||await this.git.fetch(["origin",`${e}:refs/remotes/origin/${e}`,"--depth","1","--quiet"]).catch(e=>{console.error("[git-diff-tracker] Failed to fetch base branch:",e)}),await this.git.diff([`origin/${e}`])}async cleanup(){this.snapshotIndexPath&&(await mt(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function mt(e){try{await h.unlink(e)}catch{}}var gt={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},_t=({allowReserved:e,explode:t,name:n,style:r,value:o})=>{if(!t){const t=(e?o:o.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(r));switch(r){case"label":return`.${t}`;case"matrix":return`;${n}=${t}`;case"simple":return t;default:return`${n}=${t}`}}const s=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),i=o.map(t=>"label"===r||"simple"===r?e?t:encodeURIComponent(t):yt({allowReserved:e,name:n,value:t})).join(s);return"label"===r||"matrix"===r?s+i:i},yt=({allowReserved:e,name:t,value:n})=>{if(null==n)return"";if("object"==typeof n)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},Et=({allowReserved:e,explode:t,name:n,style:r,value:o,valueOnly:s})=>{if(o instanceof Date)return s?o.toISOString():`${n}=${o.toISOString()}`;if("deepObject"!==r&&!t){let t=[];Object.entries(o).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});const s=t.join(",");switch(r){case"form":return`${n}=${s}`;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return s}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),a=Object.entries(o).map(([t,o])=>yt({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:o})).join(i);return"label"===r||"matrix"===r?i+a:a},bt=/\{[^{}]+\}/g;function It(e){const t=void 0!==e.body;return t&&e.bodySerializer?"serializedBody"in e?void 0!==e.serializedBody&&""!==e.serializedBody?e.serializedBody:null:""!==e.body?e.body:null:t?e.body:void 0}var wt,vt=async(e,t)=>{const n="function"==typeof t?await t(e):t;if(n)return"bearer"===e.scheme?`Bearer ${n}`:"basic"===e.scheme?`Basic ${btoa(n)}`:n},Tt=({parameters:e={},...t}={})=>n=>{const r=[];if(n&&"object"==typeof n)for(const o in n){const s=n[o];if(null==s)continue;const i=e[o]||t;if(Array.isArray(s)){const e=_t({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&r.push(e)}else if("object"==typeof s){const e=Et({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&r.push(e)}else{const e=yt({allowReserved:i.allowReserved,name:o,value:s});e&&r.push(e)}}return r.join("&")},Rt=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),St=e=>(({baseUrl:e,path:t,query:n,querySerializer:r,url:o})=>{let s=(e??"")+(o.startsWith("/")?o:`/${o}`);t&&(s=(({path:e,url:t})=>{let n=t;const r=t.match(bt);if(r)for(const t of r){let r=!1,o=t.substring(1,t.length-1),s="simple";o.endsWith("*")&&(r=!0,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),s="label"):o.startsWith(";")&&(o=o.substring(1),s="matrix");const i=e[o];if(null==i)continue;if(Array.isArray(i)){n=n.replace(t,_t({explode:r,name:o,style:s,value:i}));continue}if("object"==typeof i){n=n.replace(t,Et({explode:r,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){n=n.replace(t,`;${yt({name:o,value:i})}`);continue}const a=encodeURIComponent("label"===s?`.${i}`:i);n=n.replace(t,a)}return n})({path:t,url:s}));let i=n?r(n):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(s+=`?${i}`),s})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:Tt(e.querySerializer),url:e.url}),Ct=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=At(e.headers,t.headers),n},xt=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},At=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?xt(n):Object.entries(n);for(const[n,r]of e)if(null===r)t.delete(n);else if(Array.isArray(r))for(const e of r)t.append(n,e);else void 0!==r&&t.set(n,"object"==typeof r?JSON.stringify(r):r)}return t},Ut=class{fns=[];clear(){this.fns=[]}eject(e){const t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){const t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){return"number"==typeof e?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){const n=this.getInterceptorIndex(e);return!!this.fns[n]&&(this.fns[n]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}},Pt=Tt({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Lt={"Content-Type":"application/json"},Ot=(e={})=>({...gt,headers:Lt,parseAs:"auto",querySerializer:Pt,...e}),Bt=(e={})=>{let t=Ct(Ot(),e);const n=()=>({...t}),r={error:new Ut,request:new Ut,response:new Ut},o=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:At(t.headers,e.headers),serializedBody:void 0};return n.security&&await(async({security:e,...t})=>{for(const n of e){if(Rt(t,n.name))continue;const e=await vt(n,t.auth);if(!e)continue;const r=n.name??"Authorization";switch(n.in){case"query":t.query||(t.query={}),t.query[r]=e;break;case"cookie":t.headers.append("Cookie",`${r}=${e}`);break;default:t.headers.set(r,e)}}})({...n,security:n.security}),n.requestValidator&&await n.requestValidator(n),void 0!==n.body&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),void 0!==n.body&&""!==n.serializedBody||n.headers.delete("Content-Type"),{opts:n,url:St(n)}},s=async e=>{const{opts:t,url:n}=await o(e),s={redirect:"follow",...t,body:It(t)};let i=new Request(n,s);for(const e of r.request.fns)e&&(i=await e(i,t));const a=t.fetch;let c;try{c=await a(i)}catch(e){let n=e;for(const o of r.error.fns)o&&(n=await o(e,void 0,i,t));if(n=n||{},t.throwOnError)throw n;return"data"===t.responseStyle?void 0:{error:n,request:i,response:void 0}}for(const e of r.response.fns)e&&(c=await e(c,i,t));const l={request:i,response:c};if(c.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(c.headers.get("Content-Type")):t.parseAs)??"json";if(204===c.status||"0"===c.headers.get("Content-Length")){let n;switch(e){case"arrayBuffer":case"blob":case"text":n=await c[e]();break;case"formData":n=new FormData;break;case"stream":n=c.body;break;default:n={}}return"data"===t.responseStyle?n:{data:n,...l}}let n;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":n=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),"data"===t.responseStyle?n:{data:n,...l}}const d=await c.text();let u;try{u=JSON.parse(d)}catch{}const p=u??d;let f=p;for(const e of r.error.fns)e&&(f=await e(p,c,i,t));if(f=f||{},t.throwOnError)throw f;return"data"===t.responseStyle?void 0:{error:f,...l}},i=e=>t=>s({...t,method:e}),a=e=>async t=>{const{opts:n,url:s}=await o(t);return(({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:o,sseDefaultRetryDelay:s,sseMaxRetryAttempts:i,sseMaxRetryDelay:a,sseSleepFn:c,url:l,...d})=>{let u;const p=c??(e=>new Promise(t=>setTimeout(t,e))),f=async function*(){let c=s??3e3,f=0;const h=d.signal??(new AbortController).signal;for(;!h.aborted;){f++;const s=d.headers instanceof Headers?d.headers:new Headers(d.headers);void 0!==u&&s.set("Last-Event-ID",u);try{const t={redirect:"follow",...d,body:d.serializedBody,headers:s,signal:h};let i=new Request(l,t);e&&(i=await e(l,t));const a=d.fetch??globalThis.fetch,p=await a(i);if(!p.ok)throw new Error(`SSE failed: ${p.status} ${p.statusText}`);if(!p.body)throw new Error("No body in SSE response");const f=p.body.pipeThrough(new TextDecoderStream).getReader();let m="";const g=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",g);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;m+=t;const s=m.split("\n\n");m=s.pop()??"";for(const e of s){const t=e.split("\n"),s=[];let i,a;for(const e of t)if(e.startsWith("data:"))s.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))i=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))u=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(c=t)}let l=!1;if(s.length){const e=s.join("\n");try{a=JSON.parse(e),l=!0}catch{a=e}}l&&(o&&await o(a),r&&(a=await r(a))),n?.({data:a,event:i,id:u,retry:c}),s.length&&(yield a)}}}finally{h.removeEventListener("abort",g),f.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&f>=i)break;const n=Math.min(c*2**(f-1),a??3e4);await p(n)}}}();return{stream:f}})({...n,body:n.body,headers:n.headers,method:e,onRequest:async(e,t)=>{let o=new Request(e,t);for(const e of r.request.fns)e&&(o=await e(o,n));return o},url:s})};return{buildUrl:St,connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),getConfig:n,head:i("HEAD"),interceptors:r,options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),request:s,setConfig:e=>(t=Ct(t,e),n()),sse:{connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),head:a("HEAD"),options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),trace:a("TRACE")},trace:i("TRACE")}},Nt=Bt(Ot({baseUrl:"https://api.stably.ai"})),Dt="x-stably-org-id",jt="4.3.7",kt=process.env.STABLY_API_URL||"https://api.stably.ai",$t=process.env.AUTH_URL||"https://auth.stably.ai",Mt=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",Ht=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",Gt="http://localhost:9876/auth/callback",Ft=()=>wt||(wt=Bt(Ot({baseUrl:kt,headers:{"X-STABLY-CLI-VERSION":jt,"X-STABLY-SOURCE":"cli"}}))),Yt=async(e,t)=>{const n=await(r={body:{accessToken:e,orgId:t},client:Ft()},(r.client??Nt).post({url:"/internal/v1/cli/exchange-token",...r,headers:{"Content-Type":"application/json",...r.headers}}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this organization");if(n.error)throw new Error(`Failed to exchange token: ${n.response.status}`);return n.data},zt=_.z.object({org_id:_.z.string(),org_name:_.z.string()}),Wt=_.z.object({email:_.z.string(),org_id_to_org_member_info:_.z.record(_.z.string(),zt).optional(),org_member_info:zt.optional(),user_id:_.z.string()});_.z.object({email:_.z.string(),firstName:_.z.string().optional(),lastName:_.z.string().optional(),organizations:_.z.array(_.z.object({id:_.z.string(),name:_.z.string()})),userId:_.z.string()});var Kt=e=>{const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const n=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=Buffer.from(n,"base64").toString("utf-8");return JSON.parse(r)},Vt=e=>{try{const t=Wt.parse(Kt(e)),n=t.org_id_to_org_member_info?Object.entries(t.org_id_to_org_member_info).map(([e,t])=>({id:e,name:t.org_name})):t.org_member_info?[{id:t.org_member_info.org_id,name:t.org_member_info.org_name}]:[];return{email:t.email,organizations:n,userId:t.user_id}}catch(e){throw new Error(`Failed to decode token: ${e instanceof Error?e.message:"Unknown error"}`)}},qt=R.default.join(x.default.homedir(),".stably"),Jt=R.default.join(qt,"auth.json"),Xt=".stably",Qt="project.json",Zt=L.default.object({accessToken:L.default.string(),expiresAt:L.default.number(),idToken:L.default.string().optional(),refreshToken:L.default.string()}),en=L.default.object({orgId:L.default.string(),orgName:L.default.string(),projectId:L.default.string(),projectName:L.default.string()}),tn=async()=>{try{const e=await h.readFile(Jt,"utf-8");return Zt.parse(JSON.parse(e))}catch{return}},nn=async e=>{await h.mkdir(qt,{recursive:!0}),await h.writeFile(Jt,JSON.stringify(e,null,2),{mode:384})},rn=async()=>{try{await h.unlink(Jt)}catch{}},on=async e=>{let t=e;const{root:n}=R.default.parse(t);for(;t!==n;){const e=R.default.join(t,Xt);try{return await h.access(e),e}catch{t=R.default.dirname(t)}}},sn=async()=>{try{const e=await on(process.cwd());if(!e)return;const t=R.default.join(e,Qt),n=await h.readFile(t,"utf-8");return en.parse(JSON.parse(n))}catch{return}},an=async()=>{try{const e=await on(process.cwd());e&&await h.unlink(R.default.join(e,Qt))}catch{}},cn=e=>Date.now()>=e.expiresAt-3e5,ln=async e=>{const t=new URLSearchParams({client_id:Mt,grant_type:"refresh_token",refresh_token:e}),n=await fetch(`${$t}/propelauth/oauth/token`,{body:t.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!n.ok)throw new Error(`Token refresh failed: ${n.status}`);const r=await n.json();return{accessToken:r.access_token,expiresAt:Date.now()+1e3*r.expires_in,refreshToken:r.refresh_token}},dn=e=>`\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authentication Failed Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #ef4444;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .error-box {\n background: rgba(239, 68, 68, 0.1);\n border: 1px solid rgba(239, 68, 68, 0.3);\n border-radius: 8px;\n padding: 16px;\n margin-bottom: 24px;\n }\n .error-label {\n font-size: 11px;\n font-weight: 600;\n color: #ef4444;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 8px;\n }\n .error-message {\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 13px;\n color: #fafafa;\n word-break: break-word;\n }\n .hint {\n color: #666;\n font-size: 13px;\n }\n .hint code {\n background: #111;\n border: 1px solid #333;\n border-radius: 4px;\n padding: 2px 6px;\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 12px;\n color: #888;\n }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>\n </svg>\n </div>\n <h1 class="title">Authentication Failed</h1>\n <p class="subtitle">Something went wrong during login.</p>\n <div class="error-box">\n <div class="error-label">Error</div>\n <div class="error-message">${e}</div>\n </div>\n <p class="hint">Run <code>stably login</code> to try again.</p>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n`,un=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(n)},pn=(e,t)=>{const n=new URLSearchParams({client_id:Mt,code_challenge:e,code_challenge_method:"S256",redirect_uri:Gt,response_type:"code",state:t});return`${$t}/propelauth/oauth/authorize?${n.toString()}`},fn=async e=>{const t=m.spinner();let n;t.start("Loading user info...");try{n=Vt(e.accessToken),t.stop(U.default.green(`✓ Logged in as ${U.default.cyan(n.email)}`))}catch(e){t.stop(U.default.red("✗ Failed to load user info"));const n=e instanceof Error?e.message:"Unknown error";return m.log.error(n),{success:!1}}const r=await(async e=>{if(0===e.length)return void m.log.error("You don't belong to any organizations.");if(1===e.length)return m.log.info(`Using organization: ${U.default.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return m.log.info(`Auto-selecting organization: ${U.default.cyan(e[0].name)}`),e[0];const t=await m.select({message:"Select an organization",options:e.map(e=>({label:e.name,value:e.id}))});return m.isCancel(t)?void 0:e.find(e=>e.id===t)})(n.organizations);if(!r)return m.log.warn("Organization selection cancelled."),{success:!1};let o;t.start("Getting org credentials...");try{const n=await Yt(e.accessToken,r.id);o={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(U.default.green("✓ Credentials obtained"))}catch(e){t.stop(U.default.red("✗ Failed to get org credentials"));const n=e instanceof Error?e.message:"Unknown error";return m.log.error(n),{success:!1}}const s=await(async(e,t)=>{const n=m.spinner();let r;n.start("Loading projects...");try{r=await(async({accessToken:e,orgId:t})=>{const n=await(r={auth:e,client:Ft(),path:{orgId:t}},(r.client??Nt).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/orgs/{orgId}/projects",...r}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this organization");if(n.error)throw new Error(`Failed to list projects: ${n.response.status}`);return n.data.projects})({accessToken:e,orgId:t}),n.stop(U.default.green("✓ Projects loaded"))}catch(e){n.stop(U.default.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void m.log.error(t)}if(0===r.length)return m.log.error("No projects found in this organization."),void m.log.info(`Create a project at ${U.default.underline(U.default.cyan("https://app.stably.ai"))}`);if(1===r.length)return m.log.info(`Using project: ${U.default.cyan(r[0].name)}`),r[0];if(!process.stdin.isTTY)return m.log.info(`Auto-selecting project: ${U.default.cyan(r[0].name)}`),r[0];const o=await m.select({message:"Select a project",options:r.map(e=>({label:e.name,value:e.id}))});return m.isCancel(o)?void 0:r.find(e=>e.id===o)})(o.accessToken,r.id);return s?(await(async e=>{const t=R.default.join(process.cwd(),Xt),n=R.default.join(t,Qt);await h.mkdir(t,{recursive:!0}),await h.writeFile(n,JSON.stringify(e,null,2)),await(async e=>{const t=R.default.join(e,".gitignore"),n="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await h.readFile(t,"utf-8"),r=e.split("\n").map(e=>e.trim());if(r.includes(".stably/*")&&r.includes("!.stably/docs/"))return;const o=/^# Stably CLI\n\.stably\/?$/m,s=/^\.stably\/?$/m;if(o.test(e)){const r=e.replace(o,`\n${n}\n`);await h.writeFile(t,r)}else if(s.test(e)){const r=e.replace(s,`\n${n}\n`);await h.writeFile(t,r)}else await h.appendFile(t,`\n${n}\n`)}catch{await h.writeFile(t,`${n}\n`)}})(process.cwd())})({orgId:r.id,orgName:r.name,projectId:s.id,projectName:s.name}),m.log.info(U.default.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(m.log.warn("Project selection cancelled."),{success:!1})},hn=async()=>{if(mn())return m.log.warn(`Environment variables ${U.default.cyan("STABLY_API_KEY")} and ${U.default.cyan("STABLY_PROJECT_ID")} are set.`),m.log.warn("These will be used for authentication instead of OAuth login."),m.log.warn("To use OAuth login, unset these environment variables first."),void m.outro(U.default.yellow("Login skipped - using environment variable authentication."));const e=await tn();if(e){if(!cn(e)){if(await sn())return void m.outro(U.default.yellow("You are already logged in. Run `stably logout` first to log out."));m.log.info("You are logged in but haven't selected a project yet.");const t=await fn(e);return void(t.success?(await nn(t.scopedTokens),m.outro(U.default.green("Setup complete! You can now use Stably CLI."))):m.outro(U.default.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=m.spinner();t.start("Refreshing session...");try{const n=await ln(e.refreshToken);t.stop(U.default.green("✓ Session refreshed"));const r=await sn();if(r){t.start("Getting org credentials...");try{const e=await Yt(n.accessToken,r.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:n.idToken,refreshToken:n.refreshToken};await nn(o),t.stop(U.default.green("✓ Credentials obtained")),m.outro(U.default.green("Login successful"))}catch{await nn(n),t.stop(U.default.yellow("Using full credentials")),m.outro(U.default.green("Login successful"))}}else{const e=await fn(n);e.success?(await nn(e.scopedTokens),m.outro(U.default.green("Setup complete! You can now use Stably CLI."))):m.outro(U.default.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(U.default.yellow("Session expired, proceeding with fresh login...")),await rn(),await an()}}const{authorizeUrl:t,waitForCallback:n}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:n}=(()=>{const e=P.default.randomBytes(32).toString("base64url"),t=(n=e,P.default.createHash("sha256").update(n).digest("base64url"));var n;const r=P.default.randomBytes(16).toString("base64url");return{authorizeUrl:pn(t,r),codeVerifier:e,state:r}})();return{authorizeUrl:e,waitForCallback:async()=>(async(e,t)=>{const n=await(r=e,new Promise((e,t)=>{const n=setTimeout(()=>{i.close(),e({error:"Login timed out",success:!1})},3e5),o=()=>{clearTimeout(n)},i=B.default.createServer((t,n)=>{const a=new s.URL(t.url||"","http://localhost:9876");if("/auth/callback"!==a.pathname)return n.writeHead(404),void n.end("Not found");const c=a.searchParams.get("code"),l=a.searchParams.get("state"),d=a.searchParams.get("error");return d?(un(n,400,dn(d)),o(),i.close(),void e({error:d,success:!1})):c&&l?l!==r?(un(n,400,dn("Invalid state parameter (possible CSRF attack)")),o(),i.close(),void e({error:"State mismatch",success:!1})):(un(n,200,'\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authenticated Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #22c55e;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .terminal {\n background: #111;\n border: 1px solid #333;\n border-radius: 8px;\n padding: 16px;\n text-align: left;\n font-family: \'SF Mono\', \'Fira Code\', \'Consolas\', monospace;\n font-size: 13px;\n }\n .terminal-header {\n display: flex;\n gap: 6px;\n margin-bottom: 12px;\n }\n .terminal-dot {\n width: 10px;\n height: 10px;\n border-radius: 50%;\n background: #333;\n }\n .terminal-line {\n color: #888;\n }\n .terminal-line .prompt { color: #888; }\n .terminal-line .cmd { color: #fafafa; }\n .terminal-line.success { color: #22c55e; }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>\n </svg>\n </div>\n <h1 class="title">Authenticated</h1>\n <p class="subtitle">You can close this tab and return to your terminal.</p>\n <div class="terminal">\n <div class="terminal-header">\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n </div>\n <div class="terminal-line"><span class="prompt">$</span> <span class="cmd">stably login</span></div>\n <div class="terminal-line success">Logged in successfully</div>\n </div>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n'),o(),i.close(),void e({code:c,state:l,success:!0})):(un(n,400,dn("Missing code or state parameter")),o(),i.close(),void e({error:"Missing code or state parameter",success:!1}))});i.on("error",e=>{o(),"EADDRINUSE"!==e.code?t(new Error(`Failed to start callback server: ${e.message}`)):t(new Error("Port 9876 is already in use. Please close the application using it and try again."))}),i.listen(9876)}));var r;if(!n.success)throw new Error(n.error);return(async(e,t)=>{const n=new URLSearchParams({client_id:Mt,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:Gt}),r=await fetch(`${$t}/propelauth/oauth/token`,{body:n.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!r.ok){const e=await r.text();throw new Error(`Token exchange failed: ${r.status} ${e}`)}const o=await r.json();return{accessToken:o.access_token,expiresAt:Date.now()+1e3*o.expires_in,idToken:o.id_token,refreshToken:o.refresh_token}})(n.code,t)})(n,t)}})();m.log.info("Opening browser for authentication..."),m.log.info(U.default.dim("If browser doesn't open, visit:")),m.log.info(U.default.underline(U.default.cyan(t)));try{await O.default(t)}catch{m.log.warn("Could not open browser automatically. Please open the URL above manually.")}const r=m.spinner();let o;r.start("Waiting for authentication...");try{o=await n(),r.stop(U.default.green("✓ Authentication successful"))}catch(e){r.stop(U.default.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";m.outro(U.default.red(`Login failed: ${t}`)),process.exit(1)}const i=await fn(o);i.success?(await nn(i.scopedTokens),m.outro(U.default.green("Setup complete! You can now use Stably CLI."))):(m.outro(U.default.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},mn=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return{apiKey:e,projectId:t}},gn=!1,_n=()=>{gn||(gn=!0,m.log.warn("Both environment variable auth and stored OAuth login were detected."),m.log.warn(`Honoring environment variables (${U.default.cyan("STABLY_API_KEY")} + ${U.default.cyan("STABLY_PROJECT_ID")}).`),m.log.warn("To use OAuth login instead, unset those environment variables."))},yn=async()=>{const e=await tn();if(e){if(!cn(e)){const t=await sn();if(t&&"full"===(e=>{try{const t=Wt.parse(Kt(e));if(t.org_id_to_org_member_info)return"full";if(t.org_member_info)return"org"}catch{return"unknown"}return"unknown"})(e.accessToken))try{const n=await Yt(e.accessToken,t.orgId),r={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await nn(r),r}catch{return e}return e}try{const t=await ln(e.refreshToken),n=await sn();if(n)try{const e=await Yt(t.accessToken,n.orgId),r={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await nn(r),r}catch{return await nn(t),t}return await nn(t),t}catch{return}}},En=async(e={})=>{const t=mn();if(t){try{await tn()&&_n()}catch{}return{auth:t,type:"env"}}let n=await yn(),r=n?await sn():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if((!n||!r)&&e.autoLogin&&o){n?m.log.info("You are logged in but need to select an organization and project."):m.log.info("You are not logged in."),m.log.info("Press Enter to log in."),process.stdout.write(`${U.default.dim("Alternatively, set environment variables for an org API key:")}\n${U.default.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=g.createInterface({input:process.stdin,output:process.stdout});try{await e.question(U.default.dim("Press Enter to continue... "))}finally{e.close()}await hn(),n=await yn(),r=n?await sn():void 0}return n||(m.outro(U.default.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),r||(m.outro(U.default.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),{auth:{accessToken:n.accessToken,context:r},type:"oauth"}},bn=e=>e?{...process.env,...e}:process.env,In=async()=>{const e=mn();if(e)return{STABLY_API_KEY:e.apiKey,STABLY_PROJECT_ID:e.projectId};const t=await(async()=>{const e=mn();if(e){try{await tn()&&_n()}catch{}return{auth:e,type:"env"}}const t=await yn(),n=t?await sn():void 0;if(t&&n)return{auth:{accessToken:t.accessToken,context:n},type:"oauth"}})();if(!t||"env"===t.type)return;const n=process.env.STABLY_PROJECT_ID?.trim(),r=n||(e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId)(t);if(!r)return;const o=await(async(e,t)=>{try{return(await(async({accessToken:e,projectId:t})=>{const n=await(r={auth:e,client:Ft(),path:{projectId:t}},(r.client??Nt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/api-key",...r}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this project");if(n.error)throw new Error(`Failed to get API key: ${n.response.status}`);return n.data})({accessToken:e,projectId:t})).apiKey}catch{return e}})(t.auth.accessToken,r);return o?{STABLY_API_KEY:o,STABLY_PROJECT_ID:r}:void 0},wn=e=>e?{[Dt]:e}:void 0,vn=_.z.object({context:_.z.string().min(1),autohealReportUrl:_.z.string()}),Tn=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},Rn=e=>null!=e&&"object"==typeof e&&"tool_response"in e,Sn=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},Cn=e=>{const t=Sn(e);if(t)return t.filter(Tn).map(e=>e.text).join("\n")||void 0},xn=/\u001b\[[0-9;]*m/g,An=e=>e.replace(xn,""),Un=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function Pn({envVars:e}){return async t=>{if(!function(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}(t))return{decision:"approve"};const n=t.tool_input,r="string"==typeof n.text?n.text:void 0;if(!r)return{decision:"approve"};const o=r.replace(Un,(t,n)=>{const r=e[n];return null!=r?r:t});return o===r?{decision:"approve"}:{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser text input.",updatedInput:{...n,text:o}}}}}function Ln({onResult:e}){return async t=>{if(!Rn(t))return{decision:"approve"};const n=Cn(t);if(!n)return{decision:"approve"};const r=function(e){const t=An(e),n=t.split(/Running \d+ tests? using \d+ workers?/).at(-1)??t,r=parseInt(n.match(/(\d+)\s+passed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0"),o=parseInt(n.match(/(\d+)\s+failed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0");if(0===r&&0===o)return;const s=[r>0?`${r} test${1===r?"":"s"} passed ✓`:void 0,o>0?`${o} test${1===o?"":"s"} failed ✗`:void 0].filter(e=>void 0!==e).join(", ");if(0===o)return s;const i=n.split(/\n\s+\d+\)\s+\[id=/).slice(1).map(e=>e.match(/\n\s{4}((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/)?.[1]?.trim()).filter(e=>void 0!==e);return 0===i.length?s:`${s}\n${i.map(e=>` - ${e}`).join("\n")}`}(n);return r&&e(r),{decision:"approve"}}}function On({onResult:e}){return async t=>{if(!Rn(t))return{decision:"approve"};const n=Cn(t);if(!n)return{decision:"approve"};const r=function(e){const t=An(e);if(t.match(/### Paused on error:/)){const e=t.match(/### Paused on error:\s*\n((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/);return e?`Test paused on error - ${e[1].trim()}`:"Test paused on error"}const n=t.match(/(\d+)\s+passed/);if(n){const e=parseInt(n[1]);return`${e} test${1===e?"":"s"} passed ✓`}}(n);return r&&e(r),{decision:"approve"}}}var Bn=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function Nn({onFileCreated:e}){return async t=>{const n=(e=>{if(!e||"object"!=typeof e)return;const t=e;return t.tool_input&&"object"==typeof t.tool_input&&!Array.isArray(t.tool_input)?t.tool_input:void 0})(t),r=n?.file_path;return"string"==typeof r&&Bn.test(r)&&e(r),{decision:"approve"}}}var Dn=class{queue=[];pendingResolve=void 0;done=!1;canSend=!0;[Symbol.asyncIterator](){return this}pushText(e){const t=e.trim();t&&!this.done&&(this.queue.push(t),this.maybeFlush())}allowNextTurn(){this.done||(this.canSend=!0,this.maybeFlush())}finish(){this.done=!0,this.pendingResolve&&(this.pendingResolve({done:!0,value:void 0}),this.pendingResolve=void 0)}maybeFlush(){if(!this.pendingResolve)return;if(!this.canSend)return;const e=this.queue.shift();if(void 0===e)return;const t={message:{content:[{text:e,type:"text"}],role:"user"},parent_tool_use_id:null,type:"user",session_id:""};this.canSend=!1,this.pendingResolve({done:!1,value:t}),this.pendingResolve=void 0}next(){return this.done?Promise.resolve({done:!0,value:void 0}):new Promise(e=>{this.pendingResolve=e,this.maybeFlush()})}},jn=[".ts",".js",".mts",".mjs",".cts",".cjs"],kn=10240,$n=async({defaultContent:e,fileName:t,filePath:n})=>{try{const e=(await h.stat(n)).size,r=await h.readFile(n,"utf-8"),o=Buffer.byteLength(r,"utf-8");if(o<=kn)return r;const s=(e=>{const t=e.split("\n"),n=[];let r=!1,o=!1,s=0,i=!1;for(let e=0;e<t.length;e++){const a=t[e],c=a.trim();c.startsWith("/*")&&(r=!0),c.includes("*/")?r=!1:r||c.startsWith("//")&&!c.startsWith("///")||(c.startsWith("import ")||c.startsWith("export ")?(n.push(a),i=!0):i&&""===c?(n.push(a),i=!1):(i=!1,c.startsWith("type ")||c.startsWith("interface ")?n.push(a):c.startsWith("function ")||c.startsWith("const ")||c.startsWith("async function ")||c.startsWith("export function ")||c.startsWith("export const ")||c.startsWith("test.describe(")||c.startsWith("test(")?(n.push(a),o=!0,s=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===s&&(c.endsWith(";")||c.endsWith(","))&&(o=!1)):o?(s+=(a.match(/{/g)||[]).length,s-=(a.match(/}/g)||[]).length,0===s&&c.includes("}")?(n.push(a),o=!1):s>0&&" // ... implementation omitted ..."!==n.at(-1)&&n.push(" // ... implementation omitted ...")):c.match(/^[a-zA-Z_]+:/)&&n.push(a)))}return n.join("\n")})(r),i=Buffer.byteLength(s,"utf-8");return i<=kn?s:s.slice(0,kn)+`\n\n... [TRUNCATED: File "${t}" at ${n} was ${e} bytes (${o} bytes as UTF-8), reduced to ~${i} bytes of essential content, then truncated to 10240 bytes] ...`}catch(n){let r;if(n&&"object"==typeof n&&"code"in n){const e=n.code;"string"==typeof e&&(r=e)}return"ENOENT"!==r&&console.warn(`Failed to read ${t}: ${n}`),e}},Mn=async({defaultContent:e,dirName:t,dirPath:n})=>{try{const e=await h.readdir(n);return e.length>0?e.join("\n"):"(empty)"}catch(n){let r;if(n&&"object"==typeof n&&"code"in n){const e=n.code;"string"==typeof e&&(r=e)}return"ENOENT"!==r&&console.warn(`Failed to read ${t}: ${n}`),e}},Hn=".stably-playwright-wrapper.config.*",Gn=[".ts",".js",".mts",".mjs",".cts",".cjs"];function Fn(e){const t=n.resolve(e);if(a.existsSync(t))for(const e of Gn){const r=n.join(t,`playwright.config${e}`);if(a.existsSync(r))return r}}var Yn=["tests","e2e","__tests__","test"];function zn(e){try{return a.existsSync(e)&&a.statSync(e).isDirectory()}catch{return!1}}function Wn(e,t){const n="output-flag"===t?"--output flag":"playwright.config.ts"===t?"playwright.config.ts":"auto-detected"===t?"auto-detected":"cwd fallback";console.error(U.default.dim(`Using output directory: ${e} (from ${n})`))}var Kn=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__test-doc-sync__","mcp__stably-agent-control__"],Vn=["planner_","generator_"],qn={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools"},Jn=(e,t)=>{const n=t.find(t=>e.startsWith(t));return n?e.slice(n.length):e},Xn=e=>{const t=qn[e];if(t)return t;const n=Jn(e,Kn);return Jn(n,Vn).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")},Qn=(e,t)=>{if(!t||"object"!=typeof t)return;const n=t,r="string"==typeof n.intent?n.intent:void 0;if("Read"!==e&&"Write"!==e&&"Edit"!==e){if("Glob"===e||"Grep"===e)return"string"==typeof n.pattern?n.pattern:void 0;if("mcp__playwright-test__test_run"!==e&&"test_run"!==e){if("mcp__playwright-test__test_debug"===e||"test_debug"===e){const e=n.test;return"string"==typeof e?.title?e.title:void 0}return"mcp__playwright-test__generator_setup_page"===e||"generator_setup_page"===e?"string"==typeof n.seedFile?n.seedFile:"tests/seed.spec.ts":"mcp__playwright-test__generator_write_test"===e||"generator_write_test"===e?"string"==typeof n.fileName?n.fileName:void 0:"Bash"===e?"string"==typeof n.command?n.command.length>50?`${n.command.slice(0,50)}...`:n.command:void 0:e.includes("browser_navigate")&&!e.includes("back")?"string"==typeof n.url?n.url:r:e.includes("browser_type")?("string"==typeof n.text?`"${n.text}"`:void 0)??r:e.includes("browser_click")?"string"==typeof n.element?n.element:r:e.includes("browser_wait_for")?"string"==typeof n.text?`text: "${n.text}"`:"number"==typeof n.time?`${n.time}ms`:r:e.includes("verify_text")?"string"==typeof n.text?`"${n.text}"`:r:e.includes("verify_element")?"string"==typeof n.accessibleName?n.accessibleName:r:e.includes("screenshot")&&"string"==typeof n.filename?n.filename:r}if(Array.isArray(n.locations)){const e=n.locations.filter(e=>"string"==typeof e);return e.length>0?e.join(", "):void 0}}else if("string"==typeof n.file_path)return n.file_path.split("/").at(-1)??void 0},Zn=w.z.object({bucket:w.z.string(),key:w.z.string()}),er=w.z.object({diffBucketPath:Zn,expiresInSeconds:w.z.number(),key:w.z.string(),uploadUrl:w.z.string()}),tr=["test","bug","other"],nr={bug:"Application code defect; behavior diverges from expected requirements.",other:"External dependencies, environment, or infra issues outside test/app code.",test:"Test code is incorrect, out-of-date, or missing necessary setup."},rr=e=>nr[e],{zSuiteAutoHealReport:or}=function(e){const t=e.enum(tr),n=["Classification of the root cause:","",`- test: ${rr("test")}`,`- bug: ${rr("bug")}`,`- other: ${rr("other")}`].join("\n"),r=e.object({erroredUrl:e.string().optional(),issueType:t.describe(n),relatedTestCaseIds:e.array(e.string()).min(1).describe("List of ALL test case IDs impacted by this root cause and fix (must be existing IDs only)."),rootCause:e.string().describe("Brief explanation of what happened (1-2 sentences).")}),o=e.discriminatedUnion("result",[r.extend({fixApplied:e.string().describe("What fix was applied (brief, specific)."),result:e.literal("fixed")}),r.extend({followUpActions:e.string().optional().describe("Optional list of follow-up actions for any unfixed issues or missing data."),reasonNotFixed:e.string().describe("Why it could not be auto-fixed (brief)."),result:e.literal("unfixed")})]);return{zAutoHealReport:o,zIssueCategory:t,zSuiteAutoHealReport:e.object({issues:e.array(o).min(1).describe("List of all auto-heal issues/outcomes for this suite."),summary:e.string().min(3).describe("High-level summary (2-3 sentences) of the suite auto-heal results.")})}}(w.z),sr=({authHeader:e,diffTracker:t,orgId:n,runId:r})=>l.createSdkMcpServer({name:"auto-heal-report",tools:[l.tool("generate-report",["After attempting to fix all broken tests (skip only those truly infeasible), generate and return a suite auto-heal report in the required schema.","","Ensure the payload matches zSuiteAutoHealReport exactly; include every issue discovered."].join("\n"),{report:or},async({report:o})=>{const s=await t.computeDiff(),i=or.parse(o);try{await(async({authHeader:e,orgId:t,report:n,runId:r})=>{const o=await(s={auth:e,body:{report:JSON.stringify(n)},client:Ft(),headers:wn(t),path:{runId:r}},(s.client??Nt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to upload auto-heal report (${o.response.status})`)})({authHeader:e,orgId:n,report:i,runId:r});const{uploadUrl:t}=await(async({authHeader:e,contentType:t="text/plain",orgId:n,runId:r})=>{const o=await(s={auth:e,body:{contentType:t},client:Ft(),headers:wn(n),path:{runId:r}},(s.client??Nt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to presign diff upload (${o.response.status})`);const i=er.parse(o.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}})({authHeader:e,contentType:"text/plain",orgId:n,runId:r});await(async({contentType:e="text/plain",diff:t,uploadUrl:n})=>{const r=await fetch(n,{body:t,headers:{"Content-Type":e},method:"PUT"});if(!r.ok)throw new Error(`Failed to upload diff (${r.status})`)})({contentType:"text/plain",diff:s,uploadUrl:t})}catch(e){return console.error("[auto-heal-report] Failed to upload report or diff:",e),{content:[{text:"Error: Failed to upload auto-heal report or diff. Please surface this to the user, and terminate the session.",type:"text"}]}}return{content:[{text:"Auto-heal report generated. You may terminate this session now.",type:"text"}]}})],version:"0.0.1"}),ir=({onComplete:e})=>l.createSdkMcpServer({name:"session-control",tools:[l.tool("complete_session",["Call this tool when you have completed your task and the session should end.","Use this instead of waiting for the user to manually terminate.","Only call this when you are confident the task is fully complete."].join("\n"),{summary:w.z.string().describe("A brief summary of what was accomplished")},async({summary:t})=>{const n=t;return e(),`Session complete: ${n}`})]}),ar=e=>e.replace(/Bearer\s+[A-Za-z0-9._-]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{16,}\b/g,"[redacted]").replace(/\bstably_[A-Za-z0-9_-]{16,}\b/g,"[redacted]"),cr=(e,t)=>({message:ar(e),status:t?.status,statusText:t?.statusText}),lr=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_MODEL","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","AWS_BEARER_TOKEN_BEDROCK","BASH_DEFAULT_TIMEOUT_MS","BASH_MAX_OUTPUT_LENGTH","BASH_MAX_TIMEOUT_MS","CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR","CLAUDE_CODE_API_KEY_HELPER_TTL_MS","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_DISABLE_TERMINAL_TITLE","CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL","CLAUDE_CODE_MAX_OUTPUT_TOKENS","CLAUDE_CODE_SHELL_PREFIX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX","CLAUDE_CONFIG_DIR","DISABLE_AUTOUPDATER","DISABLE_BUG_COMMAND","DISABLE_COST_WARNINGS","DISABLE_ERROR_REPORTING","DISABLE_NON_ESSENTIAL_MODEL_CALLS","DISABLE_PROMPT_CACHING","DISABLE_PROMPT_CACHING_HAIKU","DISABLE_PROMPT_CACHING_OPUS","DISABLE_PROMPT_CACHING_SONNET","DISABLE_TELEMETRY","HTTP_PROXY","HTTPS_PROXY","MAX_MCP_OUTPUT_TOKENS","MAX_THINKING_TOKENS","MCP_TIMEOUT","MCP_TOOL_TIMEOUT","NO_PROXY","SLASH_COMMAND_TOOL_CHAR_BUDGET","USE_BUILTIN_RIPGREP","VERTEX_REGION_CLAUDE_3_5_HAIKU","VERTEX_REGION_CLAUDE_3_7_SONNET","VERTEX_REGION_CLAUDE_4_0_OPUS","VERTEX_REGION_CLAUDE_4_0_SONNET","VERTEX_REGION_CLAUDE_4_1_OPUS"]),dr=["Bash","Read","Write","Edit","Glob","Grep"],ur=["mcp__playwright-test"],pr=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],fr=e=>{if("EPIPE"!==e.code)throw e},hr=async e=>{process.stdout.on("error",fr),process.stderr.on("error",fr);const t=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",t);const o=await En({autoLogin:"chat"===e.mode||"init"===e.mode}),s=(e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken)(o),i="oauth"===o.type?o.auth.context.orgId:void 0,c=R.default.resolve(process.cwd()),u=R.default.join(c,".env"),p=A.default.existsSync(u)&&A.default.statSync(u).isFile()?d.parse(A.default.readFileSync(u,"utf8")):{},f="chat"!==e.mode&&"init"!==e.mode,m="chat"===e.mode||"init"===e.mode?new Dn:void 0,g="chat"===e.mode?e.getHelpText:void 0,_={log:[],promptDisplay:"chat"===e.mode?"Ask Stably to build tests for you":"init"===e.mode?"Setting up Playwright and Stably SDK":"fix"===e.mode?"Fixing broken tests":(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim()||"Creating tests from PR/branch changes",status:"running"};let y,E=f,w=!1;const v={current:e=>{}},T={current:async()=>{}},{addTool:S,addToolResult:C,appendText:x,appendUserMessage:P,cleanup:L,setExiting:O,setStatus:B,showPermissionPrompt:N}=await(async(e,t)=>{const{Box:n,Static:r,Text:o,render:s,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=()=>I.jsx(o,{inverse:!0,children:" "}),d=(({Box:e,Text:t,useInput:n},r,o)=>function({onChoice:s,prompt:i}){const[a,c]=b.useState(0),[l,d]=b.useState(!1),[u,p]=b.useState(""),f=[{label:"Yes, allow this once",value:"allow"},{label:"Yes, always allow for this session",value:"always"},{label:"No, tell AI what to do differently",value:"deny_with_message"}];n((e,t)=>{if(l)return t.return?void s("deny_with_message",u||"User denied this action"):t.escape?(d(!1),void p("")):t.backspace||t.delete?void p(e=>e.slice(0,-1)):void(t.ctrl||t.meta||p(t=>`${t}${e}`));if(t.upArrow)return void c(e=>e>0?e-1:f.length-1);if(t.downArrow)return void c(e=>e<f.length-1?e+1:0);if(t.return){const e=f[a];return"deny_with_message"===e.value?void d(!0):void s(e.value)}const n=parseInt(e,10);if(n>=1&&n<=f.length){const e=f[n-1];if("deny_with_message"===e.value)return void d(!0);s(e.value)}},{isActive:o});const h=Xn(i.toolName),m=Qn(i.toolName,i.input);return I.jsxs(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[I.jsx(t,{bold:!0,color:"yellow",children:"Permission Required"}),I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"magenta",children:h}),null!=m&&I.jsxs(t,{color:"gray",children:[" ",m]})]}),null!=i.decisionReason&&I.jsx(e,{marginTop:1,children:I.jsxs(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),l?I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),I.jsxs(t,{children:[I.jsx(t,{color:"yellow",children:">"})," ",u,I.jsx(r,{})]})]}):I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,n)=>I.jsx(t,{children:I.jsxs(t,{color:n===a?"cyan":void 0,children:[n===a?"❯":" "," ",n+1,". ",e.label]})},e.value))]})]})})({Box:n,Text:o,useInput:i},l,a),u=(({Cursor:e,inkComponents:{Box:t,Static:n,Text:r,useInput:o},isRawModeSupported:s,PermissionPrompt:i,Spinner:a})=>{const c=e=>"tool"===e.kind?I.jsxs(r,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?I.jsx(r,{color:"gray",children:e.content},e.id):"user"===e.kind?I.jsxs(r,{color:"cyan",children:["You: ",e.content]},e.id):I.jsx(r,{children:e.content},e.id),l="vscode"===process.env.TERM_PROGRAM,d=(e,t)=>{if(t<=0)return 0;let n=t-1;for(;n>0&&/\s/.test(e[n]);)n--;for(;n>0&&!/\s/.test(e[n-1]);)n--;return n};return function({onExit:u,onPermissionChoice:p,onSend:f,showSpinnerImmediately:h,state:m}){const[g,_]=b.useState(""),[y,E]=b.useState(0),w=b.useRef(!1),v=b.useRef(void 0),[T,R]=b.useState(!1),S=b.useRef(0),C=m.log.at(-1),x="text"===C?.kind&&"running"===m.status,A=l?0:x?m.log.length-1:m.log.length;b.useEffect(()=>{m.log.length<S.current&&(S.current=0),A>S.current&&(S.current=A)},[m.log.length,A]);const U=m.log.slice(0,S.current),P=m.log.slice(S.current),L=!!m.permissionPrompt,O=b.useCallback(()=>{w.current?(v.current&&clearTimeout(v.current),u?.(),process.exit(0)):(w.current=!0,R(!0),v.current=setTimeout(()=>{w.current=!1,R(!1)},2e3))},[u]);o((e,t)=>{t.ctrl&&"c"===e&&O()},{isActive:s}),b.useEffect(()=>{if(L||!f)return;const e=e=>{const t=e.toString();"[1;5H"!==t&&"[1;5~"!==t?"[1;5F"!==t&&"[4;5~"!==t?"[H"!==t&&"[1~"!==t&&"OH"!==t&&"[7~"!==t?"[F"!==t&&"[4~"!==t&&"OF"!==t&&"[8~"!==t||E(e=>((e,t)=>{const n=e.indexOf("\n",t);return-1===n?e.length:n})(g,e)):E(e=>((e,t)=>{if(t<=0)return 0;const n=e.lastIndexOf("\n",t-1);return-1===n?0:n+1})(g,e)):E(g.length):E(0)};return process.stdin.on("data",e),()=>{process.stdin.off("data",e)}},[L,f,g]),o((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){const e=g.trim();return e&&f?.(e),_(""),void E(0)}if(t.ctrl&&"w"===e||t.ctrl&&t.backspace){const e=d(g,y);return _(t=>t.slice(0,e)+t.slice(y)),void E(e)}!t.backspace&&!t.delete||t.ctrl?t.ctrl&&t.leftArrow||t.meta&&"b"===e?E(d(g,y)):t.ctrl&&t.rightArrow||t.meta&&"f"===e?E(((e,t)=>{if(t>=e.length)return e.length;let n=t;for(;n<e.length&&!/\s/.test(e[n]);)n++;for(;n<e.length&&/\s/.test(e[n]);)n++;return n})(g,y)):t.leftArrow?E(e=>Math.max(0,e-1)):t.rightArrow?E(e=>Math.min(g.length,e+1)):t.ctrl&&"a"===e?E(0):t.ctrl&&"e"===e?E(g.length):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||(_(t=>t.slice(0,y)+e+t.slice(y)),E(t=>t+e.length)):y>0&&(_(e=>e.slice(0,y-1)+e.slice(y)),E(e=>e-1))}},{isActive:s&&!!f&&!L});const B=b.useMemo(()=>"running"===m.status?I.jsx(a,{label:"Working"}):"success"!==m.status?I.jsx(r,{color:"red",children:"✖ Failed"}):void 0,[m.status]),N=!(h||!f||"running"!==m.status||0!==m.log.length||m.resultText||m.errorText),D="running"===m.status&&!N||m.log.length>0||m.resultText||m.errorText||"running"!==m.status;return I.jsxs(t,{flexDirection:"column",children:[I.jsx(n,{items:["header"],children:()=>I.jsxs(t,{flexDirection:"column",flexShrink:0,children:[I.jsx(r,{color:"cyan",bold:!0,children:"Stably Agent"}),I.jsx(t,{flexDirection:"column",marginTop:1,children:I.jsx(r,{color:"gray",children:m.promptDisplay})})]},"header")}),U.length>0&&I.jsx(n,{items:U,children:e=>c(e)}),P.length>0&&I.jsx(t,{flexDirection:"column",children:P.map(e=>c(e))}),"error"===m.status&&m.errorText&&I.jsx(t,{marginTop:1,children:I.jsx(r,{color:"red",children:m.errorText})}),"success"===m.status&&m.resultText&&I.jsx(t,{marginTop:1,children:I.jsx(r,{children:m.resultText})}),D&&I.jsx(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:B}),null!=m.permissionPrompt&&null!=p&&I.jsx(i,{onChoice:p,prompt:m.permissionPrompt}),null!=f&&null==m.permissionPrompt&&!m.isExiting&&I.jsxs(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[I.jsx(r,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),I.jsxs(r,{children:[I.jsx(r,{color:"yellow",children:">"})," ",g.slice(0,y),I.jsx(e,{}),g.slice(y)]})]}),T&&I.jsx(t,{marginTop:1,children:I.jsx(r,{color:"yellow",children:"Press Ctrl+C again to exit"})})]})}})({Cursor:l,inkComponents:{Box:n,Static:r,Text:o,useInput:i},isRawModeSupported:a,PermissionPrompt:d,Spinner:({label:e})=>{const[t,n]=b.useState(0);return b.useEffect(()=>{const e=setInterval(()=>n(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),I.jsxs(o,{color:"yellow",children:[c[t]," ",e]})}});let p=e;const f={current:(e,t)=>{}},h=s(I.jsx(u,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}),{exitOnCtrlC:!1}),m=()=>{p={...p},h.rerender(I.jsx(u,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}))},g=({text:e})=>{e&&(p.log=[...p.log,{content:e,id:p.log.length,kind:"user"}],m())};return{addTool:({rawName:e,toolInput:t})=>{const n=Xn(e),r=Qn(e,t),o=r?`${n} (${r})`:n;p.log=[...p.log,{content:o,id:p.log.length,kind:"tool"}],m()},addToolResult:({message:e})=>{p.log=[...p.log,{content:e,id:p.log.length,kind:"tool_result"}],m()},appendText:({text:e})=>{if(!e)return;const t=p.log.at(-1),n=t&&"text"===t.kind?e:e.replace(/^\s*\n+/,"");t&&"text"===t.kind?p.log=[...p.log.slice(0,-1),{...t,content:`${t.content}${n}`}]:p.log=[...p.log,{content:n,id:p.log.length,kind:"text"}],m()},appendUserMessage:g,cleanup:async()=>{const e=h.waitUntilExit();h.unmount(),await e},setExiting:()=>{p.isExiting=!0,m()},setStatus:({error:e,result:t,status:n})=>{p.errorText=e,p.resultText=t,p.status=n,m()},showPermissionPrompt:e=>new Promise(t=>{f.current=(n,r)=>{if(p.permissionPrompt=void 0,m(),"allow"===n)t({behavior:"allow",updatedInput:e.input});else if("always"===n)t({behavior:"allow",updatedInput:e.input,updatedPermissions:e.suggestions});else{const e=r??"User denied this action";g({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},p.permissionPrompt={...e,resolve:t},m()})}})(_,"chat"===e.mode||"init"===e.mode?{onExit:()=>{T.current()},onSend:e=>v.current(e),showSpinnerImmediately:"init"===e.mode}:void 0);let D=_.status;const j=({error:e,result:t,status:n})=>{D=n,B({error:e,result:t,status:n})};let k;v.current=e=>{if("/help"===e.trim()){E&&m&&(w=!0,y?.interrupt?.(),m.allowNextTurn(),E=!1),"running"===D&&j({status:"success"}),P({text:e});const t=g?.();return void x({text:t??"Help is not available in this session."})}m&&(E&&(w=!0,y?.interrupt?.(),m.allowNextTurn(),E=!1),j({status:"running"}),P({text:e}),m.pushText(e),E=!0)};const $=[];let M;const H=await(async()=>{if("single"===e.mode){const r=await async function(e,t){const r=n.resolve(e);if(t){const e=n.resolve(r,t);return Wn(e,"output-flag"),{path:e,source:"output-flag"}}const o=Fn(r);if(o){const e=await async function(e){try{const t=(await h.readFile(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(o);if(e){const t=n.resolve(n.dirname(o),e);if(zn(t))return Wn(t,"playwright.config.ts"),{path:t,source:"playwright.config.ts"}}}for(const e of Yn){const t=n.join(r,e);if(zn(t))return Wn(t,"auto-detected"),{path:t,source:"auto-detected"}}return Wn(r,"cwd-fallback"),{path:r,source:"cwd-fallback"}}(c,e.outputDir);return M=r.path,t=e.prompt,`${(Array.isArray(t)?t.join(" "):t).trim()||"Create tests based on the changes in the current PR or branch. Use the Pull Request Context or Git Branch Context section of the system prompt to understand what code was changed, then create appropriate tests for the new or modified functionality. After generating the tests, run them locally (e.g. `pnpm playwright test` or the repo's Playwright test command) and iterate until the new tests pass."}\n\n[Output directory: ${M}]`}var t;if("fix"===e.mode)try{const{context:t,autohealReportUrl:n}=await(async({authHeader:e,orgId:t,runId:n})=>{const r=await(o={auth:e,client:Ft(),headers:wn(t),path:{runId:n}},(o.client??Nt).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...o}));var o;if(404===r.response.status)throw new Error(`Run ID "${n}" was not found.`);if(401===r.response.status)throw new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===r.response.status)throw new Error(r.error?.error??"Failed to fetch autoheal context (422).");if(!r.error){const e=vn.safeParse(r.data);if(e.success)return{context:e.data.context,autohealReportUrl:e.data.autohealReportUrl};throw new Error("Autoheal context response missing or invalid context.")}throw new Error("Failed to fetch autoheal context")})({authHeader:s,orgId:i,runId:e.runId});return k=n,t}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";j({error:t,status:"error"}),await L(),process.exit(1)}return"init"===e.mode?"Please analyze this project and set up Playwright with the Stably SDK. Check for existing configurations and install the necessary dependencies.":""})(),G=await async function(e){const t=R.default.resolve(e),n=R.default.join(t,"tests"),r=R.default.join(n,"helpers"),o=R.default.join(n,"assets"),s=function(e){const t=R.default.resolve(e);if(a.existsSync(t))for(const e of jn){const n=R.default.join(t,`playwright.config${e}`);if(a.existsSync(n))return n}}(t)??R.default.join(t,"playwright.config.ts"),i=R.default.basename(s),c=R.default.join(n,"seed.spec.ts"),[l,d,u,p,f,h]=await Promise.all([Mn({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),Mn({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:n}),Mn({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:r}),Mn({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:o}),$n({defaultContent:"File does not exist or could not be read",fileName:i,filePath:s}),$n({defaultContent:"File does not exist or could not be read",fileName:"seed.spec.ts",filePath:c})]);return{absolutePath:t,directories:{assets:p,helpers:u,root:l,tests:d},files:{playwrightConfig:f,playwrightConfigFilename:i,seedSpec:h}}}(c),F=await(async({allowedEnvVars:e,mode:t,workspaceInfo:n,authHeader:o})=>{const s=Ft(),i=function(e){try{const t=r.execSync("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}(n.absolutePath),a=await(c={client:s,auth:o,body:{mode:t,workspaceInfo:n,allowedEnvVars:e,gitContext:i}},(c.client??Nt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...c,headers:{"Content-Type":"application/json",...c.headers}}));var c;if(401===a.response.status)throw await rn(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===a.response.status)throw await rn(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(a.error)throw new Error(`Failed to fetch system prompt: ${JSON.stringify(a.error)}`);return a.data.systemPrompt})({allowedEnvVars:Object.keys(p),mode:e.mode,workspaceInfo:G,authHeader:s}),Y={...p,...process.env},z=Object.fromEntries(Object.entries(Y).filter(([e])=>!lr.has(e))),W=await async function({auth:e,client:t,source:n,metadata:r,duration:o}){try{const i=await(s={auth:e,client:t,body:{source:n,metadata:r??{},duration:o}},(s.client??Nt).post({security:[{scheme:"bearer",type:"http"}],url:"/v1/proxy/api-key",...s,headers:{"Content-Type":"application/json",...s.headers}})),a=i.response;if(i.error){const e="object"==typeof i.error&&"error"in i.error?i.error.error:"Unknown error";return{error:cr(e,a)}}return i.data?{key:i.data.key}:{error:cr("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:cr(t)}}var s}({auth:s,client:Ft(),source:"cli"}),K=W?.key;K||(j({error:W?.error?.message?`Unable to make AI calls: ${W.error.message}`:"Unable to make AI calls. Check if you are authenticated.",status:"error"}),await L(),process.exit(1));const V=await In(),q=V?Object.fromEntries(Object.entries(bn(V)).filter(e=>null!=e[1])):void 0,J="init"===e.mode,X="fix"===e.mode,Q="chat"===e.mode,Z=X?ht.createLocal({workingDir:c}):void 0;Z&&await Z.captureSnapshot();const ee=J?pr:[...dr,...X?["mcp__auto-heal-report"]:[]],te=J?pr:ur,ne=J?{"session-control":ir({onComplete:()=>{j({status:"success"}),O(),m?.finish(),process.exit(0)}})}:X&&Z?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:q},"auto-heal-report":sr({authHeader:s,diffTracker:Z,orgId:i,runId:e.runId})}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:q}},re="single"===e.mode,oe=J?[]:[{hooks:[async e=>{const t=Sn(e);if(!t)return{decision:"approve"};let n=!1;const r=t.map(e=>Tn(e)?e.text.length<=4e4?e:(n=!0,{...e,text:`${e.text.slice(0,4e4)}...[truncated to 40000 characters]`}):e);return n?{decision:"approve",hookSpecificOutput:{hookEventName:"PostToolUse",updatedMCPToolOutput:r}}:{decision:"approve"}}],matcher:"mcp__playwright-test__.*"},{matcher:"mcp__playwright-test__test_run",hooks:[Ln({onResult:e=>C({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[On({onResult:e=>C({message:e})})]},...re?[{matcher:"Write",hooks:[Nn({onFileCreated:e=>$.push(e)})]}]:[]],se=J?[]:[{matcher:"mcp__playwright-test__browser_type",hooks:[Pn({envVars:p})]}],ie={...z};K&&(ie.ANTHROPIC_API_KEY=K,ie.ANTHROPIC_BASE_URL=Ht),y=l.query({options:{tools:ee,allowedTools:te,canUseTool:async(e,t,{suggestions:n,decisionReason:r})=>Q||J?N({decisionReason:r,input:t,suggestions:n,toolName:e}):{behavior:"allow",updatedInput:t},cwd:c,env:ie,hooks:{PostToolUse:oe,PreToolUse:se},includePartialMessages:!0,mcpServers:ne,model:process.env.STABLY_AGENT_MODEL??"claude-opus-4-5-20251101",permissionMode:"default",systemPrompt:F},prompt:m??H}),"init"===e.mode&&m&&m.pushText(H),T.current=async()=>{O();try{await(y?.interrupt?.())}catch{}m?.finish(),L()};try{for await(const e of y){if("stream_event"===e.type){const{event:t}=e;if("content_block_delta"===t?.type){const{delta:e}=t;"text_delta"===e?.type&&e.text&&x({text:e.text})}"message_stop"===t?.type&&m&&m.allowNextTurn();continue}if("assistant"===e.type){const{content:t}=e.message??{};if(Array.isArray(t))for(const e of t)if("tool_use"===e?.type){if(e.name.startsWith("mcp__session-control__"))continue;S({rawName:e.name,toolInput:e.input})}continue}if("result"!==e.type);else{if(f){if("success"===e.subtype){if(re&&$.length>0){U.default.green("Created files:");for(const e of $)U.default.green(`- ${e}`)}const e=k?U.default.cyan(`📊 View Autoheal Report:\n ${U.default.cyan(U.default.bold(U.default.underline(k)))}`):void 0;j({status:"success",result:e})}else w||(j({error:"Run failed.",status:"error"}),process.exitCode=1);w=!1;break}"success"!==e.subtype?w||(j({error:"Run failed.",status:"error"}),process.exitCode=1):j({status:"success"}),E=!1,w=!1,m?.allowNextTurn()}}}catch(e){w||(j({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1)}finally{E=!1,w=!1,process.off("uncaughtException",t),m?.finish(),await(Z?.cleanup()),await L()}};function mr(e=process.cwd()){let t=n.resolve(e);for(;;){const e=gr(t);if(e){const r={...e.dependencies,...e.devDependencies},o="@playwright/test"in r?"@playwright/test":"playwright"in r?"playwright":void 0;if(o){const e=_r(t);let r=!1,s=t;for(;;){const e=n.join(s,"node_modules"),t=n.join(e,o);if(a.existsSync(t)){r=!0;break}const i=n.dirname(s);if(i===s)break;s=i}return{inNodeModules:r,installed:!0,packageManager:e,packageName:o}}}const r=n.dirname(t);if(r===t)return{inNodeModules:!1,installed:!1,packageManager:void 0};t=r}}function gr(e){const t=n.join(e,"package.json");let r;try{r=a.readFileSync(t,"utf-8")}catch{return}try{return JSON.parse(r)}catch{return}}function _r(e){const t=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];let r=e;for(;;){for(const[e,o]of t)if(a.existsSync(n.join(r,o)))return e;const e=n.dirname(r);if(e===r)return;r=e}}function yr(e){if("npm"===e)return["npx","playwright"];if("pnpm"===e)return["pnpm","exec","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}var Er=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}];function br(e){const[t,...n]=yr(e),r=[t,...n.slice(0,-1)].join(" ");return(t,n)=>{let o=t.toString();for(const e of Er)o=o.replaceAll(`${r} playwright ${e.name}`,`${r} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===e){const e=o.split("\n");return e.length>0&&e[0].includes("/.bin/playwright")&&e.shift(),void n.write(e.join("\n"))}n.write(o)}}function Ir(e=""){process.stdout.write(`${e}\n`)}function wr(...e){process.stderr.write(`${e.join(" ")}\n`)}var vr="stably",Tr=`https://registry.npmjs.org/${vr}/latest`,Rr=_.z.object({version:_.z.string()});function Sr(e){const t=e.match(/^(\d+)\.(\d+)\.(\d+)/);return t?{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10)}:null}var Cr=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);-1!==Cr&&process.argv[Cr+1]&&(process.chdir(process.argv[Cr+1]),process.argv.splice(Cr,2));var xr=new e.Command;xr.name("stably").description("AI-assisted Playwright testing CLI").version(jt),xr.enablePositionalOptions(),xr.showHelpAfterError(),xr.exitOverride();var Ar=[];xr.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{Ar.push(e)}});var Ur=()=>{const e=xr.helpInformation().trimEnd();return e?`${e}\n`:""},Pr=(e,t)=>{let n=e;for(const e of t){const t=n.commands.find(t=>t.name()===e||t.aliases().includes(e));if(!t)return;n=t}return n},Lr=()=>{process.stdout.write(Ur())};xr.command("help").description("Show help for a command or subcommand").argument("[command...]","Command path to show help for (e.g. create test)").action(e=>{if(!e||0===e.length)return void Lr();const t=Pr(xr,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),Lr(),void(process.exitCode=1);var n;n=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(n))}),xr.action(()=>hr({mode:"chat",getHelpText:Ur})),xr.command("login").description("Authenticate with Stably in your browser").action(hn),xr.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=mn();e&&(m.log.warn(`Environment variables ${U.default.cyan("STABLY_API_KEY")} and ${U.default.cyan("STABLY_PROJECT_ID")} are set.`),m.log.warn("They will continue to be used for authentication even after logout."),m.log.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await tn();if(!t)return void m.outro(e?U.default.yellow("No stored OAuth login found to clear."):U.default.yellow("You are not logged in."));const n=m.spinner();n.start("Logging out..."),await(async e=>{try{await fetch(`${$t}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await rn(),await an(),n.stop(U.default.green("✓ Logged out")),m.outro(U.default.green("You have been logged out successfully."))}),xr.command("whoami").description("Show auth status and current project").action(async()=>{m.log.info(`${U.default.bold("CLI Version:")} ${U.default.cyan(jt)}`);const e=mn();if(e){m.log.info(U.default.dim("Authentication: Environment variables")),m.log.info(` ${U.default.bold("API Key:")} ${U.default.cyan(e.apiKey.slice(0,8))}...`),m.log.info(` ${U.default.bold("Project ID:")} ${U.default.cyan(e.projectId)}`);const t=await tn();if(t){let e;try{e=Vt(t.accessToken).email}catch{e=void 0}m.log.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&m.log.info(` ${U.default.bold("OAuth Email:")} ${U.default.cyan(e)}`),m.log.info(` ${U.default.bold("Tip:")} Unset env vars to use OAuth`)}return void m.outro(U.default.green("Authenticated via environment variables"))}const t=await tn();if(!t)return void m.outro(U.default.yellow("Not logged in. Run `stably login` to authenticate."));let n;try{n=Vt(t.accessToken).email}catch{n=void 0}const r=await sn();if(!r)return m.log.info(U.default.dim("Authentication: OAuth (not linked to a project)")),n&&m.log.info(` ${U.default.bold("Email:")} ${U.default.cyan(n)}`),void m.outro(U.default.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const o=await(async()=>on(process.cwd()))(),s=o?R.default.dirname(o):process.cwd(),i=R.default.relative(process.cwd(),s)||".";m.log.info(U.default.dim("Authentication: OAuth")),n&&m.log.info(` ${U.default.bold("Email:")} ${U.default.cyan(n)}`),m.log.info(` ${U.default.bold("Organization:")} ${U.default.cyan(r.orgName)}`),m.log.info(` ${U.default.bold("Project:")} ${U.default.cyan(r.projectName)}`),m.log.info(` ${U.default.bold("Linked at:")} ${U.default.dim(i)}`),m.outro(U.default.green("Authenticated"))}),xr.command("tunnel",{hidden:!0}).description("Expose a local server with a secure tunnel URL").option("-p, --port <number>","Local port to expose","3000").action(async e=>{m.intro(`Starting development server for port ${e.port}...`);const t=await En(),n="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),r=m.spinner();r.start("Starting development server...");const o=await v.startTunnel(`http://localhost:${e.port}`,{subdomain:n});r.stop(`Your local environment is available at: ${U.default.underline(U.default.cyan(o.url))}`)}),xr.command("create").description("Generate a Playwright test from a prompt (or from current PR/branch if no prompt given)").argument("[prompt...]","Prompt describing the test to generate (optional - uses PR/diff context if omitted)").option("-o, --output <dir>","Output directory for generated test files").action((e,t)=>{const n=e.length>0&&"test"===e[0]?e.slice(1):e;return hr({mode:"single",prompt:n,outputDir:t.output})}).command("test",{hidden:!0}).description("Generate a Playwright test from a prompt (deprecated: use `stably create <prompt>` directly)").argument("<prompt...>","Prompt describing the test to generate").option("-o, --output <dir>","Output directory for generated test files").action((e,t)=>hr({mode:"single",prompt:e,outputDir:t.output})),xr.command("fix").description("Fix failing Playwright tests using debug context").argument("[runId]","Run ID for the failing test suite (defaults to CI's unique runId if available)").action(e=>{const t=(e??function(){if(process.env.CI_BUILD_ID)return process.env.CI_BUILD_ID;const e=(({env:e=process.env,cwd:t=process.cwd()}={})=>{for(const n of Object.keys(ft))if(ft[n].detect({env:e,cwd:t}))return{isCi:!0,...ft[n].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(n={env:e,cwd:t},{commit:Me(n),branch:He(n)})};var n})();if(!e.isCi)return;const t=function(e){switch(e){case"github":return process.env.GITHUB_RUN_ATTEMPT;case"azure-devops":return process.env.SYSTEM_JOBATTEMPT;case"bitbucket":return process.env.BITBUCKET_STEP_RUN_NUMBER;default:return}}(e.service),n=[e.service,"slug"in e?e.slug:void 0,"build"in e?String(e.build):void 0,"job"in e?String(e.job):void 0,t&&String(t)].filter(Boolean);return n.length>0?n.join("-"):void 0}())?.replace(/\//g,"_");return t||(process.stderr.write("Run ID is required. Provide <runId>.\n"),process.exit(1)),hr({mode:"fix",runId:t})}),xr.command("init").description("Initialize Playwright and Stably SDK in your project").action(()=>hr({mode:"init"})),xr.command("upgrade").description("Upgrade Stably CLI to the latest version").option("-c, --check","Only check for updates without upgrading").action(e=>async function(e){const{check:t=!1}=e;let n;Ir(U.default.cyan("Checking for updates...\n"));try{n=await async function(){const e=await async function(){const e=new AbortController,t=setTimeout(()=>e.abort(),1e4);try{const t=await fetch(Tr,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return Rr.parse(await t.json()).version}finally{clearTimeout(t)}}(),t=jt,n=function(e,t){const n=Sr(e),r=Sr(t);return!(!n||!r)&&(r.major>n.major||!(r.major<n.major)&&(r.minor>n.minor||!(r.minor<n.minor)&&r.patch>n.patch))}(t,e);return{current:t,latest:e,isOutdated:n}}()}catch(e){return wr(U.default.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(Ir(`Current version: ${U.default.yellow(n.current)}`),Ir(`Latest version: ${U.default.green(n.latest)}`),Ir(),!n.isOutdated)return void Ir(U.default.green("✓ You are already on the latest version!"));if(Ir(U.default.yellow(`⚠ A new version is available: ${n.current} → ${n.latest}`)),Ir(),t)return Ir(U.default.dim("Exiting with code 1 to indicate update available (useful for CI).")),void(process.exitCode=1);const o=function(){const e=process.argv[1]||"";if(e.includes("_npx")||e.includes(".npm/_cacache"))return"npx";try{const t=r.execSync("npm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-npm"}catch{}if(e.includes("node_modules/stably"))return"global-npm";try{const t=r.execSync("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=r.execSync("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=r.execSync("yarn config get globalFolder",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-berry"}catch{}return"unknown"}(),s=function(e){switch(e){case"global-npm":case"global-yarn-berry":case"unknown":return{command:"npm",args:["install","-g",`${vr}@latest`],description:`npm install -g ${vr}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${vr}@latest`],description:`pnpm add -g ${vr}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${vr}@latest`],description:`yarn global add ${vr}@latest`};case"npx":return{command:"npx",args:[`${vr}@latest`],description:`npx ${vr}@latest (always uses latest)`}}}(o);if("npx"===o)return Ir(U.default.dim("You are running via npx, which always fetches the latest version.")),void Ir(U.default.dim(`Simply run: ${U.default.white("npx stably")} to use the latest version.`));"unknown"===o?(Ir(U.default.yellow("Could not detect installation method. Falling back to npm.")),Ir()):"global-yarn-berry"===o&&(Ir(U.default.yellow("Yarn Berry does not support global packages. Falling back to npm.")),Ir()),Ir(`Upgrade command: ${U.default.cyan(s.description)}`),Ir(),Ir(U.default.cyan("Upgrading...")),Ir();try{await(i=s.command,a=s.args,new Promise((e,t)=>{const n=r.spawn(i,a,{stdio:"inherit",shell:"win32"===process.platform});n.on("close",n=>{0===n?e():t(new Error(`Upgrade command exited with code ${n}`))}),n.on("error",e=>{t(e)})})),Ir(),Ir(U.default.green("✓ Upgrade complete!")),Ir(U.default.dim(`Run ${U.default.white("stably --version")} to verify.`))}catch(e){wr(U.default.red("Upgrade failed:"),e instanceof Error?e.message:e),Ir(),Ir(U.default.dim("You can try manually running:")),Ir(U.default.cyan(` ${s.description}`)),process.exitCode=1}var i,a}(e)),Er.forEach(({args:e,description:t,name:o})=>{xr.command(o).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>async function({overrideArgs:e,subcommand:t}){const o=process.argv,s=o.findIndex((e,n)=>n>1&&e===t),i=-1===s?[]:o.slice(s+1),c="--"===i[0],l=c?i.slice(1):i;if(!c&&("--help"===l[0]||"-h"===l[0]))return async function({subcommand:e}){const t=Er.find(t=>t.name===e),n=e=>process.stdout.write(`${e}\n`);n(`stably ${e} - ${t?.description??""}`),n(""),"test"===e&&(n('IMPORTANT: Always use "stably" commands instead of "playwright" directly.'),n(""),n("Stably commands:"),n(" stably test [file] Run tests (auto-enables tracing and analytics)"),n(" stably fix [file] Auto-fix failing tests using AI"),n(" stably create <url> Generate new tests from a URL using AI"),n(""),n("Why use Stably?"),n(' - "stably fix" automatically repairs broken tests'),n(' - "stably test" enables --trace=on and test analytics'),n(' - "stably create" generates tests from prompt'),n(""));const o=mr();if(!o.installed||!o.inNodeModules)return void n('No Playwright project found in this directory or its parents.\nMake sure you\'re in a directory within your Playwright project, or run "stably init" to create a new playwright directory.');const{packageManager:s}=o;if(!s)return void n("Could not determine package manager.");n("Playwright options:"),n("");const[i,...a]=yr(s),c=br(s);return new Promise(t=>{const n=r.spawn(i,[...a,e,"--help"],{stdio:["inherit","pipe","pipe"],env:{...process.env,...process.env.CI?{}:{FORCE_COLOR:"1"}}});n.stdout?.on("data",e=>{c(e,process.stdout)}),n.stderr?.on("data",e=>{c(e,process.stderr)}),n.on("close",()=>{t()})})}({subcommand:t});const d=e??[],u=new Set(d.map(e=>{const[t]=e.split("=");return t})),p=[];for(let e=0;e<l.length;e++){const t=l[e],[n]=t.split("=");u.has(n)?!t.includes("=")&&e+1<l.length&&!l[e+1].startsWith("-")&&e++:p.push(t)}const f=[t,...d,...p],h="test"===t?await In():void 0,m="test"===t?function({forwardedArgs:e,hasCredentials:t}){if(!t)return console.warn("[33m⚠️ Stably credentials not found. Test results will not be reported to Stably.[0m"),console.warn("[33m To enable reporting, either:[0m"),console.warn("[33m • Run `npx stably login` to authenticate[0m"),void console.warn("[33m • Set STABLY_API_KEY and STABLY_PROJECT_ID environment variables[0m\n");const o=process.cwd(),s=e=>{const t=function(e){let t=n.resolve(e);for(;;){if([n.join(t,"node_modules","@stablyai","playwright-test"),n.join(t,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>a.existsSync(e)))return!0;const e=n.dirname(t);if(e===t)return!1;t=e}}(e);return t||(console.warn("[33m⚠️ @stablyai/playwright-test is not installed. Stably reporter will not be injected.[0m"),console.warn("[33m Install it with: npm install @stablyai/playwright-test[0m"),console.warn("[33m Reference: https://docs.stably.ai/getting-started/sdk-setup-guide[0m\n")),t},i=(e,t)=>{try{return function({baseConfigPath:e,projectDir:t}){const o=function(e){try{const t=r.execSync("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return"module"===JSON.parse(t.trim())}catch{return!1}}(t),s=o?"mts":"ts",i=n.dirname(n.resolve(e)),c=n.basename(e),l=n.join(i,`.stably-playwright-wrapper.config.${s}`),d=`\n// Auto-generated wrapper config by Stably CLI\n// This file injects the Stably reporter and ensures trace is enabled\nimport baseConfig from './${c}';\nimport { defineConfig, stablyReporter } from '@stablyai/playwright-test';\n\n// Inline type definitions to avoid import failures when @stablyai/playwright-test is not installed\ntype StablyNotificationConfig = {\n email?: { to: string[]; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' | null } | null;\n slack?: { channelName: string; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' } | null;\n};\n\ntype ProjectNotificationConfig = {\n projectName: string;\n notifications: StablyNotificationConfig;\n};\n\n// Extract notification configs from projects that have stably.notifications defined\n// This runs at config-load time before Playwright strips custom properties\nconst extractNotificationConfigs = (): ProjectNotificationConfig[] | undefined => {\n const projects = baseConfig.projects;\n if (!projects || !Array.isArray(projects)) return undefined;\n\n const configs = projects\n .map((p: { name?: string; stably?: { notifications?: StablyNotificationConfig } }) => {\n const notifications = p.stably?.notifications;\n return notifications ? { projectName: p.name ?? '', notifications } : undefined;\n })\n .filter((config): config is ProjectNotificationConfig => config != null);\n\n return configs.length > 0 ? configs : undefined;\n};\n\nconst hasStablyReporter = (reporters: unknown): boolean => {\n if (!Array.isArray(reporters)) return false;\n return reporters.some((reporter) => {\n if (typeof reporter === 'string') {\n return reporter.includes('stablyai') || reporter.includes('stably');\n }\n if (Array.isArray(reporter) && typeof reporter[0] === 'string') {\n return reporter[0].includes('stablyai') || reporter[0].includes('stably');\n }\n return false;\n });\n};\n\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\n\n // If already has stably reporter, don't add another\n if (hasStablyReporter(existingReporters)) {\n return existingReporters;\n }\n\n // Create the stably reporter entry with notification configs\n const stablyReporterEntry = stablyReporter({\n apiKey: process.env.STABLY_API_KEY,\n projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n });\n\n // Merge with existing reporters\n if (!existingReporters) {\n return [stablyReporterEntry];\n }\n\n if (Array.isArray(existingReporters)) {\n return [...existingReporters, stablyReporterEntry];\n }\n\n // Single reporter as string - convert to tuple format [name, {}]\n return [[existingReporters, {}], stablyReporterEntry];\n};\n\nexport default defineConfig({\n ...baseConfig,\n use: {\n ...baseConfig.use,\n trace: 'on',\n },\n reporter: buildReporterList(),\n});\n`.trim();return a.existsSync(i)||a.mkdirSync(i,{recursive:!0}),a.writeFileSync(l,d,"utf-8"),function(e){const t=n.join(e,".gitignore");try{if(a.existsSync(t)){const e=a.readFileSync(t,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(Hn))return;const n=e.length>0&&!e.endsWith("\n");a.appendFileSync(t,`${n?"\n":""}${Hn}\n`)}else a.writeFileSync(t,`${Hn}\n`)}catch{}}(i),l}({baseConfigPath:e,projectDir:t})}catch{return void console.warn("[33m⚠️ Could not create Stably wrapper config. Reporter injection skipped.[0m")}};if(e.some(e=>"--config"===e||"-c"===e||e.startsWith("--config=")||e.startsWith("-c="))){const t=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==t&&e[t+1]){const r=n.resolve(o,e[t+1]),a=n.dirname(r);if(!s(a))return;const c=i(r,a);if(!c)return;return e[t+1]=c,c}const r=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==r){const t=n.resolve(o,e[r].split("=")[1]),a=n.dirname(t);if(!s(a))return;const c=i(t,a);if(!c)return;const l=e[r].startsWith("--config=")?"--config=":"-c=";return e[r]=`${l}${c}`,c}}const c=Fn(o);if(!c)return;const l=n.dirname(c);if(!s(l))return;const d=i(c,l);return d?(e.push("--config",d),d):void 0}({forwardedArgs:f,hasCredentials:null!=h}):void 0;!function(e,t={}){const n=mr();n.installed||(console.error('Playwright is not installed. Please run "stably init" to install it.'),process.exit(1)),n.inNodeModules||(console.error("Playwright is present in your project, but not in node_modules. Please install your dependencies before proceeding."),process.exit(1));const{packageManager:o}=n;o||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[s,...i]=yr(o),a=bn(t.env),c=r.spawn(s,[...i,...e],{stdio:["inherit","pipe","pipe"],env:{...a,...process.env.CI?{}:{FORCE_COLOR:"1"}}}),l=br(o);c.stdout?.on("data",e=>{l(e,process.stdout)}),c.stderr?.on("data",e=>{l(e,process.stderr)});let d=!1;const u=()=>{d||(d=!0,t.onClose?.())};c.on("close",e=>{u(),process.exit(e??0)});const p=e=>{u(),c.kill(e);const t="SIGINT"===e?130:143;process.exit(t)};process.on("SIGINT",p),process.on("SIGTERM",p)}(f,{env:h,onClose:()=>{var e;(e=m)&&a.existsSync(e)&&a.rmSync(e)}})}({overrideArgs:e,subcommand:o}))});var Or=()=>{0!==Ar.length&&(process.stderr.write(Ar.join("")),Ar=[])};(async()=>{try{await xr.parseAsync(process.argv)}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e))throw Or(),e;const t="number"==typeof e.exitCode?e.exitCode:1,n=process.argv.slice(2).find(e=>!e.startsWith("-")),r=!!n&&!!Pr(xr,[n]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&n&&!r)return Ar=[],process.stderr.write(`command '${n}' not found\n`),Lr(),void(process.exitCode=t);Or(),process.exitCode=t}})();
|
|
2
|
+
"use strict";var e=require("commander"),t=require("buffer"),n=require("path"),r=require("child_process"),o=require("process"),s=require("url"),i=require("os"),a=require("fs");require("timers/promises");var c=require("util"),l=require("@anthropic-ai/claude-agent-sdk"),d=require("dotenv"),u=require("picocolors"),p=require("simple-git"),f=require("crypto"),h=require("fs/promises"),m=require("@clack/prompts"),g=require("readline/promises"),_=require("zod"),y=require("open"),E=require("http"),b=require("react"),I=require("react/jsx-runtime"),w=require("zod/v3"),v=require("@stablyhq/runner-sdk");function T(e){return e&&e.__esModule?e:{default:e}}var R=T(n),S=T(r),C=T(o),x=T(i),A=T(a),U=T(u),P=T(f),L=T(_),O=T(y),B=T(E),N=Object.create,D=Object.defineProperty,j=Object.getOwnPropertyDescriptor,k=Object.getOwnPropertyNames,$=Object.getPrototypeOf,M=Object.prototype.hasOwnProperty,H=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),G=(e,t)=>function(){return t||(0,e[k(e)[0]])((t={exports:{}}).exports,t),t.exports},F=(e,t,n)=>(n=null!=e?N($(e)):{},((e,t,n,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of k(t))M.call(e,n)||void 0===n||D(e,n,{get:()=>t[n],enumerable:!(r=j(t,n))||r.enumerable});return e})(D(n,"default",{value:e,enumerable:!0}),e)),Y=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(e,t){t.exports=o,o.sync=function(e,t){return r(n.statSync(e),e,t)};var n=H("fs");function r(e,t,n){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var n=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!n)return!0;if(-1!==(n=n.split(";")).indexOf(""))return!0;for(var r=0;r<n.length;r++){var o=n[r].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}(t,n)}function o(e,t,o){n.stat(e,function(n,s){o(n,!n&&r(s,e,t))})}}}),z=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(e,t){t.exports=r,r.sync=function(e,t){return o(n.statSync(e),t)};var n=H("fs");function r(e,t,r){n.stat(e,function(e,n){r(e,!e&&o(n,t))})}function o(e,t){return e.isFile()&&function(e,t){var n=e.mode,r=e.uid,o=e.gid,s=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),i=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8);return n&parseInt("001",8)||n&c&&o===i||n&a&&r===s||n&(a|c)&&0===s}(e,t)}}}),V=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(e,t){var n;function r(e,t,o){if("function"==typeof t&&(o=t,t={}),!o){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(n,o){r(e,t||{},function(e,t){e?o(e):n(t)})})}n(e,t||{},function(e,n){e&&("EACCES"===e.code||t&&t.ignoreErrors)&&(e=null,n=!1),o(e,n)})}H("fs"),n="win32"===process.platform||global.TESTING_WINDOWS?Y():z(),t.exports=r,r.sync=function(e,t){try{return n.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||"EACCES"===e.code)return!1;throw e}}}}),K=G({"node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(e,t){var n="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,r=H("path"),o=n?";":":",s=V(),i=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),a=(e,t)=>{const r=t.colon||o,s=e.match(/\//)||n&&e.match(/\\/)?[""]:[...n?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(r)],i=n?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=n?i.split(r):[""];return n&&-1!==e.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:s,pathExt:a,pathExtExe:i}},c=(e,t,n)=>{"function"==typeof t&&(n=t,t={}),t||(t={});const{pathEnv:o,pathExt:c,pathExtExe:l}=a(e,t),d=[],u=n=>new Promise((s,a)=>{if(n===o.length)return t.all&&d.length?s(d):a(i(e));const c=o[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=r.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;s(p(f,n,0))}),p=(e,n,r)=>new Promise((o,i)=>{if(r===c.length)return o(u(n+1));const a=c[r];s(e+a,{pathExt:l},(s,i)=>{if(!s&&i){if(!t.all)return o(e+a);d.push(e+a)}return o(p(e,n,r+1))})});return n?u(0).then(e=>n(null,e),n):u(0)};t.exports=c,c.sync=(e,t)=>{t=t||{};const{pathEnv:n,pathExt:o,pathExtExe:c}=a(e,t),l=[];for(let i=0;i<n.length;i++){const a=n[i],d=/^".*"$/.test(a)?a.slice(1,-1):a,u=r.join(d,e),p=!d&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let e=0;e<o.length;e++){const n=p+o[e];try{if(s.sync(n,{pathExt:c})){if(!t.all)return n;l.push(n)}}catch(e){}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw i(e)}}}),W=G({"node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(e,t){var n=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};t.exports=n,t.exports.default=n}}),q=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){var n=H("path"),r=K(),o=W();function s(e,t){const s=e.options.env||process.env,i=process.cwd(),a=null!=e.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch(e){}let l;try{l=r.sync(e.command,{path:s[o({env:s})],pathExt:t?n.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=n.resolve(a?e.options.cwd:"",l)),l}t.exports=function(e){return s(e)||s(e,!0)}}}),J=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(e,t){var n=/([()\][%!^"`<>&|;, *?])/g;t.exports.command=function(e){return e.replace(n,"^$1")},t.exports.argument=function(e,t){return e=(e=`"${e=(e=(e=`${e}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(n,"^$1"),t&&(e=e.replace(n,"^$1")),e}}}),X=G({"node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(e,t){t.exports=/^#!(.*)/}}),Q=G({"node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(e,t){var n=X();t.exports=(e="")=>{const t=e.match(n);if(!t)return null;const[r,o]=t[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return"env"===s?o:o?`${s} ${o}`:s}}}),Z=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(e,t){var n=H("fs"),r=Q();t.exports=function(e){const t=Buffer.alloc(150);let o;try{o=n.openSync(e,"r"),n.readSync(o,t,0,150,0),n.closeSync(o)}catch(e){}return r(t.toString())}}}),ee=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(e,t){var n=H("path"),r=q(),o=J(),s=Z(),i="win32"===process.platform,a=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;t.exports=function(e,t,l){t&&!Array.isArray(t)&&(l=t,t=null);const d={command:e,args:t=t?t.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:e,args:t}};return l.shell?d:function(e){if(!i)return e;const t=function(e){e.file=r(e);const t=e.file&&s(e.file);return t?(e.args.unshift(e.file),e.command=t,r(e)):e.file}(e),l=!a.test(t);if(e.options.forceShell||l){const r=c.test(t);e.command=n.normalize(e.command),e.command=o.command(e.command),e.args=e.args.map(e=>o.argument(e,r));const s=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${s}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}(d)}}}),te=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(e,t){var n="win32"===process.platform;function r(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function o(e,t){return n&&1===e&&!t.file?r(t.original,"spawn"):null}t.exports={hookChildProcess:function(e,t){if(!n)return;const r=e.emit;e.emit=function(n,s){if("exit"===n){const n=o(s,t);if(n)return r.call(e,"error",n)}return r.apply(e,arguments)}},verifyENOENT:o,verifyENOENTSync:function(e,t){return n&&1===e&&!t.file?r(t.original,"spawnSync"):null},notFoundError:r}}}),ne=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(e,t){var n=H("child_process"),r=ee(),o=te();function s(e,t,s){const i=r(e,t,s),a=n.spawn(i.command,i.args,i.options);return o.hookChildProcess(a,i),a}t.exports=s,t.exports.spawn=s,t.exports.sync=function(e,t,s){const i=r(e,t,s),a=n.spawnSync(i.command,i.args,i.options);return a.error=a.error||o.verifyENOENTSync(a.status,i),a},t.exports._parse=r,t.exports._enoent=o}}),re=G({"node_modules/.pnpm/merge-stream@2.0.0/node_modules/merge-stream/index.js"(e,t){var{PassThrough:n}=H("stream");t.exports=function(){var e=[],t=new n({objectMode:!0});return t.setMaxListeners(0),t.add=r,t.isEmpty=function(){return 0==e.length},t.on("unpipe",o),Array.prototype.slice.call(arguments).forEach(r),t;function r(n){return Array.isArray(n)?(n.forEach(r),this):(e.push(n),n.once("end",o.bind(null,n)),n.once("error",t.emit.bind(t,"error")),n.pipe(t,{end:!1}),this)}function o(n){!(e=e.filter(function(e){return e!==n})).length&&t.readable&&t.end()}}}}),oe=G({"node_modules/.pnpm/java-properties@1.0.2/node_modules/java-properties/dist-node/index.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.of=e.PropertiesFile=void 0;var t,n=(t=H("fs"))&&t.__esModule?t:{default:t},r=class{constructor(...e){this.objs={},e.length&&this.of.apply(this,e)}makeKeys(e){if(e&&0!==e.indexOf("#")){let t=["=",":"].map(t=>e.indexOf(t)).filter(e=>e>-1),n=Math.min(...t),r=e.substring(0,n).trim(),o=e.substring(n+1).trim();if(this.objs.hasOwnProperty(r))if(Array.isArray(this.objs[r]))this.objs[r].push(o);else{let e=this.objs[r];this.objs[r]=[e,o]}else{const e=o.replace(/"/g,'\\"').replace(/\\:/g,":").replace(/\\=/g,"=");this.objs[r]=unescape(JSON.parse('"'+e+'"'))}}}addFile(e){let t=n.default.readFileSync(e,"utf-8").split(/\r?\n/),r=this;for(let e=0;e<t.length;e++){let n=t[e];for(;"\\"===n.substring(n.length-1);)n=n.slice(0,-1),n+=t[e+1].trim(),e++;r.makeKeys(n)}}of(...e){for(let t=0;t<e.length;t++)this.addFile(e[t])}get(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){let t=[];for(let n=0;n<this.objs[e].length;n++)t[n]=this.interpolate(this.objs[e][n]);return t}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getLast(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){var n=this.objs[e].length;return this.interpolate(this.objs[e][n-1])}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getFirst(e,t){return this.objs.hasOwnProperty(e)?Array.isArray(this.objs[e])?this.interpolate(this.objs[e][0]):void 0===this.objs[e]?"":this.interpolate(this.objs[e]):t}getInt(e,t){let n=this.getLast(e);return n?parseInt(n,10):t}getFloat(e,t){let n=this.getLast(e);return n?parseFloat(n):t}getBoolean(e,t){let n=this.getLast(e);return n?!/^(false|0)$/i.test(r=n)&&!!r:t||!1;var r}set(e,t){this.objs[e]=t}interpolate(e){let t=this;return e.replace(/\\\\/g,"\\").replace(/\$\{([A-Za-z0-9\.\-\_]*)\}/g,function(e){return t.getLast(e.substring(2,e.length-1))})}getKeys(){let e=[];for(let t in this.objs)e.push(t);return e}getMatchingKeys(e){let t=[];for(let n in this.objs)-1!==n.search(e)&&t.push(n);return t}reset(){this.objs={}}};e.PropertiesFile=r,e.of=function(...e){let t=new r;return t.of.apply(t,e),t}}}),se={detect:({env:e})=>Boolean(e.APPVEYOR),configuration({env:e}){const t=e.APPVEYOR_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Appveyor",service:"appveyor",commit:e.APPVEYOR_REPO_COMMIT,tag:e.APPVEYOR_REPO_TAG_NAME,build:e.APPVEYOR_BUILD_NUMBER,buildUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/${e.APPVEYOR_BUILD_VERSION}`,branch:e.APPVEYOR_REPO_BRANCH,job:e.APPVEYOR_JOB_NUMBER,jobUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/job/${e.APPVEYOR_JOB_ID}`,pr:t,isPr:n,prBranch:e.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH,slug:e.APPVEYOR_REPO_NAME,root:e.APPVEYOR_BUILD_FOLDER}}};function ie(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function ae(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var ce={detect:({env:e})=>Boolean(e.BUILD_BUILDURI),configuration({env:e}){const t=e.SYSTEM_PULLREQUEST_PULLREQUESTID,n=Boolean(t);return{name:"Azure Pipelines",service:"azurePipelines",commit:e.BUILD_SOURCEVERSION,build:e.BUILD_BUILDNUMBER,branch:ae(n?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:n,prBranch:ae(n?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},le={detect:({env:e})=>Boolean(e.bamboo_agentId),configuration:({env:e})=>({name:"Bamboo",service:"bamboo",commit:e.bamboo_planRepository_1_revision,build:e.bamboo_buildNumber,buildUrl:e.bamboo_buildResultsUrl,branch:e.bamboo_planRepository_1_branchName,job:e.bamboo_buildKey,root:e.bamboo_build_working_directory})},de={detect:({env:e})=>Boolean(e.BITBUCKET_BUILD_NUMBER),configuration:({env:e})=>({name:"Bitbucket Pipelines",service:"bitbucket",commit:e.BITBUCKET_COMMIT,tag:e.BITBUCKET_TAG,build:e.BITBUCKET_BUILD_NUMBER,buildUrl:`https://bitbucket.org/${e.BITBUCKET_REPO_FULL_NAME}/addon/pipelines/home#!/results/${e.BITBUCKET_BUILD_NUMBER}`,branch:e.BITBUCKET_BRANCH,slug:e.BITBUCKET_REPO_FULL_NAME,root:e.BITBUCKET_CLONE_DIR})},ue={detect:({env:e})=>Boolean(e.BITRISE_IO),configuration({env:e}){const t="false"===e.BITRISE_PULL_REQUEST?void 0:e.BITRISE_PULL_REQUEST,n=Boolean(t);return{name:"Bitrise",service:"bitrise",commit:e.BITRISE_GIT_COMMIT,tag:e.BITRISE_GIT_TAG,build:e.BITRISE_BUILD_NUMBER,buildUrl:e.BITRISE_BUILD_URL,branch:n?e.BITRISEIO_GIT_BRANCH_DEST:e.BITRISE_GIT_BRANCH,pr:t,isPr:n,prBranch:n?e.BITRISE_GIT_BRANCH:void 0,slug:e.BITRISE_APP_SLUG}}},pe={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=ie(e.BUDDY_EXECUTION_PULL_REQUEST_ID),n=Boolean(t);return{name:"Buddy",service:"buddy",commit:e.BUDDY_EXECUTION_REVISION,tag:e.BUDDY_EXECUTION_TAG,build:e.BUDDY_EXECUTION_ID,buildUrl:e.BUDDY_EXECUTION_URL,branch:n?e.BUDDY_EXECUTION_PULL_REQUEST_HEAD_BRANCH:e.BUDDY_EXECUTION_BRANCH,pr:t,isPr:n,slug:e.BUDDY_REPO_SLUG}}},fe=F(ne());function he(e={}){const{env:t=process.env,platform:n=process.platform}=e;return"win32"!==n?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"}var me=(e,t)=>({name:`SIGRT${t+1}`,number:ge+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),ge=34,_e=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],ye=()=>{const e=(()=>{const e=64-ge+1;return Array.from({length:e},me)})();return[..._e,...e].map(Ee)},Ee=({name:e,number:t,description:n,action:r,forced:o=!1,standard:s})=>{const{signals:{[e]:a}}=i.constants,c=void 0!==a;return{name:e,number:c?a:t,description:n,supported:c,action:r,forced:o,standard:s}},be=({name:e,number:t,description:n,supported:r,action:o,forced:s,standard:i})=>[e,{name:e,number:t,description:n,supported:r,action:o,forced:s,standard:i}],Ie=(()=>{const e=ye();return Object.fromEntries(e.map(be))})();(()=>{const e=ye(),t=Array.from({length:65},(t,n)=>((e,t)=>{const n=((e,t)=>{const n=t.find(({name:t})=>i.constants.signals[t]===e);return void 0!==n?n:t.find(t=>t.number===e)})(e,t);if(void 0===n)return{};const{name:r,description:o,supported:s,action:a,forced:c,standard:l}=n;return{[e]:{name:r,number:e,description:o,supported:s,action:a,forced:c,standard:l}}})(n,e));Object.assign({},...t)})();var we=({stdout:e,stderr:t,all:n,error:r,signal:o,exitCode:s,command:i,escapedCommand:a,timedOut:c,isCanceled:l,killed:d,parsed:{options:{timeout:u,cwd:p=C.default.cwd()}}})=>{s=null===s?void 0:s;const f=void 0===(o=null===o?void 0:o)?void 0:Ie[o].description,h=(({timedOut:e,timeout:t,errorCode:n,signal:r,signalDescription:o,exitCode:s,isCanceled:i})=>e?`timed out after ${t} milliseconds`:void 0!==n?`failed with ${n}`:void 0!==r?`was killed with ${r} (${o})`:void 0!==s?`failed with exit code ${s}`:"failed")({timedOut:c,timeout:u,errorCode:r&&r.code,signal:o,signalDescription:f,exitCode:s,isCanceled:l}),m=`Command ${h}: ${i}`,g="[object Error]"===Object.prototype.toString.call(r),_=g?`${m}\n${r.message}`:m,y=[_,t,e].filter(Boolean).join("\n");return g?(r.originalMessage=r.message,r.message=y):r=new Error(y),r.shortMessage=_,r.command=i,r.escapedCommand=a,r.exitCode=s,r.signal=o,r.signalDescription=f,r.stdout=e,r.stderr=t,r.cwd=p,void 0!==n&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=Boolean(c),r.isCanceled=l,r.killed=d&&!c,r},ve=["stdin","stdout","stderr"],Te=[];Te.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&Te.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&Te.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Re=e=>!!e&&"object"==typeof e&&"function"==typeof e.removeListener&&"function"==typeof e.emit&&"function"==typeof e.reallyExit&&"function"==typeof e.listeners&&"function"==typeof e.kill&&"number"==typeof e.pid&&"function"==typeof e.on,Se=Symbol.for("signal-exit emitter"),Ce=globalThis,xe=Object.defineProperty.bind(Object),Ae=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ce[Se])return Ce[Se];xe(Ce,Se,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const n=this.listeners[e],r=n.indexOf(t);-1!==r&&(0===r&&1===n.length?n.length=0:n.splice(r,1))}emit(e,t,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let r=!1;for(const o of this.listeners[e])r=!0===o(t,n)||r;return"exit"===e&&(r=this.emit("afterExit",t,n)||r),r}},Ue=class{},Pe=globalThis.process;Re(Pe)?new class extends Ue{#e="win32"===Pe.platform?"SIGINT":"SIGHUP";#t=new Ae;#n;#r;#o;#s={};#i=!1;constructor(e){super(),this.#n=e,this.#s={};for(const t of Te)this.#s[t]=()=>{const n=this.#n.listeners(t);let{count:r}=this.#t;const o=e;if("object"==typeof o.__signal_exit_emitter__&&"number"==typeof o.__signal_exit_emitter__.count&&(r+=o.__signal_exit_emitter__.count),n.length===r){this.unload();const n=this.#t.emit("exit",null,t),r="SIGHUP"===t?this.#e:t;n||e.kill(e.pid,r)}};this.#o=e.reallyExit,this.#r=e.emit}onExit(e,t){if(!Re(this.#n))return()=>{};!1===this.#i&&this.load();const n=t?.alwaysLast?"afterExit":"exit";return this.#t.on(n,e),()=>{this.#t.removeListener(n,e),0===this.#t.listeners.exit.length&&0===this.#t.listeners.afterExit.length&&this.unload()}}load(){if(!this.#i){this.#i=!0,this.#t.count+=1;for(const e of Te)try{const t=this.#s[e];t&&this.#n.on(e,t)}catch(e){}this.#n.emit=(e,...t)=>this.#a(e,...t),this.#n.reallyExit=e=>this.#c(e)}}unload(){this.#i&&(this.#i=!1,Te.forEach(e=>{const t=this.#s[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#n.removeListener(e,t)}catch(e){}}),this.#n.emit=this.#r,this.#n.reallyExit=this.#o,this.#t.count-=1)}#c(e){return Re(this.#n)?(this.#n.exitCode=e||0,this.#t.emit("exit",this.#n.exitCode,null),this.#o.call(this.#n,this.#n.exitCode)):0}#a(e,...t){const n=this.#r;if("exit"===e&&Re(this.#n)){"number"==typeof t[0]&&(this.#n.exitCode=t[0]);const r=n.call(this.#n,e,...t);return this.#t.emit("exit",this.#n.exitCode,null),r}return n.call(this.#n,e,...t)}}(Pe):new class extends Ue{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,F(re());var Le=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Le,e)]);var Oe=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Be=/^[\w.-]+$/,Ne=c.debuglog("execa").enabled,De=(e,t)=>String(e).padStart(t,"0"),je=(e,t,n={})=>{const r=fe.default._parse(e,t,n);return e=r.command,t=r.args,(n={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(n=r.options).cwd||C.default.cwd(),execPath:C.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ne,...n}).env=(({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:o})=>{const i=t?{...C.default.env,...e}:e;return n?(({env:e=C.default.env,...t}={})=>{const n=he({env:e={...e}});return t.path=e[n],e[n]=(({cwd:e=C.default.cwd(),path:t=C.default.env[he()],preferLocal:n=!0,execPath:r=C.default.execPath,addExecPath:o=!0}={})=>{const i=e instanceof URL?s.fileURLToPath(e):e,a=R.default.resolve(i),c=[];return n&&((e,t)=>{let n;for(;n!==t;)e.push(R.default.join(t,"node_modules/.bin")),n=t,t=R.default.resolve(t,"..")})(c,a),o&&((e,t,n)=>{const r=t instanceof URL?s.fileURLToPath(t):t;e.push(R.default.resolve(n,r,".."))})(c,r,a),[...c,t].join(R.default.delimiter)})(t),e})({env:i,cwd:r,execPath:o}):i})(n),n.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return ve.map(t=>e[t]);if((e=>ve.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${ve.map(e=>`\`${e}\``).join(", ")}`);if("string"==typeof t)return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const n=Math.max(t.length,ve.length);return Array.from({length:n},(e,n)=>t[n])})(n),"win32"===C.default.platform&&"cmd"===R.default.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},ke=(e,n,r)=>"string"==typeof n||t.Buffer.isBuffer(n)?e.stripFinalNewline?function(e){const t="string"==typeof e?"\n":"\n".charCodeAt(),n="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===n&&(e=e.slice(0,-1)),e}(n):n:void 0===r?void 0:"";function $e(e,t,n){const r=je(e,t,n),o=((e,t)=>Oe(e,t).join(" "))(e,t),s=((e,t)=>Oe(e,t).map(e=>(e=>"string"!=typeof e||Be.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&C.default.stderr.write(`[${(()=>{const e=new Date;return`${De(e.getHours(),2)}:${De(e.getMinutes(),2)}:${De(e.getSeconds(),2)}.${De(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(s,r.options);const i=(e=>{const t=(({input:e,inputFile:t})=>"string"!=typeof t?e:((e=>{if(void 0!==e)throw new TypeError("The `input` and `inputFile` options cannot be both set.")})(e),a.readFileSync(t)))(e);if(null!==(n=t)&&"object"==typeof n&&"function"==typeof n.pipe)throw new TypeError("The `input` option cannot be a stream in sync mode");var n;return t})(r.options);let c;try{c=S.default.spawnSync(r.file,r.args,{...r.options,input:i})}catch(e){throw we({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1})}const l=ke(r.options,c.stdout,c.error),d=ke(r.options,c.stderr,c.error);if(c.error||0!==c.status||null!==c.signal){const e=we({stdout:l,stderr:d,error:c.error,signal:c.signal,exitCode:c.status,command:o,escapedCommand:s,parsed:r,timedOut:c.error&&"ETIMEDOUT"===c.error.code,isCanceled:!1,killed:null!==c.signal});if(!r.options.reject)return e;throw e}return{command:o,escapedCommand:s,exitCode:0,stdout:l,stderr:d,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function Me(e){try{return $e("git",["rev-parse","HEAD"],e).stdout}catch{return}}function He(e){try{const t=$e("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=$e("git",["show","-s","--pretty=%d","HEAD"],e).stdout.replace(/^\(|\)$/g,"").split(", ").find(e=>e.startsWith("origin/"));return t?t.match(/^origin\/(?<branch>.+)/)[1]:void 0}return t}catch{return}}var Ge=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Fe=/^\/(.*)\.git$/;function Ye(e){if(e){if(e.match(Ge))return e.replace(Ge,"$1");try{return new URL(e).pathname.replace(Fe,"$1")}catch{return}}}var ze={detect:({env:e})=>Boolean(e.BUILDKITE),configuration({env:e}){const t="false"===e.BUILDKITE_PULL_REQUEST?void 0:e.BUILDKITE_PULL_REQUEST,n=Boolean(t);return{name:"Buildkite",service:"buildkite",build:e.BUILDKITE_BUILD_NUMBER,buildUrl:e.BUILDKITE_BUILD_URL,commit:e.BUILDKITE_COMMIT,tag:e.BUILDKITE_TAG,branch:n?e.BUILDKITE_PULL_REQUEST_BASE_BRANCH:e.BUILDKITE_BRANCH,slug:Ye(e.BUILDKITE_REPO),pr:t,isPr:n,prBranch:n?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},Ve={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||ie(e.CIRCLE_PULL_REQUEST||e.CI_PULL_REQUEST),n=Boolean(t);return{name:"CircleCI",service:"circleci",build:e.CIRCLE_BUILD_NUM,buildUrl:e.CIRCLE_BUILD_URL,job:`${e.CIRCLE_BUILD_NUM}.${e.CIRCLE_NODE_INDEX}`,commit:e.CIRCLE_SHA1,tag:e.CIRCLE_TAG,branch:n?void 0:e.CIRCLE_BRANCH,pr:t,isPr:n,prBranch:n?e.CIRCLE_BRANCH:void 0,slug:`${e.CIRCLE_PROJECT_USERNAME}/${e.CIRCLE_PROJECT_REPONAME}`}}},Ke="https://cirrus-ci.com",We={detect:({env:e})=>Boolean(e.CIRRUS_CI),configuration({env:e}){const t=e.CIRRUS_PR,n=Boolean(t);return{name:"Cirrus CI",service:"cirrus",commit:e.CIRRUS_CHANGE_IN_REPO,tag:e.CIRRUS_TAG,build:e.CIRRUS_BUILD_ID,buildUrl:`${Ke}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${Ke}/task/${e.CIRRUS_TASK_ID}`,branch:n?e.CIRRUS_BASE_BRANCH:e.CIRRUS_BRANCH,pr:t,isPr:n,prBranch:n?e.CIRRUS_BRANCH:void 0,slug:e.CIRRUS_REPO_FULL_NAME,root:e.CIRRUS_WORKING_DIR}}},qe={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:Me({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:He({env:e,cwd:t}),buildUrl:`https://console.aws.amazon.com/codebuild/home?region=${e.AWS_REGION}#/builds/${e.CODEBUILD_BUILD_ID}/view/new`,root:e.PWD})},Je={detect:({env:e})=>Boolean(e.CF_BUILD_ID),configuration({env:e}){const t=e.CF_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Codefresh",service:"codefresh",commit:e.CF_REVISION,build:e.CF_BUILD_ID,buildUrl:e.CF_BUILD_URL,branch:n?e.CF_PULL_REQUEST_TARGET:e.CF_BRANCH,pr:t,isPr:n,prBranch:n?e.CF_BRANCH:void 0,slug:`${e.CF_REPO_OWNER}/${e.CF_REPO_NAME}`,root:e.CF_VOLUME_PATH}}},Xe={detect:({env:e})=>Boolean(e.DRONE),configuration({env:e}){const t="pull_request"===e.DRONE_BUILD_EVENT;return{name:"Drone",service:"drone",commit:e.DRONE_COMMIT_SHA,tag:e.DRONE_TAG,build:e.DRONE_BUILD_NUMBER,buildUrl:e.DRONE_BUILD_LINK,branch:t?e.DRONE_TARGET_BRANCH:e.DRONE_BRANCH,job:e.DRONE_JOB_NUMBER,jobUrl:e.DRONE_BUILD_LINK,pr:e.DRONE_PULL_REQUEST,isPr:t,prBranch:t?e.DRONE_SOURCE_BRANCH:void 0,slug:`${e.DRONE_REPO_OWNER}/${e.DRONE_REPO_NAME}`,root:e.DRONE_WORKSPACE}}},Qe=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(a.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?ae(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},Ze={detect:({env:e})=>Boolean(e.GITHUB_ACTIONS),configuration({env:e,cwd:t}){const n="pull_request"===e.GITHUB_EVENT_NAME||"pull_request_target"===e.GITHUB_EVENT_NAME,r=ae("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(a.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;return t&&t.pull_request?t.pull_request.number:void 0})(e)}/merge`:e.GITHUB_REF);return{name:"GitHub Actions",service:"github",commit:e.GITHUB_SHA,build:e.GITHUB_RUN_ID,buildUrl:`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`,isPr:n,branch:r,prBranch:n?r:void 0,slug:e.GITHUB_REPOSITORY,root:e.GITHUB_WORKSPACE,...n?Qe({env:e}):void 0}}},et={detect:({env:e})=>Boolean(e.GITLAB_CI),configuration({env:e}){const t=e.CI_MERGE_REQUEST_ID,n=Boolean(t);return{name:"GitLab CI/CD",service:"gitlab",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_ID,buildUrl:`${e.CI_PROJECT_URL}/pipelines/${e.CI_PIPELINE_ID}`,job:e.CI_JOB_ID,jobUrl:`${e.CI_PROJECT_URL}/-/jobs/${e.CI_JOB_ID}`,branch:n?e.CI_MERGE_REQUEST_TARGET_BRANCH_NAME:e.CI_COMMIT_REF_NAME,pr:t,isPr:n,prBranch:e.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,slug:e.CI_PROJECT_PATH,root:e.CI_PROJECT_DIR}}},tt={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const n=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,r=Boolean(n),o=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||Me({env:e,cwd:t}),branch:r?e.ghprbTargetBranch||e.gitlabTargetBranch:o,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,root:e.WORKSPACE,pr:n,isPr:r,prBranch:r?e.ghprbSourceBranch||e.gitlabSourceBranch||o:void 0}}},nt={detect:({env:e})=>"true"===e.NETLIFY,configuration({env:e}){const t="true"===e.PULL_REQUEST;return{name:"Netlify",service:"netlify",commit:e.COMMIT_REF,build:e.DEPLOY_ID,buildUrl:`https://app.netlify.com/sites/${e.SITE_NAME}/deploys/${e.DEPLOY_ID}`,branch:t?void 0:e.HEAD,pr:e.REVIEW_ID,isPr:t,prBranch:t?e.HEAD:void 0,slug:e.REPOSITORY_URL.match(/[^/:]+\/[^/]+?$/)[0],root:e.PWD}}},rt={detect:({env:e})=>Boolean(e.DISTELLI_APPNAME),configuration:({env:e})=>({name:"Puppet",service:"puppet",build:e.DISTELLI_BUILDNUM,buildUrl:e.DISTELLI_RELEASE,commit:e.DISTELLI_RELREVISION,branch:e.DISTELLI_RELBRANCH,root:e.DISTELLI_INSTALLHOME})},ot={detect:({env:e})=>Boolean(e.SAILCI),configuration({env:e}){const t=e.SAIL_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Sail CI",service:"sail",commit:e.SAIL_COMMIT_SHA,branch:n?void 0:e.SAIL_COMMIT_BRANCH,pr:t,isPr:n,slug:`${e.SAIL_REPO_OWNER}/${e.SAIL_REPO_NAME}`,root:e.SAIL_CLONE_DIR}}},st={detect:({env:e})=>Boolean(e.SCREWDRIVER),configuration({env:e}){const t=e.SD_PULL_REQUEST,n=Boolean(t);return{name:"Screwdriver.cd",service:"screwdriver",branch:n?e.PR_BASE_BRANCH_NAME:e.GIT_BRANCH,prBranch:n?e.PR_BRANCH_NAME:void 0,commit:e.SD_BUILD_SHA,build:e.SD_BUILD_ID,buildUrl:e.SD_UI_BUILD_URL,job:e.SD_JOB_ID,pr:t,isPr:n,slug:e.SD_PIPELINE_NAME,root:e.SD_ROOT_DIR}}},it={detect:({env:e})=>Boolean(e.SCRUTINIZER),configuration({env:e}){const t=e.SCRUTINIZER_PR_NUMBER,n=Boolean(t);return{name:"Scrutinizer",service:"scrutinizer",commit:e.SCRUTINIZER_SHA1,build:e.SCRUTINIZER_INSPECTION_UUID,branch:e.SCRUTINIZER_BRANCH,pr:t,isPr:n,prBranch:e.SCRUTINIZER_PR_SOURCE_BRANCH}}},at={detect:({env:e})=>Boolean(e.SEMAPHORE),configuration({env:e,cwd:t}){const n=e.SEMAPHORE_GIT_PR_NUMBER||e.PULL_REQUEST_NUMBER,r=Boolean(n);return{name:"Semaphore",service:"semaphore",commit:e.SEMAPHORE_GIT_SHA||Me({env:e,cwd:t}),tag:e.SEMAPHORE_GIT_TAG_NAME,build:e.SEMAPHORE_JOB_ID||e.SEMAPHORE_BUILD_NUMBER,branch:e.SEMAPHORE_GIT_BRANCH||(r?void 0:e.BRANCH_NAME),pr:n,isPr:r,prBranch:e.SEMAPHORE_GIT_PR_BRANCH||(r?e.BRANCH_NAME:void 0),slug:e.SEMAPHORE_GIT_REPO_SLUG||e.SEMAPHORE_REPO_SLUG,root:e.SEMAPHORE_GIT_DIR||e.SEMAPHORE_PROJECT_DIR}}},ct={detect:({env:e})=>Boolean(e.SHIPPABLE),configuration({env:e}){const t="true"===e.IS_PULL_REQUEST?e.PULL_REQUEST:void 0,n=Boolean(t);return{name:"Shippable",service:"shippable",commit:e.COMMIT,tag:e.GIT_TAG_NAME,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,branch:n?e.BASE_BRANCH:e.BRANCH,job:e.JOB_NUMBER,pr:t,isPr:n,prBranch:n?e.HEAD_BRANCH:void 0,slug:e.SHIPPABLE_REPO_SLUG,root:e.SHIPPABLE_BUILD_DIR}}},lt=F(oe()),dt={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},ut=e=>{try{return lt.default.of(e)}catch{return}},pt=({env:e,cwd:t})=>{const n=e.TEAMCITY_BUILD_PROPERTIES_FILE?ut(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,r=n?n.get("teamcity.configuration.properties.file"):void 0,o=r?ut(r):r;return Object.fromEntries(Object.keys(dt).map(r=>[r,(n?n.get(dt[r]):void 0)||(o?o.get(dt[r]):void 0)||("branch"===r?He({env:e,cwd:t}):void 0)]))},ft={appveyor:se,azurePipelines:ce,bamboo:le,bitbucket:de,bitrise:ue,buddy:pe,buildkite:ze,circleci:Ve,cirrus:We,cloudflarePages:{detect:({env:e})=>"1"===e.CF_PAGES,configuration:({env:e})=>({name:"Cloudflare Pages",service:"cloudflarePages",commit:e.CF_PAGES_COMMIT_SHA,branch:e.CF_PAGES_BRANCH,root:e.PWD})},codebuild:qe,codefresh:Je,codeship:{detect:({env:e})=>e.CI_NAME&&"codeship"===e.CI_NAME,configuration:({env:e})=>({name:"Codeship",service:"codeship",build:e.CI_BUILD_NUMBER,buildUrl:e.CI_BUILD_URL,commit:e.CI_COMMIT_ID,branch:e.CI_BRANCH,slug:e.CI_REPO_NAME})},drone:Xe,github:Ze,gitlab:et,jenkins:tt,netlify:nt,puppet:rt,sail:ot,screwdriver:st,scrutinizer:it,semaphore:at,shippable:ct,teamcity:{detect:({env:e})=>Boolean(e.TEAMCITY_VERSION),configuration:({env:e,cwd:t})=>({name:"TeamCity",service:"teamcity",commit:e.BUILD_VCS_NUMBER,build:e.BUILD_NUMBER,slug:e.TEAMCITY_BUILDCONF_NAME,...pt({env:e,cwd:t})})},travis:{detect:({env:e})=>Boolean(e.TRAVIS),configuration({env:e}){const t="false"===e.TRAVIS_PULL_REQUEST?void 0:e.TRAVIS_PULL_REQUEST,n=Boolean(t);return{name:"Travis CI",service:"travis",commit:e.TRAVIS_COMMIT,tag:e.TRAVIS_TAG,build:e.TRAVIS_BUILD_NUMBER,buildUrl:e.TRAVIS_BUILD_WEB_URL,branch:e.TRAVIS_BRANCH,job:e.TRAVIS_JOB_NUMBER,jobUrl:e.TRAVIS_JOB_WEB_URL,pr:t,isPr:n,prBranch:e.TRAVIS_PULL_REQUEST_BRANCH,slug:e.TRAVIS_REPO_SLUG,root:e.TRAVIS_BUILD_DIR}}},vela:{detect:({env:e})=>Boolean(e.VELA),configuration({env:e}){const t="pull_request"===e.VELA_BUILD_EVENT;return{name:"Vela",service:"vela",branch:t?e.VELA_PULL_REQUEST_TARGET:e.VELA_BUILD_BRANCH,commit:e.VELA_BUILD_COMMIT,tag:e.VELA_BUILD_TAG,build:e.VELA_BUILD_NUMBER,buildUrl:e.VELA_BUILD_LINK,job:void 0,jobUrl:void 0,isPr:t,pr:e.VELA_BUILD_PULL_REQUEST,prBranch:e.VELA_PULL_REQUEST_SOURCE,slug:e.VELA_REPO_FULL_NAME,root:e.VELA_BUILD_WORKSPACE}}},vercel:{detect:({env:e})=>Boolean(e.VERCEL)||Boolean(e.NOW_GITHUB_DEPLOYMENT),configuration({env:e}){const t="Vercel",n="vercel";return e.VERCEL?{name:t,service:n,commit:e.VERCEL_GIT_COMMIT_SHA,branch:e.VERCEL_GIT_COMMIT_REF,slug:`${e.VERCEL_GIT_REPO_OWNER}/${e.VERCEL_GIT_REPO_SLUG}`}:{name:t,service:n,commit:e.NOW_GITHUB_COMMIT_SHA,branch:e.NOW_GITHUB_COMMIT_REF,slug:`${e.NOW_GITHUB_ORG}/${e.NOW_GITHUB_REPO}`}}},wercker:{detect:({env:e})=>Boolean(e.WERCKER_MAIN_PIPELINE_STARTED),configuration:({env:e})=>({name:"Wercker",service:"wercker",commit:e.WERCKER_GIT_COMMIT,build:e.WERCKER_MAIN_PIPELINE_STARTED,buildUrl:e.WERCKER_RUN_URL,branch:e.WERCKER_GIT_BRANCH,slug:`${e.WERCKER_GIT_OWNER}/${e.WERCKER_GIT_REPOSITORY}`,root:e.WERCKER_ROOT})},woodpecker:{detect:({env:e})=>e.CI&&"woodpecker"===e.CI,configuration({env:e}){const t="pull_request"===e.CI_PIPELINE_EVENT;return{name:"Woodpecker CI",service:"woodpecker",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_NUMBER,buildUrl:e.CI_PIPELINE_URL,branch:t?e.CI_COMMIT_TARGET_BRANCH:e.CI_COMMIT_BRANCH,job:e.CI_STEP_NUMBER,jobUrl:e.CI_STEP_URL,pr:e.CI_COMMIT_PULL_REQUEST,isPr:t,prBranch:t?e.CI_COMMIT_SOURCE_BRANCH:void 0,slug:`${e.CI_REPO_OWNER}/${e.CI_REPO_NAME}`,root:e.CI_WORKSPACE}}},jetbrainsSpace:{detect:({env:e})=>Boolean(e.JB_SPACE_EXECUTION_NUMBER),configuration({env:e}){const t=e.JB_SPACE_PROJECT_KEY,n=e.JB_SPACE_GIT_REPOSITORY_NAME;return{name:"JetBrains Space",service:"jetbrainsSpace",commit:e.JB_SPACE_GIT_REVISION,build:e.JB_SPACE_EXECUTION_NUMBER,branch:ae(e.JB_SPACE_GIT_BRANCH),slug:t&&n?`${t.toLowerCase()}/${n}`:void 0}}}},ht=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=p.simpleGit({baseDir:e.workingDir,maxConcurrentProcesses:1})}static createLocal({workingDir:t}){return new e({mode:"local",workingDir:t})}static createCloud({workingDir:t,baseBranch:n}){return new e({mode:"cloud",workingDir:t,baseBranch:n})}async captureSnapshot(){if("local"!==this.config.mode)return;this.snapshotIndexPath=n.join(i.tmpdir(),`git-diff-tracker-${f.randomUUID()}.index`),await this.git.env("GIT_INDEX_FILE",this.snapshotIndexPath).add(["-A"]);const e=await this.git.env("GIT_INDEX_FILE",this.snapshotIndexPath).raw(["write-tree"]);this.snapshotTreeHash=e.trim()}async computeDiff(){return"local"===this.config.mode?this.computeLocalDiff():this.computeCloudDiff()}async computeLocalDiff(){if(!this.snapshotTreeHash)throw new Error("No snapshot captured. Call captureSnapshot() first.");const e=n.join(i.tmpdir(),`git-diff-tracker-${f.randomUUID()}.index`);try{await this.git.env("GIT_INDEX_FILE",e).add(["-A"]);const t=(await this.git.env("GIT_INDEX_FILE",e).raw(["write-tree"])).trim();return await this.git.raw(["diff-tree","-p","--no-color",this.snapshotTreeHash,t])}finally{await mt(e)}}async computeCloudDiff(){if("cloud"!==this.config.mode)throw new Error("computeCloudDiff called but mode is not cloud");const{baseBranch:e}=this.config;return await this.git.revparse([`origin/${e}`]).then(()=>!0).catch(()=>!1)||await this.git.fetch(["origin",`${e}:refs/remotes/origin/${e}`,"--depth","1","--quiet"]).catch(e=>{console.error("[git-diff-tracker] Failed to fetch base branch:",e)}),await this.git.diff([`origin/${e}`])}async cleanup(){this.snapshotIndexPath&&(await mt(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function mt(e){try{await h.unlink(e)}catch{}}var gt={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},_t=({allowReserved:e,explode:t,name:n,style:r,value:o})=>{if(!t){const t=(e?o:o.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(r));switch(r){case"label":return`.${t}`;case"matrix":return`;${n}=${t}`;case"simple":return t;default:return`${n}=${t}`}}const s=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),i=o.map(t=>"label"===r||"simple"===r?e?t:encodeURIComponent(t):yt({allowReserved:e,name:n,value:t})).join(s);return"label"===r||"matrix"===r?s+i:i},yt=({allowReserved:e,name:t,value:n})=>{if(null==n)return"";if("object"==typeof n)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},Et=({allowReserved:e,explode:t,name:n,style:r,value:o,valueOnly:s})=>{if(o instanceof Date)return s?o.toISOString():`${n}=${o.toISOString()}`;if("deepObject"!==r&&!t){let t=[];Object.entries(o).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});const s=t.join(",");switch(r){case"form":return`${n}=${s}`;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return s}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),a=Object.entries(o).map(([t,o])=>yt({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:o})).join(i);return"label"===r||"matrix"===r?i+a:a},bt=/\{[^{}]+\}/g;function It(e){const t=void 0!==e.body;return t&&e.bodySerializer?"serializedBody"in e?void 0!==e.serializedBody&&""!==e.serializedBody?e.serializedBody:null:""!==e.body?e.body:null:t?e.body:void 0}var wt,vt=async(e,t)=>{const n="function"==typeof t?await t(e):t;if(n)return"bearer"===e.scheme?`Bearer ${n}`:"basic"===e.scheme?`Basic ${btoa(n)}`:n},Tt=({parameters:e={},...t}={})=>n=>{const r=[];if(n&&"object"==typeof n)for(const o in n){const s=n[o];if(null==s)continue;const i=e[o]||t;if(Array.isArray(s)){const e=_t({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&r.push(e)}else if("object"==typeof s){const e=Et({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&r.push(e)}else{const e=yt({allowReserved:i.allowReserved,name:o,value:s});e&&r.push(e)}}return r.join("&")},Rt=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),St=e=>(({baseUrl:e,path:t,query:n,querySerializer:r,url:o})=>{let s=(e??"")+(o.startsWith("/")?o:`/${o}`);t&&(s=(({path:e,url:t})=>{let n=t;const r=t.match(bt);if(r)for(const t of r){let r=!1,o=t.substring(1,t.length-1),s="simple";o.endsWith("*")&&(r=!0,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),s="label"):o.startsWith(";")&&(o=o.substring(1),s="matrix");const i=e[o];if(null==i)continue;if(Array.isArray(i)){n=n.replace(t,_t({explode:r,name:o,style:s,value:i}));continue}if("object"==typeof i){n=n.replace(t,Et({explode:r,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){n=n.replace(t,`;${yt({name:o,value:i})}`);continue}const a=encodeURIComponent("label"===s?`.${i}`:i);n=n.replace(t,a)}return n})({path:t,url:s}));let i=n?r(n):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(s+=`?${i}`),s})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:Tt(e.querySerializer),url:e.url}),Ct=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=At(e.headers,t.headers),n},xt=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},At=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?xt(n):Object.entries(n);for(const[n,r]of e)if(null===r)t.delete(n);else if(Array.isArray(r))for(const e of r)t.append(n,e);else void 0!==r&&t.set(n,"object"==typeof r?JSON.stringify(r):r)}return t},Ut=class{fns=[];clear(){this.fns=[]}eject(e){const t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){const t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){return"number"==typeof e?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){const n=this.getInterceptorIndex(e);return!!this.fns[n]&&(this.fns[n]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}},Pt=Tt({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Lt={"Content-Type":"application/json"},Ot=(e={})=>({...gt,headers:Lt,parseAs:"auto",querySerializer:Pt,...e}),Bt=(e={})=>{let t=Ct(Ot(),e);const n=()=>({...t}),r={error:new Ut,request:new Ut,response:new Ut},o=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:At(t.headers,e.headers),serializedBody:void 0};return n.security&&await(async({security:e,...t})=>{for(const n of e){if(Rt(t,n.name))continue;const e=await vt(n,t.auth);if(!e)continue;const r=n.name??"Authorization";switch(n.in){case"query":t.query||(t.query={}),t.query[r]=e;break;case"cookie":t.headers.append("Cookie",`${r}=${e}`);break;default:t.headers.set(r,e)}}})({...n,security:n.security}),n.requestValidator&&await n.requestValidator(n),void 0!==n.body&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),void 0!==n.body&&""!==n.serializedBody||n.headers.delete("Content-Type"),{opts:n,url:St(n)}},s=async e=>{const{opts:t,url:n}=await o(e),s={redirect:"follow",...t,body:It(t)};let i=new Request(n,s);for(const e of r.request.fns)e&&(i=await e(i,t));const a=t.fetch;let c;try{c=await a(i)}catch(e){let n=e;for(const o of r.error.fns)o&&(n=await o(e,void 0,i,t));if(n=n||{},t.throwOnError)throw n;return"data"===t.responseStyle?void 0:{error:n,request:i,response:void 0}}for(const e of r.response.fns)e&&(c=await e(c,i,t));const l={request:i,response:c};if(c.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(c.headers.get("Content-Type")):t.parseAs)??"json";if(204===c.status||"0"===c.headers.get("Content-Length")){let n;switch(e){case"arrayBuffer":case"blob":case"text":n=await c[e]();break;case"formData":n=new FormData;break;case"stream":n=c.body;break;default:n={}}return"data"===t.responseStyle?n:{data:n,...l}}let n;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":n=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),"data"===t.responseStyle?n:{data:n,...l}}const d=await c.text();let u;try{u=JSON.parse(d)}catch{}const p=u??d;let f=p;for(const e of r.error.fns)e&&(f=await e(p,c,i,t));if(f=f||{},t.throwOnError)throw f;return"data"===t.responseStyle?void 0:{error:f,...l}},i=e=>t=>s({...t,method:e}),a=e=>async t=>{const{opts:n,url:s}=await o(t);return(({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:o,sseDefaultRetryDelay:s,sseMaxRetryAttempts:i,sseMaxRetryDelay:a,sseSleepFn:c,url:l,...d})=>{let u;const p=c??(e=>new Promise(t=>setTimeout(t,e))),f=async function*(){let c=s??3e3,f=0;const h=d.signal??(new AbortController).signal;for(;!h.aborted;){f++;const s=d.headers instanceof Headers?d.headers:new Headers(d.headers);void 0!==u&&s.set("Last-Event-ID",u);try{const t={redirect:"follow",...d,body:d.serializedBody,headers:s,signal:h};let i=new Request(l,t);e&&(i=await e(l,t));const a=d.fetch??globalThis.fetch,p=await a(i);if(!p.ok)throw new Error(`SSE failed: ${p.status} ${p.statusText}`);if(!p.body)throw new Error("No body in SSE response");const f=p.body.pipeThrough(new TextDecoderStream).getReader();let m="";const g=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",g);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;m+=t;const s=m.split("\n\n");m=s.pop()??"";for(const e of s){const t=e.split("\n"),s=[];let i,a;for(const e of t)if(e.startsWith("data:"))s.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))i=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))u=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(c=t)}let l=!1;if(s.length){const e=s.join("\n");try{a=JSON.parse(e),l=!0}catch{a=e}}l&&(o&&await o(a),r&&(a=await r(a))),n?.({data:a,event:i,id:u,retry:c}),s.length&&(yield a)}}}finally{h.removeEventListener("abort",g),f.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&f>=i)break;const n=Math.min(c*2**(f-1),a??3e4);await p(n)}}}();return{stream:f}})({...n,body:n.body,headers:n.headers,method:e,onRequest:async(e,t)=>{let o=new Request(e,t);for(const e of r.request.fns)e&&(o=await e(o,n));return o},url:s})};return{buildUrl:St,connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),getConfig:n,head:i("HEAD"),interceptors:r,options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),request:s,setConfig:e=>(t=Ct(t,e),n()),sse:{connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),head:a("HEAD"),options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),trace:a("TRACE")},trace:i("TRACE")}},Nt=Bt(Ot({baseUrl:"https://api.stably.ai"})),Dt="x-stably-org-id",jt="4.3.8",kt=process.env.STABLY_API_URL||"https://api.stably.ai",$t=process.env.AUTH_URL||"https://auth.stably.ai",Mt=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",Ht=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",Gt="http://localhost:9876/auth/callback",Ft=()=>wt||(wt=Bt(Ot({baseUrl:kt,headers:{"X-STABLY-CLI-VERSION":jt,"X-STABLY-SOURCE":"cli"}}))),Yt=async(e,t)=>{const n=await(r={body:{accessToken:e,orgId:t},client:Ft()},(r.client??Nt).post({url:"/internal/v1/cli/exchange-token",...r,headers:{"Content-Type":"application/json",...r.headers}}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this organization");if(n.error)throw new Error(`Failed to exchange token: ${n.response.status}`);return n.data},zt=_.z.object({org_id:_.z.string(),org_name:_.z.string()}),Vt=_.z.object({email:_.z.string(),org_id_to_org_member_info:_.z.record(_.z.string(),zt).optional(),org_member_info:zt.optional(),user_id:_.z.string()});_.z.object({email:_.z.string(),firstName:_.z.string().optional(),lastName:_.z.string().optional(),organizations:_.z.array(_.z.object({id:_.z.string(),name:_.z.string()})),userId:_.z.string()});var Kt=e=>{const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const n=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=Buffer.from(n,"base64").toString("utf-8");return JSON.parse(r)},Wt=e=>{try{const t=Vt.parse(Kt(e)),n=t.org_id_to_org_member_info?Object.entries(t.org_id_to_org_member_info).map(([e,t])=>({id:e,name:t.org_name})):t.org_member_info?[{id:t.org_member_info.org_id,name:t.org_member_info.org_name}]:[];return{email:t.email,organizations:n,userId:t.user_id}}catch(e){throw new Error(`Failed to decode token: ${e instanceof Error?e.message:"Unknown error"}`)}},qt=R.default.join(x.default.homedir(),".stably"),Jt=R.default.join(qt,"auth.json"),Xt=".stably",Qt="project.json",Zt=L.default.object({accessToken:L.default.string(),expiresAt:L.default.number(),idToken:L.default.string().optional(),refreshToken:L.default.string()}),en=L.default.object({orgId:L.default.string(),orgName:L.default.string(),projectId:L.default.string(),projectName:L.default.string()}),tn=async()=>{try{const e=await h.readFile(Jt,"utf-8");return Zt.parse(JSON.parse(e))}catch{return}},nn=async e=>{await h.mkdir(qt,{recursive:!0}),await h.writeFile(Jt,JSON.stringify(e,null,2),{mode:384})},rn=async()=>{try{await h.unlink(Jt)}catch{}},on=async e=>{let t=e;const{root:n}=R.default.parse(t);for(;t!==n;){const e=R.default.join(t,Xt);try{return await h.access(e),e}catch{t=R.default.dirname(t)}}},sn=async()=>{try{const e=await on(process.cwd());if(!e)return;const t=R.default.join(e,Qt),n=await h.readFile(t,"utf-8");return en.parse(JSON.parse(n))}catch{return}},an=async()=>{try{const e=await on(process.cwd());e&&await h.unlink(R.default.join(e,Qt))}catch{}},cn=e=>Date.now()>=e.expiresAt-3e5,ln=async e=>{const t=new URLSearchParams({client_id:Mt,grant_type:"refresh_token",refresh_token:e}),n=await fetch(`${$t}/propelauth/oauth/token`,{body:t.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!n.ok)throw new Error(`Token refresh failed: ${n.status}`);const r=await n.json();return{accessToken:r.access_token,expiresAt:Date.now()+1e3*r.expires_in,refreshToken:r.refresh_token}},dn=e=>`\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authentication Failed Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #ef4444;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .error-box {\n background: rgba(239, 68, 68, 0.1);\n border: 1px solid rgba(239, 68, 68, 0.3);\n border-radius: 8px;\n padding: 16px;\n margin-bottom: 24px;\n }\n .error-label {\n font-size: 11px;\n font-weight: 600;\n color: #ef4444;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 8px;\n }\n .error-message {\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 13px;\n color: #fafafa;\n word-break: break-word;\n }\n .hint {\n color: #666;\n font-size: 13px;\n }\n .hint code {\n background: #111;\n border: 1px solid #333;\n border-radius: 4px;\n padding: 2px 6px;\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 12px;\n color: #888;\n }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>\n </svg>\n </div>\n <h1 class="title">Authentication Failed</h1>\n <p class="subtitle">Something went wrong during login.</p>\n <div class="error-box">\n <div class="error-label">Error</div>\n <div class="error-message">${e}</div>\n </div>\n <p class="hint">Run <code>stably login</code> to try again.</p>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n`,un=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(n)},pn=(e,t)=>{const n=new URLSearchParams({client_id:Mt,code_challenge:e,code_challenge_method:"S256",redirect_uri:Gt,response_type:"code",state:t});return`${$t}/propelauth/oauth/authorize?${n.toString()}`},fn=async e=>{const t=m.spinner();let n;t.start("Loading user info...");try{n=Wt(e.accessToken),t.stop(U.default.green(`✓ Logged in as ${U.default.cyan(n.email)}`))}catch(e){t.stop(U.default.red("✗ Failed to load user info"));const n=e instanceof Error?e.message:"Unknown error";return m.log.error(n),{success:!1}}const r=await(async e=>{if(0===e.length)return void m.log.error("You don't belong to any organizations.");if(1===e.length)return m.log.info(`Using organization: ${U.default.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return m.log.info(`Auto-selecting organization: ${U.default.cyan(e[0].name)}`),e[0];const t=await m.select({message:"Select an organization",options:e.map(e=>({label:e.name,value:e.id}))});return m.isCancel(t)?void 0:e.find(e=>e.id===t)})(n.organizations);if(!r)return m.log.warn("Organization selection cancelled."),{success:!1};let o;t.start("Getting org credentials...");try{const n=await Yt(e.accessToken,r.id);o={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(U.default.green("✓ Credentials obtained"))}catch(e){t.stop(U.default.red("✗ Failed to get org credentials"));const n=e instanceof Error?e.message:"Unknown error";return m.log.error(n),{success:!1}}const s=await(async(e,t)=>{const n=m.spinner();let r;n.start("Loading projects...");try{r=await(async({accessToken:e,orgId:t})=>{const n=await(r={auth:e,client:Ft(),path:{orgId:t}},(r.client??Nt).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/orgs/{orgId}/projects",...r}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this organization");if(n.error)throw new Error(`Failed to list projects: ${n.response.status}`);return n.data.projects})({accessToken:e,orgId:t}),n.stop(U.default.green("✓ Projects loaded"))}catch(e){n.stop(U.default.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void m.log.error(t)}if(0===r.length)return m.log.error("No projects found in this organization."),void m.log.info(`Create a project at ${U.default.underline(U.default.cyan("https://app.stably.ai"))}`);if(1===r.length)return m.log.info(`Using project: ${U.default.cyan(r[0].name)}`),r[0];if(!process.stdin.isTTY)return m.log.info(`Auto-selecting project: ${U.default.cyan(r[0].name)}`),r[0];const o=await m.select({message:"Select a project",options:r.map(e=>({label:e.name,value:e.id}))});return m.isCancel(o)?void 0:r.find(e=>e.id===o)})(o.accessToken,r.id);return s?(await(async e=>{const t=R.default.join(process.cwd(),Xt),n=R.default.join(t,Qt);await h.mkdir(t,{recursive:!0}),await h.writeFile(n,JSON.stringify(e,null,2)),await(async e=>{const t=R.default.join(e,".gitignore"),n="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await h.readFile(t,"utf-8"),r=e.split("\n").map(e=>e.trim());if(r.includes(".stably/*")&&r.includes("!.stably/docs/"))return;const o=/^# Stably CLI\n\.stably\/?$/m,s=/^\.stably\/?$/m;if(o.test(e)){const r=e.replace(o,`\n${n}\n`);await h.writeFile(t,r)}else if(s.test(e)){const r=e.replace(s,`\n${n}\n`);await h.writeFile(t,r)}else await h.appendFile(t,`\n${n}\n`)}catch{await h.writeFile(t,`${n}\n`)}})(process.cwd())})({orgId:r.id,orgName:r.name,projectId:s.id,projectName:s.name}),m.log.info(U.default.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(m.log.warn("Project selection cancelled."),{success:!1})},hn=async()=>{if(mn())return m.log.warn(`Environment variables ${U.default.cyan("STABLY_API_KEY")} and ${U.default.cyan("STABLY_PROJECT_ID")} are set.`),m.log.warn("These will be used for authentication instead of OAuth login."),m.log.warn("To use OAuth login, unset these environment variables first."),void m.outro(U.default.yellow("Login skipped - using environment variable authentication."));const e=await tn();if(e){if(!cn(e)){if(await sn())return void m.outro(U.default.yellow("You are already logged in. Run `stably logout` first to log out."));m.log.info("You are logged in but haven't selected a project yet.");const t=await fn(e);return void(t.success?(await nn(t.scopedTokens),m.outro(U.default.green("Setup complete! You can now use Stably CLI."))):m.outro(U.default.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=m.spinner();t.start("Refreshing session...");try{const n=await ln(e.refreshToken);t.stop(U.default.green("✓ Session refreshed"));const r=await sn();if(r){t.start("Getting org credentials...");try{const e=await Yt(n.accessToken,r.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:n.idToken,refreshToken:n.refreshToken};await nn(o),t.stop(U.default.green("✓ Credentials obtained")),m.outro(U.default.green("Login successful"))}catch{await nn(n),t.stop(U.default.yellow("Using full credentials")),m.outro(U.default.green("Login successful"))}}else{const e=await fn(n);e.success?(await nn(e.scopedTokens),m.outro(U.default.green("Setup complete! You can now use Stably CLI."))):m.outro(U.default.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(U.default.yellow("Session expired, proceeding with fresh login...")),await rn(),await an()}}const{authorizeUrl:t,waitForCallback:n}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:n}=(()=>{const e=P.default.randomBytes(32).toString("base64url"),t=(n=e,P.default.createHash("sha256").update(n).digest("base64url"));var n;const r=P.default.randomBytes(16).toString("base64url");return{authorizeUrl:pn(t,r),codeVerifier:e,state:r}})();return{authorizeUrl:e,waitForCallback:async()=>(async(e,t)=>{const n=await(r=e,new Promise((e,t)=>{const n=setTimeout(()=>{i.close(),e({error:"Login timed out",success:!1})},3e5),o=()=>{clearTimeout(n)},i=B.default.createServer((t,n)=>{const a=new s.URL(t.url||"","http://localhost:9876");if("/auth/callback"!==a.pathname)return n.writeHead(404),void n.end("Not found");const c=a.searchParams.get("code"),l=a.searchParams.get("state"),d=a.searchParams.get("error");return d?(un(n,400,dn(d)),o(),i.close(),void e({error:d,success:!1})):c&&l?l!==r?(un(n,400,dn("Invalid state parameter (possible CSRF attack)")),o(),i.close(),void e({error:"State mismatch",success:!1})):(un(n,200,'\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authenticated Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #22c55e;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .terminal {\n background: #111;\n border: 1px solid #333;\n border-radius: 8px;\n padding: 16px;\n text-align: left;\n font-family: \'SF Mono\', \'Fira Code\', \'Consolas\', monospace;\n font-size: 13px;\n }\n .terminal-header {\n display: flex;\n gap: 6px;\n margin-bottom: 12px;\n }\n .terminal-dot {\n width: 10px;\n height: 10px;\n border-radius: 50%;\n background: #333;\n }\n .terminal-line {\n color: #888;\n }\n .terminal-line .prompt { color: #888; }\n .terminal-line .cmd { color: #fafafa; }\n .terminal-line.success { color: #22c55e; }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>\n </svg>\n </div>\n <h1 class="title">Authenticated</h1>\n <p class="subtitle">You can close this tab and return to your terminal.</p>\n <div class="terminal">\n <div class="terminal-header">\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n </div>\n <div class="terminal-line"><span class="prompt">$</span> <span class="cmd">stably login</span></div>\n <div class="terminal-line success">Logged in successfully</div>\n </div>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n'),o(),i.close(),void e({code:c,state:l,success:!0})):(un(n,400,dn("Missing code or state parameter")),o(),i.close(),void e({error:"Missing code or state parameter",success:!1}))});i.on("error",e=>{o(),"EADDRINUSE"!==e.code?t(new Error(`Failed to start callback server: ${e.message}`)):t(new Error("Port 9876 is already in use. Please close the application using it and try again."))}),i.listen(9876)}));var r;if(!n.success)throw new Error(n.error);return(async(e,t)=>{const n=new URLSearchParams({client_id:Mt,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:Gt}),r=await fetch(`${$t}/propelauth/oauth/token`,{body:n.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!r.ok){const e=await r.text();throw new Error(`Token exchange failed: ${r.status} ${e}`)}const o=await r.json();return{accessToken:o.access_token,expiresAt:Date.now()+1e3*o.expires_in,idToken:o.id_token,refreshToken:o.refresh_token}})(n.code,t)})(n,t)}})();m.log.info("Opening browser for authentication..."),m.log.info(U.default.dim("If browser doesn't open, visit:")),m.log.info(U.default.underline(U.default.cyan(t)));try{await O.default(t)}catch{m.log.warn("Could not open browser automatically. Please open the URL above manually.")}const r=m.spinner();let o;r.start("Waiting for authentication...");try{o=await n(),r.stop(U.default.green("✓ Authentication successful"))}catch(e){r.stop(U.default.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";m.outro(U.default.red(`Login failed: ${t}`)),process.exit(1)}const i=await fn(o);i.success?(await nn(i.scopedTokens),m.outro(U.default.green("Setup complete! You can now use Stably CLI."))):(m.outro(U.default.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},mn=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return{apiKey:e,projectId:t}},gn=!1,_n=()=>{gn||(gn=!0,m.log.warn("Both environment variable auth and stored OAuth login were detected."),m.log.warn(`Honoring environment variables (${U.default.cyan("STABLY_API_KEY")} + ${U.default.cyan("STABLY_PROJECT_ID")}).`),m.log.warn("To use OAuth login instead, unset those environment variables."))},yn=async()=>{const e=await tn();if(e){if(!cn(e)){const t=await sn();if(t&&"full"===(e=>{try{const t=Vt.parse(Kt(e));if(t.org_id_to_org_member_info)return"full";if(t.org_member_info)return"org"}catch{return"unknown"}return"unknown"})(e.accessToken))try{const n=await Yt(e.accessToken,t.orgId),r={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await nn(r),r}catch{return e}return e}try{const t=await ln(e.refreshToken),n=await sn();if(n)try{const e=await Yt(t.accessToken,n.orgId),r={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await nn(r),r}catch{return await nn(t),t}return await nn(t),t}catch{return}}},En=async(e={})=>{const t=mn();if(t){try{await tn()&&_n()}catch{}return{auth:t,type:"env"}}let n=await yn(),r=n?await sn():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if((!n||!r)&&e.autoLogin&&o){n?m.log.info("You are logged in but need to select an organization and project."):m.log.info("You are not logged in."),m.log.info("Press Enter to log in."),process.stdout.write(`${U.default.dim("Alternatively, set environment variables for an org API key:")}\n${U.default.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=g.createInterface({input:process.stdin,output:process.stdout});try{await e.question(U.default.dim("Press Enter to continue... "))}finally{e.close()}await hn(),n=await yn(),r=n?await sn():void 0}return n||(m.outro(U.default.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),r||(m.outro(U.default.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),{auth:{accessToken:n.accessToken,context:r},type:"oauth"}},bn=e=>e?{...process.env,...e}:process.env,In=async()=>{const e=mn();if(e)return{STABLY_API_KEY:e.apiKey,STABLY_PROJECT_ID:e.projectId};const t=await(async()=>{const e=mn();if(e){try{await tn()&&_n()}catch{}return{auth:e,type:"env"}}const t=await yn(),n=t?await sn():void 0;if(t&&n)return{auth:{accessToken:t.accessToken,context:n},type:"oauth"}})();if(!t||"env"===t.type)return;const n=process.env.STABLY_PROJECT_ID?.trim(),r=n||(e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId)(t);if(!r)return;const o=await(async(e,t)=>{try{return(await(async({accessToken:e,projectId:t})=>{const n=await(r={auth:e,client:Ft(),path:{projectId:t}},(r.client??Nt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/api-key",...r}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this project");if(n.error)throw new Error(`Failed to get API key: ${n.response.status}`);return n.data})({accessToken:e,projectId:t})).apiKey}catch{return e}})(t.auth.accessToken,r);return o?{STABLY_API_KEY:o,STABLY_PROJECT_ID:r}:void 0},wn=e=>e?{[Dt]:e}:void 0,vn=_.z.object({context:_.z.string().min(1),autohealReportUrl:_.z.string()}),Tn=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},Rn=e=>null!=e&&"object"==typeof e&&"tool_response"in e,Sn=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},Cn=e=>{const t=Sn(e);if(t)return t.filter(Tn).map(e=>e.text).join("\n")||void 0},xn=/\u001b\[[0-9;]*m/g,An=e=>e.replace(xn,""),Un=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function Pn({envVars:e}){return async t=>{if(!function(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}(t))return{decision:"approve"};const n=t.tool_input,r="string"==typeof n.text?n.text:void 0;if(!r)return{decision:"approve"};const o=r.replace(Un,(t,n)=>{const r=e[n];return null!=r?r:t});return o===r?{decision:"approve"}:{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser text input.",updatedInput:{...n,text:o}}}}}function Ln({onResult:e}){return async t=>{if(!Rn(t))return{decision:"approve"};const n=Cn(t);if(!n)return{decision:"approve"};const r=function(e){const t=An(e),n=t.split(/Running \d+ tests? using \d+ workers?/).at(-1)??t,r=parseInt(n.match(/(\d+)\s+passed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0"),o=parseInt(n.match(/(\d+)\s+failed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0");if(0===r&&0===o)return;const s=[r>0?`${r} test${1===r?"":"s"} passed ✓`:void 0,o>0?`${o} test${1===o?"":"s"} failed ✗`:void 0].filter(e=>void 0!==e).join(", ");if(0===o)return s;const i=n.split(/\n\s+\d+\)\s+\[id=/).slice(1).map(e=>e.match(/\n\s{4}((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/)?.[1]?.trim()).filter(e=>void 0!==e);return 0===i.length?s:`${s}\n${i.map(e=>` - ${e}`).join("\n")}`}(n);return r&&e(r),{decision:"approve"}}}function On({onResult:e}){return async t=>{if(!Rn(t))return{decision:"approve"};const n=Cn(t);if(!n)return{decision:"approve"};const r=function(e){const t=An(e);if(t.match(/### Paused on error:/)){const e=t.match(/### Paused on error:\s*\n((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/);return e?`Test paused on error - ${e[1].trim()}`:"Test paused on error"}const n=t.match(/(\d+)\s+passed/);if(n){const e=parseInt(n[1]);return`${e} test${1===e?"":"s"} passed ✓`}}(n);return r&&e(r),{decision:"approve"}}}var Bn=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function Nn({onFileCreated:e}){return async t=>{const n=(e=>{if(!e||"object"!=typeof e)return;const t=e;return t.tool_input&&"object"==typeof t.tool_input&&!Array.isArray(t.tool_input)?t.tool_input:void 0})(t),r=n?.file_path;return"string"==typeof r&&Bn.test(r)&&e(r),{decision:"approve"}}}var Dn=c.promisify(r.exec);async function jn(){try{const{stdout:e}=await Dn('pgrep -f "playwright run-test-mcp-server" 2>/dev/null || true'),t=e.trim();if(!t)return;const n=t.split("\n").filter(Boolean);await Promise.allSettled(n.map(async e=>{await Dn(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var kn=null;function $n(){return e=>(kn&&clearTimeout(kn),kn=setTimeout(async()=>{await jn(),kn=null},6e5),Promise.resolve({decision:"approve"}))}function Mn(){return e=>(kn&&(clearTimeout(kn),kn=null),Promise.resolve({decision:"approve"}))}function Hn(){kn&&(clearTimeout(kn),kn=null)}var Gn=class{queue=[];pendingResolve=void 0;done=!1;canSend=!0;[Symbol.asyncIterator](){return this}pushText(e){const t=e.trim();t&&!this.done&&(this.queue.push(t),this.maybeFlush())}allowNextTurn(){this.done||(this.canSend=!0,this.maybeFlush())}finish(){this.done=!0,this.pendingResolve&&(this.pendingResolve({done:!0,value:void 0}),this.pendingResolve=void 0)}maybeFlush(){if(!this.pendingResolve)return;if(!this.canSend)return;const e=this.queue.shift();if(void 0===e)return;const t={message:{content:[{text:e,type:"text"}],role:"user"},parent_tool_use_id:null,type:"user",session_id:""};this.canSend=!1,this.pendingResolve({done:!1,value:t}),this.pendingResolve=void 0}next(){return this.done?Promise.resolve({done:!0,value:void 0}):new Promise(e=>{this.pendingResolve=e,this.maybeFlush()})}},Fn=[".ts",".js",".mts",".mjs",".cts",".cjs"],Yn=10240,zn=async({defaultContent:e,fileName:t,filePath:n})=>{try{const e=(await h.stat(n)).size,r=await h.readFile(n,"utf-8"),o=Buffer.byteLength(r,"utf-8");if(o<=Yn)return r;const s=(e=>{const t=e.split("\n"),n=[];let r=!1,o=!1,s=0,i=!1;for(let e=0;e<t.length;e++){const a=t[e],c=a.trim();c.startsWith("/*")&&(r=!0),c.includes("*/")?r=!1:r||c.startsWith("//")&&!c.startsWith("///")||(c.startsWith("import ")||c.startsWith("export ")?(n.push(a),i=!0):i&&""===c?(n.push(a),i=!1):(i=!1,c.startsWith("type ")||c.startsWith("interface ")?n.push(a):c.startsWith("function ")||c.startsWith("const ")||c.startsWith("async function ")||c.startsWith("export function ")||c.startsWith("export const ")||c.startsWith("test.describe(")||c.startsWith("test(")?(n.push(a),o=!0,s=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===s&&(c.endsWith(";")||c.endsWith(","))&&(o=!1)):o?(s+=(a.match(/{/g)||[]).length,s-=(a.match(/}/g)||[]).length,0===s&&c.includes("}")?(n.push(a),o=!1):s>0&&" // ... implementation omitted ..."!==n.at(-1)&&n.push(" // ... implementation omitted ...")):c.match(/^[a-zA-Z_]+:/)&&n.push(a)))}return n.join("\n")})(r),i=Buffer.byteLength(s,"utf-8");return i<=Yn?s:s.slice(0,Yn)+`\n\n... [TRUNCATED: File "${t}" at ${n} was ${e} bytes (${o} bytes as UTF-8), reduced to ~${i} bytes of essential content, then truncated to 10240 bytes] ...`}catch(n){let r;if(n&&"object"==typeof n&&"code"in n){const e=n.code;"string"==typeof e&&(r=e)}return"ENOENT"!==r&&console.warn(`Failed to read ${t}: ${n}`),e}},Vn=async({defaultContent:e,dirName:t,dirPath:n})=>{try{const e=await h.readdir(n);return e.length>0?e.join("\n"):"(empty)"}catch(n){let r;if(n&&"object"==typeof n&&"code"in n){const e=n.code;"string"==typeof e&&(r=e)}return"ENOENT"!==r&&console.warn(`Failed to read ${t}: ${n}`),e}},Kn=".stably-playwright-wrapper.config.*",Wn=[".ts",".js",".mts",".mjs",".cts",".cjs"];function qn(e){const t=n.resolve(e);if(a.existsSync(t))for(const e of Wn){const r=n.join(t,`playwright.config${e}`);if(a.existsSync(r))return r}}var Jn=["tests","e2e","__tests__","test"];function Xn(e){try{return a.existsSync(e)&&a.statSync(e).isDirectory()}catch{return!1}}function Qn(e,t){const n="output-flag"===t?"--output flag":"playwright.config.ts"===t?"playwright.config.ts":"auto-detected"===t?"auto-detected":"cwd fallback";console.error(U.default.dim(`Using output directory: ${e} (from ${n})`))}var Zn=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__test-doc-sync__","mcp__stably-agent-control__"],er=["planner_","generator_"],tr={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools"},nr=(e,t)=>{const n=t.find(t=>e.startsWith(t));return n?e.slice(n.length):e},rr=e=>{const t=tr[e];if(t)return t;const n=nr(e,Zn);return nr(n,er).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")},or=(e,t)=>{if(!t||"object"!=typeof t)return;const n=t,r="string"==typeof n.intent?n.intent:void 0;if("Read"!==e&&"Write"!==e&&"Edit"!==e){if("Glob"===e||"Grep"===e)return"string"==typeof n.pattern?n.pattern:void 0;if("mcp__playwright-test__test_run"!==e&&"test_run"!==e){if("mcp__playwright-test__test_debug"===e||"test_debug"===e){const e=n.test;return"string"==typeof e?.title?e.title:void 0}return"mcp__playwright-test__generator_setup_page"===e||"generator_setup_page"===e?"string"==typeof n.seedFile?n.seedFile:"tests/seed.spec.ts":"mcp__playwright-test__generator_write_test"===e||"generator_write_test"===e?"string"==typeof n.fileName?n.fileName:void 0:"Bash"===e?"string"==typeof n.command?n.command.length>50?`${n.command.slice(0,50)}...`:n.command:void 0:e.includes("browser_navigate")&&!e.includes("back")?"string"==typeof n.url?n.url:r:e.includes("browser_type")?("string"==typeof n.text?`"${n.text}"`:void 0)??r:e.includes("browser_click")?"string"==typeof n.element?n.element:r:e.includes("browser_wait_for")?"string"==typeof n.text?`text: "${n.text}"`:"number"==typeof n.time?`${n.time}ms`:r:e.includes("verify_text")?"string"==typeof n.text?`"${n.text}"`:r:e.includes("verify_element")?"string"==typeof n.accessibleName?n.accessibleName:r:e.includes("screenshot")&&"string"==typeof n.filename?n.filename:r}if(Array.isArray(n.locations)){const e=n.locations.filter(e=>"string"==typeof e);return e.length>0?e.join(", "):void 0}}else if("string"==typeof n.file_path)return n.file_path.split("/").at(-1)??void 0},sr=w.z.object({bucket:w.z.string(),key:w.z.string()}),ir=w.z.object({diffBucketPath:sr,expiresInSeconds:w.z.number(),key:w.z.string(),uploadUrl:w.z.string()}),ar=["test","bug","other"],cr={bug:"Application code defect; behavior diverges from expected requirements.",other:"External dependencies, environment, or infra issues outside test/app code.",test:"Test code is incorrect, out-of-date, or missing necessary setup."},lr=e=>cr[e],{zSuiteAutoHealReport:dr}=function(e){const t=e.enum(ar),n=["Classification of the root cause:","",`- test: ${lr("test")}`,`- bug: ${lr("bug")}`,`- other: ${lr("other")}`].join("\n"),r=e.object({erroredUrl:e.string().optional(),issueType:t.describe(n),relatedTestCaseIds:e.array(e.string()).min(1).describe("List of ALL test case IDs impacted by this root cause and fix (must be existing IDs only)."),rootCause:e.string().describe("Brief explanation of what happened (1-2 sentences).")}),o=e.discriminatedUnion("result",[r.extend({fixApplied:e.string().describe("What fix was applied (brief, specific)."),result:e.literal("fixed")}),r.extend({followUpActions:e.string().optional().describe("Optional list of follow-up actions for any unfixed issues or missing data."),reasonNotFixed:e.string().describe("Why it could not be auto-fixed (brief)."),result:e.literal("unfixed")})]);return{zAutoHealReport:o,zIssueCategory:t,zSuiteAutoHealReport:e.object({issues:e.array(o).min(1).describe("List of all auto-heal issues/outcomes for this suite."),summary:e.string().min(3).describe("High-level summary (2-3 sentences) of the suite auto-heal results.")})}}(w.z),ur=({authHeader:e,diffTracker:t,orgId:n,runId:r})=>l.createSdkMcpServer({name:"auto-heal-report",tools:[l.tool("generate-report",["After attempting to fix all broken tests (skip only those truly infeasible), generate and return a suite auto-heal report in the required schema.","","Ensure the payload matches zSuiteAutoHealReport exactly; include every issue discovered."].join("\n"),{report:dr},async({report:o})=>{const s=await t.computeDiff(),i=dr.parse(o);try{await(async({authHeader:e,orgId:t,report:n,runId:r})=>{const o=await(s={auth:e,body:{report:JSON.stringify(n)},client:Ft(),headers:wn(t),path:{runId:r}},(s.client??Nt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to upload auto-heal report (${o.response.status})`)})({authHeader:e,orgId:n,report:i,runId:r});const{uploadUrl:t}=await(async({authHeader:e,contentType:t="text/plain",orgId:n,runId:r})=>{const o=await(s={auth:e,body:{contentType:t},client:Ft(),headers:wn(n),path:{runId:r}},(s.client??Nt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to presign diff upload (${o.response.status})`);const i=ir.parse(o.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}})({authHeader:e,contentType:"text/plain",orgId:n,runId:r});await(async({contentType:e="text/plain",diff:t,uploadUrl:n})=>{const r=await fetch(n,{body:t,headers:{"Content-Type":e},method:"PUT"});if(!r.ok)throw new Error(`Failed to upload diff (${r.status})`)})({contentType:"text/plain",diff:s,uploadUrl:t})}catch(e){return console.error("[auto-heal-report] Failed to upload report or diff:",e),{content:[{text:"Error: Failed to upload auto-heal report or diff. Please surface this to the user, and terminate the session.",type:"text"}]}}return{content:[{text:"Auto-heal report generated. You may terminate this session now.",type:"text"}]}})],version:"0.0.1"}),pr=({onComplete:e})=>l.createSdkMcpServer({name:"session-control",tools:[l.tool("complete_session",["Call this tool when you have completed your task and the session should end.","Use this instead of waiting for the user to manually terminate.","Only call this when you are confident the task is fully complete."].join("\n"),{summary:w.z.string().describe("A brief summary of what was accomplished")},async({summary:t})=>{const n=t;return e(),`Session complete: ${n}`})]}),fr=e=>e.replace(/Bearer\s+[A-Za-z0-9._-]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{16,}\b/g,"[redacted]").replace(/\bstably_[A-Za-z0-9_-]{16,}\b/g,"[redacted]"),hr=(e,t)=>({message:fr(e),status:t?.status,statusText:t?.statusText}),mr=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_MODEL","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","AWS_BEARER_TOKEN_BEDROCK","BASH_DEFAULT_TIMEOUT_MS","BASH_MAX_OUTPUT_LENGTH","BASH_MAX_TIMEOUT_MS","CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR","CLAUDE_CODE_API_KEY_HELPER_TTL_MS","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_DISABLE_TERMINAL_TITLE","CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL","CLAUDE_CODE_MAX_OUTPUT_TOKENS","CLAUDE_CODE_SHELL_PREFIX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX","CLAUDE_CONFIG_DIR","DISABLE_AUTOUPDATER","DISABLE_BUG_COMMAND","DISABLE_COST_WARNINGS","DISABLE_ERROR_REPORTING","DISABLE_NON_ESSENTIAL_MODEL_CALLS","DISABLE_PROMPT_CACHING","DISABLE_PROMPT_CACHING_HAIKU","DISABLE_PROMPT_CACHING_OPUS","DISABLE_PROMPT_CACHING_SONNET","DISABLE_TELEMETRY","HTTP_PROXY","HTTPS_PROXY","MAX_MCP_OUTPUT_TOKENS","MAX_THINKING_TOKENS","MCP_TIMEOUT","MCP_TOOL_TIMEOUT","NO_PROXY","SLASH_COMMAND_TOOL_CHAR_BUDGET","USE_BUILTIN_RIPGREP","VERTEX_REGION_CLAUDE_3_5_HAIKU","VERTEX_REGION_CLAUDE_3_7_SONNET","VERTEX_REGION_CLAUDE_4_0_OPUS","VERTEX_REGION_CLAUDE_4_0_SONNET","VERTEX_REGION_CLAUDE_4_1_OPUS"]),gr=["Bash","Read","Write","Edit","Glob","Grep"],_r=["mcp__playwright-test"],yr=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],Er=e=>{if("EPIPE"!==e.code)throw e},br=async e=>{process.stdout.on("error",Er),process.stderr.on("error",Er);const t=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",t);const o=await En({autoLogin:"chat"===e.mode||"init"===e.mode}),s=(e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken)(o),i="oauth"===o.type?o.auth.context.orgId:void 0,c=R.default.resolve(process.cwd()),u=R.default.join(c,".env"),p=A.default.existsSync(u)&&A.default.statSync(u).isFile()?d.parse(A.default.readFileSync(u,"utf8")):{},f="chat"!==e.mode&&"init"!==e.mode,m="chat"===e.mode||"init"===e.mode?new Gn:void 0,g="chat"===e.mode?e.getHelpText:void 0,_={log:[],promptDisplay:"chat"===e.mode?"Ask Stably to build tests for you":"init"===e.mode?"Setting up Playwright and Stably SDK":"fix"===e.mode?"Fixing broken tests":(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim()||"Creating tests from PR/branch changes",status:"running"};let y,E=f,w=!1;const v={current:e=>{}},T={current:async()=>{}},{addTool:S,addToolResult:C,appendText:x,appendUserMessage:P,cleanup:L,setExiting:O,setStatus:B}=await(async(e,t)=>{const{Box:n,Static:r,Text:o,render:s,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=()=>I.jsx(o,{inverse:!0,children:" "}),d=(({Box:e,Text:t,useInput:n},r,o)=>function({onChoice:s,prompt:i}){const[a,c]=b.useState(0),[l,d]=b.useState(!1),[u,p]=b.useState(""),f=[{label:"Yes, allow this once",value:"allow"},{label:"Yes, always allow for this session",value:"always"},{label:"No, tell AI what to do differently",value:"deny_with_message"}];n((e,t)=>{if(l)return t.return?void s("deny_with_message",u||"User denied this action"):t.escape?(d(!1),void p("")):t.backspace||t.delete?void p(e=>e.slice(0,-1)):void(t.ctrl||t.meta||p(t=>`${t}${e}`));if(t.upArrow)return void c(e=>e>0?e-1:f.length-1);if(t.downArrow)return void c(e=>e<f.length-1?e+1:0);if(t.return){const e=f[a];return"deny_with_message"===e.value?void d(!0):void s(e.value)}const n=parseInt(e,10);if(n>=1&&n<=f.length){const e=f[n-1];if("deny_with_message"===e.value)return void d(!0);s(e.value)}},{isActive:o});const h=rr(i.toolName),m=or(i.toolName,i.input);return I.jsxs(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[I.jsx(t,{bold:!0,color:"yellow",children:"Permission Required"}),I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"magenta",children:h}),null!=m&&I.jsxs(t,{color:"gray",children:[" ",m]})]}),null!=i.decisionReason&&I.jsx(e,{marginTop:1,children:I.jsxs(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),l?I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),I.jsxs(t,{children:[I.jsx(t,{color:"yellow",children:">"})," ",u,I.jsx(r,{})]})]}):I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,n)=>I.jsx(t,{children:I.jsxs(t,{color:n===a?"cyan":void 0,children:[n===a?"❯":" "," ",n+1,". ",e.label]})},e.value))]})]})})({Box:n,Text:o,useInput:i},l,a),u=(({Cursor:e,inkComponents:{Box:t,Static:n,Text:r,useInput:o},isRawModeSupported:s,PermissionPrompt:i,Spinner:a})=>{const c=e=>"tool"===e.kind?I.jsxs(r,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?I.jsx(r,{color:"gray",children:e.content},e.id):"user"===e.kind?I.jsxs(r,{color:"cyan",children:["You: ",e.content]},e.id):I.jsx(r,{children:e.content},e.id),l="vscode"===process.env.TERM_PROGRAM,d=(e,t)=>{if(t<=0)return 0;let n=t-1;for(;n>0&&/\s/.test(e[n]);)n--;for(;n>0&&!/\s/.test(e[n-1]);)n--;return n};return function({onExit:u,onPermissionChoice:p,onSend:f,showSpinnerImmediately:h,state:m}){const[g,_]=b.useState(""),[y,E]=b.useState(0),w=b.useRef(!1),v=b.useRef(void 0),[T,R]=b.useState(!1),S=b.useRef(0),C=m.log.at(-1),x="text"===C?.kind&&"running"===m.status,A=l?0:x?m.log.length-1:m.log.length;b.useEffect(()=>{m.log.length<S.current&&(S.current=0),A>S.current&&(S.current=A)},[m.log.length,A]);const U=m.log.slice(0,S.current),P=m.log.slice(S.current),L=!!m.permissionPrompt,O=b.useCallback(()=>{w.current?(v.current&&clearTimeout(v.current),u?.(),process.exit(0)):(w.current=!0,R(!0),v.current=setTimeout(()=>{w.current=!1,R(!1)},2e3))},[u]);o((e,t)=>{t.ctrl&&"c"===e&&O()},{isActive:s}),b.useEffect(()=>{if(L||!f)return;const e=e=>{const t=e.toString();"[1;5H"!==t&&"[1;5~"!==t?"[1;5F"!==t&&"[4;5~"!==t?"[H"!==t&&"[1~"!==t&&"OH"!==t&&"[7~"!==t?"[F"!==t&&"[4~"!==t&&"OF"!==t&&"[8~"!==t||E(e=>((e,t)=>{const n=e.indexOf("\n",t);return-1===n?e.length:n})(g,e)):E(e=>((e,t)=>{if(t<=0)return 0;const n=e.lastIndexOf("\n",t-1);return-1===n?0:n+1})(g,e)):E(g.length):E(0)};return process.stdin.on("data",e),()=>{process.stdin.off("data",e)}},[L,f,g]),o((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){const e=g.trim();return e&&f?.(e),_(""),void E(0)}if(t.ctrl&&"w"===e||t.ctrl&&t.backspace){const e=d(g,y);return _(t=>t.slice(0,e)+t.slice(y)),void E(e)}!t.backspace&&!t.delete||t.ctrl?t.ctrl&&t.leftArrow||t.meta&&"b"===e?E(d(g,y)):t.ctrl&&t.rightArrow||t.meta&&"f"===e?E(((e,t)=>{if(t>=e.length)return e.length;let n=t;for(;n<e.length&&!/\s/.test(e[n]);)n++;for(;n<e.length&&/\s/.test(e[n]);)n++;return n})(g,y)):t.leftArrow?E(e=>Math.max(0,e-1)):t.rightArrow?E(e=>Math.min(g.length,e+1)):t.ctrl&&"a"===e?E(0):t.ctrl&&"e"===e?E(g.length):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||(_(t=>t.slice(0,y)+e+t.slice(y)),E(t=>t+e.length)):y>0&&(_(e=>e.slice(0,y-1)+e.slice(y)),E(e=>e-1))}},{isActive:s&&!!f&&!L});const B=b.useMemo(()=>"running"===m.status?I.jsx(a,{label:"Working"}):"success"!==m.status?I.jsx(r,{color:"red",children:"✖ Failed"}):void 0,[m.status]),N=!(h||!f||"running"!==m.status||0!==m.log.length||m.resultText||m.errorText),D="running"===m.status&&!N||m.log.length>0||m.resultText||m.errorText||"running"!==m.status;return I.jsxs(t,{flexDirection:"column",children:[I.jsx(n,{items:["header"],children:()=>I.jsxs(t,{flexDirection:"column",flexShrink:0,children:[I.jsx(r,{color:"cyan",bold:!0,children:"Stably Agent"}),I.jsx(t,{flexDirection:"column",marginTop:1,children:I.jsx(r,{color:"gray",children:m.promptDisplay})})]},"header")}),U.length>0&&I.jsx(n,{items:U,children:e=>c(e)}),P.length>0&&I.jsx(t,{flexDirection:"column",children:P.map(e=>c(e))}),"error"===m.status&&m.errorText&&I.jsx(t,{marginTop:1,children:I.jsx(r,{color:"red",children:m.errorText})}),"success"===m.status&&m.resultText&&I.jsx(t,{marginTop:1,children:I.jsx(r,{children:m.resultText})}),D&&I.jsx(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:B}),null!=m.permissionPrompt&&null!=p&&I.jsx(i,{onChoice:p,prompt:m.permissionPrompt}),null!=f&&null==m.permissionPrompt&&!m.isExiting&&I.jsxs(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[I.jsx(r,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),I.jsxs(r,{children:[I.jsx(r,{color:"yellow",children:">"})," ",g.slice(0,y),I.jsx(e,{}),g.slice(y)]})]}),T&&I.jsx(t,{marginTop:1,children:I.jsx(r,{color:"yellow",children:"Press Ctrl+C again to exit"})})]})}})({Cursor:l,inkComponents:{Box:n,Static:r,Text:o,useInput:i},isRawModeSupported:a,PermissionPrompt:d,Spinner:({label:e})=>{const[t,n]=b.useState(0);return b.useEffect(()=>{const e=setInterval(()=>n(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),I.jsxs(o,{color:"yellow",children:[c[t]," ",e]})}});let p=e;const f={current:(e,t)=>{}},h=s(I.jsx(u,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}),{exitOnCtrlC:!1}),m=()=>{p={...p},h.rerender(I.jsx(u,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}))},g=({text:e})=>{e&&(p.log=[...p.log,{content:e,id:p.log.length,kind:"user"}],m())};return{addTool:({rawName:e,toolInput:t})=>{const n=rr(e),r=or(e,t),o=r?`${n} (${r})`:n;p.log=[...p.log,{content:o,id:p.log.length,kind:"tool"}],m()},addToolResult:({message:e})=>{p.log=[...p.log,{content:e,id:p.log.length,kind:"tool_result"}],m()},appendText:({text:e})=>{if(!e)return;const t=p.log.at(-1),n=t&&"text"===t.kind?e:e.replace(/^\s*\n+/,"");t&&"text"===t.kind?p.log=[...p.log.slice(0,-1),{...t,content:`${t.content}${n}`}]:p.log=[...p.log,{content:n,id:p.log.length,kind:"text"}],m()},appendUserMessage:g,cleanup:async()=>{const e=h.waitUntilExit();h.unmount(),await e},setExiting:()=>{p.isExiting=!0,m()},setStatus:({error:e,result:t,status:n})=>{p.errorText=e,p.resultText=t,p.status=n,m()},showPermissionPrompt:e=>new Promise(t=>{f.current=(n,r)=>{if(p.permissionPrompt=void 0,m(),"allow"===n)t({behavior:"allow",updatedInput:e.input});else if("always"===n)t({behavior:"allow",updatedInput:e.input,updatedPermissions:e.suggestions});else{const e=r??"User denied this action";g({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},p.permissionPrompt={...e,resolve:t},m()})}})(_,"chat"===e.mode||"init"===e.mode?{onExit:()=>{T.current()},onSend:e=>v.current(e),showSpinnerImmediately:"init"===e.mode}:void 0);let N=_.status;const D=({error:e,result:t,status:n})=>{N=n,B({error:e,result:t,status:n})};let j;v.current=e=>{if("/help"===e.trim()){E&&m&&(w=!0,y?.interrupt?.(),m.allowNextTurn(),E=!1),"running"===N&&D({status:"success"}),P({text:e});const t=g?.();return void x({text:t??"Help is not available in this session."})}m&&(E&&(w=!0,y?.interrupt?.(),m.allowNextTurn(),E=!1),D({status:"running"}),P({text:e}),m.pushText(e),E=!0)};const k=[];let $;const M=await(async()=>{if("single"===e.mode){const r=await async function(e,t){const r=n.resolve(e);if(t){const e=n.resolve(r,t);return Qn(e,"output-flag"),{path:e,source:"output-flag"}}const o=qn(r);if(o){const e=await async function(e){try{const t=(await h.readFile(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(o);if(e){const t=n.resolve(n.dirname(o),e);if(Xn(t))return Qn(t,"playwright.config.ts"),{path:t,source:"playwright.config.ts"}}}for(const e of Jn){const t=n.join(r,e);if(Xn(t))return Qn(t,"auto-detected"),{path:t,source:"auto-detected"}}return Qn(r,"cwd-fallback"),{path:r,source:"cwd-fallback"}}(c,e.outputDir);return $=r.path,t=e.prompt,`${(Array.isArray(t)?t.join(" "):t).trim()||"Create tests based on the changes in the current PR or branch. Use the Pull Request Context or Git Branch Context section of the system prompt to understand what code was changed, then create appropriate tests for the new or modified functionality. After generating the tests, run them locally (e.g. `pnpm playwright test` or the repo's Playwright test command) and iterate until the new tests pass."}\n\n[Output directory: ${$}]`}var t;if("fix"===e.mode)try{const{context:t,autohealReportUrl:n}=await(async({authHeader:e,orgId:t,runId:n})=>{const r=await(o={auth:e,client:Ft(),headers:wn(t),path:{runId:n}},(o.client??Nt).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...o}));var o;if(404===r.response.status)throw new Error(`Run ID "${n}" was not found.`);if(401===r.response.status)throw new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===r.response.status)throw new Error(r.error?.error??"Failed to fetch autoheal context (422).");if(!r.error){const e=vn.safeParse(r.data);if(e.success)return{context:e.data.context,autohealReportUrl:e.data.autohealReportUrl};throw new Error("Autoheal context response missing or invalid context.")}throw new Error("Failed to fetch autoheal context")})({authHeader:s,orgId:i,runId:e.runId});return j=n,t}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";D({error:t,status:"error"}),await L(),process.exit(1)}return"init"===e.mode?"Please analyze this project and set up Playwright with the Stably SDK. Check for existing configurations and install the necessary dependencies.":""})(),H=await async function(e){const t=R.default.resolve(e),n=R.default.join(t,"tests"),r=R.default.join(n,"helpers"),o=R.default.join(n,"assets"),s=function(e){const t=R.default.resolve(e);if(a.existsSync(t))for(const e of Fn){const n=R.default.join(t,`playwright.config${e}`);if(a.existsSync(n))return n}}(t)??R.default.join(t,"playwright.config.ts"),i=R.default.basename(s),c=R.default.join(n,"seed.spec.ts"),[l,d,u,p,f,h]=await Promise.all([Vn({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),Vn({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:n}),Vn({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:r}),Vn({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:o}),zn({defaultContent:"File does not exist or could not be read",fileName:i,filePath:s}),zn({defaultContent:"File does not exist or could not be read",fileName:"seed.spec.ts",filePath:c})]);return{absolutePath:t,directories:{assets:p,helpers:u,root:l,tests:d},files:{playwrightConfig:f,playwrightConfigFilename:i,seedSpec:h}}}(c),G=await(async({allowedEnvVars:e,mode:t,workspaceInfo:n,authHeader:o})=>{const s=Ft(),i=function(e){try{const t=r.execSync("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}(n.absolutePath),a=await(c={client:s,auth:o,body:{mode:t,workspaceInfo:n,allowedEnvVars:e,gitContext:i}},(c.client??Nt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...c,headers:{"Content-Type":"application/json",...c.headers}}));var c;if(401===a.response.status)throw await rn(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===a.response.status)throw await rn(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(a.error)throw new Error(`Failed to fetch system prompt: ${JSON.stringify(a.error)}`);return a.data.systemPrompt})({allowedEnvVars:Object.keys(p),mode:e.mode,workspaceInfo:H,authHeader:s}),F={...p,...process.env},Y=Object.fromEntries(Object.entries(F).filter(([e])=>!mr.has(e))),z=await async function({auth:e,client:t,source:n,metadata:r,duration:o}){try{const i=await(s={auth:e,client:t,body:{source:n,metadata:r??{},duration:o}},(s.client??Nt).post({security:[{scheme:"bearer",type:"http"}],url:"/v1/proxy/api-key",...s,headers:{"Content-Type":"application/json",...s.headers}})),a=i.response;if(i.error){const e="object"==typeof i.error&&"error"in i.error?i.error.error:"Unknown error";return{error:hr(e,a)}}return i.data?{key:i.data.key}:{error:hr("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:hr(t)}}var s}({auth:s,client:Ft(),source:"cli"}),V=z?.key;V||(D({error:z?.error?.message?`Unable to make AI calls: ${z.error.message}`:"Unable to make AI calls. Check if you are authenticated.",status:"error"}),await L(),process.exit(1));const K=await In(),W=K?Object.fromEntries(Object.entries(bn(K)).filter(e=>null!=e[1])):void 0,q="init"===e.mode,J="fix"===e.mode,X=J?ht.createLocal({workingDir:c}):void 0;X&&await X.captureSnapshot();const Q=q?yr:[...gr,...J?["mcp__auto-heal-report"]:[]],Z=q?yr:_r,ee=q?{"session-control":pr({onComplete:()=>{D({status:"success"}),O(),m?.finish(),process.exit(0)}})}:J&&X?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:W},"auto-heal-report":ur({authHeader:s,diffTracker:X,orgId:i,runId:e.runId})}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:W}},te="single"===e.mode,ne=q?[]:[{hooks:[async e=>{const t=Sn(e);if(!t)return{decision:"approve"};let n=!1;const r=t.map(e=>Tn(e)?e.text.length<=4e4?e:(n=!0,{...e,text:`${e.text.slice(0,4e4)}...[truncated to 40000 characters]`}):e);return n?{decision:"approve",hookSpecificOutput:{hookEventName:"PostToolUse",updatedMCPToolOutput:r}}:{decision:"approve"}}],matcher:"mcp__playwright-test__.*"},{matcher:"mcp__playwright-test__test_run",hooks:[Ln({onResult:e=>C({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[On({onResult:e=>C({message:e})})]},...te?[{matcher:"Write",hooks:[Nn({onFileCreated:e=>k.push(e)})]}]:[],{matcher:"mcp__playwright-test__generator_setup_page",hooks:[Mn()]},{matcher:"mcp__playwright-test__planner_setup_page",hooks:[Mn()]}],re=q?[]:[{matcher:"mcp__playwright-test__browser_type",hooks:[Pn({envVars:p})]},{matcher:"mcp__playwright-test__generator_setup_page",hooks:[$n()]},{matcher:"mcp__playwright-test__planner_setup_page",hooks:[$n()]}],oe={...Y};V&&(oe.ANTHROPIC_API_KEY=V,oe.ANTHROPIC_BASE_URL=Ht),y=l.query({options:{tools:Q,allowedTools:Z,canUseTool:async(e,t)=>({behavior:"allow",updatedInput:t}),cwd:c,env:oe,hooks:{PostToolUse:ne,PreToolUse:re},includePartialMessages:!0,mcpServers:ee,model:process.env.STABLY_AGENT_MODEL??"claude-opus-4-5-20251101",permissionMode:"default",systemPrompt:G},prompt:m??M}),"init"===e.mode&&m&&m.pushText(M),T.current=async()=>{O();try{await(y?.interrupt?.())}catch{}q||(Hn(),jn()),m?.finish(),L()};try{for await(const e of y){if("stream_event"===e.type){const{event:t}=e;if("content_block_delta"===t?.type){const{delta:e}=t;"text_delta"===e?.type&&e.text&&x({text:e.text})}"message_stop"===t?.type&&m&&m.allowNextTurn();continue}if("assistant"===e.type){const{content:t}=e.message??{};if(Array.isArray(t))for(const e of t)if("tool_use"===e?.type){if(e.name.startsWith("mcp__session-control__"))continue;S({rawName:e.name,toolInput:e.input})}continue}if("result"!==e.type);else{if(f){if("success"===e.subtype){if(te&&k.length>0){U.default.green("Created files:");for(const e of k)U.default.green(`- ${e}`)}const e=j?U.default.cyan(`📊 View Autoheal Report:\n ${U.default.cyan(U.default.bold(U.default.underline(j)))}`):void 0;D({status:"success",result:e})}else w||(D({error:"Run failed.",status:"error"}),process.exitCode=1);w=!1;break}"success"!==e.subtype?w||(D({error:"Run failed.",status:"error"}),process.exitCode=1):D({status:"success"}),E=!1,w=!1,m?.allowNextTurn()}}}catch(e){w||(D({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1)}finally{E=!1,w=!1,process.off("uncaughtException",t),m?.finish(),q||(Hn(),await jn()),await(X?.cleanup()),await L()}};function Ir(e=process.cwd()){let t=n.resolve(e);for(;;){const e=wr(t);if(e){const r={...e.dependencies,...e.devDependencies},o="@playwright/test"in r?"@playwright/test":"playwright"in r?"playwright":void 0;if(o){const e=vr(t);let r=!1,s=t;for(;;){const e=n.join(s,"node_modules"),t=n.join(e,o);if(a.existsSync(t)){r=!0;break}const i=n.dirname(s);if(i===s)break;s=i}return{inNodeModules:r,installed:!0,packageManager:e,packageName:o}}}const r=n.dirname(t);if(r===t)return{inNodeModules:!1,installed:!1,packageManager:void 0};t=r}}function wr(e){const t=n.join(e,"package.json");let r;try{r=a.readFileSync(t,"utf-8")}catch{return}try{return JSON.parse(r)}catch{return}}function vr(e){const t=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];let r=e;for(;;){for(const[e,o]of t)if(a.existsSync(n.join(r,o)))return e;const e=n.dirname(r);if(e===r)return;r=e}}function Tr(e){if("npm"===e)return["npx","playwright"];if("pnpm"===e)return["pnpm","exec","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}var Rr=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}];function Sr(e){const[t,...n]=Tr(e),r=[t,...n.slice(0,-1)].join(" ");return(t,n)=>{let o=t.toString();for(const e of Rr)o=o.replaceAll(`${r} playwright ${e.name}`,`${r} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===e){const e=o.split("\n");return e.length>0&&e[0].includes("/.bin/playwright")&&e.shift(),void n.write(e.join("\n"))}n.write(o)}}function Cr(e=""){process.stdout.write(`${e}\n`)}function xr(...e){process.stderr.write(`${e.join(" ")}\n`)}var Ar="stably",Ur=`https://registry.npmjs.org/${Ar}/latest`,Pr=_.z.object({version:_.z.string()});function Lr(e){const t=e.match(/^(\d+)\.(\d+)\.(\d+)/);return t?{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10)}:null}function Or(e,t){const n=Lr(e),r=Lr(t);return!(!n||!r)&&(r.major>n.major||!(r.major<n.major)&&(r.minor>n.minor||!(r.minor<n.minor)&&r.patch>n.patch))}var Br=R.default.join(x.default.homedir(),".stably"),Nr=R.default.join(Br,"update-check.json"),Dr=`https://registry.npmjs.org/${Ar}/latest`,jr=_.z.object({lastCheck:_.z.number(),latestVersion:_.z.string()}),kr=!1;!function(){const e=function(){try{const e=A.default.readFileSync(Nr,"utf-8");return jr.parse(JSON.parse(e))}catch{return null}}(),t=Date.now();if((null==e||t-e.lastCheck>=18e5)&&function(){const e=`\n const https = require('https');\n const fs = require('fs');\n const url = '${Dr}';\n const cacheFile = ${JSON.stringify(Nr)};\n const cacheDir = ${JSON.stringify(Br)};\n\n const req = https.get(url, { timeout: 5000 }, (res) => {\n if (res.statusCode !== 200) process.exit(1);\n let data = '';\n res.on('data', (chunk) => data += chunk);\n res.on('end', () => {\n try {\n const version = JSON.parse(data).version;\n if (!fs.existsSync(cacheDir)) fs.mkdirSync(cacheDir, { recursive: true });\n fs.writeFileSync(cacheFile, JSON.stringify({ lastCheck: Date.now(), latestVersion: version }));\n } catch {}\n process.exit(0);\n });\n });\n req.on('error', () => process.exit(1));\n req.on('timeout', () => { req.destroy(); process.exit(1); });\n `;try{r.spawn(process.execPath,["-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&Or(jt,e.latestVersion)){if(kr)return;kr=!0;let t=!1;const n=()=>{if(t)return;t=!0;const n=`${U.default.yellow(`update available (${jt} → ${e.latestVersion})`)} - run \`${Ar} upgrade\` to get the latest version\n`;try{A.default.writeSync(2,n)}catch{}};process.once("beforeExit",n),process.once("exit",n)}}();var $r=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);-1!==$r&&process.argv[$r+1]&&(process.chdir(process.argv[$r+1]),process.argv.splice($r,2));var Mr=new e.Command;Mr.name("stably").description("AI-assisted Playwright testing CLI").version(jt),Mr.enablePositionalOptions(),Mr.showHelpAfterError(),Mr.exitOverride(),Mr.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}});var Hr=[];Mr.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{Hr.push(e)}});var Gr=()=>{const e=Mr.helpInformation().trimEnd();return e?`${e}\n`:""},Fr=(e,t)=>{let n=e;for(const e of t){const t=n.commands.find(t=>t.name()===e||t.aliases().includes(e));if(!t)return;n=t}return n},Yr=()=>{process.stdout.write(Gr())};Mr.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void Yr();const t=Fr(Mr,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),Yr(),void(process.exitCode=1);var n;n=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(n))}),Mr.action(()=>br({mode:"chat",getHelpText:Gr})),Mr.command("login").description("Authenticate with Stably in your browser").action(hn),Mr.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=mn();e&&(m.log.warn(`Environment variables ${U.default.cyan("STABLY_API_KEY")} and ${U.default.cyan("STABLY_PROJECT_ID")} are set.`),m.log.warn("They will continue to be used for authentication even after logout."),m.log.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await tn();if(!t)return void m.outro(e?U.default.yellow("No stored OAuth login found to clear."):U.default.yellow("You are not logged in."));const n=m.spinner();n.start("Logging out..."),await(async e=>{try{await fetch(`${$t}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await rn(),await an(),n.stop(U.default.green("✓ Logged out")),m.outro(U.default.green("You have been logged out successfully."))}),Mr.command("whoami").description("Show auth status and current project").action(async()=>{m.log.info(`${U.default.bold("CLI Version:")} ${U.default.cyan(jt)}`);const e=mn();if(e){m.log.info(U.default.dim("Authentication: Environment variables")),m.log.info(` ${U.default.bold("API Key:")} ${U.default.cyan(e.apiKey.slice(0,8))}...`),m.log.info(` ${U.default.bold("Project ID:")} ${U.default.cyan(e.projectId)}`);const t=await tn();if(t){let e;try{e=Wt(t.accessToken).email}catch{e=void 0}m.log.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&m.log.info(` ${U.default.bold("OAuth Email:")} ${U.default.cyan(e)}`),m.log.info(` ${U.default.bold("Tip:")} Unset env vars to use OAuth`)}return void m.outro(U.default.green("Authenticated via environment variables"))}const t=await tn();if(!t)return void m.outro(U.default.yellow("Not logged in. Run `stably login` to authenticate."));let n;try{n=Wt(t.accessToken).email}catch{n=void 0}const r=await sn();if(!r)return m.log.info(U.default.dim("Authentication: OAuth (not linked to a project)")),n&&m.log.info(` ${U.default.bold("Email:")} ${U.default.cyan(n)}`),void m.outro(U.default.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const o=await(async()=>on(process.cwd()))(),s=o?R.default.dirname(o):process.cwd(),i=R.default.relative(process.cwd(),s)||".";m.log.info(U.default.dim("Authentication: OAuth")),n&&m.log.info(` ${U.default.bold("Email:")} ${U.default.cyan(n)}`),m.log.info(` ${U.default.bold("Organization:")} ${U.default.cyan(r.orgName)}`),m.log.info(` ${U.default.bold("Project:")} ${U.default.cyan(r.projectName)}`),m.log.info(` ${U.default.bold("Linked at:")} ${U.default.dim(i)}`),m.outro(U.default.green("Authenticated"))}),Mr.command("tunnel",{hidden:!0}).description("Expose a local server with a secure tunnel URL").option("-p, --port <number>","Local port to expose","3000").action(async e=>{m.intro(`Starting development server for port ${e.port}...`);const t=await En(),n="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),r=m.spinner();r.start("Starting development server...");const o=await v.startTunnel(`http://localhost:${e.port}`,{subdomain:n});r.stop(`Your local environment is available at: ${U.default.underline(U.default.cyan(o.url))}`)}),Mr.command("create [prompt...]").description("Generate a test from prompt (omit prompt to infer from branch diff)").option("-o, --output <dir>","Output directory for generated test files").action((e,t)=>{const n=e.length>0&&"test"===e[0]?e.slice(1):e;return br({mode:"single",prompt:n,outputDir:t.output})}).command("test",{hidden:!0}).description("Generate a Playwright test from a prompt (deprecated: use `stably create <prompt>` directly)").argument("<prompt...>","Prompt describing the test to generate").option("-o, --output <dir>","Output directory for generated test files").action((e,t)=>br({mode:"single",prompt:e,outputDir:t.output})),Mr.command("fix [runId]").description("Fix failing tests from a run (auto-detects runId in CI)").action(e=>{const t=(e??function(){if(process.env.CI_BUILD_ID)return process.env.CI_BUILD_ID;const e=(({env:e=process.env,cwd:t=process.cwd()}={})=>{for(const n of Object.keys(ft))if(ft[n].detect({env:e,cwd:t}))return{isCi:!0,...ft[n].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(n={env:e,cwd:t},{commit:Me(n),branch:He(n)})};var n})();if(!e.isCi)return;const t=function(e){switch(e){case"github":return process.env.GITHUB_RUN_ATTEMPT;case"azure-devops":return process.env.SYSTEM_JOBATTEMPT;case"bitbucket":return process.env.BITBUCKET_STEP_RUN_NUMBER;default:return}}(e.service),n=[e.service,"slug"in e?e.slug:void 0,"build"in e?String(e.build):void 0,"job"in e?String(e.job):void 0,t&&String(t)].filter(Boolean);return n.length>0?n.join("-"):void 0}())?.replace(/\//g,"_");return t||(process.stderr.write("Run ID is required. Provide <runId>.\n"),process.exit(1)),br({mode:"fix",runId:t})}),Mr.command("init").description("Initialize Playwright and Stably SDK in your project").action(()=>br({mode:"init"})),Mr.command("upgrade").description("Upgrade to latest version (use --check to only check)").option("-c, --check","Only check for updates without upgrading").action(e=>async function(e){const{check:t=!1}=e;let n;Cr(U.default.cyan("Checking for updates...\n"));try{n=await async function(){const e=await async function(){const e=new AbortController,t=setTimeout(()=>e.abort(),1e4);t.unref();try{const t=await fetch(Ur,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return Pr.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:jt,latest:e,isOutdated:Or(jt,e)}}()}catch(e){return xr(U.default.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(Cr(`Current version: ${U.default.yellow(n.current)}`),Cr(`Latest version: ${U.default.green(n.latest)}`),Cr(),!n.isOutdated)return void Cr(U.default.green("✓ You are already on the latest version!"));if(Cr(U.default.yellow(`⚠ A new version is available: ${n.current} → ${n.latest}`)),Cr(),t)return Cr(U.default.dim("Exiting with code 1 to indicate update available (useful for CI).")),void(process.exitCode=1);const o=function(){const e=process.argv[1]||"";if(e.includes("_npx")||e.includes(".npm/_cacache"))return"npx";try{const t=r.execSync("npm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-npm"}catch{}if(e.includes("node_modules/stably"))return"global-npm";try{const t=r.execSync("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=r.execSync("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=r.execSync("yarn config get globalFolder",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-berry"}catch{}return"unknown"}(),s=function(e){switch(e){case"global-npm":case"global-yarn-berry":case"unknown":return{command:"npm",args:["install","-g",`${Ar}@latest`],description:`npm install -g ${Ar}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${Ar}@latest`],description:`pnpm add -g ${Ar}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${Ar}@latest`],description:`yarn global add ${Ar}@latest`};case"npx":return{command:"npx",args:[`${Ar}@latest`],description:`npx ${Ar}@latest (always uses latest)`}}}(o);if("npx"===o)return Cr(U.default.dim("You are running via npx, which always fetches the latest version.")),void Cr(U.default.dim(`Simply run: ${U.default.white("npx stably")} to use the latest version.`));"unknown"===o?(Cr(U.default.yellow("Could not detect installation method. Falling back to npm.")),Cr()):"global-yarn-berry"===o&&(Cr(U.default.yellow("Yarn Berry does not support global packages. Falling back to npm.")),Cr()),Cr(`Upgrade command: ${U.default.cyan(s.description)}`),Cr(),Cr(U.default.cyan("Upgrading...")),Cr();try{await(i=s.command,a=s.args,new Promise((e,t)=>{const n=r.spawn(i,a,{stdio:"inherit",shell:"win32"===process.platform});n.on("close",n=>{0===n?e():t(new Error(`Upgrade command exited with code ${n}`))}),n.on("error",e=>{t(e)})})),Cr(),Cr(U.default.green("✓ Upgrade complete!")),Cr(U.default.dim(`Run ${U.default.white("stably --version")} to verify.`))}catch(e){xr(U.default.red("Upgrade failed:"),e instanceof Error?e.message:e),Cr(),Cr(U.default.dim("You can try manually running:")),Cr(U.default.cyan(` ${s.description}`)),process.exitCode=1}var i,a}(e)),Rr.forEach(({args:e,description:t,name:o})=>{Mr.command(o).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>async function({overrideArgs:e,subcommand:t}){const o=process.argv,s=o.findIndex((e,n)=>n>1&&e===t),i=-1===s?[]:o.slice(s+1),c="--"===i[0],l=c?i.slice(1):i;if(!c&&("--help"===l[0]||"-h"===l[0]))return async function({subcommand:e}){const t=Rr.find(t=>t.name===e),n=e=>process.stdout.write(`${e}\n`);n(`stably ${e} - ${t?.description??""}`),n(""),"test"===e&&(n('IMPORTANT: Always use "stably" commands instead of "playwright" directly.'),n(""),n("Stably commands:"),n(" stably test [file] Run tests (auto-enables tracing and analytics)"),n(" stably fix [file] Auto-fix failing tests using AI"),n(" stably create <url> Generate new tests from a URL using AI"),n(""),n("Why use Stably?"),n(' - "stably fix" automatically repairs broken tests'),n(' - "stably test" enables --trace=on and test analytics'),n(' - "stably create" generates tests from prompt'),n(""));const o=Ir();if(!o.installed||!o.inNodeModules)return void n('No Playwright project found in this directory or its parents.\nMake sure you\'re in a directory within your Playwright project, or run "stably init" to create a new playwright directory.');const{packageManager:s}=o;if(!s)return void n("Could not determine package manager.");n("Playwright options:"),n("");const[i,...a]=Tr(s),c=Sr(s);return new Promise(t=>{const n=r.spawn(i,[...a,e,"--help"],{stdio:["inherit","pipe","pipe"],env:{...process.env,...process.env.CI?{}:{FORCE_COLOR:"1"}}});n.stdout?.on("data",e=>{c(e,process.stdout)}),n.stderr?.on("data",e=>{c(e,process.stderr)}),n.on("close",()=>{t()})})}({subcommand:t});const d=e??[],u=new Set(d.map(e=>{const[t]=e.split("=");return t})),p=[];for(let e=0;e<l.length;e++){const t=l[e],[n]=t.split("=");u.has(n)?!t.includes("=")&&e+1<l.length&&!l[e+1].startsWith("-")&&e++:p.push(t)}const f=[t,...d,...p],h="test"===t?await In():void 0,m="test"===t?function({forwardedArgs:e,hasCredentials:t}){if(!t)return console.warn("[33m⚠️ Stably credentials not found. Test results will not be reported to Stably.[0m"),console.warn("[33m To enable reporting, either:[0m"),console.warn("[33m • Run `npx stably login` to authenticate[0m"),void console.warn("[33m • Or set STABLY_API_KEY and STABLY_PROJECT_ID environment variables[0m\n");const o=process.cwd(),s=e=>{const t=function(e){let t=n.resolve(e);for(;;){if([n.join(t,"node_modules","@stablyai","playwright-test"),n.join(t,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>a.existsSync(e)))return!0;const e=n.dirname(t);if(e===t)return!1;t=e}}(e);return t||(console.warn("[33m⚠️ @stablyai/playwright-test is not installed. Stably reporter will not be injected.[0m"),console.warn("[33m Install it with: npm install @stablyai/playwright-test[0m"),console.warn("[33m Reference: https://docs.stably.ai/getting-started/sdk-setup-guide[0m\n")),t},i=(e,t)=>{try{return function({baseConfigPath:e,projectDir:t}){const o=function(e){try{const t=r.execSync("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return"module"===JSON.parse(t.trim())}catch{return!1}}(t),s=o?"mts":"ts",i=n.dirname(n.resolve(e)),c=n.basename(e),l=n.join(i,`.stably-playwright-wrapper.config.${s}`),d=`\n// Auto-generated wrapper config by Stably CLI\n// This file injects the Stably reporter and ensures trace is enabled\nimport baseConfig from './${c}';\nimport { defineConfig, stablyReporter } from '@stablyai/playwright-test';\n\n// Inline type definitions to avoid import failures when @stablyai/playwright-test is not installed\ntype StablyNotificationConfig = {\n email?: { to: string[]; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' | null } | null;\n slack?: { channelName: string; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' } | null;\n};\n\ntype ProjectNotificationConfig = {\n projectName: string;\n notifications: StablyNotificationConfig;\n};\n\n// Extract notification configs from projects that have stably.notifications defined\n// This runs at config-load time before Playwright strips custom properties\nconst extractNotificationConfigs = (): ProjectNotificationConfig[] | undefined => {\n const projects = baseConfig.projects;\n if (!projects || !Array.isArray(projects)) return undefined;\n\n const configs = projects\n .map((p: { name?: string; stably?: { notifications?: StablyNotificationConfig } }) => {\n const notifications = p.stably?.notifications;\n return notifications ? { projectName: p.name ?? '', notifications } : undefined;\n })\n .filter((config): config is ProjectNotificationConfig => config != null);\n\n return configs.length > 0 ? configs : undefined;\n};\n\nconst hasStablyReporter = (reporters: unknown): boolean => {\n if (!Array.isArray(reporters)) return false;\n return reporters.some((reporter) => {\n if (typeof reporter === 'string') {\n return reporter.includes('stablyai') || reporter.includes('stably');\n }\n if (Array.isArray(reporter) && typeof reporter[0] === 'string') {\n return reporter[0].includes('stablyai') || reporter[0].includes('stably');\n }\n return false;\n });\n};\n\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\n\n // If already has stably reporter, don't add another\n if (hasStablyReporter(existingReporters)) {\n return existingReporters;\n }\n\n // Create the stably reporter entry with notification configs\n const stablyReporterEntry = stablyReporter({\n apiKey: process.env.STABLY_API_KEY,\n projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n });\n\n // Merge with existing reporters\n if (!existingReporters) {\n return [stablyReporterEntry];\n }\n\n if (Array.isArray(existingReporters)) {\n return [...existingReporters, stablyReporterEntry];\n }\n\n // Single reporter as string - convert to tuple format [name, {}]\n return [[existingReporters, {}], stablyReporterEntry];\n};\n\nexport default defineConfig({\n ...baseConfig,\n use: {\n ...baseConfig.use,\n trace: 'on',\n },\n reporter: buildReporterList(),\n});\n`.trim();return a.existsSync(i)||a.mkdirSync(i,{recursive:!0}),a.writeFileSync(l,d,"utf-8"),function(e){const t=n.join(e,".gitignore");try{if(a.existsSync(t)){const e=a.readFileSync(t,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(Kn))return;const n=e.length>0&&!e.endsWith("\n");a.appendFileSync(t,`${n?"\n":""}${Kn}\n`)}else a.writeFileSync(t,`${Kn}\n`)}catch{}}(i),l}({baseConfigPath:e,projectDir:t})}catch{return void console.warn("[33m⚠️ Could not create Stably wrapper config. Reporter injection skipped.[0m")}};if(e.some(e=>"--config"===e||"-c"===e||e.startsWith("--config=")||e.startsWith("-c="))){const t=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==t&&e[t+1]){const r=n.resolve(o,e[t+1]),a=n.dirname(r);if(!s(a))return;const c=i(r,a);if(!c)return;return e[t+1]=c,c}const r=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==r){const t=n.resolve(o,e[r].split("=")[1]),a=n.dirname(t);if(!s(a))return;const c=i(t,a);if(!c)return;const l=e[r].startsWith("--config=")?"--config=":"-c=";return e[r]=`${l}${c}`,c}}const c=qn(o);if(!c)return;const l=n.dirname(c);if(!s(l))return;const d=i(c,l);return d?(e.push("--config",d),d):void 0}({forwardedArgs:f,hasCredentials:null!=h}):void 0;!function(e,t={}){const n=Ir();n.installed||(console.error('Playwright is not installed. Please run "stably init" to install it.'),process.exit(1)),n.inNodeModules||(console.error("Playwright is present in your project, but not in node_modules. Please install your dependencies before proceeding."),process.exit(1));const{packageManager:o}=n;o||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[s,...i]=Tr(o),a=bn(t.env),c=r.spawn(s,[...i,...e],{stdio:["inherit","pipe","pipe"],env:{...a,...process.env.CI?{}:{FORCE_COLOR:"1"}}}),l=Sr(o);c.stdout?.on("data",e=>{l(e,process.stdout)}),c.stderr?.on("data",e=>{l(e,process.stderr)});let d=!1;const u=()=>{d||(d=!0,t.onClose?.())};c.on("close",e=>{u(),process.exit(e??0)});const p=e=>{u(),c.kill(e);const t="SIGINT"===e?130:143;process.exit(t)};process.on("SIGINT",p),process.on("SIGTERM",p)}(f,{env:h,onClose:()=>{var e;(e=m)&&a.existsSync(e)&&a.rmSync(e)}})}({overrideArgs:e,subcommand:o}))});var zr=()=>{0!==Hr.length&&(process.stderr.write(Hr.join("")),Hr=[])};(async()=>{try{await Mr.parseAsync(process.argv)}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e))throw zr(),e;const t="number"==typeof e.exitCode?e.exitCode:1,n=process.argv.slice(2).find(e=>!e.startsWith("-")),r=!!n&&!!Fr(Mr,[n]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&n&&!r)return Hr=[],process.stderr.write(`command '${n}' not found\n`),Yr(),void(process.exitCode=t);zr(),process.exitCode=t}})();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "stably",
|
|
3
|
-
"version": "4.3.
|
|
3
|
+
"version": "4.3.8",
|
|
4
4
|
"packageManager": "pnpm@10.24.0",
|
|
5
5
|
"description": "AI-powered E2E Playwright testing CLI. Stably can understand your codebase, edit/run tests, and handle complex test scenarios for you.",
|
|
6
6
|
"main": "dist/index.js",
|