stably 4.6.1 → 4.6.2-rc.1
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 +7 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var e=require("dotenv"),t=require("path"),r=require("commander"),n=require("buffer"),s=require("child_process"),o=require("process"),i=require("fs"),a=require("url"),c=require("os");require("timers/promises");var l=require("stream"),u=require("util"),d=require("@anthropic-ai/claude-agent-sdk"),p=require("ts-pattern"),f=require("crypto"),h=require("picocolors"),g=require("simple-git"),m=require("fs/promises"),y=require("@clack/prompts"),b=require("readline/promises"),w=require("zod"),v=require("open"),_=require("http"),E=require("pino"),I=require("sonic-boom"),T=require("zod/v3"),x=require("ws"),S=require("react"),A=require("react/jsx-runtime"),C=require("module"),R=require("yaml"),P=require("@stablyhq/runner-sdk"),U="undefined"!=typeof document?document.currentScript:null;function k(e){return e&&e.__esModule?e:{default:e}}var L,D,O=k(t),B=k(s),N=k(o),$=k(i),j=k(c),M=k(l),F=k(f),H=k(h),G=k(m),z=k(w),Y=k(v),W=k(_),V=k(E),q=k(I),K=k(x),J=Object.create,X=Object.defineProperty,Q=Object.getOwnPropertyDescriptor,Z=Object.getOwnPropertyNames,ee=Object.getPrototypeOf,te=Object.prototype.hasOwnProperty,re=(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')}),ne=(L={"../playwright-trace-scrubber/node_modules/.pnpm/isbinaryfile@5.0.7/node_modules/isbinaryfile/lib/index.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.isBinaryFileSync=e.isBinaryFile=void 0;var t=re("fs"),r=re("util"),n=(0,r.promisify)(t.stat),s=(0,r.promisify)(t.open),o=(0,r.promisify)(t.close),i=class{fileBuffer;size;offset;error;constructor(e,t){this.fileBuffer=e,this.size=t,this.offset=0,this.error=!1}hasError(){return this.error}nextByte(){return this.offset===this.size||this.hasError()?(this.error=!0,255):this.fileBuffer[this.offset++]}next(e){const t=new Array;for(let r=0;r<e;r++){if(this.error)return t;t[r]=this.nextByte()}return t}};function a(e){let t=0,r=0;for(;!e.hasError();){const n=e.nextByte();if(r|=(127&n)<<7*t,!(128&n))break;if(t>=10){e.error=!0;break}t++}return r}function c(e){switch(7&a(e)){case 0:return a(e),!0;case 1:return e.next(8),!0;case 2:const t=a(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function l(e,t){if(0===t)return!1;let r=0;const n=Math.min(t,515),s=Math.min(n,512);if(t>=3&&239===e[0]&&187===e[1]&&191===e[2])return!1;if(t>=4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return!1;if(t>=4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return!1;if(t>=4&&132===e[0]&&49===e[1]&&149===e[2]&&51===e[3])return!1;if(n>=5&&"%PDF-"===e.slice(0,5).toString())return!0;if(t>=2&&254===e[0]&&255===e[1])return!1;if(t>=2&&255===e[0]&&254===e[1])return!1;for(let t=0;t<s;t++){if(0===e[t])return!0;if((e[t]<7||e[t]>14)&&(e[t]<32||e[t]>127)){if(e[t]>=192&&e[t]<=223&&t+1<n){if(t++,e[t]>=128&&e[t]<=191)continue}else if(e[t]>=224&&e[t]<=239&&t+2<n){if(t++,e[t]>=128&&e[t]<=191&&e[t+1]>=128&&e[t+1]<=191){t++;continue}}else if(e[t]>=240&&e[t]<=247&&t+3<n&&(t++,e[t]>=128&&e[t]<=191&&e[t+1]>=128&&e[t+1]<=191&&e[t+2]>=128&&e[t+2]<=191)){t+=2;continue}if(r++,t>=32&&100*r/s>10)return!0}}return 100*r/s>10||!!(r>1&&function(e,t){const r=new i(e,t);let n=0;for(;;){if(!c(r)&&!r.hasError())return!1;if(r.hasError())break;n++}return n>0}(e,s))}function u(e){return"string"==typeof e}function d(e){if(!e.isFile())throw new Error("Path provided was not a file!")}e.isBinaryFile=async function(e,r){if(u(e)){d(await n(e));const r=await s(e,"r"),i=Buffer.alloc(515);return new Promise((e,n)=>{t.read(r,i,0,515,0,(t,s,a)=>{if(o(r),t)n(t);else try{e(l(i,s))}catch(e){n(e)}})})}return void 0===r&&(r=e.length),l(e,r)},e.isBinaryFileSync=function(e,r){if(u(e)){d(t.statSync(e));const r=t.openSync(e,"r"),n=Buffer.alloc(515),s=t.readSync(r,n,0,515,0);return t.closeSync(r),l(n,s)}return void 0===r&&(r=e.length),l(e,r)}}},function(){return D||(0,L[Z(L)[0]])((D={exports:{}}).exports,D),D.exports}),se={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[]},oe=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);if(-1!==oe&&process.argv[oe+1]){const e=process.argv[oe+1];process.chdir(e),se.cwdChanged=!0,se.newCwd=e,process.argv.splice(oe,2)}for(var ie=[],ae=0;ae<process.argv.length;)if("--env-file"===process.argv[ae]){const e=process.argv[ae+1];e&&!e.startsWith("-")?(ie.push(e),process.argv.splice(ae,2)):ae++}else ae++;for(const t of ie){const r=O.default.resolve(process.cwd(),t),n=e.config({path:r,override:!0,quiet:!0});if(n.error){const e=`warning: could not load env file: ${r} (${n.error.message})`;se.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else se.envFilesLoaded.push(r)}var ce={detect:({env:e})=>Boolean(e.APPVEYOR),configuration({env:e}){const t=e.APPVEYOR_PULL_REQUEST_NUMBER,r=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:r,prBranch:e.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH,slug:e.APPVEYOR_REPO_NAME,root:e.APPVEYOR_BUILD_FOLDER}}};function le(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function ue(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var de={detect:({env:e})=>Boolean(e.BUILD_BUILDURI),configuration({env:e}){const t=e.SYSTEM_PULLREQUEST_PULLREQUESTID,r=Boolean(t);return{name:"Azure Pipelines",service:"azurePipelines",commit:e.BUILD_SOURCEVERSION,build:e.BUILD_BUILDNUMBER,branch:ue(r?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:r,prBranch:ue(r?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},pe={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})},fe={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})},he={detect:({env:e})=>Boolean(e.BITRISE_IO),configuration({env:e}){const t="false"===e.BITRISE_PULL_REQUEST?void 0:e.BITRISE_PULL_REQUEST,r=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:r?e.BITRISEIO_GIT_BRANCH_DEST:e.BITRISE_GIT_BRANCH,pr:t,isPr:r,prBranch:r?e.BITRISE_GIT_BRANCH:void 0,slug:e.BITRISE_APP_SLUG}}},ge={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=le(e.BUDDY_EXECUTION_PULL_REQUEST_ID),r=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:r?e.BUDDY_EXECUTION_PULL_REQUEST_HEAD_BRANCH:e.BUDDY_EXECUTION_BRANCH,pr:t,isPr:r,slug:e.BUDDY_REPO_SLUG}}},me="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function ye(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var be,we,ve,_e,Ee,Ie,Te,xe,Se={exports:{}};var Ae,Ce,Re,Pe,Ue,ke,Le,De,Oe,Be,Ne,$e,je,Me,Fe,He={exports:{}},Ge={};function ze(){if($e)return Ne;$e=1;const e=O.default,t=function(){if(Re)return Ce;Re=1;const e=O.default,t=function(){if(xe)return Te;xe=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=O.default,r=e?";":":",n=function(){if(Ie)return Ee;var e;function t(r,n,s){if("function"==typeof n&&(s=n,n={}),!s){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,s){t(r,n||{},function(t,r){t?s(t):e(r)})})}e(r,n||{},function(e,t){e&&("EACCES"===e.code||n&&n.ignoreErrors)&&(e=null,t=!1),s(e,t)})}return Ie=1,e="win32"===process.platform||me.TESTING_WINDOWS?function(){if(we)return be;we=1,be=r,r.sync=function(r,n){return t(e.statSync(r),r,n)};var e=$.default;function t(e,t,r){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var r=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!r)return!0;if(-1!==(r=r.split(";")).indexOf(""))return!0;for(var n=0;n<r.length;n++){var s=r[n].toLowerCase();if(s&&e.substr(-s.length).toLowerCase()===s)return!0}return!1}(t,r)}function r(r,n,s){e.stat(r,function(e,o){s(e,!e&&t(o,r,n))})}return be}():function(){if(_e)return ve;_e=1,ve=t,t.sync=function(t,n){return r(e.statSync(t),n)};var e=$.default;function t(t,n,s){e.stat(t,function(e,t){s(e,!e&&r(t,n))})}function r(e,t){return e.isFile()&&function(e,t){var r=e.mode,n=e.uid,s=e.gid,o=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 r&parseInt("001",8)||r&c&&s===i||r&a&&n===o||r&(a|c)&&0===o}(e,t)}return ve}(),Ee=t,t.sync=function(t,r){try{return e.sync(t,r||{})}catch(e){if(r&&r.ignoreErrors||"EACCES"===e.code)return!1;throw e}},Ee}(),s=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),o=(t,n)=>{const s=n.colon||r,o=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(n.path||process.env.PATH||"").split(s)],i=e?n.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?i.split(s):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:o,pathExt:a,pathExtExe:i}},i=(e,r,i)=>{"function"==typeof r&&(i=r,r={}),r||(r={});const{pathEnv:a,pathExt:c,pathExtExe:l}=o(e,r),u=[],d=n=>new Promise((o,i)=>{if(n===a.length)return r.all&&u.length?o(u):i(s(e));const c=a[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,d=t.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;o(p(f,n,0))}),p=(e,t,s)=>new Promise((o,i)=>{if(s===c.length)return o(d(t+1));const a=c[s];n(e+a,{pathExt:l},(n,i)=>{if(!n&&i){if(!r.all)return o(e+a);u.push(e+a)}return o(p(e,t,s+1))})});return i?d(0).then(e=>i(null,e),i):d(0)};return Te=i,i.sync=(e,r)=>{r=r||{};const{pathEnv:i,pathExt:a,pathExtExe:c}=o(e,r),l=[];for(let s=0;s<i.length;s++){const o=i[s],u=/^".*"$/.test(o)?o.slice(1,-1):o,d=t.join(u,e),p=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<a.length;e++){const t=p+a[e];try{if(n.sync(t,{pathExt:c})){if(!r.all)return t;l.push(t)}}catch(e){}}}if(r.all&&l.length)return l;if(r.nothrow)return null;throw s(e)},Te}(),r=function(){if(Ae)return He.exports;Ae=1;const e=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};return He.exports=e,He.exports.default=e,He.exports}();function n(n,s){const o=n.options.env||process.env,i=process.cwd(),a=null!=n.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(n.options.cwd)}catch(e){}let l;try{l=t.sync(n.command,{path:o[r({env:o})],pathExt:s?e.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=e.resolve(a?n.options.cwd:"",l)),l}return Ce=function(e){return n(e)||n(e,!0)}}(),r=function(){if(Pe)return Ge;Pe=1;const e=/([()\][%!^"`<>&|;, *?])/g;return Ge.command=function(t){return t.replace(e,"^$1")},Ge.argument=function(t,r){return t=(t=`"${t=(t=(t=`${t}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(e,"^$1"),r&&(t=t.replace(e,"^$1")),t},Ge}(),n=function(){if(Be)return Oe;Be=1;const e=$.default,t=function(){if(De)return Le;De=1;const e=ke?Ue:(ke=1,Ue=/^#!(.*)/);return Le=(t="")=>{const r=t.match(e);if(!r)return null;const[n,s]=r[0].replace(/#! ?/,"").split(" "),o=n.split("/").pop();return"env"===o?s:s?`${o} ${s}`:o}}();return Oe=function(r){const n=Buffer.alloc(150);let s;try{s=e.openSync(r,"r"),e.readSync(s,n,0,150,0),e.closeSync(s)}catch(e){}return t(n.toString())},Oe}(),s="win32"===process.platform,o=/\.(?:com|exe)$/i,i=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;return Ne=function(a,c,l){c&&!Array.isArray(c)&&(l=c,c=null);const u={command:a,args:c=c?c.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:a,args:c}};return l.shell?u:function(a){if(!s)return a;const c=function(e){e.file=t(e);const r=e.file&&n(e.file);return r?(e.args.unshift(e.file),e.command=r,t(e)):e.file}(a),l=!o.test(c);if(a.options.forceShell||l){const t=i.test(c);a.command=e.normalize(a.command),a.command=r.command(a.command),a.args=a.args.map(e=>r.argument(e,t));const n=[a.command].concat(a.args).join(" ");a.args=["/d","/s","/c",`"${n}"`],a.command=process.env.comspec||"cmd.exe",a.options.windowsVerbatimArguments=!0}return a}(u)}}var Ye=ye(function(){if(Fe)return Se.exports;Fe=1;const e=B.default,t=ze(),r=function(){if(Me)return je;Me=1;const e="win32"===process.platform;function t(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 r(r,n){return e&&1===r&&!n.file?t(n.original,"spawn"):null}return je={hookChildProcess:function(t,n){if(!e)return;const s=t.emit;t.emit=function(e,o){if("exit"===e){const e=r(o,n);if(e)return s.call(t,"error",e)}return s.apply(t,arguments)}},verifyENOENT:r,verifyENOENTSync:function(r,n){return e&&1===r&&!n.file?t(n.original,"spawnSync"):null},notFoundError:t},je}();function n(n,s,o){const i=t(n,s,o),a=e.spawn(i.command,i.args,i.options);return r.hookChildProcess(a,i),a}return Se.exports=n,Se.exports.spawn=n,Se.exports.sync=function(n,s,o){const i=t(n,s,o),a=e.spawnSync(i.command,i.args,i.options);return a.error=a.error||r.verifyENOENTSync(a.status,i),a},Se.exports._parse=t,Se.exports._enoent=r,Se.exports}());function We(e={}){const{env:t=process.env,platform:r=process.platform}=e;return"win32"!==r?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"}var Ve=(e,t)=>({name:`SIGRT${t+1}`,number:qe+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),qe=34,Ke=[{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"}],Je=()=>{const e=(()=>{const e=64-qe+1;return Array.from({length:e},Ve)})();return[...Ke,...e].map(Xe)},Xe=({name:e,number:t,description:r,action:n,forced:s=!1,standard:o})=>{const{signals:{[e]:i}}=c.constants,a=void 0!==i;return{name:e,number:a?i:t,description:r,supported:a,action:n,forced:s,standard:o}},Qe=({name:e,number:t,description:r,supported:n,action:s,forced:o,standard:i})=>[e,{name:e,number:t,description:r,supported:n,action:s,forced:o,standard:i}],Ze=(()=>{const e=Je();return Object.fromEntries(e.map(Qe))})();(()=>{const e=Je(),t=Array.from({length:65},(t,r)=>((e,t)=>{const r=((e,t)=>{const r=t.find(({name:t})=>c.constants.signals[t]===e);return void 0!==r?r:t.find(t=>t.number===e)})(e,t);if(void 0===r)return{};const{name:n,description:s,supported:o,action:i,forced:a,standard:l}=r;return{[e]:{name:n,number:e,description:s,supported:o,action:i,forced:a,standard:l}}})(r,e));Object.assign({},...t)})();var et=({stdout:e,stderr:t,all:r,error:n,signal:s,exitCode:o,command:i,escapedCommand:a,timedOut:c,isCanceled:l,killed:u,parsed:{options:{timeout:d,cwd:p=N.default.cwd()}}})=>{o=null===o?void 0:o;const f=void 0===(s=null===s?void 0:s)?void 0:Ze[s].description,h=(({timedOut:e,timeout:t,errorCode:r,signal:n,signalDescription:s,exitCode:o,isCanceled:i})=>e?`timed out after ${t} milliseconds`:void 0!==r?`failed with ${r}`:void 0!==n?`was killed with ${n} (${s})`:void 0!==o?`failed with exit code ${o}`:"failed")({timedOut:c,timeout:d,errorCode:n&&n.code,signal:s,signalDescription:f,exitCode:o,isCanceled:l}),g=`Command ${h}: ${i}`,m="[object Error]"===Object.prototype.toString.call(n),y=m?`${g}\n${n.message}`:g,b=[y,t,e].filter(Boolean).join("\n");return m?(n.originalMessage=n.message,n.message=b):n=new Error(b),n.shortMessage=y,n.command=i,n.escapedCommand=a,n.exitCode=o,n.signal=s,n.signalDescription=f,n.stdout=e,n.stderr=t,n.cwd=p,void 0!==r&&(n.all=r),"bufferedData"in n&&delete n.bufferedData,n.failed=!0,n.timedOut=Boolean(c),n.isCanceled=l,n.killed=u&&!c,n},tt=["stdin","stdout","stderr"],rt=[];rt.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&rt.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&rt.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var nt,st,ot=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,it=Symbol.for("signal-exit emitter"),at=globalThis,ct=Object.defineProperty.bind(Object),lt=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(at[it])return at[it];ct(at,it,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const r=this.listeners[e],n=r.indexOf(t);-1!==n&&(0===n&&1===r.length?r.length=0:r.splice(n,1))}emit(e,t,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(const s of this.listeners[e])n=!0===s(t,r)||n;return"exit"===e&&(n=this.emit("afterExit",t,r)||n),n}},ut=class{},dt=globalThis.process;ot(dt)?new class extends ut{#e="win32"===dt.platform?"SIGINT":"SIGHUP";#t=new lt;#r;#n;#s;#o={};#i=!1;constructor(e){super(),this.#r=e,this.#o={};for(const t of rt)this.#o[t]=()=>{const r=this.#r.listeners(t);let{count:n}=this.#t;const s=e;if("object"==typeof s.__signal_exit_emitter__&&"number"==typeof s.__signal_exit_emitter__.count&&(n+=s.__signal_exit_emitter__.count),r.length===n){this.unload();const r=this.#t.emit("exit",null,t),n="SIGHUP"===t?this.#e:t;r||e.kill(e.pid,n)}};this.#s=e.reallyExit,this.#n=e.emit}onExit(e,t){if(!ot(this.#r))return()=>{};!1===this.#i&&this.load();const r=t?.alwaysLast?"afterExit":"exit";return this.#t.on(r,e),()=>{this.#t.removeListener(r,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 rt)try{const t=this.#o[e];t&&this.#r.on(e,t)}catch(e){}this.#r.emit=(e,...t)=>this.#a(e,...t),this.#r.reallyExit=e=>this.#c(e)}}unload(){this.#i&&(this.#i=!1,rt.forEach(e=>{const t=this.#o[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#r.removeListener(e,t)}catch(e){}}),this.#r.emit=this.#n,this.#r.reallyExit=this.#s,this.#t.count-=1)}#c(e){return ot(this.#r)?(this.#r.exitCode=e||0,this.#t.emit("exit",this.#r.exitCode,null),this.#s.call(this.#r,this.#r.exitCode)):0}#a(e,...t){const r=this.#n;if("exit"===e&&ot(this.#r)){"number"==typeof t[0]&&(this.#r.exitCode=t[0]);const n=r.call(this.#r,e,...t);return this.#t.emit("exit",this.#r.exitCode,null),n}return r.call(this.#r,e,...t)}}(dt):new class extends ut{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if(st)return nt;st=1;const{PassThrough:e}=M.default;nt=function(){var t=[],r=new e({objectMode:!0});return r.setMaxListeners(0),r.add=n,r.isEmpty=function(){return 0==t.length},r.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(n),r;function n(e){return Array.isArray(e)?(e.forEach(n),this):(t.push(e),e.once("end",s.bind(null,e)),e.once("error",r.emit.bind(r,"error")),e.pipe(r,{end:!1}),this)}function s(e){!(t=t.filter(function(t){return t!==e})).length&&r.readable&&r.end()}}}();var pt=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(pt,e)]);var ft=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],ht=/^[\w.-]+$/,gt=u.debuglog("execa").enabled,mt=(e,t)=>String(e).padStart(t,"0"),yt=(e,t,r={})=>{const n=Ye._parse(e,t,r);return e=n.command,t=n.args,(r={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(r=n.options).cwd||N.default.cwd(),execPath:N.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:gt,...r}).env=(({env:e,extendEnv:t,preferLocal:r,localDir:n,execPath:s})=>{const o=t?{...N.default.env,...e}:e;return r?(({env:e=N.default.env,...t}={})=>{const r=We({env:e={...e}});return t.path=e[r],e[r]=(({cwd:e=N.default.cwd(),path:t=N.default.env[We()],preferLocal:r=!0,execPath:n=N.default.execPath,addExecPath:s=!0}={})=>{const o=e instanceof URL?a.fileURLToPath(e):e,i=O.default.resolve(o),c=[];return r&&((e,t)=>{let r;for(;r!==t;)e.push(O.default.join(t,"node_modules/.bin")),r=t,t=O.default.resolve(t,"..")})(c,i),s&&((e,t,r)=>{const n=t instanceof URL?a.fileURLToPath(t):t;e.push(O.default.resolve(r,n,".."))})(c,n,i),[...c,t].join(O.default.delimiter)})(t),e})({env:o,cwd:n,execPath:s}):o})(r),r.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return tt.map(t=>e[t]);if((e=>tt.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${tt.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 r=Math.max(t.length,tt.length);return Array.from({length:r},(e,r)=>t[r])})(r),"win32"===N.default.platform&&"cmd"===O.default.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:r,parsed:n}},bt=(e,t,r)=>"string"==typeof t||n.Buffer.isBuffer(t)?e.stripFinalNewline?function(e){const t="string"==typeof e?"\n":"\n".charCodeAt(),r="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===r&&(e=e.slice(0,-1)),e}(t):t:void 0===r?void 0:"";function wt(e,t,r){const n=yt(e,t,r),s=((e,t)=>ft(e,t).join(" "))(e,t),o=((e,t)=>ft(e,t).map(e=>(e=>"string"!=typeof e||ht.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&N.default.stderr.write(`[${(()=>{const e=new Date;return`${mt(e.getHours(),2)}:${mt(e.getMinutes(),2)}:${mt(e.getSeconds(),2)}.${mt(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(o,n.options);const a=(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),i.readFileSync(t)))(e);if(null!==(r=t)&&"object"==typeof r&&"function"==typeof r.pipe)throw new TypeError("The `input` option cannot be a stream in sync mode");var r;return t})(n.options);let c;try{c=B.default.spawnSync(n.file,n.args,{...n.options,input:a})}catch(e){throw et({error:e,stdout:"",stderr:"",all:"",command:s,escapedCommand:o,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const l=bt(n.options,c.stdout,c.error),u=bt(n.options,c.stderr,c.error);if(c.error||0!==c.status||null!==c.signal){const e=et({stdout:l,stderr:u,error:c.error,signal:c.signal,exitCode:c.status,command:s,escapedCommand:o,parsed:n,timedOut:c.error&&"ETIMEDOUT"===c.error.code,isCanceled:!1,killed:null!==c.signal});if(!n.options.reject)return e;throw e}return{command:s,escapedCommand:o,exitCode:0,stdout:l,stderr:u,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function vt(e){try{return wt("git",["rev-parse","HEAD"],e).stdout}catch{return}}function _t(e){try{const t=wt("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=wt("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 Et=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,It=/^\/(.*)\.git$/;function Tt(e){if(e){if(e.match(Et))return e.replace(Et,"$1");try{return new URL(e).pathname.replace(It,"$1")}catch{return}}}var xt,St={detect:({env:e})=>Boolean(e.BUILDKITE),configuration({env:e}){const t="false"===e.BUILDKITE_PULL_REQUEST?void 0:e.BUILDKITE_PULL_REQUEST,r=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:r?e.BUILDKITE_PULL_REQUEST_BASE_BRANCH:e.BUILDKITE_BRANCH,slug:Tt(e.BUILDKITE_REPO),pr:t,isPr:r,prBranch:r?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},At={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||le(e.CIRCLE_PULL_REQUEST||e.CI_PULL_REQUEST),r=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:r?void 0:e.CIRCLE_BRANCH,pr:t,isPr:r,prBranch:r?e.CIRCLE_BRANCH:void 0,slug:`${e.CIRCLE_PROJECT_USERNAME}/${e.CIRCLE_PROJECT_REPONAME}`}}},Ct="https://cirrus-ci.com",Rt={detect:({env:e})=>Boolean(e.CIRRUS_CI),configuration({env:e}){const t=e.CIRRUS_PR,r=Boolean(t);return{name:"Cirrus CI",service:"cirrus",commit:e.CIRRUS_CHANGE_IN_REPO,tag:e.CIRRUS_TAG,build:e.CIRRUS_BUILD_ID,buildUrl:`${Ct}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${Ct}/task/${e.CIRRUS_TASK_ID}`,branch:r?e.CIRRUS_BASE_BRANCH:e.CIRRUS_BRANCH,pr:t,isPr:r,prBranch:r?e.CIRRUS_BRANCH:void 0,slug:e.CIRRUS_REPO_FULL_NAME,root:e.CIRRUS_WORKING_DIR}}},Pt={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:vt({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:_t({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})},Ut={detect:({env:e})=>Boolean(e.CF_BUILD_ID),configuration({env:e}){const t=e.CF_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Codefresh",service:"codefresh",commit:e.CF_REVISION,build:e.CF_BUILD_ID,buildUrl:e.CF_BUILD_URL,branch:r?e.CF_PULL_REQUEST_TARGET:e.CF_BRANCH,pr:t,isPr:r,prBranch:r?e.CF_BRANCH:void 0,slug:`${e.CF_REPO_OWNER}/${e.CF_REPO_NAME}`,root:e.CF_VOLUME_PATH}}},kt={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}}},Lt=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(i.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?ue(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},Dt={detect:({env:e})=>Boolean(e.GITHUB_ACTIONS),configuration({env:e,cwd:t}){const r="pull_request"===e.GITHUB_EVENT_NAME||"pull_request_target"===e.GITHUB_EVENT_NAME,n=ue("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(i.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:r,branch:n,prBranch:r?n:void 0,slug:e.GITHUB_REPOSITORY,root:e.GITHUB_WORKSPACE,...r?Lt({env:e}):void 0}}},Ot={detect:({env:e})=>Boolean(e.GITLAB_CI),configuration({env:e}){const t=e.CI_MERGE_REQUEST_ID,r=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:r?e.CI_MERGE_REQUEST_TARGET_BRANCH_NAME:e.CI_COMMIT_REF_NAME,pr:t,isPr:r,prBranch:e.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,slug:e.CI_PROJECT_PATH,root:e.CI_PROJECT_DIR}}},Bt={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const r=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,n=Boolean(r),s=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||vt({env:e,cwd:t}),branch:n?e.ghprbTargetBranch||e.gitlabTargetBranch:s,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,root:e.WORKSPACE,pr:r,isPr:n,prBranch:n?e.ghprbSourceBranch||e.gitlabSourceBranch||s: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}}},$t={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})},jt={detect:({env:e})=>Boolean(e.SAILCI),configuration({env:e}){const t=e.SAIL_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Sail CI",service:"sail",commit:e.SAIL_COMMIT_SHA,branch:r?void 0:e.SAIL_COMMIT_BRANCH,pr:t,isPr:r,slug:`${e.SAIL_REPO_OWNER}/${e.SAIL_REPO_NAME}`,root:e.SAIL_CLONE_DIR}}},Mt={detect:({env:e})=>Boolean(e.SCREWDRIVER),configuration({env:e}){const t=e.SD_PULL_REQUEST,r=Boolean(t);return{name:"Screwdriver.cd",service:"screwdriver",branch:r?e.PR_BASE_BRANCH_NAME:e.GIT_BRANCH,prBranch:r?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:r,slug:e.SD_PIPELINE_NAME,root:e.SD_ROOT_DIR}}},Ft={detect:({env:e})=>Boolean(e.SCRUTINIZER),configuration({env:e}){const t=e.SCRUTINIZER_PR_NUMBER,r=Boolean(t);return{name:"Scrutinizer",service:"scrutinizer",commit:e.SCRUTINIZER_SHA1,build:e.SCRUTINIZER_INSPECTION_UUID,branch:e.SCRUTINIZER_BRANCH,pr:t,isPr:r,prBranch:e.SCRUTINIZER_PR_SOURCE_BRANCH}}},Ht={detect:({env:e})=>Boolean(e.SEMAPHORE),configuration({env:e,cwd:t}){const r=e.SEMAPHORE_GIT_PR_NUMBER||e.PULL_REQUEST_NUMBER,n=Boolean(r);return{name:"Semaphore",service:"semaphore",commit:e.SEMAPHORE_GIT_SHA||vt({env:e,cwd:t}),tag:e.SEMAPHORE_GIT_TAG_NAME,build:e.SEMAPHORE_JOB_ID||e.SEMAPHORE_BUILD_NUMBER,branch:e.SEMAPHORE_GIT_BRANCH||(n?void 0:e.BRANCH_NAME),pr:r,isPr:n,prBranch:e.SEMAPHORE_GIT_PR_BRANCH||(n?e.BRANCH_NAME:void 0),slug:e.SEMAPHORE_GIT_REPO_SLUG||e.SEMAPHORE_REPO_SLUG,root:e.SEMAPHORE_GIT_DIR||e.SEMAPHORE_PROJECT_DIR}}},Gt={detect:({env:e})=>Boolean(e.SHIPPABLE),configuration({env:e}){const t="true"===e.IS_PULL_REQUEST?e.PULL_REQUEST:void 0,r=Boolean(t);return{name:"Shippable",service:"shippable",commit:e.COMMIT,tag:e.GIT_TAG_NAME,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,branch:r?e.BASE_BRANCH:e.BRANCH,job:e.JOB_NUMBER,pr:t,isPr:r,prBranch:r?e.HEAD_BRANCH:void 0,slug:e.SHIPPABLE_REPO_SLUG,root:e.SHIPPABLE_BUILD_DIR}}},zt={};function Yt(){if(xt)return zt;xt=1,Object.defineProperty(zt,"__esModule",{value:!0}),zt.of=zt.PropertiesFile=void 0;var e,t=(e=$.default)&&e.__esModule?e:{default:e};class r{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),r=Math.min(...t),n=e.substring(0,r).trim(),s=e.substring(r+1).trim();if(this.objs.hasOwnProperty(n))if(Array.isArray(this.objs[n]))this.objs[n].push(s);else{let e=this.objs[n];this.objs[n]=[e,s]}else{const e=s.replace(/"/g,'\\"').replace(/\\:/g,":").replace(/\\=/g,"=");this.objs[n]=unescape(JSON.parse('"'+e+'"'))}}}addFile(e){let r=t.default.readFileSync(e,"utf-8").split(/\r?\n/),n=this;for(let e=0;e<r.length;e++){let t=r[e];for(;"\\"===t.substring(t.length-1);)t=t.slice(0,-1),t+=r[e+1].trim(),e++;n.makeKeys(t)}}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 r=0;r<this.objs[e].length;r++)t[r]=this.interpolate(this.objs[e][r]);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 r=this.objs[e].length;return this.interpolate(this.objs[e][r-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 r=this.getLast(e);return r?parseInt(r,10):t}getFloat(e,t){let r=this.getLast(e);return r?parseFloat(r):t}getBoolean(e,t){let r=this.getLast(e);return r?!/^(false|0)$/i.test(n=r)&&!!n:t||!1;var n}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 r in this.objs)-1!==r.search(e)&&t.push(r);return t}reset(){this.objs={}}}return zt.PropertiesFile=r,zt.of=function(...e){let t=new r;return t.of.apply(t,e),t},zt}var Wt=ye(Yt()),Vt={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},qt=e=>{try{return Wt.of(e)}catch{return}},Kt=({env:e,cwd:t})=>{const r=e.TEAMCITY_BUILD_PROPERTIES_FILE?qt(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,n=r?r.get("teamcity.configuration.properties.file"):void 0,s=n?qt(n):n;return Object.fromEntries(Object.keys(Vt).map(n=>[n,(r?r.get(Vt[n]):void 0)||(s?s.get(Vt[n]):void 0)||("branch"===n?_t({env:e,cwd:t}):void 0)]))},Jt={appveyor:ce,azurePipelines:de,bamboo:pe,bitbucket:fe,bitrise:he,buddy:ge,buildkite:St,circleci:At,cirrus:Rt,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:Pt,codefresh:Ut,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:kt,github:Dt,gitlab:Ot,jenkins:Bt,netlify:Nt,puppet:$t,sail:jt,screwdriver:Mt,scrutinizer:Ft,semaphore:Ht,shippable:Gt,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,...Kt({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,r=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:r,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",r="vercel";return e.VERCEL?{name:t,service:r,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:r,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,r=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:ue(e.JB_SPACE_GIT_BRANCH),slug:t&&r?`${t.toLowerCase()}/${r}`:void 0}}}},Xt=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=g.simpleGit({baseDir:e.workingDir,maxConcurrentProcesses:1})}static createLocal({workingDir:t}){return new e({mode:"local",workingDir:t})}static createCloud({workingDir:t,baseBranch:r}){return new e({mode:"cloud",workingDir:t,baseBranch:r})}async captureSnapshot(){if("local"!==this.config.mode)return;this.snapshotIndexPath=t.join(c.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=t.join(c.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 Qt(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 Qt(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function Qt(e){try{await m.unlink(e)}catch{}}var Zt="x-stably-org-id",er={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},tr=({allowReserved:e,explode:t,name:r,style:n,value:s})=>{if(!t){const t=(e?s:s.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(n));switch(n){case"label":return`.${t}`;case"matrix":return`;${r}=${t}`;case"simple":return t;default:return`${r}=${t}`}}const o=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),i=s.map(t=>"label"===n||"simple"===n?e?t:encodeURIComponent(t):rr({allowReserved:e,name:r,value:t})).join(o);return"label"===n||"matrix"===n?o+i:i},rr=({allowReserved:e,name:t,value:r})=>{if(null==r)return"";if("object"==typeof r)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?r:encodeURIComponent(r)}`},nr=({allowReserved:e,explode:t,name:r,style:n,value:s,valueOnly:o})=>{if(s instanceof Date)return o?s.toISOString():`${r}=${s.toISOString()}`;if("deepObject"!==n&&!t){let t=[];Object.entries(s).forEach(([r,n])=>{t=[...t,r,e?n:encodeURIComponent(n)]});const o=t.join(",");switch(n){case"form":return`${r}=${o}`;case"label":return`.${o}`;case"matrix":return`;${r}=${o}`;default:return o}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),a=Object.entries(s).map(([t,s])=>rr({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:s})).join(i);return"label"===n||"matrix"===n?i+a:a},sr=/\{[^{}]+\}/g;function or(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 ir,ar=async(e,t)=>{const r="function"==typeof t?await t(e):t;if(r)return"bearer"===e.scheme?`Bearer ${r}`:"basic"===e.scheme?`Basic ${btoa(r)}`:r},cr=({parameters:e={},...t}={})=>r=>{const n=[];if(r&&"object"==typeof r)for(const s in r){const o=r[s];if(null==o)continue;const i=e[s]||t;if(Array.isArray(o)){const e=tr({allowReserved:i.allowReserved,explode:!0,name:s,style:"form",value:o,...i.array});e&&n.push(e)}else if("object"==typeof o){const e=nr({allowReserved:i.allowReserved,explode:!0,name:s,style:"deepObject",value:o,...i.object});e&&n.push(e)}else{const e=rr({allowReserved:i.allowReserved,name:s,value:o});e&&n.push(e)}}return n.join("&")},lr=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),ur=e=>(({baseUrl:e,path:t,query:r,querySerializer:n,url:s})=>{let o=(e??"")+(s.startsWith("/")?s:`/${s}`);t&&(o=(({path:e,url:t})=>{let r=t;const n=t.match(sr);if(n)for(const t of n){let n=!1,s=t.substring(1,t.length-1),o="simple";s.endsWith("*")&&(n=!0,s=s.substring(0,s.length-1)),s.startsWith(".")?(s=s.substring(1),o="label"):s.startsWith(";")&&(s=s.substring(1),o="matrix");const i=e[s];if(null==i)continue;if(Array.isArray(i)){r=r.replace(t,tr({explode:n,name:s,style:o,value:i}));continue}if("object"==typeof i){r=r.replace(t,nr({explode:n,name:s,style:o,value:i,valueOnly:!0}));continue}if("matrix"===o){r=r.replace(t,`;${rr({name:s,value:i})}`);continue}const a=encodeURIComponent("label"===o?`.${i}`:i);r=r.replace(t,a)}return r})({path:t,url:o}));let i=r?n(r):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(o+=`?${i}`),o})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:cr(e.querySerializer),url:e.url}),dr=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=fr(e.headers,t.headers),r},pr=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},fr=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?pr(r):Object.entries(r);for(const[r,n]of e)if(null===n)t.delete(r);else if(Array.isArray(n))for(const e of n)t.append(r,e);else void 0!==n&&t.set(r,"object"==typeof n?JSON.stringify(n):n)}return t},hr=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 r=this.getInterceptorIndex(e);return!!this.fns[r]&&(this.fns[r]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}},gr=cr({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),mr={"Content-Type":"application/json"},yr=(e={})=>({...er,headers:mr,parseAs:"auto",querySerializer:gr,...e}),br=(e={})=>{let t=dr(yr(),e);const r=()=>({...t}),n={error:new hr,request:new hr,response:new hr},s=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:fr(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(lr(t,r.name))continue;const e=await ar(r,t.auth);if(!e)continue;const n=r.name??"Authorization";switch(r.in){case"query":t.query||(t.query={}),t.query[n]=e;break;case"cookie":t.headers.append("Cookie",`${n}=${e}`);break;default:t.headers.set(n,e)}}})({...r,security:r.security}),r.requestValidator&&await r.requestValidator(r),void 0!==r.body&&r.bodySerializer&&(r.serializedBody=r.bodySerializer(r.body)),void 0!==r.body&&""!==r.serializedBody||r.headers.delete("Content-Type"),{opts:r,url:ur(r)}},o=async e=>{const{opts:t,url:r}=await s(e),o={redirect:"follow",...t,body:or(t)};let i=new Request(r,o);for(const e of n.request.fns)e&&(i=await e(i,t));const a=t.fetch;let c;try{c=await a(i)}catch(e){let r=e;for(const s of n.error.fns)s&&(r=await s(e,void 0,i,t));if(r=r||{},t.throwOnError)throw r;return"data"===t.responseStyle?void 0:{error:r,request:i,response:void 0}}for(const e of n.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 r;switch(e){case"arrayBuffer":case"blob":case"text":r=await c[e]();break;case"formData":r=new FormData;break;case"stream":r=c.body;break;default:r={}}return"data"===t.responseStyle?r:{data:r,...l}}let r;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":r=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(r),t.responseTransformer&&(r=await t.responseTransformer(r))),"data"===t.responseStyle?r:{data:r,...l}}const u=await c.text();let d;try{d=JSON.parse(u)}catch{}const p=d??u;let f=p;for(const e of n.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=>o({...t,method:e}),a=e=>async t=>{const{opts:r,url:o}=await s(t);return(({onRequest:e,onSseError:t,onSseEvent:r,responseTransformer:n,responseValidator:s,sseDefaultRetryDelay:o,sseMaxRetryAttempts:i,sseMaxRetryDelay:a,sseSleepFn:c,url:l,...u})=>{let d;const p=c??(e=>new Promise(t=>setTimeout(t,e))),f=async function*(){let c=o??3e3,f=0;const h=u.signal??(new AbortController).signal;for(;!h.aborted;){f++;const o=u.headers instanceof Headers?u.headers:new Headers(u.headers);void 0!==d&&o.set("Last-Event-ID",d);try{const t={redirect:"follow",...u,body:u.serializedBody,headers:o,signal:h};let i=new Request(l,t);e&&(i=await e(l,t));const a=u.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 g="";const m=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",m);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;g+=t;const o=g.split("\n\n");g=o.pop()??"";for(const e of o){const t=e.split("\n"),o=[];let i,a;for(const e of t)if(e.startsWith("data:"))o.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))i=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))d=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(o.length){const e=o.join("\n");try{a=JSON.parse(e),l=!0}catch{a=e}}l&&(s&&await s(a),n&&(a=await n(a))),r?.({data:a,event:i,id:d,retry:c}),o.length&&(yield a)}}}finally{h.removeEventListener("abort",m),f.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&f>=i)break;const r=Math.min(c*2**(f-1),a??3e4);await p(r)}}}();return{stream:f}})({...r,body:r.body,headers:r.headers,method:e,onRequest:async(e,t)=>{let s=new Request(e,t);for(const e of n.request.fns)e&&(s=await e(s,r));return s},url:o})};return{buildUrl:ur,connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),getConfig:r,head:i("HEAD"),interceptors:n,options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),request:o,setConfig:e=>(t=dr(t,e),r()),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")}},wr=br(yr({baseUrl:"https://api.stably.ai"})),vr="4.6.1",_r=process.env.STABLY_API_URL||"https://api.stably.ai",Er=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},Ir=process.env.AUTH_URL||"https://auth.stably.ai",Tr=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",xr=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",Sr=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",Er(_r)).toString(),Ar=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",Er(_r)).toString(),Cr="http://localhost:9876/auth/callback",Rr=()=>ir||(ir=br(yr({baseUrl:_r,headers:{"X-STABLY-CLI-VERSION":vr,"X-STABLY-SOURCE":"cli"}}))),Pr=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:Rr()},(n.client??wr).post({url:"/internal/v1/cli/exchange-token",...n,headers:{"Content-Type":"application/json",...n.headers}}));var n;if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to exchange token: ${r.response.status}`);return r.data},Ur=w.z.object({org_id:w.z.string(),org_name:w.z.string()}),kr=w.z.object({email:w.z.string(),org_id_to_org_member_info:w.z.record(w.z.string(),Ur).optional(),org_member_info:Ur.optional(),user_id:w.z.string()});w.z.object({email:w.z.string(),firstName:w.z.string().optional(),lastName:w.z.string().optional(),organizations:w.z.array(w.z.object({id:w.z.string(),name:w.z.string()})),userId:w.z.string()});var Lr=e=>{const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf-8");return JSON.parse(n)},Dr=e=>{try{const t=kr.parse(Lr(e)),r=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:r,userId:t.user_id}}catch(e){throw new Error(`Failed to decode token: ${e instanceof Error?e.message:"Unknown error"}`)}},Or=async(e,t)=>{let r=e;const{root:n}=O.default.parse(r);for(;r!==n;){const e=O.default.join(r,t);try{return await m.access(e),e}catch{r=O.default.dirname(r)}}},Br=O.default.join(j.default.homedir(),".stably"),Nr=O.default.join(Br,"auth.json"),$r=".stably",jr="project.json",Mr=z.default.object({accessToken:z.default.string(),expiresAt:z.default.number(),idToken:z.default.string().optional(),refreshToken:z.default.string()}),Fr=z.default.object({orgId:z.default.string(),orgName:z.default.string(),projectId:z.default.string(),projectName:z.default.string()}),Hr=async()=>{try{const e=await m.readFile(Nr,"utf-8");return Mr.parse(JSON.parse(e))}catch{return}},Gr=async e=>{await m.mkdir(Br,{recursive:!0}),await m.writeFile(Nr,JSON.stringify(e,null,2),{mode:384})},zr=async()=>{try{await m.unlink(Nr)}catch{}},Yr=async()=>{try{const e=await Or(process.cwd(),$r);if(!e)return;const t=O.default.join(e,jr),r=await m.readFile(t,"utf-8");return Fr.parse(JSON.parse(r))}catch{return}},Wr=async()=>{try{const e=await Or(process.cwd(),$r);e&&await m.unlink(O.default.join(e,jr))}catch{}},Vr=e=>Date.now()>=e.expiresAt-3e5,qr=async e=>{const t=new URLSearchParams({client_id:Tr,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${Ir}/propelauth/oauth/token`,{body:t.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);const n=await r.json();return{accessToken:n.access_token,expiresAt:Date.now()+1e3*n.expires_in,refreshToken:n.refresh_token}},Kr=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`,Jr=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},Xr=(e,t)=>{const r=new URLSearchParams({client_id:Tr,code_challenge:e,code_challenge_method:"S256",redirect_uri:Cr,response_type:"code",state:t});return`${Ir}/propelauth/oauth/authorize?${r.toString()}`},Qr=async e=>{const t=y.spinner();let r;t.start("Loading user info...");try{r=Dr(e.accessToken),t.stop(H.default.green(`✓ Logged in as ${H.default.cyan(r.email)}`))}catch(e){t.stop(H.default.red("✗ Failed to load user info"));const r=e instanceof Error?e.message:"Unknown error";return y.log.error(r),{success:!1}}const n=await(async e=>{if(0===e.length)return void y.log.error("You don't belong to any organizations.");if(1===e.length)return y.log.info(`Using organization: ${H.default.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return y.log.info(`Auto-selecting organization: ${H.default.cyan(e[0].name)}`),e[0];const t=await y.select({message:"Select an organization",options:[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({label:e.name,value:e.id}))});return y.isCancel(t)?void 0:e.find(e=>e.id===t)})(r.organizations);if(!n)return y.log.warn("Organization selection cancelled."),{success:!1};let s;t.start("Getting org credentials...");try{const r=await Pr(e.accessToken,n.id);s={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(H.default.green("✓ Credentials obtained"))}catch(e){t.stop(H.default.red("✗ Failed to get org credentials"));const r=e instanceof Error?e.message:"Unknown error";return y.log.error(r),{success:!1}}const o=await(async(e,t)=>{const r=y.spinner();let n;r.start("Loading projects...");try{n=await(async({accessToken:e,orgId:t})=>{const r=await(n={auth:e,client:Rr(),path:{orgId:t}},(n.client??wr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/orgs/{orgId}/projects",...n}));var n;if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to list projects: ${r.response.status}`);return r.data.projects})({accessToken:e,orgId:t}),r.stop(H.default.green("✓ Projects loaded"))}catch(e){r.stop(H.default.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void y.log.error(t)}if(0===n.length)return y.log.error("No projects found in this organization."),void y.log.info(`Create a project at ${H.default.underline(H.default.cyan("https://app.stably.ai"))}`);if(1===n.length)return y.log.info(`Using project: ${H.default.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return y.log.info(`Auto-selecting project: ${H.default.cyan(n[0].name)}`),n[0];const s=await y.select({message:"Select a project",options:n.map(e=>({label:e.name,value:e.id}))});return y.isCancel(s)?void 0:n.find(e=>e.id===s)})(s.accessToken,n.id);return o?(await(async e=>{const t=O.default.join(process.cwd(),$r),r=O.default.join(t,jr);await m.mkdir(t,{recursive:!0}),await m.writeFile(r,JSON.stringify(e,null,2)),await(async e=>{const t=O.default.join(e,".gitignore"),r="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await m.readFile(t,"utf-8"),n=e.split("\n").map(e=>e.trim());if(n.includes(".stably/*")&&n.includes("!.stably/docs/"))return;const s=/^# Stably CLI\n\.stably\/?$/m,o=/^\.stably\/?$/m;if(s.test(e)){const n=e.replace(s,`\n${r}\n`);await m.writeFile(t,n)}else if(o.test(e)){const n=e.replace(o,`\n${r}\n`);await m.writeFile(t,n)}else await m.appendFile(t,`\n${r}\n`)}catch{await m.writeFile(t,`${r}\n`)}})(process.cwd())})({orgId:n.id,orgName:n.name,projectId:o.id,projectName:o.name}),y.log.info(H.default.dim("Linked this directory to your Stably project.")),{scopedTokens:s,success:!0}):(y.log.warn("Project selection cancelled."),{success:!1})},Zr=async()=>{if(vn())return y.log.warn(`Environment variables ${H.default.cyan("STABLY_API_KEY")} and ${H.default.cyan("STABLY_PROJECT_ID")} are set.`),y.log.warn("These will be used for authentication instead of OAuth login."),y.log.warn("To use OAuth login, unset these environment variables first."),void y.outro(H.default.yellow("Login skipped - using environment variable authentication."));const e=await Hr();if(e){if(!Vr(e)){if(await Yr())return void y.outro(H.default.yellow("You are already logged in. Run `stably logout` first to log out."));y.log.info("You are logged in but haven't selected a project yet.");const t=await Qr(e);return void(t.success?(await Gr(t.scopedTokens),y.outro(H.default.green("Setup complete! You can now use Stably CLI."))):y.outro(H.default.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=y.spinner();t.start("Refreshing session...");try{const r=await qr(e.refreshToken);t.stop(H.default.green("✓ Session refreshed"));const n=await Yr();if(n){t.start("Getting org credentials...");try{const e=await Pr(r.accessToken,n.orgId),s={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:r.idToken,refreshToken:r.refreshToken};await Gr(s),t.stop(H.default.green("✓ Credentials obtained")),y.outro(H.default.green("Login successful"))}catch{await Gr(r),t.stop(H.default.yellow("Using full credentials")),y.outro(H.default.green("Login successful"))}}else{const e=await Qr(r);e.success?(await Gr(e.scopedTokens),y.outro(H.default.green("Setup complete! You can now use Stably CLI."))):y.outro(H.default.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(H.default.yellow("Session expired, proceeding with fresh login...")),await zr(),await Wr()}}const{authorizeUrl:t,serverReady:r,waitForCallback:n}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=F.default.randomBytes(32).toString("base64url"),t=(r=e,F.default.createHash("sha256").update(r).digest("base64url"));var r;const n=F.default.randomBytes(16).toString("base64url");return{authorizeUrl:Xr(t,n),codeVerifier:e,state:n}})(),{ready:n,result:s}=(e=>{let t,r;return{ready:new Promise((e,n)=>{t=e,r=n}),result:new Promise((n,s)=>{const o=setTimeout(()=>{c.close(),n({error:"Login timed out",success:!1})},3e5),i=()=>{clearTimeout(o)},c=W.default.createServer((t,r)=>{const s=new a.URL(t.url||"","http://localhost:9876");if("/auth/callback"!==s.pathname)return r.writeHead(404),void r.end("Not found");const o=s.searchParams.get("code"),l=s.searchParams.get("state"),u=s.searchParams.get("error");return u?(Jr(r,400,Kr(u)),i(),c.close(),void n({error:u,success:!1})):o&&l?l!==e?(Jr(r,400,Kr("Invalid state parameter (possible CSRF attack)")),i(),c.close(),void n({error:"State mismatch",success:!1})):(Jr(r,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'),i(),c.close(),void n({code:o,state:l,success:!0})):(Jr(r,400,Kr("Missing code or state parameter")),i(),c.close(),void n({error:"Missing code or state parameter",success:!1}))});c.on("error",e=>{if(i(),"EADDRINUSE"===e.code){const e=new Error("Port 9876 is already in use. Please close the application using it and try again.");return r(e),void s(e)}const t=new Error(`Failed to start callback server: ${e.message}`);r(t),s(t)}),c.listen(9876,()=>{t()})})}})(r);return{authorizeUrl:e,serverReady:n,waitForCallback:async()=>{const e=await s;if(!e.success)throw new Error(e.error);return(async(e,t)=>{const r=new URLSearchParams({client_id:Tr,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:Cr}),n=await fetch(`${Ir}/propelauth/oauth/token`,{body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!n.ok){const e=await n.text();throw new Error(`Token exchange failed: ${n.status} ${e}`)}const s=await n.json();return{accessToken:s.access_token,expiresAt:Date.now()+1e3*s.expires_in,idToken:s.id_token,refreshToken:s.refresh_token}})(e.code,t)}}})();await r,y.log.info("Opening browser for authentication..."),y.log.info(H.default.dim("If browser doesn't open, visit:")),y.log.info(`]8;;${t}${H.default.underline(H.default.cyan(t))}]8;;`);try{await Y.default(t)}catch{y.log.warn("Could not open browser automatically. Please open the URL above manually.")}const s=y.spinner();let o;s.start("Waiting for authentication...");try{o=await n(),s.stop(H.default.green("✓ Authentication successful"))}catch(e){s.stop(H.default.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";y.outro(H.default.red(`Login failed: ${t}`)),process.exit(1)}const i=await Qr(o);i.success?(await Gr(i.scopedTokens),y.outro(H.default.green("Setup complete! You can now use Stably CLI."))):(y.outro(H.default.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},en={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},tn=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),rn=(new Date).toISOString().split("T")[0],nn=O.default.join(j.default.tmpdir(),"stably-logs",rn);$.default.mkdirSync(nn,{recursive:!0});var sn,on=process.argv.includes("--verbose")||process.argv.includes("-v"),an=process.env.STABLY_LOG_LEVEL?.toLowerCase(),cn=on?"debug":void 0!==(sn=an)&&sn in en?an:"warn",ln=en[cn],un=null,dn=null,pn=null,fn=[],hn=!1,gn=e=>{if(!hn){un=(e=>{const t=(()=>{const e=new Date;return[e.getHours().toString().padStart(2,"0"),e.getMinutes().toString().padStart(2,"0"),e.getSeconds().toString().padStart(2,"0")].join("-")})(),r=((e,t=100)=>e.replace(/[/\\:*?"<>|]/g,"-").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9\-_]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).toLowerCase()||"session")(e);return O.default.join(nn,`${t}-${r}.log`)})(e),(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${vr}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${j.default.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${cn}`,"=".repeat(60),""].join("\n");e.write(t)})(dn=new q.default({dest:un,minLength:4096,sync:!1,append:!0})),pn=V.default({level:"debug",timestamp:V.default.stdTimeFunctions.isoTime,base:{version:vr}},dn);for(const{level:e,msg:t,context:r}of fn)r?pn[e](r,t):pn[e](t);fn=[],hn=!0,on&&process.stderr.write(`${H.default.dim(`Debug log: ${un}`)}\n\n`)}},mn=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&tn.has(e)?e:null})();mn&&gn(mn);var yn=e=>(t,r)=>{if(pn?r?pn[e](r,t):pn[e](t):fn.push({level:e,msg:t,context:r}),(e=>en[e]>=ln)(e)){const r=((e,t)=>`${{fatal:H.default.bgRed(H.default.white(" FATAL ")),error:H.default.red("error"),warn:H.default.yellow("warn"),info:H.default.cyan("info"),debug:H.default.dim("debug"),trace:H.default.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${r}\n`)}},bn={fatal:yn("fatal"),error:yn("error"),warn:yn("warn"),info:yn("info"),debug:yn("debug"),trace:yn("trace"),initSession:e=>{hn||gn(e)},getLogFilePath:()=>un,flush:()=>{if(dn)try{dn.flushSync()}catch{}},printLogFileInfo:()=>{un&&(process.stderr.write(`\n${H.default.dim("Debug log written to:")}\n`),process.stderr.write(` ${H.default.cyan(un)}\n`),process.stderr.write(`${H.default.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>pn};setInterval(()=>{bn.flush()},3e4).unref(),process.on("beforeExit",()=>{bn.flush()});var wn=e=>{const t=()=>{bn.flush(),on&&bn.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",wn("SIGINT")),process.on("SIGTERM",wn("SIGTERM"));var vn=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return bn.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};bn.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},_n=!1,En=()=>{_n||(_n=!0,y.log.warn("Both environment variable auth and stored OAuth login were detected."),y.log.warn(`Honoring environment variables (${H.default.cyan("STABLY_API_KEY")} + ${H.default.cyan("STABLY_PROJECT_ID")}).`),y.log.warn("To use OAuth login instead, unset those environment variables."))},In=async()=>{bn.debug("Checking for stored auth tokens");const e=await Hr();if(!e)return void bn.debug("No stored auth tokens found");const t=Vr(e);if(bn.debug("Auth tokens status",{expired:t}),!t){const t=await Yr(),r=(e=>{try{const t=kr.parse(Lr(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);if(bn.debug("Token scope check",{scope:r,hasContext:!!t}),t&&"full"===r)try{bn.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const r=await Pr(e.accessToken,t.orgId),n={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await Gr(n),bn.debug("Token exchange successful"),n}catch(t){return bn.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{bn.debug("Attempting token refresh");const t=await qr(e.refreshToken);bn.debug("Token refresh successful");const r=await Yr();if(r)try{bn.debug("Exchanging refreshed token for org-scoped token");const e=await Pr(t.accessToken,r.orgId),n={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await Gr(n),n}catch{return await Gr(t),t}return await Gr(t),t}catch(e){return void bn.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},Tn=async(e={})=>{bn.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=vn();if(t){bn.info("Using environment variable authentication");try{await Hr()&&En()}catch{}return{auth:t,type:"env"}}let r=await In(),n=r?await Yr():void 0;const s=process.stdin.isTTY&&process.stdout.isTTY;if(bn.debug("OAuth auth check",{hasTokens:!!r,hasContext:!!n,canPrompt:s}),(!r||!n)&&e.autoLogin&&s){bn.info("Prompting user to login"),r?y.log.info("You are logged in but need to select an organization and project."):y.log.info("You are not logged in."),y.log.info("Press Enter to log in."),process.stdout.write(`${H.default.dim("Alternatively, set environment variables for an org API key:")}\n${H.default.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=b.createInterface({input:process.stdin,output:process.stdout});try{await e.question(H.default.dim("Press Enter to continue... "))}finally{e.close()}await Zr(),r=await In(),n=r?await Yr():void 0}return r||(bn.warn("Authentication required but no tokens available"),y.outro(H.default.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(bn.warn("Authentication succeeded but no project context selected"),y.outro(H.default.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),bn.info("OAuth authentication successful",{orgId:n.orgId,projectId:n.projectId}),{auth:{accessToken:r.accessToken,context:n},type:"oauth"}},xn=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,Sn=e=>e?{...process.env,...e}:process.env,An=async()=>{bn.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===_r)return;const e=_r.startsWith("http://")?"ws://":"wss://";return`${_r.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();bn.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=vn();if(t)return bn.info("[test] Using env var auth (STABLY_API_KEY + STABLY_PROJECT_ID)"),{STABLY_API_KEY:t.apiKey,STABLY_PROJECT_ID:t.projectId,...e&&{STABLY_WS_URL:e}};bn.info("[test] No env var auth, attempting OAuth auth");const r=Date.now(),n=await(async()=>{const e=vn();if(e){try{await Hr()&&En()}catch{}return{auth:e,type:"env"}}const t=await In(),r=t?await Yr():void 0;if(t&&r)return{auth:{accessToken:t.accessToken,context:r},type:"oauth"}})();if(bn.info("[test] OAuth auth resolved",{durationMs:Date.now()-r,hasAuth:!!n,authType:n?.type}),!n||"env"===n.type)return void bn.info("[test] No usable auth found");const s=process.env.STABLY_PROJECT_ID?.trim(),o=s||xn(n);if(!o)return void bn.warn("[test] No project ID available");bn.info("[test] Fetching JWT API key",{projectId:o});const i=Date.now(),a=await(async(e,t)=>{try{bn.debug("Requesting JWT API key",{projectId:t,apiUrl:_r});const r=await(async({accessToken:e,projectId:t})=>{const r=await(n={auth:e,client:Rr(),path:{projectId:t}},(n.client??wr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/api-key",...n}));var n;if(r.error){const e=r.error?.error,{status:t}=r.response;throw new Error(e??`Failed to get API key: ${t}`)}return r.data})({accessToken:e,projectId:t});return bn.debug("JWT API key obtained",{keyPrefix:r.apiKey.substring(0,10)}),r.apiKey}catch(e){return void bn.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(n.auth.accessToken,o);bn.info("[test] JWT API key fetch complete",{durationMs:Date.now()-i,success:!!a});const c=a?{STABLY_API_KEY:a,STABLY_PROJECT_ID:o,...e&&{STABLY_WS_URL:e}}:void 0;return bn.info("[test] Stably test env resolved",{hasApiKey:!!c?.STABLY_API_KEY,projectId:c?.STABLY_PROJECT_ID,wsUrl:c?.STABLY_WS_URL??process.env.STABLY_WS_URL??"(default)"}),c},Cn=e=>e?{[Zt]:e}:void 0,Rn=w.z.object({context:w.z.string().min(1),autohealReportUrl:w.z.string()}),Pn=T.z.object({bucket:T.z.string(),key:T.z.string()}),Un=T.z.object({diffBucketPath:Pn,expiresInSeconds:T.z.number(),key:T.z.string(),uploadUrl:T.z.string()}),kn=T.z.object({traceBucketPath:Pn,expiresInSeconds:T.z.number(),key:T.z.string(),uploadUrl:T.z.string(),sensitiveValues:T.z.array(T.z.string())}),Ln=async({authHeader:e,contentType:t="text/plain",orgId:r,runId:n})=>{const s=await(o={auth:e,body:{contentType:t},client:Rr(),headers:Cn(r),path:{runId:n}},(o.client??wr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to presign diff upload (${s.response.status})`);const i=Un.parse(s.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}},Dn=async({contentType:e="text/plain",diff:t,uploadUrl:r})=>{const n=await fetch(r,{body:t,headers:{"Content-Type":e},method:"PUT"});if(!n.ok)throw new Error(`Failed to upload diff (${n.status})`)},On=async({authHeader:e,diffBucketPath:t,orgId:r,runId:n})=>{const s=(Rr().getConfig().baseUrl??"").replace(/\/$/,""),o=await fetch(`${s}/internal/v1/cli/runs/${encodeURIComponent(n)}/autoheal-diff/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json",...Cn(r),authorization:e},body:JSON.stringify(t)});if(!o.ok)throw new Error(`Failed to confirm diff upload (${o.status})`)},Bn=class{socket;url;authHeader;orgId;runId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=3;reconnectDelay=2e3;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,runId:r,url:n=Sr,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.runId=r,this.url=n,this.onUserMessage=s,bn.info("[ws] Constructing AutohealWebSocketClient",{url:this.url,runId:r})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?runId=${encodeURIComponent(this.runId)}`;bn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new K.default(t,{headers:e}),this.socket.on("open",()=>{bn.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),r=JSON.parse(t);bn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(bn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(bn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{bn.info("[ws] Connection closed",{code:e,authFailed:1008===e,reconnectAttempts:this.reconnectAttempts,maxReconnect:this.maxReconnectAttempts,isClosed:this._isClosed}),this.isAuthenticated=!1,1008===e&&(this.authenticationFailed=!0),!this._isClosed&&!this.authenticationFailed&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}),this.socket.on("error",e=>{bn.warn("[ws] Connection error",{error:e.message})})}catch(e){bn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,bn.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===K.default.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void bn.debug("[ws] sendProgress called but client is closed",{phase:e.phase});const t={type:"autoheal_progress",payload:e};return this.pendingEvent=t,this.isConnected()?"complete"===e.phase?(bn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(bn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===K.default.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return bn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{bn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(bn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){bn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;bn.info("[ws] Closing WebSocket client"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.flushPending();const{socket:e}=this;this.socket=void 0,e&&setTimeout(()=>{e.close()},200)}},Nn=class{socket;url;authHeader;orgId;sessionId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=3;reconnectDelay=2e3;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,sessionId:r,url:n=Ar,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.sessionId=r,this.url=n,this.onUserMessage=s,bn.info("[ws] Constructing CreateProgressWebSocketClient",{url:this.url,sessionId:r})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?sessionId=${encodeURIComponent(this.sessionId)}`;bn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new K.default(t,{headers:e}),this.socket.on("open",()=>{bn.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),r=JSON.parse(t);bn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(bn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(bn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{bn.info("[ws] Connection closed",{code:e,authFailed:1008===e,reconnectAttempts:this.reconnectAttempts,maxReconnect:this.maxReconnectAttempts,isClosed:this._isClosed}),this.isAuthenticated=!1,1008===e&&(this.authenticationFailed=!0),!this._isClosed&&!this.authenticationFailed&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}),this.socket.on("error",e=>{bn.warn("[ws] Connection error",{error:e.message})})}catch(e){bn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,bn.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===K.default.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void bn.debug("[ws] sendProgress called but client is closed",{phase:e.phase});const t={type:"create_progress",payload:e};return this.pendingEvent=t,this.isConnected()?"complete"===e.phase?(bn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(bn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===K.default.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return bn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{bn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(bn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){bn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;bn.info("[ws] Closing WebSocket client"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.flushPending();const{socket:e}=this;this.socket=void 0,e&&setTimeout(()=>{e.close()},200)}},$n=/\.(spec|test)\.(c|m)?[jt]sx?$/,jn=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},Mn=e=>null!=e&&"object"==typeof e&&"tool_response"in e,Fn=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},Hn=e=>{const t=Fn(e);if(t)return t.filter(jn).map(e=>e.text).join("\n")||void 0},Gn=/\u001b\[[0-9;]*m/g,zn=e=>e.replace(Gn,""),Yn=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function Wn({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 r=t.tool_input,n="string"==typeof r.text?r.text:void 0;if(!n)return{decision:"approve"};const s=n.replace(Yn,(t,r)=>{const n=e[r];return null!=n?n:t});return s===n?{decision:"approve"}:{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser text input.",updatedInput:{...r,text:s}}}}}function Vn({onResult:e}){return async t=>{if(!Mn(t))return{decision:"approve"};const r=Hn(t);if(!r)return{decision:"approve"};const n=function(e){const t=zn(e),r=t.split(/Running \d+ tests? using \d+ workers?/).at(-1)??t,n=parseInt(r.match(/(\d+)\s+passed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0"),s=parseInt(r.match(/(\d+)\s+failed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0");if(0===n&&0===s)return;const o=[n>0?`${n} test${1===n?"":"s"} passed ✓`:void 0,s>0?`${s} test${1===s?"":"s"} failed ✗`:void 0].filter(e=>void 0!==e).join(", ");if(0===s)return o;const i=r.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?o:`${o}\n${i.map(e=>` - ${e}`).join("\n")}`}(r);return n&&e(n),{decision:"approve"}}}function qn({onResult:e}){return async t=>{if(!Mn(t))return{decision:"approve"};const r=Hn(t);if(!r)return{decision:"approve"};const n=function(e){const t=zn(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 r=t.match(/(\d+)\s+passed/);if(r){const e=parseInt(r[1]);return`${e} test${1===e?"":"s"} passed ✓`}}(r);return n&&e(n),{decision:"approve"}}}var Kn=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function Jn({onFileCreated:e}){return async t=>{const r=(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),n=r?.file_path;return"string"==typeof n&&Kn.test(n)&&e(n),{decision:"approve"}}}var Xn=u.promisify(s.exec);async function Qn(){try{const{stdout:e}=await Xn('pgrep -f "playwright run-test-mcp-server" 2>/dev/null || true'),t=e.trim();if(!t)return;const r=t.split("\n").filter(Boolean);await Promise.allSettled(r.map(async e=>{await Xn(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var Zn="sha256",es=/^---\r?\n([\s\S]*?)\r?\n---/;function ts(e){const t=e.replace(es,"").replace(/^(\r?\n)+/,""),r=F.default.createHash(Zn).update(t,"utf8").digest("hex");return`${Zn}:${r}`}function rs(e){const t=e.match(/^\/\*\*[\s\S]*?@prompt-hash\s+(sha256:[a-f0-9]{64})[\s\S]*?\*\//);return t?.[1]}function ns({builtAt:e=new Date,promptFile:t,promptHash:r}){const n=Array.isArray(t)?t:[t],s=n[0]??"unknown",o=e.toISOString();return["/**"," * @generated by stably build",` * @prompt-hash ${r}`,...n.map(e=>` * @prompt-file ${e}`),` * @built-at ${o}`," *",` * DO NOT EDIT MANUALLY - regenerate with: stably build ${s} --force`," */"].join("\n")}function ss({workDir:e}){return async r=>{if(null==(n=r)||"object"!=typeof n||!("file_path"in n)||"string"!=typeof n.file_path)return{};var n;const s=r.file_path;if(!/\.(spec|test)\.[jt]sx?$/.test(s))return{};const o=t.resolve(e,s);if(!o.startsWith(t.resolve(e)+t.sep))return console.error(`[PromptHash Hook] Path traversal attempt blocked: ${s}`),{};let i;try{i=await m.readFile(o,"utf-8")}catch(e){return console.error(`[PromptHash Hook] Error reading ${s}:`,e),{}}const a=function(e){const t=e.match(/\/\/\s*@stably\.spec\s+(\S+)/);return t?.[1]}(i);if(!a)return{};const c=t.resolve(e,a);if(!c.startsWith(t.resolve(e)+t.sep))return console.error(`[PromptHash Hook] Path traversal attempt blocked: ${a}`),{};let l;try{l=await m.readFile(c,"utf-8")}catch{return{}}const u=ts(l);if(rs(i)===u)return{};const d=ns({promptHash:u,promptFile:a});let p;const f=i.match(/\/\*\*[\s\S]*?@prompt-hash[\s\S]*?\*\/\n?/);p=f?i.replace(f[0],`${d}\n`):`${d}\n${i}`;try{await m.writeFile(o,p,"utf-8")}catch(e){console.error(`[PromptHash Hook] Error writing ${s}:`,e)}return{}}}var os=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())}hasQueuedMessages(){return this.queue.length>0}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()})}};function is(e){try{const t=s.execSync("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}var as=[".ts",".js",".mts",".mjs",".cts",".cjs"],cs=10240,ls=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await m.stat(r)).size,n=await m.readFile(r,"utf-8"),s=Buffer.byteLength(n,"utf-8");if(s<=cs)return n;const o=(e=>{const t=e.split("\n"),r=[];let n=!1,s=!1,o=0,i=!1;for(let e=0;e<t.length;e++){const a=t[e],c=a.trim();c.startsWith("/*")&&(n=!0),c.includes("*/")?n=!1:n||c.startsWith("//")&&!c.startsWith("///")||(c.startsWith("import ")||c.startsWith("export ")?(r.push(a),i=!0):i&&""===c?(r.push(a),i=!1):(i=!1,c.startsWith("type ")||c.startsWith("interface ")?r.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(")?(r.push(a),s=!0,o=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===o&&(c.endsWith(";")||c.endsWith(","))&&(s=!1)):s?(o+=(a.match(/{/g)||[]).length,o-=(a.match(/}/g)||[]).length,0===o&&c.includes("}")?(r.push(a),s=!1):o>0&&" // ... implementation omitted ..."!==r.at(-1)&&r.push(" // ... implementation omitted ...")):c.match(/^[a-zA-Z_]+:/)&&r.push(a)))}return r.join("\n")})(n),i=Buffer.byteLength(o,"utf-8");return i<=cs?o:o.slice(0,cs)+`\n\n... [TRUNCATED: File "${t}" at ${r} was ${e} bytes (${s} bytes as UTF-8), reduced to ~${i} bytes of essential content, then truncated to 10240 bytes] ...`}catch(r){let n;if(r&&"object"==typeof r&&"code"in r){const e=r.code;"string"==typeof e&&(n=e)}return"ENOENT"!==n&&console.warn(`Failed to read ${t}: ${r}`),e}},us=async({defaultContent:e,dirName:t,dirPath:r})=>{try{const e=await m.readdir(r);return e.length>0?e.join("\n"):"(empty)"}catch(r){let n;if(r&&"object"==typeof r&&"code"in r){const e=r.code;"string"==typeof e&&(n=e)}return"ENOENT"!==n&&console.warn(`Failed to read ${t}: ${r}`),e}},ds=async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n,customHeader:s,maxParallelWorkers:o})=>{const i=Rr(),a=is(r.absolutePath);bn.debug("Requesting system prompt from API",{mode:t,hasGitContext:!!a,envVarCount:e.length});const c=await(l={client:i,auth:n,body:{mode:t,workspaceInfo:r,allowedEnvVars:e,gitContext:a,maxParallelWorkers:o}},(l.client??wr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...l,headers:{"Content-Type":"application/json",...l.headers}}));var l;if(401===c.response.status)throw bn.warn("System prompt fetch failed: unauthorized (401)"),await zr(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===c.response.status)throw bn.warn("System prompt fetch failed: forbidden (403)"),await zr(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(c.error)throw bn.warn("System prompt fetch failed",{error:c.error}),new Error(`Failed to fetch system prompt: ${JSON.stringify(c.error)}`);const u=function({customHeader:e,systemPrompt:t}){return e?`${t}\n\nWhen writing or updating the generated test file, prepend this exact header at the top of the file without modification:\n\`\`\`ts\n${e}\n\`\`\``:t}({systemPrompt:c.data.systemPrompt,customHeader:s});return bn.debug("System prompt received",{size:u.length,appendedCustomHeader:!!s,hasPrContext:!!c.data.prContext}),{systemPrompt:u,prContext:c.data.prContext}},ps=".stably-playwright-wrapper.config.*",fs=[".ts",".js",".mts",".mjs",".cts",".cjs"];function hs(e){const r=t.resolve(e);if(i.existsSync(r))for(const e of fs){const n=t.join(r,`playwright.config${e}`);if(i.existsSync(n))return n}}var gs=["tests","e2e","__tests__","test"];function ms(e){try{return i.existsSync(e)&&i.statSync(e).isDirectory()}catch{return!1}}function ys(e,t){const r="output-flag"===t?"--output flag":"playwright.config.ts"===t?"playwright.config.ts":"auto-detected"===t?"auto-detected":"cwd fallback";console.error(H.default.dim(`Using output directory: ${e} (from ${r})`))}var bs,ws=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__test-doc-sync__","mcp__stably-agent-control__"],vs=["planner_","generator_"],_s={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools","mcp__session-control__restart_mcp_servers":"Restarting Browser Tools"},Es=(e,t)=>{const r=t.find(t=>e.startsWith(t));return r?e.slice(r.length):e},Is=e=>{const t=_s[e];if(t)return t;const r=Es(e,ws);return Es(r,vs).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")},Ts=(e,t)=>{if(!t||"object"!=typeof t)return;const r=t,n="string"==typeof r.intent?r.intent:void 0;if("Read"!==e&&"Write"!==e&&"Edit"!==e){if("Glob"===e||"Grep"===e)return"string"==typeof r.pattern?r.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=r.test;return"string"==typeof e?.title?e.title:void 0}return"mcp__playwright-test__generator_setup_page"===e||"generator_setup_page"===e?"string"==typeof r.seedFile?r.seedFile:"tests/seed.spec.ts":"mcp__playwright-test__generator_write_test"===e||"generator_write_test"===e?"string"==typeof r.fileName?r.fileName:void 0:"Bash"===e?"string"==typeof r.command?r.command.length>50?`${r.command.slice(0,50)}...`:r.command:void 0:e.includes("browser_navigate")&&!e.includes("back")?"string"==typeof r.url?r.url:n:e.includes("browser_type")?("string"==typeof r.text?`"${r.text}"`:void 0)??n:e.includes("browser_click")?"string"==typeof r.element?r.element:n:e.includes("browser_wait_for")?"string"==typeof r.text?`text: "${r.text}"`:"number"==typeof r.time?`${r.time}ms`:n:e.includes("verify_text")?"string"==typeof r.text?`"${r.text}"`:n:e.includes("verify_element")?"string"==typeof r.accessibleName?r.accessibleName:n:e.includes("screenshot")&&"string"==typeof r.filename?r.filename:n}if(Array.isArray(r.locations)){const e=r.locations.filter(e=>"string"==typeof e);return e.length>0?e.join(", "):void 0}}else if("string"==typeof r.file_path)return r.file_path.split("/").at(-1)??void 0},xs=["test","bug","other"],Ss={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."},As=e=>Ss[e],Cs=/[^a-zA-Z0-9-_]/g,Rs=e=>{const t=e.trim().replace(Cs,"_");return t.length>0?t.slice(0,80):void 0},Ps=e=>"string"==typeof e?Rs(e):void 0,Us=((e,t,r)=>(r=null!=e?J(ee(e)):{},((e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of Z(t))te.call(e,r)||void 0===r||X(e,r,{get:()=>t[r],enumerable:!(n=Q(t,r))||n.enumerable});return e})(X(r,"default",{value:e,enumerable:!0}),e)))(ne()),ks=C.createRequire("/");try{bs=ks("worker_threads").Worker}catch(e){}var Ls=bs?function(e,t,r,n,s){var o=!1,i=new bs(e+";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global",{eval:!0}).on("error",function(e){return s(e,null)}).on("message",function(e){return s(null,e)}).on("exit",function(e){e&&!o&&s(new Error("exited with code "+e),null)});return i.postMessage(r,n),i.terminate=function(){return o=!0,bs.prototype.terminate.call(i)},i}:function(e,t,r,n,s){setImmediate(function(){return s(new Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"),null)});var o=function(){};return{terminate:o,postMessage:o}},Ds=Uint8Array,Os=Uint16Array,Bs=Int32Array,Ns=new Ds([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),$s=new Ds([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),js=new Ds([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ms=function(e,t){for(var r=new Os(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];var s=new Bs(r[30]);for(n=1;n<30;++n)for(var o=r[n];o<r[n+1];++o)s[o]=o-r[n]<<5|n;return{b:r,r:s}},Fs=Ms(Ns,2),Hs=Fs.b,Gs=Fs.r;Hs[28]=258,Gs[258]=28;var zs,Ys=Ms($s,0),Ws=Ys.b,Vs=Ys.r,qs=new Os(32768);for(Xs=0;Xs<32768;++Xs)zs=(61680&(zs=(52428&(zs=(43690&Xs)>>1|(21845&Xs)<<1))>>2|(13107&zs)<<2))>>4|(3855&zs)<<4,qs[Xs]=((65280&zs)>>8|(255&zs)<<8)>>1;var Ks=function(e,t,r){for(var n=e.length,s=0,o=new Os(t);s<n;++s)e[s]&&++o[e[s]-1];var i,a=new Os(t);for(s=1;s<t;++s)a[s]=a[s-1]+o[s-1]<<1;if(r){i=new Os(1<<t);var c=15-t;for(s=0;s<n;++s)if(e[s])for(var l=s<<4|e[s],u=t-e[s],d=a[e[s]-1]++<<u,p=d|(1<<u)-1;d<=p;++d)i[qs[d]>>c]=l}else for(i=new Os(n),s=0;s<n;++s)e[s]&&(i[s]=qs[a[e[s]-1]++]>>15-e[s]);return i},Js=new Ds(288);for(Xs=0;Xs<144;++Xs)Js[Xs]=8;for(Xs=144;Xs<256;++Xs)Js[Xs]=9;for(Xs=256;Xs<280;++Xs)Js[Xs]=7;for(Xs=280;Xs<288;++Xs)Js[Xs]=8;var Xs,Qs=new Ds(32);for(Xs=0;Xs<32;++Xs)Qs[Xs]=5;var Zs=Ks(Js,9,0),eo=Ks(Js,9,1),to=Ks(Qs,5,0),ro=Ks(Qs,5,1),no=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},so=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},oo=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},io=function(e){return(e+7)/8|0},ao=function(e,t,r){return(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length),new Ds(e.subarray(t,r))},co=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],lo=function(e,t,r){var n=new Error(t||co[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,lo),!r)throw n;return n},uo=function(e,t,r,n){var s=e.length,o=n?n.length:0;if(!s||t.f&&!t.l)return r||new Ds(0);var i=!r,a=i||2!=t.i,c=t.i;i&&(r=new Ds(3*s));var l=function(e){var t=r.length;if(e>t){var n=new Ds(Math.max(2*t,e));n.set(r),r=n}},u=t.f||0,d=t.p||0,p=t.b||0,f=t.l,h=t.d,g=t.m,m=t.n,y=8*s;do{if(!f){u=so(e,d,1);var b=so(e,d+1,3);if(d+=3,!b){var w=e[(P=io(d)+4)-4]|e[P-3]<<8,v=P+w;if(v>s){c&&lo(0);break}a&&l(p+w),r.set(e.subarray(P,v),p),t.b=p+=w,t.p=d=8*v,t.f=u;continue}if(1==b)f=eo,h=ro,g=9,m=5;else if(2==b){var _=so(e,d,31)+257,E=so(e,d+10,15)+4,I=_+so(e,d+5,31)+1;d+=14;for(var T=new Ds(I),x=new Ds(19),S=0;S<E;++S)x[js[S]]=so(e,d+3*S,7);d+=3*E;var A=no(x),C=(1<<A)-1,R=Ks(x,A,1);for(S=0;S<I;){var P,U=R[so(e,d,C)];if(d+=15&U,(P=U>>4)<16)T[S++]=P;else{var k=0,L=0;for(16==P?(L=3+so(e,d,3),d+=2,k=T[S-1]):17==P?(L=3+so(e,d,7),d+=3):18==P&&(L=11+so(e,d,127),d+=7);L--;)T[S++]=k}}var D=T.subarray(0,_),O=T.subarray(_);g=no(D),m=no(O),f=Ks(D,g,1),h=Ks(O,m,1)}else lo(1);if(d>y){c&&lo(0);break}}a&&l(p+131072);for(var B=(1<<g)-1,N=(1<<m)-1,$=d;;$=d){var j=(k=f[oo(e,d)&B])>>4;if((d+=15&k)>y){c&&lo(0);break}if(k||lo(2),j<256)r[p++]=j;else{if(256==j){$=d,f=null;break}var M=j-254;if(j>264){var F=Ns[S=j-257];M=so(e,d,(1<<F)-1)+Hs[S],d+=F}var H=h[oo(e,d)&N],G=H>>4;if(H||lo(3),d+=15&H,O=Ws[G],G>3&&(F=$s[G],O+=oo(e,d)&(1<<F)-1,d+=F),d>y){c&&lo(0);break}a&&l(p+131072);var z=p+M;if(p<O){var Y=o-O,W=Math.min(O,z);for(Y+p<0&&lo(3);p<W;++p)r[p]=n[Y+p]}for(;p<z;++p)r[p]=r[p-O]}}t.l=f,t.p=$,t.b=p,t.f=u,f&&(u=1,t.m=g,t.d=h,t.n=m)}while(!u);return p!=r.length&&i?ao(r,0,p):r.subarray(0,p)},po=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},fo=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8,e[n+2]|=r>>16},ho=function(e,t){for(var r=[],n=0;n<e.length;++n)e[n]&&r.push({s:n,f:e[n]});var s=r.length,o=r.slice();if(!s)return{t:_o,l:0};if(1==s){var i=new Ds(r[0].s+1);return i[r[0].s]=1,{t:i,l:1}}r.sort(function(e,t){return e.f-t.f}),r.push({s:-1,f:25001});var a=r[0],c=r[1],l=0,u=1,d=2;for(r[0]={s:-1,f:a.f+c.f,l:a,r:c};u!=s-1;)a=r[r[l].f<r[d].f?l++:d++],c=r[l!=u&&r[l].f<r[d].f?l++:d++],r[u++]={s:-1,f:a.f+c.f,l:a,r:c};var p=o[0].s;for(n=1;n<s;++n)o[n].s>p&&(p=o[n].s);var f=new Os(p+1),h=go(r[u-1],f,0);if(h>t){n=0;var g=0,m=h-t,y=1<<m;for(o.sort(function(e,t){return f[t.s]-f[e.s]||e.f-t.f});n<s;++n){var b=o[n].s;if(!(f[b]>t))break;g+=y-(1<<h-f[b]),f[b]=t}for(g>>=m;g>0;){var w=o[n].s;f[w]<t?g-=1<<t-f[w]++-1:++n}for(;n>=0&&g;--n){var v=o[n].s;f[v]==t&&(--f[v],++g)}h=t}return{t:new Ds(f),l:h}},go=function(e,t,r){return-1==e.s?Math.max(go(e.l,t,r+1),go(e.r,t,r+1)):t[e.s]=r},mo=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new Os(++t),n=0,s=e[0],o=1,i=function(e){r[n++]=e},a=1;a<=t;++a)if(e[a]==s&&a!=t)++o;else{if(!s&&o>2){for(;o>138;o-=138)i(32754);o>2&&(i(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(i(s),--o;o>6;o-=6)i(8304);o>2&&(i(o-3<<5|8208),o=0)}for(;o--;)i(s);o=1,s=e[a]}return{c:r.subarray(0,n),n:t}},yo=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},bo=function(e,t,r){var n=r.length,s=io(t+2);e[s]=255&n,e[s+1]=n>>8,e[s+2]=255^e[s],e[s+3]=255^e[s+1];for(var o=0;o<n;++o)e[s+o+4]=r[o];return 8*(s+4+n)},wo=function(e,t,r,n,s,o,i,a,c,l,u){po(t,u++,r),++s[256];for(var d=ho(s,15),p=d.t,f=d.l,h=ho(o,15),g=h.t,m=h.l,y=mo(p),b=y.c,w=y.n,v=mo(g),_=v.c,E=v.n,I=new Os(19),T=0;T<b.length;++T)++I[31&b[T]];for(T=0;T<_.length;++T)++I[31&_[T]];for(var x=ho(I,7),S=x.t,A=x.l,C=19;C>4&&!S[js[C-1]];--C);var R,P,U,k,L=l+5<<3,D=yo(s,Js)+yo(o,Qs)+i,O=yo(s,p)+yo(o,g)+i+14+3*C+yo(I,S)+2*I[16]+3*I[17]+7*I[18];if(c>=0&&L<=D&&L<=O)return bo(t,u,e.subarray(c,c+l));if(po(t,u,1+(O<D)),u+=2,O<D){R=Ks(p,f,0),P=p,U=Ks(g,m,0),k=g;var B=Ks(S,A,0);for(po(t,u,w-257),po(t,u+5,E-1),po(t,u+10,C-4),u+=14,T=0;T<C;++T)po(t,u+3*T,S[js[T]]);u+=3*C;for(var N=[b,_],$=0;$<2;++$){var j=N[$];for(T=0;T<j.length;++T){var M=31&j[T];po(t,u,B[M]),u+=S[M],M>15&&(po(t,u,j[T]>>5&127),u+=j[T]>>12)}}}else R=Zs,P=Js,U=to,k=Qs;for(T=0;T<a;++T){var F=n[T];if(F>255){fo(t,u,R[257+(M=F>>18&31)]),u+=P[M+257],M>7&&(po(t,u,F>>23&31),u+=Ns[M]);var H=31&F;fo(t,u,U[H]),u+=k[H],H>3&&(fo(t,u,F>>5&8191),u+=$s[H])}else fo(t,u,R[F]),u+=P[F]}return fo(t,u,R[256]),u+P[256]},vo=new Bs([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),_o=new Ds(0),Eo=function(e,t,r,n,s,o){var i=o.z||e.length,a=new Ds(n+i+5*(1+Math.ceil(i/7e3))+s),c=a.subarray(n,a.length-s),l=o.l,u=7&(o.r||0);if(t){u&&(c[0]=o.r>>3);for(var d=vo[t-1],p=d>>13,f=8191&d,h=(1<<r)-1,g=o.p||new Os(32768),m=o.h||new Os(h+1),y=Math.ceil(r/3),b=2*y,w=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&h},v=new Bs(25e3),_=new Os(288),E=new Os(32),I=0,T=0,x=o.i||0,S=0,A=o.w||0,C=0;x+2<i;++x){var R=w(x),P=32767&x,U=m[R];if(g[P]=U,m[R]=P,A<=x){var k=i-x;if((I>7e3||S>24576)&&(k>423||!l)){u=wo(e,c,0,v,_,E,T,S,C,x-C,u),S=I=T=0,C=x;for(var L=0;L<286;++L)_[L]=0;for(L=0;L<30;++L)E[L]=0}var D=2,O=0,B=f,N=P-U&32767;if(k>2&&R==w(x-N))for(var $=Math.min(p,k)-1,j=Math.min(32767,x),M=Math.min(258,k);N<=j&&--B&&P!=U;){if(e[x+D]==e[x+D-N]){for(var F=0;F<M&&e[x+F]==e[x+F-N];++F);if(F>D){if(D=F,O=N,F>$)break;var H=Math.min(N,F-2),G=0;for(L=0;L<H;++L){var z=x-N+L&32767,Y=z-g[z]&32767;Y>G&&(G=Y,U=z)}}}N+=(P=U)-(U=g[P])&32767}if(O){v[S++]=268435456|Gs[D]<<18|Vs[O];var W=31&Gs[D],V=31&Vs[O];T+=Ns[W]+$s[V],++_[257+W],++E[V],A=x+D,++I}else v[S++]=e[x],++_[e[x]]}}for(x=Math.max(x,A);x<i;++x)v[S++]=e[x],++_[e[x]];u=wo(e,c,l,v,_,E,T,S,C,x-C,u),l||(o.r=7&u|c[u/8|0]<<3,u-=7,o.h=m,o.p=g,o.i=x,o.w=A)}else{for(x=o.w||0;x<i+l;x+=65535){var q=x+65535;q>=i&&(c[u/8|0]=l,q=i),u=bo(c,u+1,e.subarray(x,q))}o.i=i}return ao(a,0,n+io(u)+s)},Io=function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var r=t,n=9;--n;)r=(1&r&&-306674912)^r>>>1;e[t]=r}return e}(),To=function(e,t,r,n,s){if(!s&&(s={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),i=new Ds(o.length+e.length);i.set(o),i.set(e,o.length),e=i,s.w=o.length}return Eo(e,null==t.level?6:t.level,null==t.mem?s.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):20:12+t.mem,r,n,s)},xo=function(e,t){var r={};for(var n in e)r[n]=e[n];for(var n in t)r[n]=t[n];return r},So=function(e,t,r){for(var n=e(),s=e.toString(),o=s.slice(s.indexOf("[")+1,s.lastIndexOf("]")).replace(/\s+/g,"").split(","),i=0;i<n.length;++i){var a=n[i],c=o[i];if("function"==typeof a){t+=";"+c+"=";var l=a.toString();if(a.prototype)if(-1!=l.indexOf("[native code]")){var u=l.indexOf(" ",8)+1;t+=l.slice(u,l.indexOf("(",u))}else for(var d in t+=l,a.prototype)t+=";"+c+".prototype."+d+"="+a.prototype[d].toString();else t+=l}else r[c]=a}return t},Ao=[],Co=function(){return[Ds,Os,Bs,Ns,$s,js,Hs,Ws,eo,ro,qs,co,Ks,no,so,oo,io,ao,lo,uo,$o,Po,Uo]},Ro=function(){return[Ds,Os,Bs,Ns,$s,js,Gs,Vs,Zs,Js,to,Qs,qs,vo,_o,Ks,po,fo,ho,go,mo,yo,bo,wo,io,ao,Eo,To,No,Po]},Po=function(e){return postMessage(e,[e.buffer])},Uo=function(e){return e&&{out:e.size&&new Ds(e.size),dictionary:e.dictionary}},ko=function(e,t,r,n,s,o){var i=function(e,t,r,n){if(!Ao[r]){for(var s="",o={},i=e.length-1,a=0;a<i;++a)s=So(e[a],s,o);Ao[r]={c:So(e[i],s,o),e:o}}var c=xo({},Ao[r].e);return Ls(Ao[r].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+t.toString()+"}",r,c,function(e){var t=[];for(var r in e)e[r].buffer&&t.push((e[r]=new e[r].constructor(e[r])).buffer);return t}(c),n)}(r,n,s,function(e,t){i.terminate(),o(e,t)});return i.postMessage([e,t],t.consume?[e.buffer]:[]),function(){i.terminate()}},Lo=function(e,t){return e[t]|e[t+1]<<8},Do=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},Oo=function(e,t){return Do(e,t)+4294967296*Do(e,t+4)},Bo=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8};function No(e,t){return To(e,t||{},0,0)}function $o(e,t){return uo(e,{i:2},t&&t.out,t&&t.dictionary)}var jo=function(e,t,r,n){for(var s in e){var o=e[s],i=t+s,a=n;Array.isArray(o)&&(a=xo(n,o[1]),o=o[0]),o instanceof Ds?r[i]=[o,a]:(r[i+="/"]=[new Ds(0),a],jo(o,i,r,n))}},Mo="undefined"!=typeof TextEncoder&&new TextEncoder,Fo="undefined"!=typeof TextDecoder&&new TextDecoder;try{Fo.decode(_o,{stream:!0})}catch(e){}function Ho(e,t){if(Mo)return Mo.encode(e);for(var r=e.length,n=new Ds(e.length+(e.length>>1)),s=0,o=function(e){n[s++]=e},i=0;i<r;++i){if(s+5>n.length){var a=new Ds(s+8+(r-i<<1));a.set(n),n=a}var c=e.charCodeAt(i);c<128||t?o(c):c<2048?(o(192|c>>6),o(128|63&c)):c>55295&&c<57344?(o(240|(c=65536+(1047552&c)|1023&e.charCodeAt(++i))>>18),o(128|c>>12&63),o(128|c>>6&63),o(128|63&c)):(o(224|c>>12),o(128|c>>6&63),o(128|63&c))}return ao(n,0,s)}var Go=function(e){var t=0;if(e)for(var r in e){var n=e[r].length;n>65535&&lo(9),t+=n+4}return t},zo=function(e,t,r,n,s,o,i,a){var c=n.length,l=r.extra,u=a&&a.length,d=Go(l);Bo(e,t,null!=i?33639248:67324752),t+=4,null!=i&&(e[t++]=20,e[t++]=r.os),e[t]=20,t+=2,e[t++]=r.flag<<1|(o<0&&8),e[t++]=s&&8,e[t++]=255&r.compression,e[t++]=r.compression>>8;var p=new Date(null==r.mtime?Date.now():r.mtime),f=p.getFullYear()-1980;if((f<0||f>119)&&lo(10),Bo(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=o&&(Bo(e,t,r.crc),Bo(e,t+4,o<0?-o-2:o),Bo(e,t+8,r.size)),Bo(e,t+12,c),Bo(e,t+14,d),t+=16,null!=i&&(Bo(e,t,u),Bo(e,t+6,r.attrs),Bo(e,t+10,i),t+=14),e.set(n,t),t+=c,d)for(var h in l){var g=l[h],m=g.length;Bo(e,t,+h),Bo(e,t+2,m),e.set(g,t+4),t+=4+m}return u&&(e.set(a,t),t+=u),t},Yo="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()},Wo=[/^\/$/,/^\*+$/,/^[0-9]+$/],Vo=["/artifact/","https://","http://","*********"],qo=new Set(["sha1","_sha1","pageref","downloadsPath","tracesDir","pageId"]);function Ko({sensitiveValues:e,str:t}){return e.reduce((e,t)=>e.replaceAll(t,"[REDACTED]"),t)}function Jo({sensitiveValues:e,value:t}){return"string"==typeof t?Ko({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>Jo({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?Qo({obj:t,sensitiveValues:e}):t}function Xo(e){return!!qo.has(e)||e.toLowerCase().endsWith("sha1")}function Qo({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Xo(e)?r:Jo({sensitiveValues:t,value:r})]))}function Zo({error:e,sensitiveValues:t}){return e?{...e,message:Ko({sensitiveValues:t,str:e.message})}:void 0}function ei({content:e,sensitiveValues:t}){const r=new u.TextDecoder,n=new u.TextEncoder,s=Ko({sensitiveValues:t,str:r.decode(e)});return n.encode(s)}var ti=u.promisify(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&lo(7);var n=[],s=function(){for(var e=0;e<n.length;++e)n[e]()},o={},i=function(e,t){Yo(function(){r(e,t)})};Yo(function(){i=r});for(var a=e.length-22;101010256!=Do(e,a);--a)if(!a||e.length-a>65558)return i(lo(13,0,1),null),s;var c=Lo(e,a+8);if(c){var l=c,u=Do(e,a+16),d=4294967295==u||65535==l;if(d){var p=Do(e,a-12);(d=101075792==Do(e,p))&&(l=c=Do(e,p+32),u=Do(e,p+48))}for(var f=t&&t.filter,h=function(t){var r=function(e,t,r){var n=Lo(e,t+28),s=function(e,t){if(t){for(var r="",n=0;n<e.length;n+=16384)r+=String.fromCharCode.apply(null,e.subarray(n,n+16384));return r}if(Fo)return Fo.decode(e);var s=function(e){for(var t="",r=0;;){var n=e[r++],s=(n>127)+(n>223)+(n>239);if(r+s>e.length)return{s:t,r:ao(e,r-1)};s?3==s?(n=((15&n)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t+=String.fromCharCode(55296|n>>10,56320|1023&n)):t+=1&s?String.fromCharCode((31&n)<<6|63&e[r++]):String.fromCharCode((15&n)<<12|(63&e[r++])<<6|63&e[r++]):t+=String.fromCharCode(n)}}(e),o=s.s;return(r=s.r).length&&lo(8),o}(e.subarray(t+46,t+46+n),!(2048&Lo(e,t+8))),o=t+46+n,i=Do(e,t+20),a=r&&4294967295==i?function(e,t){for(;1!=Lo(e,t);t+=4+Lo(e,t+2));return[Oo(e,t+12),Oo(e,t+4),Oo(e,t+20)]}(e,o):[i,Do(e,t+24),Do(e,t+42)],c=a[0],l=a[1],u=a[2];return[Lo(e,t+10),c,l,s,o+Lo(e,t+30)+Lo(e,t+32),u]}(e,u,d),a=r[0],l=r[1],p=r[2],h=r[3],g=r[4],m=r[5],y=function(e,t){return t+30+Lo(e,t+26)+Lo(e,t+28)}(e,m);u=g;var b=function(e,t){e?(s(),i(e,null)):(t&&(o[h]=t),--c||i(null,o))};if(!f||f({name:h,size:l,originalSize:p,compression:a}))if(a)if(8==a){var w=e.subarray(y,y+l);if(p<524288||l>.8*p)try{b(null,$o(w,{out:new Ds(p)}))}catch(e){b(e,null)}else n.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&lo(7),ko(e,t,[Co],function(e){return Po($o(e.data[0],Uo(e.data[1])))},1,r)}(w,{size:p},b))}else b(lo(14,"unknown compression type "+a,1),null);else b(null,ao(e,y,y+l));else b(null,null)},g=0;g<l;++g)h()}else i(null,{});return s}),ri=u.promisify(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&lo(7);var n={};jo(e,"",n,t);var s=Object.keys(n),o=s.length,i=0,a=0,c=o,l=new Array(o),u=[],d=function(){for(var e=0;e<u.length;++e)u[e]()},p=function(e,t){Yo(function(){r(e,t)})};Yo(function(){p=r});var f=function(){var e=new Ds(a+22),t=i,r=a-i;a=0;for(var n=0;n<c;++n){var s=l[n];try{var o=s.c.length;zo(e,a,s,s.f,s.u,o);var u=30+s.f.length+Go(s.extra),d=a+u;e.set(s.c,d),zo(e,i,s,s.f,s.u,o,a,s.m),i+=16+u+(s.m?s.m.length:0),a=d+o}catch(e){return p(e,null)}}!function(e,t,r,n,s){Bo(e,t,101010256),Bo(e,t+8,r),Bo(e,t+10,r),Bo(e,t+12,n),Bo(e,t+16,s)}(e,i,l.length,r,t),p(null,e)};o||f();for(var h=function(e){var t=s[e],r=n[t],c=r[0],h=r[1],g=function(){var e=-1;return{p:function(t){for(var r=e,n=0;n<t.length;++n)r=Io[255&r^t[n]]^r>>>8;e=r},d:function(){return~e}}}(),m=c.length;g.p(c);var y=Ho(t),b=y.length,w=h.comment,v=w&&Ho(w),_=v&&v.length,E=Go(h.extra),I=0==h.level?0:8,T=function(r,n){if(r)d(),p(r,null);else{var s=n.length;l[e]=xo(h,{size:m,crc:g.d(),c:n,f:y,m:v,u:b!=t.length||v&&w.length!=_,compression:I}),i+=30+b+E+s,a+=76+2*(b+E)+(_||0)+s,--o||f()}};if(b>65535&&T(lo(11,0,1),null),I)if(m<16e4)try{T(null,No(c,h))}catch(e){T(e,null)}else u.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&lo(7),ko(e,t,[Ro],function(e){return Po(No(e.data[0],e.data[1]))},0,r)}(c,h,T));else T(null,c)},g=0;g<c;++g)h(g);return d});async function ni({content:e,filename:t,sensitiveValues:r}){const n=t.toLowerCase();return n.endsWith(".trace")||n.endsWith(".network")?function({content:e,sensitiveValues:t}){const r=new u.TextDecoder,n=new u.TextEncoder,s=r.decode(e).split("\n").map(e=>{if(!e.trim())return e;try{const r=function({event:e,sensitiveValues:t}){return p.match(e).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:Ko({sensitiveValues:t,str:e.preview}),value:Jo({sensitiveValues:t,value:e.value})})),text:Ko({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:Qo({obj:e.params,sensitiveValues:t}),title:e.title?Ko({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:Zo({error:e.error,sensitiveValues:t}),result:void 0!==e.result?Jo({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:Zo({error:e.error,sensitiveValues:t}),params:Qo({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?Jo({sensitiveValues:t,value:e.result}):void 0,title:e.title?Ko({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:Qo({obj:e.params,sensitiveValues:t})})).with({type:"stdout"},{type:"stderr"},e=>({...e,text:void 0!==e.text?Ko({sensitiveValues:t,str:e.text}):void 0})).with({type:"error"},e=>({...e,message:Ko({sensitiveValues:t,str:e.message})})).with({type:"log"},e=>({...e,message:Ko({sensitiveValues:t,str:e.message})})).with({type:"context-options"},e=>({...e,options:Qo({obj:e.options,sensitiveValues:t}),title:e.title?Ko({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:Qo({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:Qo({obj:e.snapshot,sensitiveValues:t})})).with({type:"screencast-frame"},{type:"input"},e=>e).exhaustive()}({event:JSON.parse(e),sensitiveValues:t});return JSON.stringify(r)}catch{return Ko({sensitiveValues:t,str:e})}});return n.encode(s.join("\n"))}({content:e,sensitiveValues:r}):n.endsWith(".html")||n.endsWith(".dat")||n.endsWith(".json")?ei({content:e,sensitiveValues:r}):n.startsWith("resources/")?async function({content:e,sensitiveValues:t}){return await(0,Us.isBinaryFile)(Buffer.from(e))?e:ei({content:e,sensitiveValues:t})}({content:e,sensitiveValues:r}):e}function si(e=process.cwd()){let r=t.resolve(e);for(;;){const e=oi(r);if(e){const n={...e.dependencies,...e.devDependencies},s="@playwright/test"in n?"@playwright/test":"playwright"in n?"playwright":void 0;if(s){const e=ii(r);let n=!1,o=r;for(;;){const e=t.join(o,"node_modules"),r=t.join(e,s);if(i.existsSync(r)){n=!0;break}const a=t.dirname(o);if(a===o)break;o=a}return{inNodeModules:n,installed:!0,packageManager:e,packageName:s}}}const n=t.dirname(r);if(n===r)return{inNodeModules:!1,installed:!1,packageManager:void 0};r=n}}function oi(e){const r=t.join(e,"package.json");let n;try{n=i.readFileSync(r,"utf-8")}catch{return}try{return JSON.parse(n)}catch{return}}function ii(e){const r=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];let n=e;for(;;){for(const[e,s]of r)if(i.existsSync(t.join(n,s)))return e;const e=t.dirname(n);if(e===n)return;n=e}}function ai(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 ci=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),li=e=>(e instanceof Error?e.message:String(e)).slice(0,400),ui=({outputDir:e,representativeTest:t})=>{const r=["test","--trace=on","--workers=1","--retries=0","--output",e];return t.filePath&&r.push(t.filePath),t.testIdentifier?r.push("--grep",`^${ci(t.testIdentifier)}$`):t.testTitle&&r.push("--grep",ci(t.testTitle)),r},di=async e=>{const t=await m.readdir(e,{withFileTypes:!0}),r=[];for(const n of t){const t=O.default.join(e,n.name);if(n.isDirectory())r.push(...await di(t));else if(n.isFile()&&"trace.zip"===n.name){const e=await m.stat(t);r.push({path:t,mtimeMs:e.mtimeMs})}}return r},{zSuiteAutoHealReport:pi,zRepresentativeTest:fi}=function(e){const t=e.enum(xs),r=["Classification of the root cause:","",`- test: ${As("test")}`,`- bug: ${As("bug")}`,`- other: ${As("other")}`].join("\n"),n=e.object({filePath:e.string().optional(),testIdentifier:e.string().optional(),testTitle:e.string().optional()}),s=e.object({status:e.enum(["captured","capture_failed","upload_failed"]),representativeTest:n,storage:e.object({bucket:e.string(),key:e.string()}).optional(),signedUrl:e.string().optional(),error:e.string().optional()}),o=s.extend({testCaseId:e.string().min(1).describe("Test case ID this trace proof corresponds to.")}),i=e.object({erroredUrl:e.string().optional(),issueType:t.describe(r),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).")}),a=e.discriminatedUnion("result",[i.extend({fixApplied:e.string().describe("What fix was applied (brief, specific)."),result:e.literal("fixed"),traceProof:s.optional().describe("Optional trace proof metadata for fixed issues."),traceProofs:e.array(o).min(1).optional().describe("Optional per-test trace proof metadata for fixed issues.")}),i.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:a,zIssueCategory:t,zRepresentativeTest:n,zSuiteAutoHealReport:e.object({issues:e.array(a).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.")}),zTraceProof:s,zTraceProofByTest:o}}(T.z),hi=({authHeader:e,diffTracker:t,orgId:r,runId:n,workingDir:o})=>d.createSdkMcpServer({name:"auto-heal-report",tools:[d.tool("capture-trace-proof",["Capture and upload a Playwright trace proof for a fixed issue or fixed test case.","","Use this only for fixed results. Pass representative test info from the worker.","Pass testCaseId and call once per fixed test case.","testCaseId is for per-test mapping/storage metadata; representativeTest selects the runnable test."].join("\n"),{issueId:T.z.string().min(1).describe("Issue identifier for deterministic output paths and storage key naming."),proofId:T.z.string().min(1).optional().describe("Optional id for deterministic proof naming and deduplication."),representativeTest:fi.optional().default({}),testCaseId:T.z.string().min(1).optional().describe("Optional test case ID when capturing per-test trace proofs.")},async({issueId:t,proofId:a,representativeTest:c,testCaseId:l})=>{const u=T.z.string().min(1).parse(t),d=null==a?void 0:T.z.string().min(1).parse(a),p=null==l?void 0:T.z.string().min(1).parse(l),f=await(async({authHeader:e,issueId:t,orgId:r,proofId:n,representativeTest:o,runId:a,testCaseId:c,workingDir:l})=>{if(!(e=>null!=e.filePath||null!=e.testTitle||null!=e.testIdentifier)(o))return{status:"capture_failed",representativeTest:o,error:"Representative test info is missing (need filePath, testTitle, or testIdentifier)."};const u=si(l);if(!u.installed||!u.inNodeModules||!u.packageManager)return{status:"capture_failed",representativeTest:o,error:"Playwright is not installed in the current workspace."};const d=(e=>Rs(e)??"issue")(t),p=(({proofId:e,testCaseId:t})=>Ps(t)??Ps(e))({testCaseId:c,proofId:n}),f=O.default.join(l,".stably","autoheal-proof",d,p??"issue"),[h,...g]=ai(u.packageManager),y=[...g,...ui({outputDir:f,representativeTest:o})];try{await m.rm(f,{force:!0,recursive:!0}),await m.mkdir(f,{recursive:!0});const{code:u,stderr:d,timedOut:p}=await(async({args:e,command:t,cwd:r,timeoutMs:n})=>await new Promise((o,i)=>{const a=s.spawn(t,e,{cwd:r,env:process.env,stdio:["ignore","ignore","pipe"]});let c="",l=!1;a.stderr.on("data",e=>{c+=e.toString()});const u=setTimeout(()=>{l=!0,a.kill("SIGTERM")},n);a.on("error",e=>{clearTimeout(u),i(e)}),a.on("close",e=>{clearTimeout(u),o({code:e,stderr:c,timedOut:l})})}))({args:y,command:h,cwd:l,timeoutMs:3e5});if(p)return{status:"capture_failed",representativeTest:o,error:"Trace proof run timed out while executing Playwright verification."};if(0!==u)return{status:"capture_failed",representativeTest:o,error:`Trace proof run failed (exit code ${u??"unknown"}): ${d.trim().slice(0,280)}`};const g=await(async e=>{const t=await di(e);if(0!==t.length)return t.sort((e,t)=>t.mtimeMs-e.mtimeMs),t[0]?.path})(f);if(!g)return{status:"capture_failed",representativeTest:o,error:"Trace proof run completed, but no trace.zip was produced."};const{traceBucketPath:b,uploadUrl:w,sensitiveValues:v}=await(async({authHeader:e,issueId:t,proofId:r,testCaseId:n,contentType:s="application/zip",orgId:o,runId:i})=>{const a=await(c={auth:e,body:{contentType:s,issueId:t,proofId:r,testCaseId:n},client:Rr(),headers:Cn(o),path:{runId:i}},(c.client??wr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-trace/upload-url",...c,headers:{"Content-Type":"application/json",...c.headers}}));var c;if(a.error)throw new Error(`Failed to presign trace upload (${a.response.status})`);const l=kn.parse(a.data);return{traceBucketPath:l.traceBucketPath,expiresInSeconds:l.expiresInSeconds,key:l.key,uploadUrl:l.uploadUrl,sensitiveValues:l.sensitiveValues}})({authHeader:e,issueId:t,proofId:n,orgId:r,runId:a,testCaseId:c}),_=await async function({tracePath:e,sensitiveValues:t}){const r=[],n=i.createReadStream(e);for await(const e of n)r.push(e);return async function({sensitiveValues:e,traceBuffer:t}){const r=e.filter(e=>!(e.length<3||Wo.some(t=>t.test(e))||Vo.some(t=>e.includes(t))));if(0===r.length)return new Uint8Array(t);const n=[...r].sort((e,t)=>t.length-e.length),s=await ti(new Uint8Array(t)),o=Object.entries(s),i=await Promise.all(o.map(async([e,t])=>[e,await ni({content:t,filename:e,sensitiveValues:n})])),a=Object.fromEntries(i);return ri(a)}({traceBuffer:new Uint8Array(Buffer.concat(r)),sensitiveValues:t})}({tracePath:g,sensitiveValues:v});try{await(async({contentType:e="application/zip",traceBuffer:t,uploadUrl:r})=>{const n=await fetch(r,{body:Buffer.from(t),headers:{"Content-Type":e},method:"PUT"});if(!n.ok)throw new Error(`Failed to upload trace (${n.status})`)})({traceBuffer:_,uploadUrl:w})}catch(e){return{status:"upload_failed",representativeTest:o,error:li(e)}}return{status:"captured",representativeTest:o,storage:b}}catch(e){return{status:"capture_failed",representativeTest:o,error:li(e)}}})({authHeader:e,issueId:u,orgId:r,proofId:d,representativeTest:fi.parse(c??{}),runId:n,testCaseId:p,workingDir:o}),h="string"==typeof p?{testCaseId:p,...f}:f;return{content:[{text:JSON.stringify(h),type:"text"}]}}),d.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:pi},async({report:s})=>{const o=await t.computeDiff(),i=(e=>{if(!e||"object"!=typeof e)return e;const t=e;if(!Array.isArray(t.issues))return e;const r=t.issues.map(e=>{if(!e||"object"!=typeof e)return e;const t=e;if("fixed"!==t.result||null!=t.traceProof||!Array.isArray(t.traceProofs))return e;const[r]=t.traceProofs;if(!r||"object"!=typeof r)return e;const n={...r};return delete n.testCaseId,{...t,traceProof:n}});return{...t,issues:r}})(s),a=pi.parse(i);try{await(async({authHeader:e,orgId:t,report:r,runId:n})=>{const s=await(o={auth:e,body:{report:JSON.stringify(r)},client:Rr(),headers:Cn(t),path:{runId:n}},(o.client??wr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to upload auto-heal report (${s.response.status})`)})({authHeader:e,orgId:r,report:a,runId:n});const{diffBucketPath:t,uploadUrl:s}=await Ln({authHeader:e,contentType:"text/plain",orgId:r,runId:n});await Dn({contentType:"text/plain",diff:o,uploadUrl:s}),await On({authHeader:e,diffBucketPath:t,orgId:r,runId:n})}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. ${e instanceof Error?e.message:String(e)} 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"}),gi=({onComplete:e,onRestartRequested:t})=>e?d.createSdkMcpServer({name:"session-control",tools:[d.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:T.z.string().describe("A brief summary of what was accomplished")},({summary:t})=>{const r="string"==typeof t?t:String(t);return e(),Promise.resolve(`Session complete: ${r}`)})]}):d.createSdkMcpServer({name:"stably-agent-control",version:"1.0.0",tools:[d.tool("restart_mcp_servers",'Restart the MCP servers to reinitialize browser tools after dependency changes.\n\nWHEN TO USE:\n- After installing or updating @playwright/test to version 1.56.x\n- When browser tools fail due to version mismatch errors\n- When the user has fixed a dependency issue and you need to reinitialize\n\nIMPORTANT: The restart happens at the END of your current turn.\n- Do NOT call any browser tools (setup_page, navigate, etc.) after this tool in the same turn - they will use the OLD servers\n- After calling this tool, END your turn naturally (no more tool calls)\n- The system will automatically continue in a new turn once the tools are restarted\n- Do NOT ask the user to reply again just to resume (only ask if you truly need additional input)\n\nEnd your turn briefly. You may say something like:\n- "Restarting browser tools now…"\n- "Tools are restarting to pick up the dependency changes…"',{},()=>(t(),Promise.resolve({content:[{type:"text",text:"MCP servers are being restarted. Browser tools will be reinitialized."}]})))]}),mi=T.z.object({commentUrl:T.z.string()}),yi=({prContext:e,authHeader:t,orgId:r,onReportPosted:n})=>d.createSdkMcpServer({name:"create-report",tools:[d.tool("post_create_report",`Post a test creation report as a GitHub comment on PR #${e.prNumber}.\nCall this tool at the end of test creation to summarize what was created.\nThe report will be posted to: ${e.prUrl}\n\nWHEN TO USE:\n- After you have finished creating test files\n- To provide a summary of the tests created on the PR for visibility\n\nThe report will include:\n- A list of all test files created\n- Your summary of what was tested`,{summary:T.z.string().describe("A summary of the tests created. Include what features/flows are tested and any important notes."),filesCreated:T.z.array(T.z.string()).describe("List of test file paths that were created (relative to workspace root)")},async({summary:s,filesCreated:o})=>{const i=Array.isArray(o)?o:[];bn.info("[create-report] Posting report to GitHub PR",{prNumber:e.prNumber,filesCount:i.length});try{const o={summary:"string"==typeof s?s:String(s),filesCreated:i.map(String)},a=await async function({authHeader:e,orgId:t,prNumber:r,owner:n,repo:s,report:o}){const i=new URL("/internal/v1/cli/create-report",_r).toString(),a={Authorization:e,"Content-Type":"application/json"};t&&(a["x-stably-org-id"]=t),bn.debug("Posting create report to GitHub",{prNumber:r,owner:n,repo:s,filesCount:o.filesCreated.length});const c=await fetch(i,{method:"POST",headers:a,body:JSON.stringify({prNumber:r,owner:n,repo:s,report:o}),signal:AbortSignal.timeout(3e4)});if(!c.ok){const e=await c.text().catch(()=>"");throw bn.error("Failed to post create report",{status:c.status,error:e.slice(0,500)}),new Error(`Failed to post create report: ${c.status} ${e.slice(0,200)}`)}const l=mi.parse(await c.json());return bn.info("Create report posted successfully",{commentUrl:l.commentUrl}),l}({authHeader:t,orgId:r,prNumber:e.prNumber,owner:e.owner,repo:e.repo,report:o});return n?.(a),bn.info("[create-report] Report posted successfully",{commentUrl:a.commentUrl}),{content:[{type:"text",text:`✅ Test creation report posted to PR #${e.prNumber}\n\nView the comment: ${a.commentUrl}`}]}}catch(e){const t=e instanceof Error?e.message:String(e);return bn.error("[create-report] Failed to post report",{error:t}),{content:[{type:"text",text:`❌ Failed to post report to GitHub: ${t}\n\nThe tests were still created successfully, but the PR comment could not be posted.`}],isError:!0}}})]}),bi=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]"),wi=(e,t)=>({message:bi(e),status:t?.status,statusText:t?.statusText}),vi=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"]),_i=async({authHeader:e,mode:t,maxTurnsOverride:r})=>{const n=Rr();bn.debug("Requesting subagent definitions from API",{mode:t,maxTurnsOverride:r});const s=await(o={client:n,auth:e,body:{mode:t,maxTurnsOverride:r}},(o.client??wr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/subagents",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(401===s.response.status)throw bn.warn("Subagent definitions fetch failed: unauthorized (401)"),await zr(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===s.response.status)throw bn.warn("Subagent definitions fetch failed: forbidden (403)"),await zr(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(s.error)throw bn.warn("Subagent definitions fetch failed",{error:s.error}),new Error(`Failed to fetch subagent definitions: ${JSON.stringify(s.error)}`);const{subagents:i}=s.data;return bn.debug("Subagent definitions received",{count:Object.keys(i).length}),i},{zStablyYaml:Ei}=function(e){const t=e.object({cron:e.string(),stablyTestArgs:e.string().optional(),timezone:e.string().optional()}),r=e.object({maxTurnsPerIssue:e.number().int().positive().optional(),maxParallelWorkers:e.number().int().positive().optional(),rules:e.string().optional()}),n=e.object({fix:r.optional()});return{zStablyYaml:e.object({schedules:e.record(e.string(),t).optional(),agent:n.optional()}),zAgentConfig:n,zAgentFixConfig:r,zScheduleEntry:t}}(w.z),Ii=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],Ti=["Task","mcp__playwright-test","Skill"],xi=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],Si=e=>{if("EPIPE"!==e.code)throw e},Ai="__main__",Ci=e=>"mcp__auto-heal-report__generate-report"===e,Ri=e=>"mcp__auto-heal-report__capture-trace-proof"===e?"Verify Test Run":"mcp__auto-heal-report__generate-report"===e?"Generate Report":Is(e);async function Pi(e,t){return!!e&&(!!e.hasQueuedMessages()||new Promise(r=>{const n=setTimeout(()=>{clearInterval(s),r(!1)},t),s=setInterval(()=>{e.hasQueuedMessages()&&(clearTimeout(n),clearInterval(s),r(!0))},200)}))}var Ui=async r=>{if("single"===r.mode||"build"===r.mode){const e=Array.isArray(r.prompt)?r.prompt.join(" "):r.prompt;bn.initSession(e||"create-from-diff")}else"fix"===r.mode&&bn.initSession(`fix-${r.runId}`);bn.info("Agent session starting",{mode:r.mode}),process.stdout.on("error",Si),process.stderr.on("error",Si);const n=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",n),bn.debug("Checking authentication");const s=await Tn({autoLogin:"chat"===r.mode||"init"===r.mode}),o=(e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken)(s);bn.debug("Authentication resolved",{authType:s.type});const c="oauth"===s.type?s.auth.context.orgId:void 0,l=O.default.resolve(process.cwd()),u=O.default.join(l,".env"),f=$.default.existsSync(u)&&$.default.statSync(u).isFile(),h=f?e.parse($.default.readFileSync(u,"utf8")):{};bn.debug("Environment file",{path:u,exists:f,variableCount:Object.keys(h).length});const g="chat"!==r.mode&&"init"!==r.mode,y="chat"===r.mode;let b=new os;const w="chat"===r.mode?r.getHelpText:void 0,v={log:[],promptDisplay:p.match(r).with({mode:"chat"},()=>"Ask Stably to build tests for you").with({mode:"init"},()=>"Setting up Playwright and Stably SDK").with({mode:"fix"},()=>"Fixing broken tests").with({mode:"build"},()=>"Building tests from specifications").with({mode:"single"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Creating tests from PR/branch changes"}).exhaustive(),status:"running"};let _,E,I,T,x=g,C=!1,P=!1,k=0,L=0,D=!1;const B=[];let N,j,M=[],G=!1,z=!1,Y=0;const W=new Map;let V=null,q=!1,K=!1;const J=Date.now();let X,Q="fix"===r.mode?{suiteId:r.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:J,endedAt:null,isError:!1,updatedAt:J,recentActivity:[],workers:[{id:Ai,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:J,endedAt:null,activity:[]}]}:null;const Z=new Set,ee=(e,t)=>{if(!Q)return;const r=Q.workers.map(r=>{if(r.id!==e)return r;const n=[...r.activity,{...t,timestamp:Date.now()}].slice(-15);return{...r,activity:n}});ne({workers:r})},te=e=>{if(!Q)return;const t=[...Q.recentActivity,{...e,timestamp:Date.now()}].slice(-10);ne({recentActivity:t})},re=e=>(Q?.workers??[]).map(t=>t.id===Ai?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),ne=e=>{Q&&!X?.isClosed&&(Q={...Q,...e,updatedAt:Date.now()},X?.sendProgress(Q))},se=async e=>{if("fix"===r.mode){if("STARTED"===e){if(q)return;q=!0}else{if(K)return;K=!0}try{await(async({authHeader:e,orgId:t,runId:r,status:n})=>{const s=await(o={auth:e,body:{status:n},client:Rr(),headers:Cn(t),path:{runId:r}},(o.client??wr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-status",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to update autoheal status (${s.response.status})`)})({authHeader:o,orgId:c,runId:r.runId,status:e})}catch{}}},oe="single"===r.mode||"build"===r.mode,ie=Date.now();let ae,ce=null;const le=e=>{ce&&!ae?.isClosed&&(ce={...ce,...e,updatedAt:Date.now()},ae?.sendProgress(ce))},ue=e=>{if(!ce)return;const t=[...ce.recentActivity,{...e,timestamp:Date.now()}].slice(-10);le({recentActivity:t})};if(oe||"fix"===r.mode)try{const e=new URL("/internal/v1/cli/progress",_r).toString(),t={Authorization:o,"Content-Type":"application/json"};c&&(t["x-stably-org-id"]=c);const n="single"===r.mode?"create":"build"===r.mode?"build":"fix",i=await fetch(e,{method:"POST",headers:t,body:JSON.stringify({mode:n,projectId:xn(s),agentId:F.default.randomUUID(),..."fix"===r.mode?{playwrightSuiteRunId:r.runId}:{}}),signal:AbortSignal.timeout(1e4)});if(i.ok){const{sessionId:e}=await i.json();if(oe){const t="single"===r.mode||"build"===r.mode?Array.isArray(r.prompt)?r.prompt.join(" "):r.prompt:null,n=is(l);ce={sessionId:e,phase:"initializing",startedAt:ie,endedAt:null,isError:!1,updatedAt:ie,currentActivity:null,filesCreated:[],recentActivity:[],prompt:t||null,environment:{gitBranch:n?.branch??null,workingDirectory:l,nodeVersion:process.version,cliVersion:vr}},ae=new Nn({authHeader:o,orgId:c,sessionId:e,onUserMessage:e=>{b&&(bn.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),ue({type:"user_message",summary:e}),be({text:`[Web] ${e}`}),b.pushText(`[Message from web UI user]: ${e}`),x||(x=!0,Se({status:"running"})))}}),ae.start(),le({phase:"initializing"})}bn.info(`[${n}] Progress session created`,{sessionId:e})}else{const t=await i.text().catch(()=>"");bn.warn(`[${n}] Failed to create progress session: ${i.status} ${e} — ${t.slice(0,300)}`)}}catch(e){const t=e instanceof Error?e.message:String(e);bn.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const de={current:e=>{}},pe={current:async()=>{}},{addSubagentActivity:fe,addSubagentStart:he,addTool:ge,addToolResult:me,appendText:ye,appendUserMessage:be,cleanup:we,setExiting:ve,setRunningLabel:_e,setStatus:Ee,setSubagentStatus:Ie,updateFixProgress:Te}=await(async(e,t)=>{const{Box:r,Static:n,Text:s,render:o,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=()=>A.jsx(s,{inverse:!0,children:" "}),u=(({Box:e,Text:t,useInput:r},n,s)=>function({onChoice:o,prompt:i}){const[a,c]=S.useState(0),[l,u]=S.useState(!1),[d,p]=S.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"}];r((e,t)=>{if(l)return t.return?void o("deny_with_message",d||"User denied this action"):t.escape?(u(!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 u(!0):void o(e.value)}const r=parseInt(e,10);if(r>=1&&r<=f.length){const e=f[r-1];if("deny_with_message"===e.value)return void u(!0);o(e.value)}},{isActive:s});const h=Is(i.toolName),g=Ts(i.toolName,i.input);return A.jsxs(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[A.jsx(t,{bold:!0,color:"yellow",children:"Permission Required"}),A.jsxs(e,{flexDirection:"column",marginTop:1,children:[A.jsx(t,{color:"magenta",children:h}),null!=g&&A.jsxs(t,{color:"gray",children:[" ",g]})]}),null!=i.decisionReason&&A.jsx(e,{marginTop:1,children:A.jsxs(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),l?A.jsxs(e,{flexDirection:"column",marginTop:1,children:[A.jsx(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),A.jsxs(t,{children:[A.jsx(t,{color:"yellow",children:">"})," ",d,A.jsx(n,{})]})]}):A.jsxs(e,{flexDirection:"column",marginTop:1,children:[A.jsx(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,r)=>A.jsx(t,{children:A.jsxs(t,{color:r===a?"cyan":void 0,children:[r===a?"❯":" "," ",r+1,". ",e.label]})},e.value))]})]})})({Box:r,Text:s,useInput:i},l,a),d=(({Cursor:e,inkComponents:{Box:t,Static:r,Text:n,useInput:s},isRawModeSupported:o,PermissionPrompt:i,Spinner:a})=>{const c=({progress:e})=>{const[r,s]=S.useState(Date.now());S.useEffect(()=>{const e=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(e)},[]);const o=r-e.startedAt,i=Math.floor(o/1e3),a=Math.floor(i/60),c=i%60,l=a>0?`${a}m ${c.toString().padStart(2,"0")}s`:`${c}s`,{label:u,color:d}={initializing:{label:"Fetching test results",color:"gray"},triage:{label:"Triaging failures",color:"yellow"},fixing:{label:"Fixing tests",color:"cyan"},validation:{label:"Validating fixes",color:"blue"},complete:{label:"Complete",color:"green"}}[e.phase],p=e.fixedTests+e.failedTests,f="fixing"===e.phase&&p>0?null!==e.totalTests?` (fixed ${e.fixedTests}/${e.totalTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:` (fixed ${e.fixedTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:"";return A.jsx(t,{flexDirection:"column",children:A.jsxs(n,{children:[A.jsx(n,{color:d,bold:!0,children:u}),A.jsx(n,{color:"gray",children:f}),A.jsxs(n,{color:"gray",children:[" [",l,"]"]})]})})},l=({progress:e})=>{const r=e.endedAt??Date.now(),s=Math.floor((r-e.startedAt)/1e3),o=Math.floor(s/60),i=s%60,a=o>0?`${o}m ${i.toString().padStart(2,"0")}s`:`${i}s`,c=e.isError?"yellow":"green",l=e.isError?"Fix stopped":"Fix complete";return A.jsxs(t,{flexDirection:"column",children:[A.jsxs(n,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&A.jsxs(n,{color:"gray",children:[e.fixedTests,"/",e.totalTests," tests fixed",e.failedTests>0?`, ${e.failedTests} failed`:""]})]})},u=e=>{if("subagent"===e.kind&&e.subagent){const{subagent:r}=e,s="complete"===r.status?"green":"error"===r.status?"red":"yellow";return A.jsxs(t,{flexDirection:"column",marginTop:1,children:[A.jsxs(n,{children:[A.jsx(n,{color:s,bold:!0,children:"Agent"}),r.description?A.jsxs(n,{color:"gray",children:[" (",r.description,")"]}):null]}),r.activities.length>0&&A.jsx(t,{flexDirection:"column",marginLeft:2,children:r.activities.map(e=>(e=>"tool"===e.kind?A.jsxs(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?A.jsx(n,{color:"gray",children:e.content},e.id):null)(e))})]},e.id)}return"tool"===e.kind?A.jsxs(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?A.jsx(n,{color:"gray",children:e.content},e.id):"user"===e.kind?A.jsxs(n,{color:"cyan",children:["You: ",e.content]},e.id):A.jsx(n,{children:e.content},e.id)},d="vscode"===process.env.TERM_PROGRAM,p=(e,t)=>{if(t<=0)return 0;let r=t-1;for(;r>0&&/\s/.test(e[r]);)r--;for(;r>0&&!/\s/.test(e[r-1]);)r--;return r},f=(e,t)=>{if(t>=e.length)return e.length;let r=t;for(;r<e.length&&!/\s/.test(e[r]);)r++;for(;r<e.length&&/\s/.test(e[r]);)r++;return r},h=(e,t)=>{if(t<=0)return 0;const r=e.lastIndexOf("\n",t-1);return-1===r?0:r+1},g=(e,t)=>{const r=e.indexOf("\n",t);return-1===r?e.length:r};return function({onExit:m,onPermissionChoice:y,onSend:b,showSpinnerImmediately:w,state:v}){const[_,E]=S.useState({value:"",cursor:0}),I=_.value,T=_.cursor,x=S.useRef(!1),C=S.useRef(void 0),[R,P]=S.useState(!1),U=S.useRef(0),k=v.log.at(-1),L="text"===k?.kind&&"running"===v.status,D=v.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),O=d?0:-1!==D?D:L?v.log.length-1:v.log.length;S.useEffect(()=>{v.log.length<U.current&&(U.current=0),O>U.current&&(U.current=O)},[v.log.length,O]);const B=v.log.slice(0,U.current),N=v.log.slice(U.current),$=!!v.permissionPrompt,j=S.useCallback(async()=>{x.current?(C.current&&clearTimeout(C.current),await(m?.()),process.exit(0)):(x.current=!0,P(!0),C.current=setTimeout(()=>{x.current=!1,P(!1)},2e3))},[m]);s((e,t)=>{t.ctrl&&"c"===e&&j().catch(()=>process.exit(1))},{isActive:o}),S.useEffect(()=>{if($||!b)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,cursor:g(e.value,e.cursor)})):E(e=>({...e,cursor:h(e.value,e.cursor)})):E(e=>({...e,cursor:e.value.length})):E(e=>({...e,cursor:0}))};return process.stdin.on("data",e),()=>{process.stdin.off("data",e)}},[$,b,I]),s((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){const e=I.trim();return e&&b?.(e),void E({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?E(e=>{const t=p(e.value,e.cursor);return{value:e.value.slice(0,t)+e.value.slice(e.cursor),cursor:t}}):!t.backspace&&!t.delete||t.ctrl?t.ctrl&&t.leftArrow||t.meta&&"b"===e?E(e=>({...e,cursor:p(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?E(e=>({...e,cursor:f(e.value,e.cursor)})):t.leftArrow?E(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?E(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?E(e=>({...e,cursor:0})):t.ctrl&&"e"===e?E(e=>({...e,cursor:e.value.length})):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||E(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):E(e=>e.cursor>0?{value:e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor),cursor:e.cursor-1}:e)}},{isActive:o&&!!b&&!$});const M=S.useMemo(()=>"running"===v.status?A.jsx(a,{label:v.runningLabel??"Working"}):"success"!==v.status?A.jsx(n,{color:"red",children:"✖ Failed"}):void 0,[v.runningLabel,v.status]),F=!(w||!b||"running"!==v.status||0!==v.log.length||v.resultText||v.errorText),H="running"===v.status&&!F||v.log.length>0||v.resultText||v.errorText||"running"!==v.status;return A.jsxs(t,{flexDirection:"column",children:[A.jsx(r,{items:["header"],children:()=>A.jsxs(t,{flexDirection:"column",flexShrink:0,children:[A.jsx(n,{color:"cyan",bold:!0,children:"Stably Agent"}),A.jsx(t,{flexDirection:"column",marginTop:1,children:A.jsx(n,{color:"gray",children:v.promptDisplay})})]},"header")}),B.length>0&&A.jsx(r,{items:B,children:e=>u(e)}),N.length>0&&A.jsx(t,{flexDirection:"column",children:N.map(e=>u(e))}),"error"===v.status&&v.errorText&&A.jsx(t,{marginTop:1,children:A.jsx(n,{color:"red",children:v.errorText})}),"success"===v.status&&v.resultText&&A.jsx(t,{marginTop:1,children:A.jsx(n,{children:v.resultText})}),H&&A.jsx(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===v.status&&v.fixProgress?A.jsxs(t,{flexDirection:"column",children:[A.jsxs(t,{children:[A.jsx(a,{}),A.jsx(n,{children:" "}),A.jsx(c,{progress:v.fixProgress})]}),"fixing"===v.fixProgress.phase&&v.log.flatMap(e=>{const{subagent:r}=e;if("subagent"!==e.kind||"fix-worker"!==r?.subagentType||"running"!==r.status)return[];const{activities:s}=r,o=s.filter(e=>"tool"===e.kind).length,i=s.at(-1),c=s.filter(e=>"tool"===e.kind).at(-1),l=(()=>{if(!i)return null;if("tool"===i.kind)return null;if("text"===i.kind){const e=i.content.trim().split("\n").at(-1)?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}if("tool_result"===i.kind){const e=i.content.trim().split("\n")[0]?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}return null})();return A.jsxs(t,{flexDirection:"column",children:[A.jsxs(n,{children:[" ",A.jsx(a,{}),A.jsxs(n,{color:"gray",children:[r.description||"fix-worker",o>0?` (${o} ${1===o?"cycle":"cycles"})`:""]})]}),c&&A.jsxs(n,{color:"gray",dimColor:!0,children:[" • ",c.content]}),l&&A.jsxs(n,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==v.status&&"error"!==v.status||!v.fixProgress?M:A.jsx(l,{progress:v.fixProgress})}),null!=v.permissionPrompt&&null!=y&&A.jsx(i,{onChoice:y,prompt:v.permissionPrompt}),null!=b&&null==v.permissionPrompt&&!v.isExiting&&A.jsxs(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[A.jsx(n,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),A.jsxs(n,{children:[A.jsx(n,{color:"yellow",children:">"})," ",I.slice(0,T),A.jsx(e,{}),I.slice(T)]})]}),R&&A.jsxs(t,{marginTop:1,flexDirection:"column",children:[A.jsx(n,{color:"yellow",children:"Press Ctrl+C again to exit"}),on&&A.jsxs(n,{color:"gray",children:["Debug log: ",un]})]})]})}})({Cursor:l,inkComponents:{Box:r,Static:n,Text:s,useInput:i},isRawModeSupported:a,PermissionPrompt:u,Spinner:({label:e})=>{const[t,r]=S.useState(0);return S.useEffect(()=>{const e=setInterval(()=>r(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),A.jsxs(s,{color:"yellow",children:[c[t]," ",e]})}});let p=e;t?.isFixMode&&(p.fixProgress={phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:Date.now(),endedAt:null,isError:!1});const f={current:(e,t)=>{}},h=o(A.jsx(d,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}),{exitOnCtrlC:!1}),g=()=>{p={...p},h.rerender(A.jsx(d,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}))},m=({text:e})=>{e&&(p.log=[...p.log,{content:e,id:p.log.length,kind:"user"}],g())},y=new Map;return{addSubagentActivity:({toolUseId:e,kind:t,content:r})=>{const n=y.get(e);if(void 0===n)return void console.error("[addSubagentActivity] No entry index for toolUseId:",e);const s=p.log[n];if(s&&"subagent"===s.kind&&s.subagent){if("text"===t){const e=s.subagent.activities.at(-1);e&&"text"===e.kind?e.content+=r:s.subagent.activities.push({id:s.subagent.activities.length,kind:"text",content:r.replace(/^\s*\n+/,"")})}else s.subagent.activities.push({id:s.subagent.activities.length,kind:t,content:r});p.log=[...p.log],g()}else console.error("[addSubagentActivity] Entry not found or not subagent:",{entryIndex:n,entryKind:s?.kind})},addSubagentStart:({toolUseId:e,subagentType:t,description:r})=>{const n=p.log.length;if(y.set(e,n),p.log=[...p.log,{content:"",id:n,kind:"subagent",subagent:{toolUseId:e,subagentType:t,description:r,status:"running",activities:[]}}],p.fixProgress)if("triage"===t&&"initializing"===p.fixProgress.phase)p.fixProgress={...p.fixProgress,phase:"triage"};else if("fix-worker"===t){const e=(p.fixProgress.totalTests??0)+1,t=r||null;p.fixProgress={...p.fixProgress,phase:"fixing",totalTests:e,currentTestDescription:t,lastTestDescription:t??p.fixProgress.lastTestDescription}}else"validation"===t?p.fixProgress={...p.fixProgress,phase:"validation",currentTestDescription:null}:"context"===t&&(p.fixProgress={...p.fixProgress,currentTestDescription:r||p.fixProgress.currentTestDescription});g()},addTool:({rawName:e,toolInput:t})=>{const r=Is(e),n=Ts(e,t),s=n?`${r} (${n})`:r;p.log=[...p.log,{content:s,id:p.log.length,kind:"tool"}],g()},addToolResult:({message:e})=>{p.log=[...p.log,{content:e,id:p.log.length,kind:"tool_result"}],g()},appendText:({text:e})=>{if(!e)return;const t=p.log.at(-1),r=t&&"text"===t.kind?e:e.replace(/^\s*\n+/,"");t&&"text"===t.kind?p.log=[...p.log.slice(0,-1),{...t,content:`${t.content}${r}`}]:p.log=[...p.log,{content:r,id:p.log.length,kind:"text"}],g()},appendUserMessage:m,cleanup:async()=>{const e=h.waitUntilExit();h.unmount(),await e},setExiting:()=>{p.isExiting=!0,g()},setRunningLabel:({label:e})=>{p.runningLabel=e,g()},setStatus:({error:e,result:t,status:r})=>{p.errorText=e,p.resultText=t,p.status=r,g()},setSubagentStatus:({toolUseId:e,status:t})=>{const r=y.get(e);if(void 0===r)return;const n=p.log[r];n&&"subagent"===n.kind&&n.subagent&&(n.subagent.status=t,p.fixProgress&&"fix-worker"===n.subagent.subagentType&&("complete"===t?p.fixProgress={...p.fixProgress,fixedTests:p.fixProgress.fixedTests+1,currentTestDescription:null}:"error"===t&&(p.fixProgress={...p.fixProgress,failedTests:p.fixProgress.failedTests+1,currentTestDescription:null})),p.log=[...p.log],g(),"complete"!==t&&"error"!==t||y.delete(e))},showPermissionPrompt:e=>new Promise(t=>{f.current=(r,n)=>{if(p.permissionPrompt=void 0,g(),"allow"===r)t({behavior:"allow",updatedInput:e.input});else if("always"===r)t({behavior:"allow",updatedInput:e.input,updatedPermissions:e.suggestions});else{const e=n??"User denied this action";m({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},p.permissionPrompt={...e,resolve:t},g()}),updateFixProgress:t?.isFixMode?e=>{p.fixProgress&&(p.fixProgress={...p.fixProgress,...e},g())}:void 0}})(v,"chat"===r.mode||"init"===r.mode?{onExit:()=>pe.current(),onSend:e=>de.current(e),showSpinnerImmediately:"init"===r.mode}:"fix"===r.mode?{onExit:()=>pe.current(),isFixMode:!0}:void 0);let xe=v.status;const Se=({error:e,result:t,status:r})=>{xe=r,Ee({error:e,result:t,status:r})};let Ae;de.current=e=>{const t=e.trim();if(y&&!bn.getLogFilePath()&&bn.initSession(t||"chat"),bn.debug("User message",{text:t}),"/help"===t){x&&b&&(C=!0,_?.interrupt?.(),b.allowNextTurn(),x=!1),"running"===xe&&Se({status:"success"}),be({text:e});const t=w?.();return void ye({text:t??"Help is not available in this session."})}const r=I||P&&x;if(y&&(k+=1,T=void 0,r||(D=!1,_e({label:void 0}))),b){if(r)return Se({status:"running"}),be({text:e}),void B.push(e);if(!P||x||I||(P=!1),x)return Se({status:"running"}),be({text:e}),b.pushText(e),void(L+=1);Se({status:"running"}),be({text:e}),b.pushText(e),x=!0}};const Ce=[];let Re;const Pe=await(async()=>{if("single"===r.mode||"build"===r.mode){const n=await async function(e,r){const n=t.resolve(e);if(r){const e=t.resolve(n,r);return ys(e,"output-flag"),{path:e,source:"output-flag"}}const s=hs(n);if(s){const e=await async function(e){try{const t=(await m.readFile(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(s);if(e){const r=t.resolve(t.dirname(s),e);if(ms(r))return ys(r,"playwright.config.ts"),{path:r,source:"playwright.config.ts"}}}for(const e of gs){const r=t.join(n,e);if(ms(r))return ys(r,"auto-detected"),{path:r,source:"auto-detected"}}return ys(n,"cwd-fallback"),{path:n,source:"cwd-fallback"}}(l,r.outputDir);return Re=n.path,e=r.prompt,`${(Array.isArray(e)?e.join(" "):e).trim()||"Create tests based on the changes in the current PR or branch. If the user references a specific PR number or branch name, first checkout that PR/branch using `gh pr checkout <number>` or `git checkout <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 stably test` or the repo's test command) and iterate until the new tests pass."}\n\n[Output directory: ${Re}]`}var e;if("fix"===r.mode)try{bn.info("[fix] Fetching autoheal context",{runId:r.runId});const e=Date.now(),{context:t,autohealReportUrl:n}=await(async({authHeader:e,orgId:t,runId:r})=>{bn.debug("Fetching autoheal context",{runId:r});const n=await(s={auth:e,client:Rr(),headers:Cn(t),path:{runId:r}},(s.client??wr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...s}));var s;if(404===n.response.status)throw bn.warn("Autoheal context not found",{runId:r,status:404}),new Error(`Run ID "${r}" was not found.`);if(401===n.response.status)throw bn.warn("Autoheal context fetch unauthorized",{runId:r,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===n.response.status)throw bn.warn("Autoheal context fetch invalid request",{runId:r,status:422,error:n.error?.error}),new Error(n.error?.error??"Failed to fetch autoheal context (422).");if(!n.error){const e=Rn.safeParse(n.data);if(e.success)return bn.debug("Autoheal context fetched successfully",{runId:r,contextSize:e.data.context.length}),{context:e.data.context,autohealReportUrl:e.data.autohealReportUrl};throw bn.warn("Autoheal context response invalid",{runId:r}),new Error("Autoheal context response missing or invalid context.")}throw bn.warn("Autoheal context fetch failed",{runId:r,error:n.error}),new Error("Failed to fetch autoheal context")})({authHeader:o,orgId:c,runId:r.runId});return bn.info("[fix] Autoheal context fetched",{runId:r.runId,durationMs:Date.now()-e,contextLength:t.length}),Ae=n,X||(bn.info("[fix] Creating WebSocket progress reporter"),X=new Bn({authHeader:o,orgId:c,runId:r.runId,onUserMessage:e=>{if(bn.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),ee(Ai,{type:"user_message",summary:e}),te({type:"user_message",summary:e}),be({text:`[Web] ${e}`}),!x)return b.pushText(`[Message from web UI user]: ${e}`),x=!0,void b.allowNextTurn();G||Date.now()-Y<2e3?b.pushText(`[Message from web UI user]: ${e}`):(M.push(e),N&&clearTimeout(N),N=setTimeout(()=>{N=void 0;const e=[...M];M=[],Y=Date.now(),vt(e)},500))}}),X.start(),ne({phase:"initializing"})),se("STARTED"),t}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";bn.error("[fix] Failed to fetch autoheal context",{error:t}),Se({error:t,status:"error"}),await we(),process.exit(1)}return"init"===r.mode?"Please analyze this project and set up Playwright with the Stably SDK. Check for existing configurations and install the necessary dependencies.":""})(),Ue=await async function(e){const t=O.default.resolve(e),r=O.default.join(t,"tests"),n=O.default.join(r,"helpers"),s=O.default.join(r,"assets"),o=function(e){const t=O.default.resolve(e);if(i.existsSync(t))for(const e of as){const r=O.default.join(t,`playwright.config${e}`);if(i.existsSync(r))return r}}(t)??O.default.join(t,"playwright.config.ts"),a=O.default.basename(o),c=O.default.join(r,"seed.spec.ts"),[l,u,d,p,f,h]=await Promise.all([us({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),us({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:r}),us({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:n}),us({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:s}),ls({defaultContent:"File does not exist or could not be read",fileName:a,filePath:o}),ls({defaultContent:"File does not exist or could not be read",fileName:"seed.spec.ts",filePath:c})]);return{absolutePath:t,directories:{assets:p,helpers:d,root:l,tests:u},files:{playwrightConfig:f,playwrightConfigFilename:a,seedSpec:h}}}(l),ke=await(async e=>{try{const t=await Or(e,"stably.yaml");if(!t)return void bn.debug("No stably.yaml found");const r=await m.readFile(t,"utf-8");if(!r.trim())return;const n=R.parseDocument(r),s=Ei.parse(n.toJS()),o=s.agent?.fix?.maxTurnsPerIssue,i=s.agent?.fix?.maxParallelWorkers,a=!!s.agent?.fix?.rules;return bn.debug(`Loaded stably.yaml: maxTurnsPerIssue=${o??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:s.agent}),s}catch(e){return void bn.warn("Failed to parse stably.yaml",{error:e})}})(l),Le=ke?.agent?.fix?.maxTurnsPerIssue,De=ke?.agent?.fix?.maxParallelWorkers,Oe=ke?.agent?.fix?.rules,Be="fix"===r.mode||"single"===r.mode||"build"===r.mode,Ne="single"===r.mode||"build"===r.mode?await(async e=>{try{const t=await Or(e,"STABLY-CREATE.md");if(!t)return void bn.debug("No STABLY-CREATE.md found");const r=await m.readFile(t,"utf-8");if(!r.trim())return;return r.length>1e4?(bn.warn(`STABLY-CREATE.md exceeds max length (${r.length} > 10000), truncating`,{path:t}),r.slice(0,1e4)):(bn.debug("Loaded STABLY-CREATE.md rules",{path:t,contentLength:r.length}),r)}catch(e){return void bn.warn("Failed to read STABLY-CREATE.md",{error:e})}})(l):void 0;bn.info("[fix] Fetching system prompt and subagent definitions",{mode:r.mode,maxTurnsOverride:Le,hasCustomRules:!!Oe,hasCreateRules:!!Ne});const $e=Date.now(),[{systemPrompt:je,prContext:Me},Fe]=await Promise.all([ds({allowedEnvVars:Object.keys(h),mode:r.mode,workspaceInfo:Ue,authHeader:o,customHeader:"single"===r.mode||"build"===r.mode?r.customHeader:void 0,maxParallelWorkers:"fix"===r.mode?De:void 0}),Be?_i({authHeader:o,mode:r.mode,maxTurnsOverride:Le}):Promise.resolve({})]);bn.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-$e,systemPromptSize:je.length,subagentCount:Object.keys(Fe).length,maxTurnsOverride:Le??"default",hasPrContext:!!Me});const He={...h,...process.env},Ge={};for(const[e,t]of Object.entries(He))vi.has(e)||void 0===t||(Ge[e]=t);const ze=!0;bn.debug("AI proxy configuration",{useStablyAiProxy:ze,wantsBypassProxy:!1,wantsUseOllama:!1}),bn.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:ze});const Ye=Date.now(),We=await async function({auth:e,client:t,source:r,metadata:n,duration:s}){try{const i=await(o={auth:e,client:t,body:{source:r,metadata:n??{},duration:s}},(o.client??wr).post({security:[{scheme:"bearer",type:"http"}],url:"/v1/proxy/api-key",...o,headers:{"Content-Type":"application/json",...o.headers}})),a=i.response;if(i.error){const e="object"==typeof i.error&&"error"in i.error?i.error.error:"Unknown error";return{error:wi(e,a)}}return i.data?{key:i.data.key}:{error:wi("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:wi(t)}}var o}({auth:o,client:Rr(),source:"cli"}),Ve=We?.key;if(bn.info("[fix] AI proxy key acquired",{durationMs:Date.now()-Ye,success:!!Ve,hasError:!!We?.error}),!Ve){const e=We?.error?.message?`Unable to make AI calls: ${We.error.message}`:"Unable to make AI calls. Check if you are authenticated.";bn.warn("Failed to get proxy API key",{error:We?.error?.message}),Se({error:e,status:"error"}),await we(),bn.flush(),bn.printLogFileInfo(),process.exit(1)}bn.debug("Proxy API key acquired",{success:!!Ve});const qe=await An(),Ke=qe?Object.fromEntries(Object.entries(Sn(qe)).filter(e=>null!=e[1])):void 0,Je="init"===r.mode,Xe="fix"===r.mode,Qe=Xe?Xt.createLocal({workingDir:l}):void 0;Qe&&await Qe.captureSnapshot();const Ze=Je?gi({onComplete:()=>{Se({status:"success"}),ve(),b?.finish(),process.exit(0)}}):y?gi({onRestartRequested:()=>{y&&(P=!0,Se({status:"running"}),_e({label:"Restarting browser tools..."}),T={createdAtUserMessageSeq:k,attempts:0})}}):void 0,et=Ze?y?{"stably-agent-control":Ze}:{"session-control":Ze}:{},tt=oe&&Me?["mcp__create-report"]:[],rt=Je?xi:[...Ii,...Xe?["mcp__auto-heal-report"]:[],...tt],nt=Je?xi:y?[...Ti,"mcp__stably-agent-control"]:[...Ti,...tt],st=oe&&Me?{"create-report":yi({prContext:Me,authHeader:o,orgId:c,onReportPosted:e=>{le({githubComment:{url:e.commentUrl,prNumber:Me.prNumber}})}})}:{},ot=Je?et:Xe&&Qe?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:Ke},"auto-heal-report":hi({authHeader:o,diffTracker:Qe,orgId:c,runId:r.runId,workingDir:l}),...et}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:Ke},...et,...st},it="single"===r.mode||"build"===r.mode,at=Je?[]:[{hooks:[async e=>{const t=Fn(e);if(!t)return{decision:"approve"};let r=!1;const n=t.map(e=>jn(e)?e.text.length<=4e4?e:(r=!0,{...e,text:`${e.text.slice(0,4e4)}...[truncated to 40000 characters]`}):e);return r?{decision:"approve",hookSpecificOutput:{hookEventName:"PostToolUse",updatedMCPToolOutput:n}}:{decision:"approve"}}],matcher:"mcp__playwright-test__.*"},{matcher:"mcp__playwright-test__test_run",hooks:[Vn({onResult:e=>me({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[qn({onResult:e=>me({message:e})})]},...it?[{matcher:"Write",hooks:[Jn({onFileCreated:e=>{Ce.push(e),ce&&le({filesCreated:[...ce.filesCreated,e]})}})]}]:[],{matcher:"Write",hooks:[ss({workDir:l})]},{matcher:"Edit",hooks:[ss({workDir:l})]}],ct=Je?[]:[{matcher:"mcp__playwright-test__browser_type",hooks:[Wn({envVars:h})]}],lt=Object.keys(Fe).length>0?Fe:void 0,ut={...Ge};ut.MCP_TOOL_TIMEOUT=String(6e5),Ve&&(ut.ANTHROPIC_API_KEY=Ve,ut.ANTHROPIC_BASE_URL=xr,ut.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1");const dt=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6",pt=Oe?`\n\n## Custom Rules\n${Oe}`:"",ft=Ne?`\n\n## Custom Test Generation Rules\n${Ne}`:"",ht=je+pt+ft;bn.debug("[fix] Final system prompt assembled",{baseSize:je.length,fixRulesSize:pt.length,createRulesSize:ft.length,finalSize:ht.length});const gt=O.default.join(__dirname,"stably-plugin"),mt=$.default.existsSync(gt)?{type:"local",path:gt}:function(){const e=function(){try{if(!("undefined"==typeof document?require("url").pathToFileURL(e).href:U&&"SCRIPT"===U.tagName.toUpperCase()&&U.src||new URL("index.js",document.baseURI).href))return;const e=a.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(e).href:U&&"SCRIPT"===U.tagName.toUpperCase()&&U.src||new URL("index.js",document.baseURI).href),r=t.dirname(e);return t.join(r,"..","stably-plugin")}catch{return}}();if(e&&i.existsSync(e))return{type:"local",path:e}}(),yt=()=>(bn.info("[fix] Starting SDK query",{model:dt,tools:rt,mcpServers:Object.keys(ot),resumeSessionId:E??null,subagentsEnabled:!!lt,subagentCount:Object.keys(Fe).length,useStablyAiProxy:ze,aiProxyUrl:xr,anthropicBaseUrl:void 0,stablyPluginPath:mt?.path,stablyPluginExists:!!mt}),d.query({options:{executableArgs:["--max-old-space-size=4096"],tools:rt,allowedTools:nt,betas:[],canUseTool:(e,t)=>(bn.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:l,env:ut,hooks:{PostToolUse:at,PreToolUse:ct},includePartialMessages:!0,agents:lt,mcpServers:ot,model:dt,permissionMode:"default",plugins:mt?[mt]:void 0,systemPrompt:ht,...E?{resume:E}:{}},prompt:b??Pe})),bt=()=>{if(b&&0!==B.length){for(const e of B)b.pushText(e);B.length=0,x=!0,Se({status:"running"})}},wt=async()=>{y&&(I||(I=(async()=>{bn.info("Restarting MCP servers for chat mode"),Se({status:"running"}),_e({label:"Restarting browser tools..."});try{await(_?.interrupt?.())}catch(e){bn.warn("Failed to interrupt response during MCP restart",{error:e instanceof Error?e.message:String(e)})}await Qn(),b?.finish(),b=new os,L=0,x=!1,C=!1,W.clear(),_=yt(),D=!0,_e({label:"Restarting browser tools..."}),y&&b&&T&&(T.createdAtUserMessageSeq===k?T.attempts>=1||B.length>0?T=void 0:(T.attempts+=1,b.pushText(["[SYSTEM] MCP servers were restarted successfully.","Continue the task using existing conversation context.","Do not ask the user to resend their message unless new input is required."].join("\n")),T=void 0,x=!0,Se({status:"running"})):T=void 0),bt()})().finally(()=>{I=void 0,bt()})),await I)},vt=async e=>{if(g&&x&&!G&&!j)j=(async()=>{bn.info("[fix] Interrupting for user message",{messageCount:e.length,phase:Q?.phase});try{await(_?.interrupt?.())}catch(e){bn.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await Qn(),b?.finish(),b=new os,W.clear(),_=yt();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");b.pushText(`[SYSTEM] The user sent a message while you were working. Read their message below, incorporate their feedback, and continue your task. Do not restart from scratch unless the user explicitly asks.\n\n${t}`),z=!0,x=!0})().finally(()=>{j=void 0}),await j;else for(const t of e)b?.pushText(`[Message from web UI user]: ${t}`)};if(Ve){const e=xr,t=`${e.replace(/\/$/,"")}/v1/messages`;bn.debug(`[fix] Pre-flight: POST ${t}`);const r=Date.now();try{const e=await fetch(t,{method:"POST",signal:AbortSignal.timeout(1e4),headers:{"x-api-key":Ve,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),n=await e.text().catch(()=>""),s=Date.now()-r;bn.debug(`[fix] Pre-flight: ${e.status} in ${s}ms — ${n.slice(0,300)}`),401===e.status||403===e.status?bn.error(`[fix] Pre-flight: AI proxy key rejected (${e.status}) at ${t}`):bn.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:s})}catch(t){bn.error("[fix] Pre-flight: AI proxy unreachable",{error:t instanceof Error?t.message:String(t),durationMs:Date.now()-r,url:e})}}bn.info("[fix] Creating initial agent query"),bn.flush(),_=yt(),bn.info("[fix] Agent query created, entering message loop"),"chat"!==r.mode&&b.pushText(Pe),pe.current=async()=>{V="CANCELED",await se("CANCELED"),ne({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:re(!0)}),X?.close(),le({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),ae?.close(),N&&(clearTimeout(N),N=void 0),bn.flush(),ve();try{await(_?.interrupt?.())}catch{}b?.finish(),we()};let _t=0,Et=null;const It=setInterval(()=>{const e=Date.now()-J;Et?bn.info("[fix] Watchdog: message loop active",{messageCount:_t,elapsed:e}):bn.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),bn.flush()},15e3);It.unref();try{let e=!1;for(;;){if(!_){bn.info("[fix] No response object, exiting message loop");break}e=!1,bn.info("[fix] Entering for-await on SDK response");for await(const t of _){_t++,Et||(Et=Date.now(),bn.info("[fix] First SDK message received",{waitDurationMs:Et-J,messageType:t.type,messageSubtype:"subtype"in t?t.subtype:void 0}));const n="session_id"in t&&"string"==typeof t.session_id?t.session_id:void 0;if(n&&n!==E&&(E=n,bn.debug("Captured Claude session id",{sessionId:E})),"stream_event"===t.type){const{event:e}=t;(_t<=5||_t%200==0)&&bn.debug("[fix] Stream event",{msgNum:_t,eventType:e?.type});const r=e&&"object"==typeof e&&"parent_tool_use_id"in e&&"string"==typeof e.parent_tool_use_id?e.parent_tool_use_id:void 0;if("content_block_delta"===e?.type){const{delta:t}=e;if("text_delta"===t?.type&&t.text){if(y&&P&&!r)continue;D&&(D=!1,_e({label:void 0})),r&&W.has(r)?fe({toolUseId:r,kind:"text",content:t.text}):ye({text:t.text})}}"message_stop"===e?.type&&b&&(G=!1,b.allowNextTurn());continue}if("assistant"===t.type){const e="parent_tool_use_id"in t&&"string"==typeof t.parent_tool_use_id?t.parent_tool_use_id:void 0,{content:n}=t.message??{};if(Array.isArray(n)&&!e){const e=n.filter(e=>e&&"object"==typeof e&&"type"in e&&"text"===e.type).map(e=>e&&"object"==typeof e&&"text"in e&&"string"==typeof e.text?e.text:void 0).filter(Boolean).join("");e&&(bn.debug("Assistant message",{text:e}),"fix"===r.mode&&(ee(Ai,{type:"ai_message",summary:e.slice(0,200)}),te({type:"ai_message",summary:e.slice(0,200)})),oe&&ue({type:"ai_message",summary:e.slice(0,200)}))}if(W.size>0){const r=Array.isArray(n)?n.filter(e=>e&&"object"==typeof e&&"type"in e&&"tool_use"===e.type).map(e=>e&&"object"==typeof e&&"name"in e&&"string"==typeof e.name?e.name:void 0):[];bn.debug("Assistant message with active subagents",{hasParentToolUseId:!!e,parentToolUseId:e,activeSubagentIds:Array.from(W.keys()),toolNames:r,fullMessageKeys:Object.keys(t),rawMessage:JSON.stringify(t).slice(0,500)})}if(Array.isArray(n))for(const t of n){if("tool_use"===t?.type){if("mcp__auto-heal-report__generate-report"===t.name&&(G=!0),"mcp__session-control__restart_mcp_servers"===t.name||"mcp__stably-agent-control__restart_mcp_servers"===t.name){ge({rawName:t.name,toolInput:t.input});continue}if(t.name.startsWith("mcp__session-control__")||t.name.startsWith("mcp__stably-agent-control__"))continue;if(Ci(t.name))continue;if(W.size>0&&bn.debug("Tool use detected with active subagents",{toolName:t.name,hasParentToolUseId:!!e,parentToolUseId:e,wouldRouteToSubagent:!!e&&W.has(e),activeSubagentIds:Array.from(W.keys())}),"Task"===t.name){const e=t.input,n=e&&"object"==typeof e?e:void 0,s=n&&"subagent_type"in n&&"string"==typeof n.subagent_type?n.subagent_type:"subagent",o=n&&"description"in n&&"string"==typeof n.description?n.description.trim():"";if(bn.info("[fix] Subagent started",{subagentType:s,description:o,toolUseId:t.id,activeSubagentCount:W.size+1}),W.set(t.id,{subagentType:s,description:o}),he({toolUseId:t.id,subagentType:s,description:o}),"fix"===r.mode){if("triage"===s){Te?.({phase:"triage"});const e={id:t.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};ne({phase:"triage",workers:[...Q?.workers??[],e]})}else if("fix-worker"===s){Z.add(o||t.id);const e={id:t.id,testDescription:o||t.id,workerType:"fix-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};Te?.({phase:"fixing",totalTests:Z.size,currentTestDescription:o||null}),ne({phase:"fixing",totalTests:Z.size,currentTestDescription:o||null,lastTestDescription:o||Q?.lastTestDescription||null,workers:[...Q?.workers??[],e]})}else"validation"===s?(Te?.({phase:"validation",currentTestDescription:null}),ne({phase:"validation",currentTestDescription:null})):"context"===s&&ne({currentTestDescription:o||null});te({type:"tool_call",summary:`[${s}] ${o}`.trim()})}continue}if(e&&W.has(e)){const n=Ri(t.name),s=Ts(t.name,t.input),o=s?`${n} (${s})`:n;if(bn.debug("Subagent tool called",{tool:t.name,parentToolUseId:e}),fe({toolUseId:e,kind:"tool",content:o}),"fix"===r.mode){te({type:"tool_call",summary:o});const t=W.get(e);"fix-worker"!==t?.subagentType&&"triage"!==t?.subagentType||ee(e,{type:"tool_call",summary:o})}continue}if(e&&bn.debug("Tool with parent_tool_use_id but no matching subagent",{tool:t.name,parentToolUseId:e,activeSubagentIds:Array.from(W.keys())}),bn.debug("Tool called",{tool:t.name,input:t.input}),ge({rawName:t.name,toolInput:t.input}),"fix"===r.mode){const e=Ri(t.name),r=Ts(t.name,t.input),n=r?`${e} (${r})`:e;ee(Ai,{type:"tool_call",summary:n}),te({type:"tool_call",summary:n})}if(oe){const e=Ri(t.name),r=Ts(t.name,t.input),n=r?`${e} (${r})`:e;"initializing"===ce?.phase?le({phase:"generating",currentActivity:n}):"mcp__playwright-test__test_run"===t.name&&"generating"===ce?.phase?le({phase:"testing",currentActivity:n}):le({currentActivity:n}),ue({type:"tool_call",summary:n})}}if("text"===t?.type&&e&&W.has(e)){const n="string"==typeof t.text?t.text:"";if(n&&(fe({toolUseId:e,kind:"text",content:n}),"fix"===r.mode)){const t=W.get(e);"fix-worker"!==t?.subagentType&&"triage"!==t?.subagentType||ee(e,{type:"ai_message",summary:n.slice(0,200)})}}}continue}if("user"===t.type){const e="message"in t&&t.message&&"object"==typeof t.message&&"content"in t.message?t.message.content:void 0;if(Array.isArray(e))for(const t of e)if(t&&"object"==typeof t&&"type"in t&&"tool_result"===t.type&&"tool_use_id"in t){const e="string"==typeof t.tool_use_id?t.tool_use_id:void 0,n="is_error"in t&&!0===t.is_error,s="content"in t&&"string"==typeof t.content?t.content:void 0;if(bn.debug("Tool result",{toolUseId:e,isError:n,output:s?.slice(0,500)}),e&&W.has(e)){const t=W.get(e);if(bn.info("[fix] Subagent completed",{toolUseId:e,isError:n,subagentType:t?.subagentType,description:t?.description,activeSubagentCount:W.size-1}),Ie({toolUseId:e,status:n?"error":"complete"}),"fix"===r.mode&&"triage"===t?.subagentType){const t=n?"failed":"succeeded",r=s?s.slice(0,500):null,o=(Q?.workers??[]).map(n=>n.id===e?{...n,status:t,summary:r,endedAt:Date.now()}:n);ne({workers:o})}if("fix"===r.mode&&"fix-worker"===t?.subagentType){const t=n?"failed":"succeeded",r=s?s.slice(0,500):null,o=(Q?.workers??[]).map(n=>n.id===e?{...n,status:t,summary:r,endedAt:Date.now()}:n);n?(Te?.({failedTests:(Q?.failedTests??0)+1,currentTestDescription:null}),ne({failedTests:(Q?.failedTests??0)+1,currentTestDescription:null,workers:o})):(Te?.({fixedTests:(Q?.fixedTests??0)+1,currentTestDescription:null}),ne({fixedTests:(Q?.fixedTests??0)+1,currentTestDescription:null,workers:o}))}W.delete(e)}}continue}if("result"===t.type){if(bn.info("[fix] Agent result received",{subtype:t.subtype,messageCount:_t,elapsed:Date.now()-J,activeSubagents:W.size,fixedTests:Q?.fixedTests,failedTests:Q?.failedTests,phase:Q?.phase}),g){if("success"===t.subtype){N&&(clearTimeout(N),N=void 0);for(const e of M)b?.pushText(`[Message from web UI user]: ${e}`);if(M=[],(oe||"fix"===r.mode)&&b){if(b.hasQueuedMessages()){bn.info("[ws] Queued web UI messages found, continuing agent"),x=!0,b.allowNextTurn();continue}if(await Pi(b,3e3)){bn.info("[ws] Web UI message received during grace period, continuing agent"),x=!0,b.allowNextTurn();continue}b.finish()}if(Te?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),ne({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:re(!1)}),le({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null}),it&&Ce.length>0){H.default.green("Created files:");for(const e of Ce)H.default.green(`- ${e}`)}const e=(e,t)=>`]8;;${e}${t}]8;;`,t=Ae?H.default.cyan(`📊 View Autoheal Report:\n ${e(Ae,H.default.cyan(H.default.bold(H.default.underline(Ae))))}`):void 0;Se({status:"success",result:t}),V="COMPLETED"}else j||z?bn.info("[fix] Suppressing error status: user-message interrupt in progress"):C?(V="CANCELED",ne({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:re(!0)}),le({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(Te?.({endedAt:Date.now(),isError:!0}),ne({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:re(!0)}),le({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Se({error:"Run failed.",status:"error"}),process.exitCode=1,V="FAILED");C=!1;break}const n=y&&P;if("success"!==t.subtype?C||(Se({error:"Run failed.",status:"error"}),process.exitCode=1):Se(n?{status:"running"}:{status:"success"}),x=!1,C=!1,n){P=!1,bn.info("Processing deferred MCP restart request in chat mode"),await wt(),e=!0;break}D=!1,_e({label:void 0}),b?.allowNextTurn(),y&&L>0&&(L-=1,x=!0,Se({status:"running"}));continue}}if(j&&await j,z&&(z=!1,e=!0,Se({status:"running"}),bn.info("[fix] Resuming after user-message interrupt")),!e)break}}catch(e){C?(V="CANCELED",ne({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:re(!0)}),le({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(bn.error("[fix] Agent encountered an error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,elapsed:Date.now()-J}),Se({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,V="FAILED",ne({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:re(!0)}),le({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),bn.flush(),bn.printLogFileInfo())}finally{if(clearInterval(It),N&&(clearTimeout(N),N=void 0),bn.info("[fix] Agent session ending",{finalStatus:V,elapsed:Date.now()-J,totalMessages:_t}),x=!1,C=!1,process.off("uncaughtException",n),b?.finish(),V){bn.info("[fix] Reporting final autoheal status",{status:V});const e=Date.now();await se(V),bn.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(bn.info("[fix] Closing WebSocket progress reporter"),X?.close(),ae?.close(),Xe&&Qe){const e=Date.now();try{bn.info("[fix] Computing diff...");const t=await Qe.computeDiff();if(t&&t.trim().length>0){bn.info("[fix] Uploading diff...",{diffLength:t.length});const{diffBucketPath:n,uploadUrl:s}=await Ln({authHeader:o,contentType:"text/plain",orgId:c,runId:r.runId});await Dn({contentType:"text/plain",diff:t,uploadUrl:s}),await On({authHeader:o,diffBucketPath:n,orgId:c,runId:r.runId}),bn.info("[fix] Diff uploaded",{durationMs:Date.now()-e})}else bn.info("[fix] No diff to upload (empty or no changes)")}catch(t){bn.warn("[fix] Failed to upload diff",{error:t instanceof Error?t.message:String(t),durationMs:Date.now()-e})}}bn.info("[fix] Cleaning up diff tracker"),await(Qe?.cleanup()),bn.info("[fix] Running final cleanup"),await we(),bn.info("[fix] Cleanup complete")}},ki=z.default.object({runId:z.default.string(),timestamp:z.default.number()}),Li=class{entries=[];warnings=[];runId;command;executionMode;constructor(e){this.runId=e.runId,this.command=e.command,this.executionMode=e.executionMode}phaseStart(e,t){this.addEntry({phase:e,level:"info",message:t}),y.log.info(function(e,t){return`${H.default.bold(H.default.cyan(`[${e}]`))} ${t}`}(e,t))}phaseEnd(e,t){this.addEntry({phase:e,level:"info",message:t})}info(e){this.addEntry({phase:e.phase,level:"info",message:e.message,fields:e.fields})}warn(e){this.addEntry({phase:e.phase,level:"warn",message:e.message,fields:e.fields}),y.log.warn(H.default.yellow(` warn: ${e.message}`))}error(e){this.addEntry({phase:e.phase,level:"error",message:e.message,fields:e.fields}),y.log.error(H.default.red(` error: ${e.message}`))}emitWarning(e){this.warnings.push(e),this.addEntry({phase:"summary",level:"warn",message:e.message,fields:{warningCode:e.code,...e.details}}),y.log.warn(function(e){return H.default.yellow(` warning: ${e.code} - ${e.message}`)}(e))}getEntries(){return[...this.entries]}getWarnings(){return[...this.warnings]}getRunId(){return this.runId}getCommand(){return this.command}getExecutionMode(){return this.executionMode}addEntry(e){this.entries.push({runId:this.runId,command:this.command,executionMode:this.executionMode,phase:e.phase,timestamp:(new Date).toISOString(),level:e.level,message:e.message,...e.fields?{fields:e.fields}:{}})}};function Di(e){return 0===e.length?[]:[H.default.yellow(H.default.bold("Warnings:")),...e.map(e=>H.default.yellow(` ${e.code}: ${e.message}`)),""]}function Oi(e){return e?[H.default.dim(`Next action: ${e}`),""]:[]}function Bi(e){const t=[],r="fix"===e.command?"Fix":"Build";if(t.push(""),"success"===e.status){const n=e.changedPaths.length;t.push(H.default.green(H.default.bold(`${r} succeeded`))+(n>0?H.default.green(` (${n} path${1!==n?"s":""} changed)`):"")),t.push(""),t.push(...Di(e.warnings))}else if("failure"===e.status)t.push(H.default.red(H.default.bold(`${r} failed`))),e.errorCode&&t.push(H.default.red(` Error: ${e.errorCode}`)),t.push(""),t.push(...Di(e.warnings)),t.push(...Oi(e.nextAction));else{const n=e.changedPaths.length,s=e.failedPaths.length,o=e.partialPaths.length;t.push(H.default.yellow(H.default.bold(`${r} partially succeeded`))+H.default.yellow(` (${n} changed, ${s} failed, ${o} partial)`)),t.push(""),t.push(...Di(e.warnings)),t.push(...Oi(e.nextAction))}return t.push(H.default.dim(`Run ID: ${e.runId}`)),t.join("\n")}var Ni=/^\/\*\*\r?\n \* @generated by stably build[\s\S]*?\*\/(?:\r?\n)*/;function $i(e){return!!e&&"object"==typeof e&&"code"in e}async function ji({errorMessage:e,filePath:t}){try{return await G.default.readFile(t,"utf8")}catch(t){if($i(t)&&"ENOENT"===t.code)throw new Error(e);throw t}}function Mi(e){return e.split(O.default.sep).join("/")}async function Fi(e){const t=[];return await async function e(r){let n;try{n=await G.default.readdir(r,{withFileTypes:!0})}catch{return}for(const s of n){const n=O.default.join(r,s.name);s.isDirectory()&&!s.isSymbolicLink()?await e(n):s.isFile()&&s.name.endsWith(".stably.md")&&t.push(n)}}(e),t.sort()}var Hi=/^---\r?\n([\s\S]*?)\r?\n---/;function Gi(e,t){const r=[],n=Hi.exec(e);let s,o={};if(n){try{const e=R.parse(n[1]??"");o=e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{y.log.warn(`Warning: Failed to parse YAML frontmatter in ${t}, treating as empty`),o={}}s=e.slice(n[0].length).replace(/^(\r?\n)+/,"")}else s=e;if(!s.trim())return{updated:e,addedFields:r};if(!o.name){const e=s.slice(0,1e4).replace(/```[\s\S]*?```/g,""),n=/^#\s+(.+)$/m.exec(e),i=O.default.basename(t).replace(/\.stably\.md$/,"").replace(/\.md$/,"");o.name=n?.[1]?.trim()??i,r.push("name")}return o.priority||(o.priority="medium",r.push("priority")),0===r.length?{updated:e,addedFields:r}:{updated:`---\n${R.stringify(o).trimEnd()}\n---\n\n${s}`,addedFields:r}}async function zi(e){try{return(await G.default.readdir(e)).filter(e=>$n.test(e)).map(t=>O.default.join(e,t))}catch(e){if($i(e)&&"ENOENT"===e.code)return[];throw e}}function Yi({runId:e,warnings:t,changedPaths:r=[],failedPaths:n=[],...s}){return{runId:e,command:"build",executionMode:"cli",warnings:t,changedPaths:r,failedPaths:n,partialPaths:[],...s}}async function Wi({force:e,inputFilePath:t}){const r=`build-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,n=new Li({runId:r,command:"build",executionMode:"cli"});n.phaseStart("preflight","Validating workspace and arguments");const s=process.cwd();n.info({phase:"preflight",message:"Input resolved",fields:{input:t}}),n.phaseEnd("preflight","Preflight complete"),n.phaseStart("scope","Resolving scope");const o=await ji({filePath:t,errorMessage:`Prompt file not found: ${t}`});if(!o.trim())throw new Error(`Prompt file is empty: ${t}`);const i=ts(o),a=Mi(O.default.relative(s,t)),c=O.default.dirname(t),l=(u=t,O.default.basename(u).replace(/\.stably\.md$/,"").replace(/\.md$/,"").replace(/\.txt$/,""));var u;const d=await async function(e,t){return(await zi(e)).find(e=>{const r=O.default.basename(e);return r.startsWith(`${t}.spec`)||r.startsWith(`${t}.test`)})}(c,l);if(!e&&d&&await async function({outputFilePath:e,promptHash:t}){try{return rs(await G.default.readFile(e,"utf8"))===t}catch(e){if($i(e)&&"ENOENT"===e.code)return!1;throw e}}({outputFilePath:d,promptHash:i})){n.info({phase:"scope",message:"Hash unchanged, skipping build"});const e={code:"STABLY_WARNING_NO_CHANGES",message:"Test code is up to date (hash unchanged)"};n.emitWarning(e);const t=Yi({runId:r,status:"success",warnings:[e]});return n.phaseStart("summary","Build summary"),y.log.info(Bi(t)),n.phaseEnd("summary","Done"),y.log.success(H.default.green(`Skipped build: ${a} (hash unchanged)`)),"skipped"}n.info({phase:"scope",message:"Scope resolved",fields:{promptFile:a,promptHash:i,resolvedScopeCount:1,unmappedPaths:[],baseSource:"prompt-file",baseRef:a}}),n.phaseEnd("scope","Scope complete"),n.phaseStart("plan","Preparing prompt");const p=new Set(await zi(c));await G.default.mkdir(c,{recursive:!0});const f=ns({promptFile:a,promptHash:i}),h=Mi(O.default.relative(s,c)||c),g=function({outputDir:e,promptContent:t,sourceSpecFile:r}){return["Compile this test specification into a Playwright test file.","",`Output directory: ${e}`,"","Choose output filename:",`- Look at existing test files in ${e} to determine the naming convention.`,"- Use the same extension pattern as existing tests (e.g., .test.ts or .spec.ts).","- If no existing tests, default to .spec.ts.","- Base the filename on the prompt content (e.g., login.spec.ts for login tests).","","File creation rules:","- Create your test file in the output directory with your chosen filename.","- You MAY create shared helper files (e.g., lib/auth.ts) if the prompt explicitly requests reusable components.","- Prefer single-file output unless shared helpers would significantly improve maintainability.","- Never modify unrelated existing files.","","Sync workflow for existing files:","1. Examine existing test files in the workspace and preserve hand edits where possible.","2. If a matching test file already exists, read it first and compare against the prompt specification.","3. Apply sync rules:"," - If file does not exist: CREATE from scratch."," - If file exists and already satisfies the prompt: KEEP behavior and make minimal edits only when needed."," - If file exists but only partially matches: UPDATE only changed scenarios so code aligns with prompt."," - If file structure conflicts heavily with prompt: REGENERATE the file content completely.","4. Prompt specification is the source of truth for final test behavior.","","Test verification:","After generating the test file, run the tests locally to verify they work correctly.","Use the appropriate test command (e.g., `pnpm stably test` or the repository's test command).","If tests fail, analyze the errors and iterate on the test code until all tests pass.","","Spec file linking:",`- Add \`// @stably.spec ${r}\` after the import statements.`,"- This links the test back to its source .md specification.","- If different test.describe()/test() blocks come from different .md files, add per-block @stably.spec instead.","","Prompt specification:",t].join("\n")}({outputDir:h,promptContent:o,sourceSpecFile:a});n.info({phase:"plan",message:"Agent prompt assembled",fields:{outputTarget:h,plannedPathCount:1,plannedPaths:[h],mode:"directory"}}),n.phaseEnd("plan","Plan complete"),n.phaseStart("execute","Running agent session"),process.exitCode=void 0;const m=Date.now();await Ui({mode:"build",prompt:g,outputDir:c,customHeader:f});const b=Date.now()-m,w=process.exitCode;if("number"==typeof w&&0!==w){n.error({phase:"execute",message:`Build generation failed for: ${a}`,fields:{toolName:"runAgentSession",durationMs:b}});const e=Yi({runId:r,status:"failure",warnings:n.getWarnings(),failedPaths:[a],nextAction:"open_agent_session",errorCode:"STABLY_WRITE_FAILED"});throw n.phaseStart("summary","Build summary"),n.info({phase:"summary",message:"Run failed",fields:{errorCode:e.errorCode,nextAction:e.nextAction}}),y.log.info(Bi(e)),n.phaseEnd("summary","Done"),new Error(`Build generation failed for: ${a}`)}n.info({phase:"execute",message:"Agent session completed",fields:{toolName:"runAgentSession",durationMs:b}}),n.phaseEnd("execute","Agent session complete"),n.phaseStart("finalize","Applying results");const v=[];let _=d;if(!_&&(_=(await zi(c)).find(e=>!p.has(e)),!_)){const e={path:a,status:"failed",error:"No new test file created"};v.push(e),n.info({phase:"finalize",message:"Write failed",fields:{path:e.path,writeStatus:e.status,error:e.error}});const t=Yi({runId:r,status:"failure",warnings:n.getWarnings(),failedPaths:[a],nextAction:"open_agent_session",errorCode:"STABLY_WRITE_FAILED"});throw n.phaseStart("summary","Build summary"),n.info({phase:"summary",message:"Run failed",fields:{errorCode:t.errorCode,nextAction:t.nextAction}}),y.log.info(Bi(t)),n.phaseEnd("summary","Done"),new Error(`Build finished but no new test file was created for: ${a}`)}const E=await ji({filePath:_,errorMessage:`Build finished but output file was not created for: ${a}`}),I=function(e){return e.replace(Ni,"")}(E),T=E.startsWith(f)?E:`${f}\n\n${I}`;T!==E&&await G.default.writeFile(_,T,"utf8");const x=Mi(O.default.relative(s,_)),S={path:x,status:"success"};v.push(S),n.info({phase:"finalize",message:"Write succeeded",fields:{path:S.path,writeStatus:S.status}}),n.phaseEnd("finalize","Finalize complete"),n.phaseStart("summary","Build summary");const A=v.filter(e=>"success"===e.status).map(e=>e.path),C=v.filter(e=>"failed"===e.status).map(e=>e.path);let R;R=C.length>0?A.length>0?"partial":"failure":"success";const P=C.length>0,U=Yi({runId:r,status:R,warnings:n.getWarnings(),changedPaths:A,failedPaths:C,nextAction:P?"inspect_failed_paths":void 0,errorCode:P?"STABLY_WRITE_FAILED":void 0});return n.info({phase:"summary",message:"Run completed",fields:{status:U.status,changedPathCount:A.length,failedPathCount:C.length,...U.errorCode?{errorCode:U.errorCode}:{},...U.nextAction?{nextAction:U.nextAction}:{}}}),y.log.info(Bi(U)),n.phaseEnd("summary","Done"),y.log.success(H.default.green(`Built: ${x}`)),"built"}var Vi=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],qi=["You have two different versions of @playwright/test"];function Ki(e){const[t,...r]=ai(e),n=[t,...r.slice(0,-1)].join(" ");return(t,r)=>{let s=t.toString();for(const e of Vi)s=s.replaceAll(`${n} playwright ${e.name}`,`${n} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===e){const e=s.split("\n");return e.length>0&&e[0].includes("/.bin/playwright")&&e.shift(),void r.write(e.join("\n"))}r.write(s)}}async function Ji({overrideArgs:e,subcommand:r}){bn.info("[test] forwardToPlaywright starting",{subcommand:r,overrideArgs:e});const n=process.argv,o=n.findIndex((e,t)=>t>1&&e===r),a=-1===o?[]:n.slice(o+1),c="--"===a[0],l=c?a.slice(1):a;if(!c&&("--help"===l[0]||"-h"===l[0]))return async function({subcommand:e}){const t=Vi.find(t=>t.name===e),r=e=>process.stdout.write(`${e}\n`);r(`stably ${e} - ${t?.description??""}`),r(""),"test"===e&&(r('IMPORTANT: Always use "stably" commands instead of "playwright" directly.'),r(""),r("Stably commands:"),r(" stably test [file] Run tests (auto-enables tracing and analytics)"),r(" stably fix [file] Auto-fix failing tests using AI"),r(" stably create <url> Generate new tests from a URL using AI"),r(""),r("Why use Stably?"),r(' - "stably fix" automatically repairs broken tests'),r(' - "stably test" enables --trace=on and test analytics'),r(' - "stably create" generates tests from prompt'),r(""));const n=si();if(!n.installed||!n.inNodeModules)return void r('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:o}=n;if(!o)return void r("Could not determine package manager.");r("Playwright options:"),r("");const[i,...a]=ai(o),c=Ki(o);return new Promise(t=>{const r=s.spawn(i,[...a,e,"--help"],{stdio:["inherit","pipe","pipe"],env:{...process.env,...process.env.CI?{}:{FORCE_COLOR:"1"}}});r.stdout?.on("data",e=>{c(e,process.stdout)}),r.stderr?.on("data",e=>{c(e,process.stderr)}),r.on("close",()=>{t()})})}({subcommand:r});const u=e??[],d=new Set(u.map(e=>{const[t]=e.split("=");return t})),p=[];for(let e=0;e<l.length;e++){const t=l[e],[r]=t.split("=");d.has(r)?!t.includes("=")&&e+1<l.length&&!l[e+1].startsWith("-")&&e++:p.push(t)}const f=[r,...u,...p];bn.info("[test] Forwarded args computed",{forwardedArgs:f}),bn.info("[test] Resolving Stably test environment");const h=Date.now(),g="test"===r?await An():void 0;bn.info("[test] Stably test environment resolved",{durationMs:Date.now()-h,hasCredentials:null!=g,hasWsUrl:!!g?.STABLY_WS_URL}),bn.info("[test] Setting up Stably reporter injection");const m="test"===r?function({forwardedArgs:e,hasCredentials:r}){if(!r)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 n=process.cwd(),o=e=>{const r=function(e){let r=t.resolve(e);for(;;){if([t.join(r,"node_modules","@stablyai","playwright-test"),t.join(r,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>i.existsSync(e)))return!0;const e=t.dirname(r);if(e===r)return!1;r=e}}(e);return r||(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: ]8;;https://docs.stably.ai/getting-started/sdk-setup-guidehttps://docs.stably.ai/getting-started/sdk-setup-guide]8;;[0m\n")),r},a=(e,r)=>{try{return function({baseConfigPath:e,projectDir:r}){const n=function(e){try{const t=s.execSync("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return"module"===JSON.parse(t.trim())}catch{return!1}}(r),o=n?"mts":"ts",a=t.dirname(t.resolve(e)),c=t.basename(e),l=t.join(a,`.stably-playwright-wrapper.config.${o}`),u=`\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 isStablyReporter = (reporter: unknown): boolean => {\n // Only match @stablyai npm scope to avoid false positives on unrelated reporters\n // that might contain "stably" substring (e.g., "unstably-runner")\n if (typeof reporter === 'string') {\n return reporter.includes('@stablyai');\n }\n if (Array.isArray(reporter) && typeof reporter[0] === 'string') {\n return reporter[0].includes('@stablyai');\n }\n return false;\n};\n\nconst getStablyReporterOptions = (reporters: unknown[]): Record<string, unknown> | undefined => {\n for (const reporter of reporters) {\n if (Array.isArray(reporter) && typeof reporter[0] === 'string' && reporter[0].includes('@stablyai')) {\n return (reporter[1] as Record<string, unknown>) ?? {};\n }\n }\n return undefined;\n};\n\nconst filterOutStablyReporter = (reporters: unknown[]): unknown[] => {\n return reporters.filter((reporter) => !isStablyReporter(reporter));\n};\n\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\n\n // Resolve errorSummary: env var STABLY_ERROR_SUMMARY=0 disables it\n const resolveErrorSummary = (existingValue?: unknown): boolean | undefined => {\n if (process.env.STABLY_ERROR_SUMMARY === '0') return false;\n if (typeof existingValue === 'boolean') return existingValue;\n return undefined; // let the reporter default (true)\n };\n\n // No existing reporters - create fresh stably reporter\n if (!existingReporters) {\n return [stablyReporter({\n apiKey: process.env.STABLY_API_KEY,\n projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(),\n })];\n }\n\n // Normalize to array\n const reportersArray: unknown[] = Array.isArray(existingReporters)\n ? existingReporters\n : [[existingReporters, {}]];\n\n // If user has a stably reporter, take their options but override credentials\n const existingOptions = getStablyReporterOptions(reportersArray);\n const stablyReporterEntry = stablyReporter({\n ...existingOptions,\n apiKey: process.env.STABLY_API_KEY,\n projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(existingOptions?.errorSummary),\n });\n\n // Keep all non-stably reporters, add our (merged or fresh) stably reporter\n const otherReporters = filterOutStablyReporter(reportersArray);\n return [...otherReporters, stablyReporterEntry];\n};\n\nexport default defineConfig({\n ...baseConfig,\n use: {\n ...baseConfig.use,\n trace: 'on',\n },\n reporter: buildReporterList(),\n});\n`.trim();return i.existsSync(a)||i.mkdirSync(a,{recursive:!0}),i.writeFileSync(l,u,"utf-8"),function(e){const r=t.join(e,".gitignore");try{if(i.existsSync(r)){const e=i.readFileSync(r,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(ps))return;const t=e.length>0&&!e.endsWith("\n");i.appendFileSync(r,`${t?"\n":""}${ps}\n`)}else i.writeFileSync(r,`${ps}\n`)}catch{}}(a),l}({baseConfigPath:e,projectDir:r})}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 r=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==r&&e[r+1]){const s=t.resolve(n,e[r+1]),i=t.dirname(s);if(!o(i))return;const c=a(s,i);if(!c)return;return e[r+1]=c,c}const s=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==s){const r=t.resolve(n,e[s].split("=")[1]),i=t.dirname(r);if(!o(i))return;const c=a(r,i);if(!c)return;const l=e[s].startsWith("--config=")?"--config=":"-c=";return e[s]=`${l}${c}`,c}}const c=hs(n);if(!c)return;const l=t.dirname(c);if(!o(l))return;const u=a(c,l);return u?(e.push("--config",u),u):void 0}({forwardedArgs:f,hasCredentials:null!=g}):void 0;bn.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!m}),bn.info("[test] Spawning Playwright process"),await function(e,t={}){bn.info("[test] Detecting Playwright installation");const r=si();bn.info("[test] Playwright installation check",{installed:r.installed,inNodeModules:r.inNodeModules,packageManager:r.packageManager,packageName:r.packageName}),r.installed||(console.error('Playwright is not installed. Please run "stably init" to install it.'),process.exit(1)),r.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:n}=r;n||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[o,...i]=ai(n),a=Sn(t.env),c=[o,...i,...e];bn.info("[test] Spawning Playwright process",{command:c.join(" "),pid:process.pid});const l=Date.now(),u=s.spawn(o,[...i,...e],{stdio:["inherit","pipe","pipe"],env:{...a,...process.env.CI?{}:{FORCE_COLOR:"1"}}});bn.info("[test] Playwright process spawned",{childPid:u.pid});const d=Ki(n),p=function(){let e=!1,t="";return(r,n)=>{if(!e){t+=r,t.length>1024&&(t=t.slice(-1024));for(const r of qi)if(t.includes(r))return n.write("\n[stably] Hint: This is a Playwright error, not caused by @stablyai/playwright-test.\n Common causes: running from the wrong directory (especially in monorepos),\n or a dependency pulling in a conflicting @playwright/test version.\n"),void(e=!0)}}}();u.stdout?.on("data",e=>{d(e,process.stdout)}),u.stderr?.on("data",e=>{const t=e.toString();d(e,process.stderr),p(t,process.stderr)});const f=new AbortController,h=()=>!f.signal.aborted&&(f.abort(),t.onClose?.(),process.removeListener("SIGINT",g),process.removeListener("SIGTERM",g),!0),g=e=>{bn.info("[test] Signal received, killing Playwright process",{signal:e,childPid:u.pid}),h(),u.kill(e);const t="SIGINT"===e?130:143;process.exit(t)};return process.on("SIGINT",g),process.on("SIGTERM",g),new Promise((e,t)=>{u.on("error",e=>{h()&&(bn.error("[test] Playwright process error",{error:e.message,childPid:u.pid}),t(e))}),u.on("close",t=>{if(!h())return;bn.info("[test] Playwright process exited",{exitCode:t,durationMs:Date.now()-l});const r=[process.stdout,process.stderr].filter(e=>e.writableNeedDrain).map(e=>new Promise(t=>e.once("drain",t)));Promise.race([Promise.all(r),new Promise(e=>setTimeout(e,5e3))]).then(()=>{process.exitCode=t??0,e(t??0)})})})}(f,{env:g,onClose:()=>{var e;bn.info("[test] Playwright process closed, cleaning up wrapper config"),(e=m)&&i.existsSync(e)&&i.rmSync(e)}})}function Xi(e=""){process.stdout.write(`${e}\n`)}function Qi(...e){process.stderr.write(`${e.join(" ")}\n`)}var Zi="stably",ea=`https://registry.npmjs.org/${Zi}/latest`,ta=w.z.object({version:w.z.string()});function ra(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 na(e,t){const r=ra(e),n=ra(t);return!(!r||!n)&&(n.major>r.major||!(n.major<r.major)&&(n.minor>r.minor||!(n.minor<r.minor)&&n.patch>r.patch))}var sa=O.default.join(j.default.homedir(),".stably"),oa=O.default.join(sa,"update-check.json"),ia=`https://registry.npmjs.org/${Zi}/latest`,aa=w.z.object({lastCheck:w.z.number(),latestVersion:w.z.string()}),ca=!1,la=!1,ua=async()=>{if(la)try{const{shutdown:e}=await import("@hyperdx/node-opentelemetry"),t=process.stderr.write.bind(process.stderr),r=process.stdout.write.bind(process.stdout),n=(e,...t)=>{const r=t[0];return!("string"!=typeof r||!r.includes("OpenTelemetry"))||!(!Buffer.isBuffer(r)||!r.toString().includes("OpenTelemetry"))||e(...t)};process.stderr.write=(...e)=>n(t,...e),process.stdout.write=(...e)=>n(r,...e);try{await e()}finally{process.stderr.write=t,process.stdout.write=r}}catch{}};!function(){const e=function(){try{const e=$.default.readFileSync(oa,"utf-8");return aa.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 = '${ia}';\n const cacheFile = ${JSON.stringify(oa)};\n const cacheDir = ${JSON.stringify(sa)};\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{s.spawn(process.execPath,["-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&na(vr,e.latestVersion)){if(ca)return;ca=!0;let t=!1;const r=()=>{if(t)return;t=!0;const r=`${H.default.yellow(`update available (${vr} → ${e.latestVersion})`)} - run \`${Zi} upgrade\` to get the latest version\n`;try{$.default.writeSync(2,r)}catch{}};process.once("beforeExit",r),process.once("exit",r)}}(),se.cwdChanged&&bn.debug("Changed working directory",{cwd:se.newCwd});for(const e of se.envFilesLoaded)bn.debug("Loaded env file",{path:e});for(const e of se.envFileErrors)bn.warn(e);var da=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==da&&process.argv.splice(da,1);var pa=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==pa&&process.argv.splice(pa,1),bn.info("CLI starting",{version:vr,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{bn.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),bn.flush(),bn.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(bn.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),bn.flush(),bn.printLogFileInfo())});var fa=new r.Command;fa.name("stably").description("AI-assisted Playwright testing CLI").version(vr),fa.enablePositionalOptions(),fa.showHelpAfterError(),fa.exitOverride(),fa.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}});var ha=[];fa.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{ha.push(e)}});var ga=()=>{const e=fa.helpInformation().trimEnd();return e?`${e}\n`:""},ma=(e,t)=>{let r=e;for(const e of t){const t=r.commands.find(t=>t.name()===e||t.aliases().includes(e));if(!t)return;r=t}return r},ya=()=>{process.stdout.write(ga())};fa.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void ya();const t=ma(fa,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),ya(),void(process.exitCode=1);var r;r=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(r))}),fa.action(()=>Ui({mode:"chat",getHelpText:ga})),fa.command("login").description("Authenticate with Stably in your browser").action(Zr),fa.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=vn();e&&(y.log.warn(`Environment variables ${H.default.cyan("STABLY_API_KEY")} and ${H.default.cyan("STABLY_PROJECT_ID")} are set.`),y.log.warn("They will continue to be used for authentication even after logout."),y.log.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await Hr();if(!t)return void y.outro(e?H.default.yellow("No stored OAuth login found to clear."):H.default.yellow("You are not logged in."));const r=y.spinner();r.start("Logging out..."),await(async e=>{try{await fetch(`${Ir}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await zr(),await Wr(),r.stop(H.default.green("✓ Logged out")),y.outro(H.default.green("You have been logged out successfully."))}),fa.command("whoami").description("Show auth status and current project").action(async()=>{y.log.info(`${H.default.bold("CLI Version:")} ${H.default.cyan(vr)}`);const e=vn();if(e){y.log.info(H.default.dim("Authentication: Environment variables")),y.log.info(` ${H.default.bold("API Key:")} ${H.default.cyan(e.apiKey.slice(0,8))}...`),y.log.info(` ${H.default.bold("Project ID:")} ${H.default.cyan(e.projectId)}`);const t=await Hr();if(t){let e;try{e=Dr(t.accessToken).email}catch{e=void 0}y.log.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&y.log.info(` ${H.default.bold("OAuth Email:")} ${H.default.cyan(e)}`),y.log.info(` ${H.default.bold("Tip:")} Unset env vars to use OAuth`)}return void y.outro(H.default.green("Authenticated via environment variables"))}const t=await Hr();if(!t)return void y.outro(H.default.yellow("Not logged in. Run `stably login` to authenticate."));let r;try{r=Dr(t.accessToken).email}catch{r=void 0}const n=await Yr();if(!n)return y.log.info(H.default.dim("Authentication: OAuth (not linked to a project)")),r&&y.log.info(` ${H.default.bold("Email:")} ${H.default.cyan(r)}`),void y.outro(H.default.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const s=await(async()=>Or(process.cwd(),$r))(),o=s?O.default.dirname(s):process.cwd(),i=O.default.relative(process.cwd(),o)||".";y.log.info(H.default.dim("Authentication: OAuth")),r&&y.log.info(` ${H.default.bold("Email:")} ${H.default.cyan(r)}`),y.log.info(` ${H.default.bold("Organization:")} ${H.default.cyan(n.orgName)}`),y.log.info(` ${H.default.bold("Project:")} ${H.default.cyan(n.projectName)}`),y.log.info(` ${H.default.bold("Linked at:")} ${H.default.dim(i)}`),y.outro(H.default.green("Authenticated"))}),fa.command("build [input...]").description("Compile test specification files (.stably.md) into Playwright tests").option("--force","Force regeneration even if prompt is unchanged").action(async(e,t)=>{try{await async function(e){const{inputs:t,force:r}=e,n=process.cwd();let o;if(0===t.length){const e=function(e){try{return s.execSync('git ls-files --cached --others --exclude-standard "*.stably.md"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).split("\n").map(e=>e.trim()).filter(Boolean)}catch{return[]}}(n);o=e.map(e=>O.default.resolve(n,e))}else o=await async function(e,t){const r=[];for(const n of e){const e=O.default.resolve(t,n);let s;try{s=await G.default.stat(e)}catch{r.push(e);continue}if(s.isDirectory()){const t=await Fi(e);r.push(...t)}else r.push(e)}const n=new Set,s=[];for(const e of r){const t=O.default.resolve(e);n.has(t)||(n.add(t),s.push(t))}return s}(t,n);if(0===o.length)throw new Error("No .stably.md files found. Create a test specification file (e.g., login.stably.md) and try again.");const{fixedFiles:i}=await async function(e,t){const r=[],n=[];for(const s of e){let e=s;try{await G.default.stat(e)}catch{n.push(e);continue}if(e.endsWith(".md")&&!e.endsWith(".stably.md")){const n=e.replace(/\.md$/,".stably.md");try{await G.default.rename(e,n);const s=Mi(O.default.relative(t,e)),o=Mi(O.default.relative(t,n)),i={code:"STABLY_WARNING_FILE_RENAMED",message:`Renamed ${s} → ${o} (test specs must use .stably.md extension)`,details:{oldPath:s,newPath:o}};r.push(i),y.log.warn(H.default.yellow(` ⚠ ${i.message}`)),e=n}catch(t){if(!(t instanceof Error&&"code"in t)||"EEXIST"!==t.code&&"ENOTEMPTY"!==t.code)throw t;y.log.warn(H.default.yellow(` ⚠ Skipping rename: ${n} already exists`)),e=n}}if(!e.endsWith(".stably.md")){n.push(e);continue}const o=await G.default.readFile(e,"utf8"),{updated:i,addedFields:a}=Gi(o,e);if(a.length>0){await G.default.writeFile(e,i,"utf8");const n=Mi(O.default.relative(t,e)),s={code:"STABLY_WARNING_FRONTMATTER_ADDED",message:`Added missing frontmatter fields to ${n}: ${a.join(", ")}`,details:{path:n,addedFields:a}};r.push(s),y.log.warn(H.default.yellow(` ⚠ ${s.message}`))}n.push(e)}return{fixedFiles:n,warnings:r}}(o,n);o=i,y.log.info(H.default.bold(`Found ${o.length} test specification${1!==o.length?"s":""}`));for(const e of o){const t=Mi(O.default.relative(n,e));y.log.info(H.default.dim(` ${t}`))}y.log.info("");const a={built:[],skipped:[],failed:[]};for(const e of o){const t=Mi(O.default.relative(n,e));try{"built"===await Wi({force:r,inputFilePath:e})?a.built.push(t):a.skipped.push(t)}catch(e){const r=e instanceof Error?e.message:String(e);y.log.error(H.default.red(`Failed to build ${t}: ${r}`)),a.failed.push(t)}}return function(e){if(y.log.info(""),y.log.info(H.default.bold("Build Summary")),y.log.info(` ${H.default.green(`${e.built.length} built`)} ${H.default.dim(`${e.skipped.length} skipped (unchanged)`)} ${e.failed.length>0?H.default.red(`${e.failed.length} failed`):H.default.dim("0 failed")}`),e.failed.length>0){y.log.info(""),y.log.error(H.default.red("Failed files:"));for(const t of e.failed)y.log.error(H.default.red(` - ${t}`))}}(a),a.failed.length>0&&(process.exitCode=1),a}({inputs:e,force:t.force??!1})}catch(e){const t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}\n`),process.exitCode=1}}),fa.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=>{y.intro(`Starting development server for port ${e.port}...`);const t=await Tn(),r="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),n=y.spinner();n.start("Starting development server...");const s=await P.startTunnel(`http://localhost:${e.port}`,{subdomain:r});n.stop(`Your local environment is available at: ]8;;${s.url}${H.default.underline(H.default.cyan(s.url))}]8;;`)}),fa.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(async(e,t)=>{const r=e.length>0&&"test"===e[0]?e.slice(1):e;return Ui({mode:"single",prompt:r,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(async(e,t)=>Ui({mode:"single",prompt:e,outputDir:t.output})),fa.command("fix [runId]").description("Fix failing tests from a run (auto-detects from last test run or CI)").action(async e=>{(function(e){try{return s.execSync("git rev-parse --is-inside-work-tree",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}})(process.cwd())||(bn.error('Not a git repository. The "stably fix" command requires a git repository to track changes made during the fix. Please run this command from inside a git repository.'),process.stderr.write('Error: Not a git repository.\nThe "stably fix" command requires a git repository to track changes made during the fix.\nPlease run this command from inside a git repository.\n'),process.exit(1));const t=await(async e=>{const t=e=>e.replace(/\//g,"_");if(e)return bn.debug("Run ID provided explicitly",{runId:e}),t(e);const r=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 r of Object.keys(Jt))if(Jt[r].detect({env:e,cwd:t}))return{isCi:!0,...Jt[r].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(r={env:e,cwd:t},{commit:vt(r),branch:_t(r)})};var r})();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),r=[e.service,"slug"in e?e.slug?.replace(/\//g,"_"):void 0,"build"in e?String(e.build):void 0,"job"in e?String(e.job):void 0,t&&String(t)].filter(Boolean);return r.length>0?r.join("-"):void 0}();if(r)return bn.debug("Run ID detected from CI environment",{runId:r}),t(r);bn.debug("No explicit run ID or CI environment detected, checking last-run.json");const n=await(async()=>{try{const e=await Or(process.cwd(),".stably/last-run.json");if(!e)return;const t=await m.readFile(e,"utf-8");return{...ki.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(n){const e=(Date.now()-n.timestamp)/36e5;return bn.debug("Run ID found in last-run.json",{runId:n.runId,timestamp:n.timestamp,filePath:n.filePath,ageHours:Math.round(e)}),e>24&&bn.warn(`Using run ID from ${Math.round(e)} hours ago (${n.filePath}). Provide an explicit run ID if this is not the run you want to fix.`),t(n.runId)}bn.debug("No run ID found in last-run.json")})(e);return t||(process.stderr.write('Run ID is required. Either:\n 1. Run "stably test" first (run ID will be auto-detected)\n 2. Provide a run ID: stably fix <runId>\n 3. Run in CI (auto-detected from environment)\n'),process.exit(1)),Ui({mode:"fix",runId:t})}),fa.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>Ui({mode:"init"})),fa.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 r;Xi(H.default.cyan("Checking for updates...\n"));try{r=await async function(){const e=await async function(){const e=new AbortController,t=setTimeout(()=>e.abort(),1e4);t.unref();try{const t=await fetch(ea,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return ta.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:vr,latest:e,isOutdated:na(vr,e)}}()}catch(e){return Qi(H.default.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(Xi(`Current version: ${H.default.yellow(r.current)}`),Xi(`Latest version: ${H.default.green(r.latest)}`),Xi(),!r.isOutdated)return void Xi(H.default.green("✓ You are already on the latest version!"));if(Xi(H.default.yellow(`⚠ A new version is available: ${r.current} → ${r.latest}`)),Xi(),t)return Xi(H.default.dim("Exiting with code 1 to indicate update available (useful for CI).")),void(process.exitCode=1);const n=function(){const e=process.argv[1]||"";if(e.includes("_npx")||e.includes(".npm/_cacache"))return"npx";try{const t=s.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=s.execSync("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=s.execSync("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=s.execSync("yarn config get globalFolder",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-berry"}catch{}return"unknown"}(),o=function(e){switch(e){case"global-npm":case"global-yarn-berry":case"unknown":return{command:"npm",args:["install","-g",`${Zi}@latest`],description:`npm install -g ${Zi}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${Zi}@latest`],description:`pnpm add -g ${Zi}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${Zi}@latest`],description:`yarn global add ${Zi}@latest`};case"npx":return{command:"npx",args:[`${Zi}@latest`],description:`npx ${Zi}@latest (always uses latest)`}}}(n);if("npx"===n)return Xi(H.default.dim("You are running via npx, which always fetches the latest version.")),void Xi(H.default.dim(`Simply run: ${H.default.white("npx stably")} to use the latest version.`));"unknown"===n?(Xi(H.default.yellow("Could not detect installation method. Falling back to npm.")),Xi()):"global-yarn-berry"===n&&(Xi(H.default.yellow("Yarn Berry does not support global packages. Falling back to npm.")),Xi()),Xi(`Upgrade command: ${H.default.cyan(o.description)}`),Xi(),Xi(H.default.cyan("Upgrading...")),Xi();try{await(i=o.command,a=o.args,new Promise((e,t)=>{const r=s.spawn(i,a,{stdio:"inherit",shell:"win32"===process.platform});r.on("close",r=>{0===r?e():t(new Error(`Upgrade command exited with code ${r}`))}),r.on("error",e=>{t(e)})})),Xi(),Xi(H.default.green("✓ Upgrade complete!")),Xi(H.default.dim(`Run ${H.default.white("stably --version")} to verify.`))}catch(e){Qi(H.default.red("Upgrade failed:"),e instanceof Error?e.message:e),Xi(),Xi(H.default.dim("You can try manually running:")),Xi(H.default.cyan(` ${o.description}`)),process.exitCode=1}var i,a}(e)),Vi.forEach(({args:e,description:t,name:r})=>{fa.command(r).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>Ji({overrideArgs:e,subcommand:r}))});var ba=()=>{0!==ha.length&&(process.stderr.write(ha.join("")),ha=[])};(async()=>{await(async()=>{if(!la&&"1"!==process.env.STABLY_DISABLE_TELEMETRY&&"1"!==process.env.DO_NOT_TRACK&&!process.argv.includes("--no-telemetry"))try{const{init:e}=await import("@hyperdx/node-opentelemetry");e({apiKey:"61d10b50-9534-47be-a732-95bfe461adb7",service:"stably-cli",consoleCapture:!0,disableTracing:!0,disableMetrics:!0,disableStartupLogs:!0,additionalResourceAttributes:{"cli.version":vr,"node.version":process.version,"os.platform":process.platform}}),la=!0}catch{}})();try{await fa.parseAsync(process.argv),bn.info("CLI completed successfully")}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e))throw bn.error("Unexpected CLI error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),ba(),bn.flush(),bn.printLogFileInfo(),await ua(),e;const t="number"==typeof e.exitCode?e.exitCode:1,r=process.argv.slice(2).find(e=>!e.startsWith("-")),n=!!r&&!!ma(fa,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return ha=[],bn.warn("Unknown command",{command:r}),process.stderr.write(`command '${r}' not found\n`),ya(),void(process.exitCode=t);bn.debug("Commander error",{code:e.code,exitCode:t}),ba(),process.exitCode=t}finally{bn.flush(),await ua()}})();
|
|
2
|
+
"use strict";var e=require("dotenv"),t=require("path"),r=require("commander"),n=require("buffer"),s=require("child_process"),a=require("process"),i=require("fs"),o=require("url"),l=require("os");require("timers/promises");var c=require("stream"),u=require("util"),d=require("events"),p=require("readline"),f=require("fs/promises"),h=require("crypto"),m=require("ts-pattern"),g=require("picocolors"),y=require("simple-git"),v=require("@clack/prompts"),_=require("readline/promises"),b=require("zod"),w=require("http"),E=require("pino"),x=require("sonic-boom"),S=require("zod/v3"),k=require("ws"),T=require("react"),I=require("react/jsx-runtime"),$=require("module"),P=require("yaml"),C=require("@stablyhq/runner-sdk"),R="undefined"!=typeof document?document.currentScript:null;function A(e){return e&&e.__esModule?e:{default:e}}function O(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}var N,j,D=A(t),U=A(s),L=A(a),M=O(i),z=A(l),B=A(c),F=A(f),q=A(h),H=A(g),Z=A(b),V=A(w),G=A(E),W=A(x),K=A(k),Y=Object.create,J=Object.defineProperty,Q=Object.getOwnPropertyDescriptor,X=Object.getOwnPropertyNames,ee=Object.getPrototypeOf,te=Object.prototype.hasOwnProperty,re=(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')}),ne=(N={"../playwright-trace-scrubber/node_modules/.pnpm/isbinaryfile@5.0.7/node_modules/isbinaryfile/lib/index.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.isBinaryFileSync=e.isBinaryFile=void 0;var t=re("fs"),r=re("util"),n=(0,r.promisify)(t.stat),s=(0,r.promisify)(t.open),a=(0,r.promisify)(t.close),i=class{fileBuffer;size;offset;error;constructor(e,t){this.fileBuffer=e,this.size=t,this.offset=0,this.error=!1}hasError(){return this.error}nextByte(){return this.offset===this.size||this.hasError()?(this.error=!0,255):this.fileBuffer[this.offset++]}next(e){const t=new Array;for(let r=0;r<e;r++){if(this.error)return t;t[r]=this.nextByte()}return t}};function o(e){let t=0,r=0;for(;!e.hasError();){const n=e.nextByte();if(r|=(127&n)<<7*t,!(128&n))break;if(t>=10){e.error=!0;break}t++}return r}function l(e){switch(7&o(e)){case 0:return o(e),!0;case 1:return e.next(8),!0;case 2:const t=o(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function c(e,t){if(0===t)return!1;let r=0;const n=Math.min(t,515),s=Math.min(n,512);if(t>=3&&239===e[0]&&187===e[1]&&191===e[2])return!1;if(t>=4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return!1;if(t>=4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return!1;if(t>=4&&132===e[0]&&49===e[1]&&149===e[2]&&51===e[3])return!1;if(n>=5&&"%PDF-"===e.slice(0,5).toString())return!0;if(t>=2&&254===e[0]&&255===e[1])return!1;if(t>=2&&255===e[0]&&254===e[1])return!1;for(let t=0;t<s;t++){if(0===e[t])return!0;if((e[t]<7||e[t]>14)&&(e[t]<32||e[t]>127)){if(e[t]>=192&&e[t]<=223&&t+1<n){if(t++,e[t]>=128&&e[t]<=191)continue}else if(e[t]>=224&&e[t]<=239&&t+2<n){if(t++,e[t]>=128&&e[t]<=191&&e[t+1]>=128&&e[t+1]<=191){t++;continue}}else if(e[t]>=240&&e[t]<=247&&t+3<n&&(t++,e[t]>=128&&e[t]<=191&&e[t+1]>=128&&e[t+1]<=191&&e[t+2]>=128&&e[t+2]<=191)){t+=2;continue}if(r++,t>=32&&100*r/s>10)return!0}}return 100*r/s>10||!!(r>1&&function(e,t){const r=new i(e,t);let n=0;for(;;){if(!l(r)&&!r.hasError())return!1;if(r.hasError())break;n++}return n>0}(e,s))}function u(e){return"string"==typeof e}function d(e){if(!e.isFile())throw new Error("Path provided was not a file!")}e.isBinaryFile=async function(e,r){if(u(e)){d(await n(e));const r=await s(e,"r"),i=Buffer.alloc(515);return new Promise((e,n)=>{t.read(r,i,0,515,0,(t,s,o)=>{if(a(r),t)n(t);else try{e(c(i,s))}catch(e){n(e)}})})}return void 0===r&&(r=e.length),c(e,r)},e.isBinaryFileSync=function(e,r){if(u(e)){d(t.statSync(e));const r=t.openSync(e,"r"),n=Buffer.alloc(515),s=t.readSync(r,n,0,515,0);return t.closeSync(r),c(n,s)}return void 0===r&&(r=e.length),c(e,r)}}},function(){return j||(0,N[X(N)[0]])((j={exports:{}}).exports,j),j.exports}),se={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[]},ae=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);if(-1!==ae&&process.argv[ae+1]){const e=process.argv[ae+1];process.chdir(e),se.cwdChanged=!0,se.newCwd=e,process.argv.splice(ae,2)}for(var ie=[],oe=0;oe<process.argv.length;)if("--env-file"===process.argv[oe]){const e=process.argv[oe+1];e&&!e.startsWith("-")?(ie.push(e),process.argv.splice(oe,2)):oe++}else oe++;for(const t of ie){const r=D.default.resolve(process.cwd(),t),n=e.config({path:r,override:!0,quiet:!0});if(n.error){const e=`warning: could not load env file: ${r} (${n.error.message})`;se.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else se.envFilesLoaded.push(r)}var le={detect:({env:e})=>Boolean(e.APPVEYOR),configuration({env:e}){const t=e.APPVEYOR_PULL_REQUEST_NUMBER,r=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:r,prBranch:e.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH,slug:e.APPVEYOR_REPO_NAME,root:e.APPVEYOR_BUILD_FOLDER}}};function ce(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function ue(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var de={detect:({env:e})=>Boolean(e.BUILD_BUILDURI),configuration({env:e}){const t=e.SYSTEM_PULLREQUEST_PULLREQUESTID,r=Boolean(t);return{name:"Azure Pipelines",service:"azurePipelines",commit:e.BUILD_SOURCEVERSION,build:e.BUILD_BUILDNUMBER,branch:ue(r?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:r,prBranch:ue(r?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},pe={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})},fe={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})},he={detect:({env:e})=>Boolean(e.BITRISE_IO),configuration({env:e}){const t="false"===e.BITRISE_PULL_REQUEST?void 0:e.BITRISE_PULL_REQUEST,r=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:r?e.BITRISEIO_GIT_BRANCH_DEST:e.BITRISE_GIT_BRANCH,pr:t,isPr:r,prBranch:r?e.BITRISE_GIT_BRANCH:void 0,slug:e.BITRISE_APP_SLUG}}},me={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=ce(e.BUDDY_EXECUTION_PULL_REQUEST_ID),r=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:r?e.BUDDY_EXECUTION_PULL_REQUEST_HEAD_BRANCH:e.BUDDY_EXECUTION_BRANCH,pr:t,isPr:r,slug:e.BUDDY_REPO_SLUG}}},ge="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function ye(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ve,_e,be,we,Ee,xe,Se,ke,Te={exports:{}};var Ie,$e,Pe,Ce,Re,Ae,Oe,Ne,je,De,Ue,Le,Me,ze,Be,Fe={exports:{}},qe={};function He(){if(Le)return Ue;Le=1;const e=D.default,t=function(){if(Pe)return $e;Pe=1;const e=D.default,t=function(){if(ke)return Se;ke=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=D.default,r=e?";":":",n=function(){if(xe)return Ee;var e;function t(r,n,s){if("function"==typeof n&&(s=n,n={}),!s){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,s){t(r,n||{},function(t,r){t?s(t):e(r)})})}e(r,n||{},function(e,t){e&&("EACCES"===e.code||n&&n.ignoreErrors)&&(e=null,t=!1),s(e,t)})}return xe=1,e="win32"===process.platform||ge.TESTING_WINDOWS?function(){if(_e)return ve;_e=1,ve=r,r.sync=function(r,n){return t(e.statSync(r),r,n)};var e=M.default;function t(e,t,r){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var r=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!r)return!0;if(-1!==(r=r.split(";")).indexOf(""))return!0;for(var n=0;n<r.length;n++){var s=r[n].toLowerCase();if(s&&e.substr(-s.length).toLowerCase()===s)return!0}return!1}(t,r)}function r(r,n,s){e.stat(r,function(e,a){s(e,!e&&t(a,r,n))})}return ve}():function(){if(we)return be;we=1,be=t,t.sync=function(t,n){return r(e.statSync(t),n)};var e=M.default;function t(t,n,s){e.stat(t,function(e,t){s(e,!e&&r(t,n))})}function r(e,t){return e.isFile()&&function(e,t){var r=e.mode,n=e.uid,s=e.gid,a=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),i=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),o=parseInt("100",8),l=parseInt("010",8);return r&parseInt("001",8)||r&l&&s===i||r&o&&n===a||r&(o|l)&&0===a}(e,t)}return be}(),Ee=t,t.sync=function(t,r){try{return e.sync(t,r||{})}catch(e){if(r&&r.ignoreErrors||"EACCES"===e.code)return!1;throw e}},Ee}(),s=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),a=(t,n)=>{const s=n.colon||r,a=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(n.path||process.env.PATH||"").split(s)],i=e?n.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",o=e?i.split(s):[""];return e&&-1!==t.indexOf(".")&&""!==o[0]&&o.unshift(""),{pathEnv:a,pathExt:o,pathExtExe:i}},i=(e,r,i)=>{"function"==typeof r&&(i=r,r={}),r||(r={});const{pathEnv:o,pathExt:l,pathExtExe:c}=a(e,r),u=[],d=n=>new Promise((a,i)=>{if(n===o.length)return r.all&&u.length?a(u):i(s(e));const l=o[n],c=/^".*"$/.test(l)?l.slice(1,-1):l,d=t.join(c,e),f=!c&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;a(p(f,n,0))}),p=(e,t,s)=>new Promise((a,i)=>{if(s===l.length)return a(d(t+1));const o=l[s];n(e+o,{pathExt:c},(n,i)=>{if(!n&&i){if(!r.all)return a(e+o);u.push(e+o)}return a(p(e,t,s+1))})});return i?d(0).then(e=>i(null,e),i):d(0)};return Se=i,i.sync=(e,r)=>{r=r||{};const{pathEnv:i,pathExt:o,pathExtExe:l}=a(e,r),c=[];for(let s=0;s<i.length;s++){const a=i[s],u=/^".*"$/.test(a)?a.slice(1,-1):a,d=t.join(u,e),p=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<o.length;e++){const t=p+o[e];try{if(n.sync(t,{pathExt:l})){if(!r.all)return t;c.push(t)}}catch(e){}}}if(r.all&&c.length)return c;if(r.nothrow)return null;throw s(e)},Se}(),r=function(){if(Ie)return Fe.exports;Ie=1;const e=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};return Fe.exports=e,Fe.exports.default=e,Fe.exports}();function n(n,s){const a=n.options.env||process.env,i=process.cwd(),o=null!=n.options.cwd,l=o&&void 0!==process.chdir&&!process.chdir.disabled;if(l)try{process.chdir(n.options.cwd)}catch(e){}let c;try{c=t.sync(n.command,{path:a[r({env:a})],pathExt:s?e.delimiter:void 0})}catch(e){}finally{l&&process.chdir(i)}return c&&(c=e.resolve(o?n.options.cwd:"",c)),c}return $e=function(e){return n(e)||n(e,!0)}}(),r=function(){if(Ce)return qe;Ce=1;const e=/([()\][%!^"`<>&|;, *?])/g;return qe.command=function(t){return t.replace(e,"^$1")},qe.argument=function(t,r){return t=(t=`"${t=(t=(t=`${t}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(e,"^$1"),r&&(t=t.replace(e,"^$1")),t},qe}(),n=function(){if(De)return je;De=1;const e=M.default,t=function(){if(Ne)return Oe;Ne=1;const e=Ae?Re:(Ae=1,Re=/^#!(.*)/);return Oe=(t="")=>{const r=t.match(e);if(!r)return null;const[n,s]=r[0].replace(/#! ?/,"").split(" "),a=n.split("/").pop();return"env"===a?s:s?`${a} ${s}`:a}}();return je=function(r){const n=Buffer.alloc(150);let s;try{s=e.openSync(r,"r"),e.readSync(s,n,0,150,0),e.closeSync(s)}catch(e){}return t(n.toString())},je}(),s="win32"===process.platform,a=/\.(?:com|exe)$/i,i=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;return Ue=function(o,l,c){l&&!Array.isArray(l)&&(c=l,l=null);const u={command:o,args:l=l?l.slice(0):[],options:c=Object.assign({},c),file:void 0,original:{command:o,args:l}};return c.shell?u:function(o){if(!s)return o;const l=function(e){e.file=t(e);const r=e.file&&n(e.file);return r?(e.args.unshift(e.file),e.command=r,t(e)):e.file}(o),c=!a.test(l);if(o.options.forceShell||c){const t=i.test(l);o.command=e.normalize(o.command),o.command=r.command(o.command),o.args=o.args.map(e=>r.argument(e,t));const n=[o.command].concat(o.args).join(" ");o.args=["/d","/s","/c",`"${n}"`],o.command=process.env.comspec||"cmd.exe",o.options.windowsVerbatimArguments=!0}return o}(u)}}var Ze=ye(function(){if(Be)return Te.exports;Be=1;const e=U.default,t=He(),r=function(){if(ze)return Me;ze=1;const e="win32"===process.platform;function t(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 r(r,n){return e&&1===r&&!n.file?t(n.original,"spawn"):null}return Me={hookChildProcess:function(t,n){if(!e)return;const s=t.emit;t.emit=function(e,a){if("exit"===e){const e=r(a,n);if(e)return s.call(t,"error",e)}return s.apply(t,arguments)}},verifyENOENT:r,verifyENOENTSync:function(r,n){return e&&1===r&&!n.file?t(n.original,"spawnSync"):null},notFoundError:t},Me}();function n(n,s,a){const i=t(n,s,a),o=e.spawn(i.command,i.args,i.options);return r.hookChildProcess(o,i),o}return Te.exports=n,Te.exports.spawn=n,Te.exports.sync=function(n,s,a){const i=t(n,s,a),o=e.spawnSync(i.command,i.args,i.options);return o.error=o.error||r.verifyENOENTSync(o.status,i),o},Te.exports._parse=t,Te.exports._enoent=r,Te.exports}());function Ve(e={}){const{env:t=process.env,platform:r=process.platform}=e;return"win32"!==r?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"}var Ge=(e,t)=>({name:`SIGRT${t+1}`,number:We+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),We=34,Ke=[{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-We+1;return Array.from({length:e},Ge)})();return[...Ke,...e].map(Je)},Je=({name:e,number:t,description:r,action:n,forced:s=!1,standard:a})=>{const{signals:{[e]:i}}=l.constants,o=void 0!==i;return{name:e,number:o?i:t,description:r,supported:o,action:n,forced:s,standard:a}},Qe=({name:e,number:t,description:r,supported:n,action:s,forced:a,standard:i})=>[e,{name:e,number:t,description:r,supported:n,action:s,forced:a,standard:i}],Xe=(()=>{const e=Ye();return Object.fromEntries(e.map(Qe))})();(()=>{const e=Ye(),t=Array.from({length:65},(t,r)=>((e,t)=>{const r=((e,t)=>{const r=t.find(({name:t})=>l.constants.signals[t]===e);return void 0!==r?r:t.find(t=>t.number===e)})(e,t);if(void 0===r)return{};const{name:n,description:s,supported:a,action:i,forced:o,standard:c}=r;return{[e]:{name:n,number:e,description:s,supported:a,action:i,forced:o,standard:c}}})(r,e));Object.assign({},...t)})();var et=({stdout:e,stderr:t,all:r,error:n,signal:s,exitCode:a,command:i,escapedCommand:o,timedOut:l,isCanceled:c,killed:u,parsed:{options:{timeout:d,cwd:p=L.default.cwd()}}})=>{a=null===a?void 0:a;const f=void 0===(s=null===s?void 0:s)?void 0:Xe[s].description,h=(({timedOut:e,timeout:t,errorCode:r,signal:n,signalDescription:s,exitCode:a,isCanceled:i})=>e?`timed out after ${t} milliseconds`:void 0!==r?`failed with ${r}`:void 0!==n?`was killed with ${n} (${s})`:void 0!==a?`failed with exit code ${a}`:"failed")({timedOut:l,timeout:d,errorCode:n&&n.code,signal:s,signalDescription:f,exitCode:a,isCanceled:c}),m=`Command ${h}: ${i}`,g="[object Error]"===Object.prototype.toString.call(n),y=g?`${m}\n${n.message}`:m,v=[y,t,e].filter(Boolean).join("\n");return g?(n.originalMessage=n.message,n.message=v):n=new Error(v),n.shortMessage=y,n.command=i,n.escapedCommand=o,n.exitCode=a,n.signal=s,n.signalDescription=f,n.stdout=e,n.stderr=t,n.cwd=p,void 0!==r&&(n.all=r),"bufferedData"in n&&delete n.bufferedData,n.failed=!0,n.timedOut=Boolean(l),n.isCanceled=c,n.killed=u&&!l,n},tt=["stdin","stdout","stderr"],rt=[];rt.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&rt.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&rt.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var nt,st,at=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,it=Symbol.for("signal-exit emitter"),ot=globalThis,lt=Object.defineProperty.bind(Object),ct=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(ot[it])return ot[it];lt(ot,it,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const r=this.listeners[e],n=r.indexOf(t);-1!==n&&(0===n&&1===r.length?r.length=0:r.splice(n,1))}emit(e,t,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(const s of this.listeners[e])n=!0===s(t,r)||n;return"exit"===e&&(n=this.emit("afterExit",t,r)||n),n}},ut=class{},dt=globalThis.process;at(dt)?new class extends ut{#e="win32"===dt.platform?"SIGINT":"SIGHUP";#t=new ct;#r;#n;#s;#a={};#i=!1;constructor(e){super(),this.#r=e,this.#a={};for(const t of rt)this.#a[t]=()=>{const r=this.#r.listeners(t);let{count:n}=this.#t;const s=e;if("object"==typeof s.__signal_exit_emitter__&&"number"==typeof s.__signal_exit_emitter__.count&&(n+=s.__signal_exit_emitter__.count),r.length===n){this.unload();const r=this.#t.emit("exit",null,t),n="SIGHUP"===t?this.#e:t;r||e.kill(e.pid,n)}};this.#s=e.reallyExit,this.#n=e.emit}onExit(e,t){if(!at(this.#r))return()=>{};!1===this.#i&&this.load();const r=t?.alwaysLast?"afterExit":"exit";return this.#t.on(r,e),()=>{this.#t.removeListener(r,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 rt)try{const t=this.#a[e];t&&this.#r.on(e,t)}catch(e){}this.#r.emit=(e,...t)=>this.#o(e,...t),this.#r.reallyExit=e=>this.#l(e)}}unload(){this.#i&&(this.#i=!1,rt.forEach(e=>{const t=this.#a[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#r.removeListener(e,t)}catch(e){}}),this.#r.emit=this.#n,this.#r.reallyExit=this.#s,this.#t.count-=1)}#l(e){return at(this.#r)?(this.#r.exitCode=e||0,this.#t.emit("exit",this.#r.exitCode,null),this.#s.call(this.#r,this.#r.exitCode)):0}#o(e,...t){const r=this.#n;if("exit"===e&&at(this.#r)){"number"==typeof t[0]&&(this.#r.exitCode=t[0]);const n=r.call(this.#r,e,...t);return this.#t.emit("exit",this.#r.exitCode,null),n}return r.call(this.#r,e,...t)}}(dt):new class extends ut{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if(st)return nt;st=1;const{PassThrough:e}=B.default;nt=function(){var t=[],r=new e({objectMode:!0});return r.setMaxListeners(0),r.add=n,r.isEmpty=function(){return 0==t.length},r.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(n),r;function n(e){return Array.isArray(e)?(e.forEach(n),this):(t.push(e),e.once("end",s.bind(null,e)),e.once("error",r.emit.bind(r,"error")),e.pipe(r,{end:!1}),this)}function s(e){!(t=t.filter(function(t){return t!==e})).length&&r.readable&&r.end()}}}();var pt=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(pt,e)]);var ft=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],ht=/^[\w.-]+$/,mt=u.debuglog("execa").enabled,gt=(e,t)=>String(e).padStart(t,"0"),yt=(e,t,r={})=>{const n=Ze._parse(e,t,r);return e=n.command,t=n.args,(r={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(r=n.options).cwd||L.default.cwd(),execPath:L.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:mt,...r}).env=(({env:e,extendEnv:t,preferLocal:r,localDir:n,execPath:s})=>{const a=t?{...L.default.env,...e}:e;return r?(({env:e=L.default.env,...t}={})=>{const r=Ve({env:e={...e}});return t.path=e[r],e[r]=(({cwd:e=L.default.cwd(),path:t=L.default.env[Ve()],preferLocal:r=!0,execPath:n=L.default.execPath,addExecPath:s=!0}={})=>{const a=e instanceof URL?o.fileURLToPath(e):e,i=D.default.resolve(a),l=[];return r&&((e,t)=>{let r;for(;r!==t;)e.push(D.default.join(t,"node_modules/.bin")),r=t,t=D.default.resolve(t,"..")})(l,i),s&&((e,t,r)=>{const n=t instanceof URL?o.fileURLToPath(t):t;e.push(D.default.resolve(r,n,".."))})(l,n,i),[...l,t].join(D.default.delimiter)})(t),e})({env:a,cwd:n,execPath:s}):a})(r),r.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return tt.map(t=>e[t]);if((e=>tt.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${tt.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 r=Math.max(t.length,tt.length);return Array.from({length:r},(e,r)=>t[r])})(r),"win32"===L.default.platform&&"cmd"===D.default.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:r,parsed:n}},vt=(e,t,r)=>"string"==typeof t||n.Buffer.isBuffer(t)?e.stripFinalNewline?function(e){const t="string"==typeof e?"\n":"\n".charCodeAt(),r="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===r&&(e=e.slice(0,-1)),e}(t):t:void 0===r?void 0:"";function _t(e,t,r){const n=yt(e,t,r),s=((e,t)=>ft(e,t).join(" "))(e,t),a=((e,t)=>ft(e,t).map(e=>(e=>"string"!=typeof e||ht.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&L.default.stderr.write(`[${(()=>{const e=new Date;return`${gt(e.getHours(),2)}:${gt(e.getMinutes(),2)}:${gt(e.getSeconds(),2)}.${gt(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(a,n.options);const o=(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),i.readFileSync(t)))(e);if(null!==(r=t)&&"object"==typeof r&&"function"==typeof r.pipe)throw new TypeError("The `input` option cannot be a stream in sync mode");var r;return t})(n.options);let l;try{l=U.default.spawnSync(n.file,n.args,{...n.options,input:o})}catch(e){throw et({error:e,stdout:"",stderr:"",all:"",command:s,escapedCommand:a,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const c=vt(n.options,l.stdout,l.error),u=vt(n.options,l.stderr,l.error);if(l.error||0!==l.status||null!==l.signal){const e=et({stdout:c,stderr:u,error:l.error,signal:l.signal,exitCode:l.status,command:s,escapedCommand:a,parsed:n,timedOut:l.error&&"ETIMEDOUT"===l.error.code,isCanceled:!1,killed:null!==l.signal});if(!n.options.reject)return e;throw e}return{command:s,escapedCommand:a,exitCode:0,stdout:c,stderr:u,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function bt(e){try{return _t("git",["rev-parse","HEAD"],e).stdout}catch{return}}function wt(e){try{const t=_t("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=_t("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 Et=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,xt=/^\/(.*)\.git$/;function St(e){if(e){if(e.match(Et))return e.replace(Et,"$1");try{return new URL(e).pathname.replace(xt,"$1")}catch{return}}}var kt,Tt={detect:({env:e})=>Boolean(e.BUILDKITE),configuration({env:e}){const t="false"===e.BUILDKITE_PULL_REQUEST?void 0:e.BUILDKITE_PULL_REQUEST,r=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:r?e.BUILDKITE_PULL_REQUEST_BASE_BRANCH:e.BUILDKITE_BRANCH,slug:St(e.BUILDKITE_REPO),pr:t,isPr:r,prBranch:r?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},It={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||ce(e.CIRCLE_PULL_REQUEST||e.CI_PULL_REQUEST),r=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:r?void 0:e.CIRCLE_BRANCH,pr:t,isPr:r,prBranch:r?e.CIRCLE_BRANCH:void 0,slug:`${e.CIRCLE_PROJECT_USERNAME}/${e.CIRCLE_PROJECT_REPONAME}`}}},$t="https://cirrus-ci.com",Pt={detect:({env:e})=>Boolean(e.CIRRUS_CI),configuration({env:e}){const t=e.CIRRUS_PR,r=Boolean(t);return{name:"Cirrus CI",service:"cirrus",commit:e.CIRRUS_CHANGE_IN_REPO,tag:e.CIRRUS_TAG,build:e.CIRRUS_BUILD_ID,buildUrl:`${$t}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${$t}/task/${e.CIRRUS_TASK_ID}`,branch:r?e.CIRRUS_BASE_BRANCH:e.CIRRUS_BRANCH,pr:t,isPr:r,prBranch:r?e.CIRRUS_BRANCH:void 0,slug:e.CIRRUS_REPO_FULL_NAME,root:e.CIRRUS_WORKING_DIR}}},Ct={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:bt({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:wt({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})},Rt={detect:({env:e})=>Boolean(e.CF_BUILD_ID),configuration({env:e}){const t=e.CF_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Codefresh",service:"codefresh",commit:e.CF_REVISION,build:e.CF_BUILD_ID,buildUrl:e.CF_BUILD_URL,branch:r?e.CF_PULL_REQUEST_TARGET:e.CF_BRANCH,pr:t,isPr:r,prBranch:r?e.CF_BRANCH:void 0,slug:`${e.CF_REPO_OWNER}/${e.CF_REPO_NAME}`,root:e.CF_VOLUME_PATH}}},At={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}}},Ot=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(i.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?ue(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},Nt={detect:({env:e})=>Boolean(e.GITHUB_ACTIONS),configuration({env:e,cwd:t}){const r="pull_request"===e.GITHUB_EVENT_NAME||"pull_request_target"===e.GITHUB_EVENT_NAME,n=ue("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(i.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:r,branch:n,prBranch:r?n:void 0,slug:e.GITHUB_REPOSITORY,root:e.GITHUB_WORKSPACE,...r?Ot({env:e}):void 0}}},jt={detect:({env:e})=>Boolean(e.GITLAB_CI),configuration({env:e}){const t=e.CI_MERGE_REQUEST_ID,r=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:r?e.CI_MERGE_REQUEST_TARGET_BRANCH_NAME:e.CI_COMMIT_REF_NAME,pr:t,isPr:r,prBranch:e.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,slug:e.CI_PROJECT_PATH,root:e.CI_PROJECT_DIR}}},Dt={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const r=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,n=Boolean(r),s=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||bt({env:e,cwd:t}),branch:n?e.ghprbTargetBranch||e.gitlabTargetBranch:s,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,root:e.WORKSPACE,pr:r,isPr:n,prBranch:n?e.ghprbSourceBranch||e.gitlabSourceBranch||s:void 0}}},Ut={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}}},Lt={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})},Mt={detect:({env:e})=>Boolean(e.SAILCI),configuration({env:e}){const t=e.SAIL_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Sail CI",service:"sail",commit:e.SAIL_COMMIT_SHA,branch:r?void 0:e.SAIL_COMMIT_BRANCH,pr:t,isPr:r,slug:`${e.SAIL_REPO_OWNER}/${e.SAIL_REPO_NAME}`,root:e.SAIL_CLONE_DIR}}},zt={detect:({env:e})=>Boolean(e.SCREWDRIVER),configuration({env:e}){const t=e.SD_PULL_REQUEST,r=Boolean(t);return{name:"Screwdriver.cd",service:"screwdriver",branch:r?e.PR_BASE_BRANCH_NAME:e.GIT_BRANCH,prBranch:r?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:r,slug:e.SD_PIPELINE_NAME,root:e.SD_ROOT_DIR}}},Bt={detect:({env:e})=>Boolean(e.SCRUTINIZER),configuration({env:e}){const t=e.SCRUTINIZER_PR_NUMBER,r=Boolean(t);return{name:"Scrutinizer",service:"scrutinizer",commit:e.SCRUTINIZER_SHA1,build:e.SCRUTINIZER_INSPECTION_UUID,branch:e.SCRUTINIZER_BRANCH,pr:t,isPr:r,prBranch:e.SCRUTINIZER_PR_SOURCE_BRANCH}}},Ft={detect:({env:e})=>Boolean(e.SEMAPHORE),configuration({env:e,cwd:t}){const r=e.SEMAPHORE_GIT_PR_NUMBER||e.PULL_REQUEST_NUMBER,n=Boolean(r);return{name:"Semaphore",service:"semaphore",commit:e.SEMAPHORE_GIT_SHA||bt({env:e,cwd:t}),tag:e.SEMAPHORE_GIT_TAG_NAME,build:e.SEMAPHORE_JOB_ID||e.SEMAPHORE_BUILD_NUMBER,branch:e.SEMAPHORE_GIT_BRANCH||(n?void 0:e.BRANCH_NAME),pr:r,isPr:n,prBranch:e.SEMAPHORE_GIT_PR_BRANCH||(n?e.BRANCH_NAME:void 0),slug:e.SEMAPHORE_GIT_REPO_SLUG||e.SEMAPHORE_REPO_SLUG,root:e.SEMAPHORE_GIT_DIR||e.SEMAPHORE_PROJECT_DIR}}},qt={detect:({env:e})=>Boolean(e.SHIPPABLE),configuration({env:e}){const t="true"===e.IS_PULL_REQUEST?e.PULL_REQUEST:void 0,r=Boolean(t);return{name:"Shippable",service:"shippable",commit:e.COMMIT,tag:e.GIT_TAG_NAME,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,branch:r?e.BASE_BRANCH:e.BRANCH,job:e.JOB_NUMBER,pr:t,isPr:r,prBranch:r?e.HEAD_BRANCH:void 0,slug:e.SHIPPABLE_REPO_SLUG,root:e.SHIPPABLE_BUILD_DIR}}},Ht={};function Zt(){if(kt)return Ht;kt=1,Object.defineProperty(Ht,"__esModule",{value:!0}),Ht.of=Ht.PropertiesFile=void 0;var e,t=(e=M.default)&&e.__esModule?e:{default:e};class r{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),r=Math.min(...t),n=e.substring(0,r).trim(),s=e.substring(r+1).trim();if(this.objs.hasOwnProperty(n))if(Array.isArray(this.objs[n]))this.objs[n].push(s);else{let e=this.objs[n];this.objs[n]=[e,s]}else{const e=s.replace(/"/g,'\\"').replace(/\\:/g,":").replace(/\\=/g,"=");this.objs[n]=unescape(JSON.parse('"'+e+'"'))}}}addFile(e){let r=t.default.readFileSync(e,"utf-8").split(/\r?\n/),n=this;for(let e=0;e<r.length;e++){let t=r[e];for(;"\\"===t.substring(t.length-1);)t=t.slice(0,-1),t+=r[e+1].trim(),e++;n.makeKeys(t)}}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 r=0;r<this.objs[e].length;r++)t[r]=this.interpolate(this.objs[e][r]);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 r=this.objs[e].length;return this.interpolate(this.objs[e][r-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 r=this.getLast(e);return r?parseInt(r,10):t}getFloat(e,t){let r=this.getLast(e);return r?parseFloat(r):t}getBoolean(e,t){let r=this.getLast(e);return r?!/^(false|0)$/i.test(n=r)&&!!n:t||!1;var n}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 r in this.objs)-1!==r.search(e)&&t.push(r);return t}reset(){this.objs={}}}return Ht.PropertiesFile=r,Ht.of=function(...e){let t=new r;return t.of.apply(t,e),t},Ht}var Vt=ye(Zt()),Gt={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},Wt=e=>{try{return Vt.of(e)}catch{return}},Kt=({env:e,cwd:t})=>{const r=e.TEAMCITY_BUILD_PROPERTIES_FILE?Wt(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,n=r?r.get("teamcity.configuration.properties.file"):void 0,s=n?Wt(n):n;return Object.fromEntries(Object.keys(Gt).map(n=>[n,(r?r.get(Gt[n]):void 0)||(s?s.get(Gt[n]):void 0)||("branch"===n?wt({env:e,cwd:t}):void 0)]))},Yt={appveyor:le,azurePipelines:de,bamboo:pe,bitbucket:fe,bitrise:he,buddy:me,buildkite:Tt,circleci:It,cirrus:Pt,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:Ct,codefresh:Rt,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:At,github:Nt,gitlab:jt,jenkins:Dt,netlify:Ut,puppet:Lt,sail:Mt,screwdriver:zt,scrutinizer:Bt,semaphore:Ft,shippable:qt,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,...Kt({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,r=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:r,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",r="vercel";return e.VERCEL?{name:t,service:r,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:r,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,r=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:ue(e.JB_SPACE_GIT_BRANCH),slug:t&&r?`${t.toLowerCase()}/${r}`:void 0}}}},Jt=Object.create,{getPrototypeOf:Qt,defineProperty:Xt,getOwnPropertyNames:er}=Object,tr=Object.prototype.hasOwnProperty,rr=(e,t,r)=>{r=null!=e?Jt(Qt(e)):{};let n=Xt(r,"default",{value:e,enumerable:!0});for(let t of er(e))tr.call(n,t)||Xt(n,t,{get:()=>e[t],enumerable:!0});return n},nr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),sr=(e,t)=>{for(var r in t)Xt(e,r,{get:t[r],enumerable:!0,configurable:!0,set:e=>t[r]=()=>e})},ar=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(e){super(),this._items="string"==typeof e?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return""===e||'""'===e}get str(){var e;return null!==(e=this._str)&&void 0!==e?e:this._str=this._items.reduce((e,t)=>`${e}${t}`,"")}get names(){var e;return null!==(e=this._names)&&void 0!==e?e:this._names=this._items.reduce((e,t)=>(t instanceof r&&(e[t.str]=(e[t.str]||0)+1),e),{})}}function s(e,...t){let r=[e[0]],s=0;for(;s<t.length;)o(r,t[s]),r.push(e[++s]);return new n(r)}e._Code=n,e.nil=new n(""),e._=s;var a=new n("+");function i(e,...t){let r=[c(e[0])],s=0;for(;s<t.length;)r.push(a),o(r,t[s]),r.push(a,c(e[++s]));return function(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let r=l(e[t-1],e[t+1]);if(void 0!==r){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}(r),new n(r)}function o(e,t){t instanceof n?e.push(...t._items):t instanceof r?e.push(t):e.push(function(e){return"number"==typeof e||"boolean"==typeof e||null===e?e:c(Array.isArray(e)?e.join(","):e)}(t))}function l(e,t){if('""'===t)return e;if('""'===e)return t;if("string"==typeof e){if(t instanceof r||'"'!==e[e.length-1])return;return"string"!=typeof t?`${e.slice(0,-1)}${t}"`:'"'===t[0]?e.slice(0,-1)+t.slice(1):void 0}return"string"!=typeof t||'"'!==t[0]||e instanceof r?void 0:`"${e}${t.slice(1)}`}function c(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.str=i,e.addCodeArg=o,e.strConcat=function(e,t){return t.emptyStr()?e:e.emptyStr()?t:i`${e}${t}`},e.stringify=function(e){return new n(c(e))},e.safeStringify=c,e.getProperty=function(t){return"string"==typeof t&&e.IDENTIFIER.test(t)?new n(`.${t}`):s`[${t}]`},e.getEsmExportName=function(t){if("string"==typeof t&&e.IDENTIFIER.test(t))return new n(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)},e.regexpCode=function(e){return new n(e.toString())}}),ir=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;var t,r,n=ar();class s extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}}(r=t||(e.UsedValueState=t={}))[r.Started=0]="Started",r[r.Completed=1]="Completed",e.varKinds={const:new n.Name("const"),let:new n.Name("let"),var:new n.Name("var")};class a{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof n.Name?e:this.name(e)}name(e){return new n.Name(this._newName(e))}_newName(e){return`${e}${(this._names[e]||this._nameGroup(e)).index++}`}_nameGroup(e){var t,r;if((null===(r=null===(t=this._parent)||void 0===t?void 0:t._prefixes)||void 0===r?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}e.Scope=a;class i extends n.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=n._`.${new n.Name(t)}[${r}]`}}e.ValueScopeName=i;var o=n._`\n`;e.ValueScope=class extends a{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:n.nil}}get(){return this._scope}name(e){return new i(e,this._newName(e))}value(e,t){var r;if(void 0===t.ref)throw Error("CodeGen: ref must be passed in value");let n=this.toName(e),{prefix:s}=n,a=null!==(r=t.key)&&void 0!==r?r:t.ref,i=this._values[s];if(i){let e=i.get(a);if(e)return e}else i=this._values[s]=new Map;i.set(a,n);let o=this._scope[s]||(this._scope[s]=[]),l=o.length;return o[l]=t.ref,n.setValue(t,{property:s,itemIndex:l}),n}getValue(e,t){let r=this._values[e];if(r)return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,t=>{if(void 0===t.scopePath)throw Error(`CodeGen: name "${t}" has no value`);return n._`${e}${t.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,e=>{if(void 0===e.value)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,r)}_reduceValues(r,a,i={},o){let l=n.nil;for(let c in r){let u=r[c];if(!u)continue;let d=i[c]=i[c]||new Map;u.forEach(r=>{if(d.has(r))return;d.set(r,t.Started);let i=a(r);if(i){let t=this.opts.es5?e.varKinds.var:e.varKinds.const;l=n._`${l}${t} ${r} = ${i};${this.opts._n}`}else{if(!(i=null==o?void 0:o(r)))throw new s(r);l=n._`${l}${i}${this.opts._n}`}d.set(r,t.Completed)})}return l}}}),or=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;var t=ar(),r=ir(),n=ar();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var s=ir();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class a{optimizeNodes(){return this}optimizeNames(e,t){return this}}class i extends a{constructor(e,t,r){super(),this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){let n=e?r.varKinds.var:this.varKind,s=void 0===this.rhs?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=P(this.rhs,e,t)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class o extends a{constructor(e,t,r){super(),this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof t.Name)||e[this.lhs.str]||this.sideEffects)return this.rhs=P(this.rhs,e,r),this}get names(){return $(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}}class l extends o{constructor(e,t,r,n){super(e,r,n),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class c extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class u extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class d extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class p extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=P(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let r=e[t].optimizeNodes();Array.isArray(r)?e.splice(t,1,...r):r?e[t]=r:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:r}=this,n=r.length;for(;n--;){let s=r[n];s.optimizeNames(e,t)||(C(e,s.names),r.splice(n,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>I(e,t.names),{})}}class h extends f{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class m extends f{}class g extends h{}g.kind="else";class y extends h{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(!0===e)return this.nodes;let t=this.else;if(t){let e=t.optimizeNodes();t=this.else=Array.isArray(e)?new g(e):e}return t?!1===e?t instanceof y?t:t.nodes:this.nodes.length?this:new y(R(e),t instanceof y?[t]:t.nodes):!1!==e&&this.nodes.length?this:void 0}optimizeNames(e,t){var r;if(this.else=null===(r=this.else)||void 0===r?void 0:r.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=P(this.condition,e,t),this}get names(){let e=super.names;return $(e,this.condition),this.else&&I(e,this.else.names),e}}y.kind="if";class v extends h{}v.kind="for";class _ extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=P(this.iteration,e,t),this}get names(){return I(super.names,this.iteration.names)}}class b extends v{constructor(e,t,r,n){super(),this.varKind=e,this.name=t,this.from=r,this.to=n}render(e){let t=e.es5?r.varKinds.var:this.varKind,{name:n,from:s,to:a}=this;return`for(${t} ${n}=${s}; ${n}<${a}; ${n}++)`+super.render(e)}get names(){let e=$(super.names,this.from);return $(e,this.to)}}class w extends v{constructor(e,t,r,n){super(),this.loop=e,this.varKind=t,this.name=r,this.iterable=n}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=P(this.iterable,e,t),this}get names(){return I(super.names,this.iterable.names)}}class E extends h{constructor(e,t,r){super(),this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}E.kind="func";class x extends f{render(e){return"return "+super.render(e)}}x.kind="return";class S extends h{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),null===(e=this.catch)||void 0===e||e.optimizeNodes(),null===(t=this.finally)||void 0===t||t.optimizeNodes(),this}optimizeNames(e,t){var r,n;return super.optimizeNames(e,t),null===(r=this.catch)||void 0===r||r.optimizeNames(e,t),null===(n=this.finally)||void 0===n||n.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&I(e,this.catch.names),this.finally&&I(e,this.finally.names),e}}class k extends h{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}k.kind="catch";class T extends h{render(e){return"finally"+super.render(e)}}function I(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function $(e,r){return r instanceof t._CodeOrName?I(e,r.names):e}function P(e,r,n){return e instanceof t.Name?a(e):(s=e)instanceof t._Code&&s._items.some(e=>e instanceof t.Name&&1===r[e.str]&&void 0!==n[e.str])?new t._Code(e._items.reduce((e,r)=>(r instanceof t.Name&&(r=a(r)),r instanceof t._Code?e.push(...r._items):e.push(r),e),[])):e;var s;function a(e){let t=n[e.str];return void 0===t||1!==r[e.str]?e:(delete r[e.str],t)}}function C(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function R(e){return"boolean"==typeof e||"number"==typeof e||null===e?!e:t._`!${j(e)}`}T.kind="finally",e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?"\n":""},this._extScope=e,this._scope=new r.Scope({parent:e}),this._nodes=[new m]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,n){let s=this._scope.toName(t);return void 0!==r&&n&&(this._constants[s.str]=r),this._leafNode(new i(e,s,r)),s}const(e,t,n){return this._def(r.varKinds.const,e,t,n)}let(e,t,n){return this._def(r.varKinds.let,e,t,n)}var(e,t,n){return this._def(r.varKinds.var,e,t,n)}assign(e,t,r){return this._leafNode(new o(e,t,r))}add(t,r){return this._leafNode(new l(t,e.operators.ADD,r))}code(e){return"function"==typeof e?e():e!==t.nil&&this._leafNode(new p(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,t.addCodeArg)(r,s));return r.push("}"),new t._Code(r)}if(e,t,r){if(this._blockNode(new y(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new y(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(y,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new _(e),t)}forRange(e,t,n,s,a=(this.opts.es5?r.varKinds.var:r.varKinds.let)){let i=this._scope.toName(e);return this._for(new b(a,i,t,n),()=>s(i))}forOf(e,n,s,a=r.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let e=n instanceof t.Name?n:this.var("_arr",n);return this.forRange("_i",0,t._`${e}.length`,r=>{this.var(i,t._`${e}[${r}]`),s(i)})}return this._for(new w("of",a,i,n),()=>s(i))}forIn(e,n,s,a=(this.opts.es5?r.varKinds.var:r.varKinds.const)){if(this.opts.ownProperties)return this.forOf(e,t._`Object.keys(${n})`,s);let i=this._scope.toName(e);return this._for(new w("in",a,i,n),()=>s(i))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new c(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new x;if(this._blockNode(t),this.code(e),1!==t.nodes.length)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(x)}try(e,t,r){if(!t&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let n=new S;if(this._blockNode(n),this.code(e),t){let e=this.name("e");this._currNode=n.catch=new k(e),t(e)}return r&&(this._currNode=n.finally=new T,this.code(r)),this._endBlockNode(k,T)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(void 0===t)throw Error("CodeGen: not in self-balancing block");let r=this._nodes.length-t;if(r<0||void 0!==e&&r!==e)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,r=t.nil,n,s){return this._blockNode(new E(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(E)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof y))throw Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}},e.not=R;var A=N(e.operators.AND);e.and=function(...e){return e.reduce(A)};var O=N(e.operators.OR);function N(e){return(r,n)=>r===t.nil?n:n===t.nil?r:t._`${j(r)} ${e} ${j(n)}`}function j(e){return e instanceof t.Name?e:t._`(${e})`}e.or=function(...e){return e.reduce(O)}}),lr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;var t=or(),r=ar();function n(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema)return;if("boolean"==typeof t)return;let s=n.RULES.keywords;for(let r in t)s[r]||f(e,`unknown keyword: "${r}"`)}function s(e,t){if("boolean"==typeof e)return!e;for(let r in e)if(t[r])return!0;return!1}function a(e){return"number"==typeof e?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}function i(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function o({mergeNames:e,mergeToName:r,mergeValues:n,resultToName:s}){return(a,i,o,l)=>{let c=void 0===o?i:o instanceof t.Name?(i instanceof t.Name?e(a,i,o):r(a,i,o),o):i instanceof t.Name?(r(a,o,i),i):n(i,o);return l!==t.Name||c instanceof t.Name?c:s(a,c)}}function l(e,r){if(!0===r)return e.var("props",!0);let n=e.var("props",t._`{}`);return void 0!==r&&c(e,n,r),n}function c(e,r,n){Object.keys(n).forEach(n=>e.assign(t._`${r}${(0,t.getProperty)(n)}`,!0))}e.toHash=function(e){let t={};for(let r of e)t[r]=!0;return t},e.alwaysValidSchema=function(e,t){return"boolean"==typeof t?t:0===Object.keys(t).length||(n(e,t),!s(t,e.self.RULES.all))},e.checkUnknownRules=n,e.schemaHasRules=s,e.schemaHasRulesButRef=function(e,t){if("boolean"==typeof e)return!e;for(let r in e)if("$ref"!==r&&t.all[r])return!0;return!1},e.schemaRefOrVal=function({topSchemaRef:e,schemaPath:r},n,s,a){if(!a){if("number"==typeof n||"boolean"==typeof n)return n;if("string"==typeof n)return t._`${n}`}return t._`${e}${r}${(0,t.getProperty)(s)}`},e.unescapeFragment=function(e){return i(decodeURIComponent(e))},e.escapeFragment=function(e){return encodeURIComponent(a(e))},e.escapeJsonPointer=a,e.unescapeJsonPointer=i,e.eachItem=function(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)},e.mergeEvaluated={props:o({mergeNames:(e,r,n)=>e.if(t._`${n} !== true && ${r} !== undefined`,()=>{e.if(t._`${r} === true`,()=>e.assign(n,!0),()=>e.assign(n,t._`${n} || {}`).code(t._`Object.assign(${n}, ${r})`))}),mergeToName:(e,r,n)=>e.if(t._`${n} !== true`,()=>{!0===r?e.assign(n,!0):(e.assign(n,t._`${n} || {}`),c(e,n,r))}),mergeValues:(e,t)=>!0===e||{...e,...t},resultToName:l}),items:o({mergeNames:(e,r,n)=>e.if(t._`${n} !== true && ${r} !== undefined`,()=>e.assign(n,t._`${r} === true ? true : ${n} > ${r} ? ${n} : ${r}`)),mergeToName:(e,r,n)=>e.if(t._`${n} !== true`,()=>e.assign(n,!0===r||t._`${n} > ${r} ? ${n} : ${r}`)),mergeValues:(e,t)=>!0===e||Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})},e.evaluatedPropsToName=l,e.setEvaluated=c;var u,d,p={};function f(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,!0===r)throw Error(t);e.self.logger.warn(t)}}e.useFunc=function(e,t){return e.scopeValue("func",{ref:t,code:p[t.code]||(p[t.code]=new r._Code(t.code))})},(d=u||(e.Type=u={}))[d.Num=0]="Num",d[d.Str=1]="Str",e.getErrorPath=function(e,r,n){if(e instanceof t.Name){let s=r===u.Num;return n?s?t._`"[" + ${e} + "]"`:t._`"['" + ${e} + "']"`:s?t._`"/" + ${e}`:t._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,t.getProperty)(e).toString():"/"+a(e)},e.checkStrictMode=f}),cr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=or(),r={data:new t.Name("data"),valCxt:new t.Name("valCxt"),instancePath:new t.Name("instancePath"),parentData:new t.Name("parentData"),parentDataProperty:new t.Name("parentDataProperty"),rootData:new t.Name("rootData"),dynamicAnchors:new t.Name("dynamicAnchors"),vErrors:new t.Name("vErrors"),errors:new t.Name("errors"),this:new t.Name("this"),self:new t.Name("self"),scope:new t.Name("scope"),json:new t.Name("json"),jsonPos:new t.Name("jsonPos"),jsonLen:new t.Name("jsonLen"),jsonPart:new t.Name("jsonPart")};e.default=r}),ur=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;var t=or(),r=lr(),n=cr();function s(e,r){let s=e.const("err",r);e.if(t._`${n.default.vErrors} === null`,()=>e.assign(n.default.vErrors,t._`[${s}]`),t._`${n.default.vErrors}.push(${s})`),e.code(t._`${n.default.errors}++`)}function a(e,r){let{gen:n,validateName:s,schemaEnv:a}=e;a.$async?n.throw(t._`new ${e.ValidationError}(${r})`):(n.assign(t._`${s}.errors`,r),n.return(!1))}e.keywordError={message:({keyword:e})=>t.str`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:r})=>r?t.str`"${e}" keyword must be ${r} ($data)`:t.str`"${e}" keyword is invalid ($data)`},e.reportError=function(r,n=e.keywordError,i,l){let{it:c}=r,{gen:u,compositeRule:d,allErrors:p}=c,f=o(r,n,i);(null!=l?l:d||p)?s(u,f):a(c,t._`[${f}]`)},e.reportExtraError=function(t,r=e.keywordError,i){let{it:l}=t,{gen:c,compositeRule:u,allErrors:d}=l;s(c,o(t,r,i)),u||d||a(l,n.default.vErrors)},e.resetErrorsCount=function(e,r){e.assign(n.default.errors,r),e.if(t._`${n.default.vErrors} !== null`,()=>e.if(r,()=>e.assign(t._`${n.default.vErrors}.length`,r),()=>e.assign(n.default.vErrors,null)))},e.extendErrors=function({gen:e,keyword:r,schemaValue:s,data:a,errsCount:i,it:o}){if(void 0===i)throw Error("ajv implementation error");let l=e.name("err");e.forRange("i",i,n.default.errors,i=>{e.const(l,t._`${n.default.vErrors}[${i}]`),e.if(t._`${l}.instancePath === undefined`,()=>e.assign(t._`${l}.instancePath`,(0,t.strConcat)(n.default.instancePath,o.errorPath))),e.assign(t._`${l}.schemaPath`,t.str`${o.errSchemaPath}/${r}`),o.opts.verbose&&(e.assign(t._`${l}.schema`,s),e.assign(t._`${l}.data`,a))})};var i={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function o(e,r,s){let{createErrors:a}=e.it;return!1===a?t._`{}`:function(e,r,s={}){let{gen:a,it:o}=e,u=[l(o,s),c(e,s)];return function(e,{params:r,message:s},a){let{keyword:o,data:l,schemaValue:c,it:u}=e,{opts:d,propertyName:p,topSchemaRef:f,schemaPath:h}=u;a.push([i.keyword,o],[i.params,"function"==typeof r?r(e):r||t._`{}`]),d.messages&&a.push([i.message,"function"==typeof s?s(e):s]),d.verbose&&a.push([i.schema,c],[i.parentSchema,t._`${f}${h}`],[n.default.data,l]),p&&a.push([i.propertyName,p])}(e,r,u),a.object(...u)}(e,r,s)}function l({errorPath:e},{instancePath:s}){let a=s?t.str`${e}${(0,r.getErrorPath)(s,r.Type.Str)}`:e;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,a)]}function c({keyword:e,it:{errSchemaPath:n}},{schemaPath:s,parentSchema:a}){let o=a?n:t.str`${n}/${e}`;return s&&(o=t.str`${o}${(0,r.getErrorPath)(s,r.Type.Str)}`),[i.schemaPath,o]}}),dr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;var t=ur(),r=or(),n=cr(),s={message:"boolean schema is false"};function a(e,r){let{gen:n,data:a}=e,i={gen:n,keyword:"false schema",data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(i,s,void 0,r)}e.topBoolOrEmptySchema=function(e){let{gen:t,schema:s,validateName:i}=e;!1===s?a(e,!1):"object"==typeof s&&!0===s.$async?t.return(n.default.data):(t.assign(r._`${i}.errors`,null),t.return(!0))},e.boolOrEmptySchema=function(e,t){let{gen:r,schema:n}=e;!1===n?(r.var(t,!1),a(e)):r.var(t,!0)}}),pr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;var t=new Set(["string","number","integer","boolean","null","object","array"]);e.isJSONType=function(e){return"string"==typeof e&&t.has(e)},e.getRules=function(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}}),fr=nr(e=>{function t(e,t){return t.rules.some(t=>r(e,t))}function r(e,t){var r;return void 0!==e[t.keyword]||(null===(r=t.definition.implements)||void 0===r?void 0:r.some(t=>void 0!==e[t]))}Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0,e.schemaHasRulesForType=function({schema:e,self:r},n){let s=r.RULES.types[n];return s&&!0!==s&&t(e,s)},e.shouldUseGroup=t,e.shouldUseRule=r}),hr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;var t,r,n=pr(),s=fr(),a=ur(),i=or(),o=lr();function l(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(n.isJSONType))return t;throw Error("type must be JSONType or JSONType[]: "+t.join(","))}(r=t||(e.DataType=t={}))[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong",e.getSchemaTypes=function(e){let t=l(e.type);if(t.includes("null")){if(!1===e.nullable)throw Error("type: null contradicts nullable: false")}else{if(!t.length&&void 0!==e.nullable)throw Error('"nullable" cannot be used without "type"');!0===e.nullable&&t.push("null")}return t},e.getJSONTypes=l,e.coerceAndCheckDataType=function(e,r){let{gen:n,data:a,opts:o}=e,l=function(e,t){return t?e.filter(e=>c.has(e)||"array"===t&&"array"===e):[]}(r,o.coerceTypes),u=r.length>0&&!(0===l.length&&1===r.length&&(0,s.schemaHasRulesForType)(e,r[0]));if(u){let s=d(r,a,o.strictNumbers,t.Wrong);n.if(s,()=>{l.length?function(e,t,r){let{gen:n,data:s,opts:a}=e,o=n.let("dataType",i._`typeof ${s}`),l=n.let("coerced",i._`undefined`);"array"===a.coerceTypes&&n.if(i._`${o} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,i._`${s}[0]`).assign(o,i._`typeof ${s}`).if(d(t,s,a.strictNumbers),()=>n.assign(l,s))),n.if(i._`${l} !== undefined`);for(let e of r)(c.has(e)||"array"===e&&"array"===a.coerceTypes)&&u(e);function u(e){switch(e){case"string":return void n.elseIf(i._`${o} == "number" || ${o} == "boolean"`).assign(l,i._`"" + ${s}`).elseIf(i._`${s} === null`).assign(l,i._`""`);case"number":return void n.elseIf(i._`${o} == "boolean" || ${s} === null
|
|
3
|
+
|| (${o} == "string" && ${s} && ${s} == +${s})`).assign(l,i._`+${s}`);case"integer":return void n.elseIf(i._`${o} === "boolean" || ${s} === null
|
|
4
|
+
|| (${o} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(l,i._`+${s}`);case"boolean":return void n.elseIf(i._`${s} === "false" || ${s} === 0 || ${s} === null`).assign(l,!1).elseIf(i._`${s} === "true" || ${s} === 1`).assign(l,!0);case"null":return n.elseIf(i._`${s} === "" || ${s} === 0 || ${s} === false`),void n.assign(l,null);case"array":n.elseIf(i._`${o} === "string" || ${o} === "number"
|
|
5
|
+
|| ${o} === "boolean" || ${s} === null`).assign(l,i._`[${s}]`)}}n.else(),f(e),n.endIf(),n.if(i._`${l} !== undefined`,()=>{n.assign(s,l),function({gen:e,parentData:t,parentDataProperty:r},n){e.if(i._`${t} !== undefined`,()=>e.assign(i._`${t}[${r}]`,n))}(e,l)})}(e,r,l):f(e)})}return u};var c=new Set(["string","number","integer","boolean","null"]);function u(e,r,n,s=t.Correct){let a,o=s===t.Correct?i.operators.EQ:i.operators.NEQ;switch(e){case"null":return i._`${r} ${o} null`;case"array":a=i._`Array.isArray(${r})`;break;case"object":a=i._`${r} && typeof ${r} == "object" && !Array.isArray(${r})`;break;case"integer":a=l(i._`!(${r} % 1) && !isNaN(${r})`);break;case"number":a=l();break;default:return i._`typeof ${r} ${o} ${e}`}return s===t.Correct?a:(0,i.not)(a);function l(e=i.nil){return(0,i.and)(i._`typeof ${r} == "number"`,e,n?i._`isFinite(${r})`:i.nil)}}function d(e,t,r,n){if(1===e.length)return u(e[0],t,r,n);let s,a=(0,o.toHash)(e);if(a.array&&a.object){let e=i._`typeof ${t} != "object"`;s=a.null?e:i._`!${t} || ${e}`,delete a.null,delete a.array,delete a.object}else s=i.nil;a.number&&delete a.integer;for(let e in a)s=(0,i.and)(s,u(e,t,r,n));return s}e.checkDataType=u,e.checkDataTypes=d;var p={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?i._`{type: ${e}}`:i._`{type: ${t}}`};function f(e){let t=function(e){let{gen:t,data:r,schema:n}=e,s=(0,o.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:e}}(e);(0,a.reportError)(t,p)}e.reportTypeError=f}),mr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;var t=or(),r=lr();function n(e,n,s){let{gen:a,compositeRule:i,data:o,opts:l}=e;if(void 0===s)return;let c=t._`${o}${(0,t.getProperty)(n)}`;if(i)return void(0,r.checkStrictMode)(e,`default is ignored for: ${c}`);let u=t._`${c} === undefined`;"empty"===l.useDefaults&&(u=t._`${u} || ${c} === null || ${c} === ""`),a.if(u,t._`${c} = ${(0,t.stringify)(s)}`)}e.assignDefaults=function(e,t){let{properties:r,items:s}=e.schema;if("object"===t&&r)for(let t in r)n(e,t,r[t].default);else"array"===t&&Array.isArray(s)&&s.forEach((t,r)=>n(e,r,t.default))}}),gr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;var t=or(),r=lr(),n=cr(),s=lr();function a(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:t._`Object.prototype.hasOwnProperty`})}function i(e,r,n){return t._`${a(e)}.call(${r}, ${n})`}function o(e,r,n,s){let a=t._`${r}${(0,t.getProperty)(n)} === undefined`;return s?(0,t.or)(a,(0,t.not)(i(e,r,n))):a}function l(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}e.checkReportMissingProp=function(e,r){let{gen:n,data:s,it:a}=e;n.if(o(n,s,r,a.opts.ownProperties),()=>{e.setParams({missingProperty:t._`${r}`},!0),e.error()})},e.checkMissingProp=function({gen:e,data:r,it:{opts:n}},s,a){return(0,t.or)(...s.map(s=>(0,t.and)(o(e,r,s,n.ownProperties),t._`${a} = ${s}`)))},e.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},e.hasPropFunc=a,e.isOwnProperty=i,e.propertyInData=function(e,r,n,s){let a=t._`${r}${(0,t.getProperty)(n)} !== undefined`;return s?t._`${a} && ${i(e,r,n)}`:a},e.noPropertyInData=o,e.allSchemaProperties=l,e.schemaProperties=function(e,t){return l(t).filter(n=>!(0,r.alwaysValidSchema)(e,t[n]))},e.callValidateCode=function({schemaCode:e,data:r,it:{gen:s,topSchemaRef:a,schemaPath:i,errorPath:o},it:l},c,u,d){let p=d?t._`${e}, ${r}, ${a}${i}`:r,f=[[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,o)],[n.default.parentData,l.parentData],[n.default.parentDataProperty,l.parentDataProperty],[n.default.rootData,n.default.rootData]];l.opts.dynamicRef&&f.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);let h=t._`${p}, ${s.object(...f)}`;return u!==t.nil?t._`${c}.call(${u}, ${h})`:t._`${c}(${h})`};var c=t._`new RegExp`;e.usePattern=function({gen:e,it:{opts:r}},n){let a=r.unicodeRegExp?"u":"",{regExp:i}=r.code,o=i(n,a);return e.scopeValue("pattern",{key:o.toString(),ref:o,code:t._`${"new RegExp"===i.code?c:(0,s.useFunc)(e,i)}(${n}, ${a})`})},e.validateArray=function(e){let{gen:n,data:s,keyword:a,it:i}=e,o=n.name("valid");if(i.allErrors){let e=n.let("valid",!0);return l(()=>n.assign(e,!1)),e}return n.var(o,!0),l(()=>n.break()),o;function l(i){let l=n.const("len",t._`${s}.length`);n.forRange("i",0,l,s=>{e.subschema({keyword:a,dataProp:s,dataPropType:r.Type.Num},o),n.if((0,t.not)(o),i)})}},e.validateUnion=function(e){let{gen:n,schema:s,keyword:a,it:i}=e;if(!Array.isArray(s))throw Error("ajv implementation error");if(s.some(e=>(0,r.alwaysValidSchema)(i,e))&&!i.opts.unevaluated)return;let o=n.let("valid",!1),l=n.name("_valid");n.block(()=>s.forEach((r,s)=>{let i=e.subschema({keyword:a,schemaProp:s,compositeRule:!0},l);n.assign(o,t._`${o} || ${l}`),e.mergeValidEvaluated(i,l)||n.if((0,t.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}}),yr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;var t=or(),r=cr(),n=gr(),s=ur();function a(e){let{gen:r,data:n,it:s}=e;r.if(s.parentData,()=>r.assign(n,t._`${s.parentData}[${s.parentDataProperty}]`))}function i(e,r,n){if(void 0===n)throw Error(`keyword "${r}" failed to compile`);return e.scopeValue("keyword","function"==typeof n?{ref:n}:{ref:n,code:(0,t.stringify)(n)})}e.macroKeywordCode=function(e,r){let{gen:n,keyword:s,schema:a,parentSchema:o,it:l}=e,c=r.macro.call(l.self,a,o,l),u=i(n,s,c);!1!==l.opts.validateSchema&&l.self.validateSchema(c,!0);let d=n.name("valid");e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${l.errSchemaPath}/${s}`,topSchemaRef:u,compositeRule:!0},d),e.pass(d,()=>e.error(!0))},e.funcKeywordCode=function(e,o){var l;let{gen:c,keyword:u,schema:d,parentSchema:p,$data:f,it:h}=e;!function({schemaEnv:e},t){if(t.async&&!e.$async)throw Error("async keyword in sync schema")}(h,o);let m=!f&&o.compile?o.compile.call(h.self,d,p,h):o.validate,g=i(c,u,m),y=c.let("valid");function v(s=(o.async?t._`await `:t.nil)){let a=h.opts.passContext?r.default.this:r.default.self,i=!("compile"in o&&!f||!1===o.schema);c.assign(y,t._`${s}${(0,n.callValidateCode)(e,g,a,i)}`,o.modifying)}function _(e){var r;c.if((0,t.not)(null!==(r=o.valid)&&void 0!==r?r:y),e)}e.block$data(y,function(){if(!1===o.errors)v(),o.modifying&&a(e),_(()=>e.error());else{let n=o.async?function(){let e=c.let("ruleErrs",null);return c.try(()=>v(t._`await `),r=>c.assign(y,!1).if(t._`${r} instanceof ${h.ValidationError}`,()=>c.assign(e,t._`${r}.errors`),()=>c.throw(r))),e}():function(){let e=t._`${g}.errors`;return c.assign(e,null),v(t.nil),e}();o.modifying&&a(e),_(()=>function(e,n){let{gen:a}=e;a.if(t._`Array.isArray(${n})`,()=>{a.assign(r.default.vErrors,t._`${r.default.vErrors} === null ? ${n} : ${r.default.vErrors}.concat(${n})`).assign(r.default.errors,t._`${r.default.vErrors}.length`),(0,s.extendErrors)(e)},()=>e.error())}(e,n))}}),e.ok(null!==(l=o.valid)&&void 0!==l?l:y)},e.validSchemaType=function(e,t,r=!1){return!t.length||t.some(t=>"array"===t?Array.isArray(e):"object"===t?e&&"object"==typeof e&&!Array.isArray(e):typeof e==t||r&&typeof e>"u")},e.validateKeywordUsage=function({schema:e,opts:t,self:r,errSchemaPath:n},s,a){if(Array.isArray(s.keyword)?!s.keyword.includes(a):s.keyword!==a)throw Error("ajv implementation error");let i=s.dependencies;if(null==i?void 0:i.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if("log"!==t.validateSchema)throw Error(e);r.logger.error(e)}}}),vr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;var t=or(),r=lr();e.getSubschema=function(e,{keyword:n,schemaProp:s,schema:a,schemaPath:i,errSchemaPath:o,topSchemaRef:l}){if(void 0!==n&&void 0!==a)throw Error('both "keyword" and "schema" passed, only one allowed');if(void 0!==n){let a=e.schema[n];return void 0===s?{schema:a,schemaPath:t._`${e.schemaPath}${(0,t.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${n}`}:{schema:a[s],schemaPath:t._`${e.schemaPath}${(0,t.getProperty)(n)}${(0,t.getProperty)(s)}`,errSchemaPath:`${e.errSchemaPath}/${n}/${(0,r.escapeFragment)(s)}`}}if(void 0!==a){if(void 0===i||void 0===o||void 0===l)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:a,schemaPath:i,topSchemaRef:l,errSchemaPath:o}}throw Error('either "keyword" or "schema" must be passed')},e.extendSubschemaData=function(e,n,{dataProp:s,dataPropType:a,data:i,dataTypes:o,propertyName:l}){if(void 0!==i&&void 0!==s)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:c}=n;if(void 0!==s){let{errorPath:i,dataPathArr:o,opts:l}=n;u(c.let("data",t._`${n.data}${(0,t.getProperty)(s)}`,!0)),e.errorPath=t.str`${i}${(0,r.getErrorPath)(s,a,l.jsPropertySyntax)}`,e.parentDataProperty=t._`${s}`,e.dataPathArr=[...o,e.parentDataProperty]}function u(t){e.data=t,e.dataLevel=n.dataLevel+1,e.dataTypes=[],n.definedProperties=new Set,e.parentData=n.data,e.dataNames=[...n.dataNames,t]}void 0!==i&&(u(i instanceof t.Name?i:c.let("data",i,!0)),void 0!==l&&(e.propertyName=l)),o&&(e.dataTypes=o)},e.extendSubschemaMode=function(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:a}){void 0!==n&&(e.compositeRule=n),void 0!==s&&(e.createErrors=s),void 0!==a&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=r}}),_r=nr((e,t)=>{t.exports=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,s,a;if(Array.isArray(t)){if((n=t.length)!=r.length)return!1;for(s=n;0!==s--;)if(!e(t[s],r[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((n=(a=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(s=n;0!==s--;)if(!Object.prototype.hasOwnProperty.call(r,a[s]))return!1;for(s=n;0!==s--;){var i=a[s];if(!e(t[i],r[i]))return!1}return!0}return t!=t&&r!=r}}),br=nr((e,t)=>{var r=t.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),n(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function n(e,t,a,i,o,l,c,u,d,p){if(i&&"object"==typeof i&&!Array.isArray(i)){for(var f in t(i,o,l,c,u,d,p),i){var h=i[f];if(Array.isArray(h)){if(f in r.arrayKeywords)for(var m=0;m<h.length;m++)n(e,t,a,h[m],o+"/"+f+"/"+m,l,o,f,i,m)}else if(f in r.propsKeywords){if(h&&"object"==typeof h)for(var g in h)n(e,t,a,h[g],o+"/"+f+"/"+s(g),l,o,f,i,g)}else(f in r.keywords||e.allKeys&&!(f in r.skipKeywords))&&n(e,t,a,h,o+"/"+f,l,o,f,i)}a(i,o,l,c,u,d,p)}}function s(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}r.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},r.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},r.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},r.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}}),wr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;var t=lr(),r=_r(),n=br(),s=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);e.inlineRef=function(e,t=!0){return"boolean"==typeof e||(!0===t?!i(e):!!t&&o(e)<=t)};var a=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function i(e){for(let t in e){if(a.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(i))return!0;if("object"==typeof r&&i(r))return!0}return!1}function o(e){let r=0;for(let n in e){if("$ref"===n)return 1/0;if(r++,!s.has(n)&&("object"==typeof e[n]&&(0,t.eachItem)(e[n],e=>r+=o(e)),r===1/0))return 1/0}return r}function l(e,t="",r){!1!==r&&(t=d(t));let n=e.parse(t);return c(e,n)}function c(e,t){return e.serialize(t).split("#")[0]+"#"}e.getFullPath=l,e._getFullPath=c;var u=/#\/?$/;function d(e){return e?e.replace(u,""):""}e.normalizeId=d,e.resolveUrl=function(e,t,r){return r=d(r),e.resolve(t,r)};var p=/^[a-z_][-a-z0-9._]*$/i;e.getSchemaRefs=function(e,t){if("boolean"==typeof e)return{};let{schemaId:s,uriResolver:a}=this.opts,i=d(e[s]||t),o={"":i},c=l(a,i,!1),u={},f=new Set;return n(e,{allKeys:!0},(e,t,r,n)=>{if(void 0===n)return;let a=c+t,i=o[n];function l(t){let r=this.opts.uriResolver.resolve;if(t=d(i?r(i,t):t),f.has(t))throw m(t);f.add(t);let n=this.refs[t];return"string"==typeof n&&(n=this.refs[n]),"object"==typeof n?h(e,n.schema,t):t!==d(a)&&("#"===t[0]?(h(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if("string"==typeof e){if(!p.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}"string"==typeof e[s]&&(i=l.call(this,e[s])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),o[t]=i}),u;function h(e,t,n){if(void 0!==t&&!r(e,t))throw m(n)}function m(e){return Error(`reference "${e}" resolves to more than one schema`)}}}),Er=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;var t=dr(),r=hr(),n=fr(),s=hr(),a=mr(),i=yr(),o=vr(),l=or(),c=cr(),u=wr(),d=lr(),p=ur();function f({gen:e,validateName:t,schema:r,schemaEnv:n,opts:s},a){s.code.es5?e.func(t,l._`${c.default.data}, ${c.default.valCxt}`,n.$async,()=>{e.code(l._`"use strict"; ${h(r,s)}`),function(e,t){e.if(c.default.valCxt,()=>{e.var(c.default.instancePath,l._`${c.default.valCxt}.${c.default.instancePath}`),e.var(c.default.parentData,l._`${c.default.valCxt}.${c.default.parentData}`),e.var(c.default.parentDataProperty,l._`${c.default.valCxt}.${c.default.parentDataProperty}`),e.var(c.default.rootData,l._`${c.default.valCxt}.${c.default.rootData}`),t.dynamicRef&&e.var(c.default.dynamicAnchors,l._`${c.default.valCxt}.${c.default.dynamicAnchors}`)},()=>{e.var(c.default.instancePath,l._`""`),e.var(c.default.parentData,l._`undefined`),e.var(c.default.parentDataProperty,l._`undefined`),e.var(c.default.rootData,c.default.data),t.dynamicRef&&e.var(c.default.dynamicAnchors,l._`{}`)})}(e,s),e.code(a)}):e.func(t,l._`${c.default.data}, ${function(e){return l._`{${c.default.instancePath}="", ${c.default.parentData}, ${c.default.parentDataProperty}, ${c.default.rootData}=${c.default.data}${e.dynamicRef?l._`, ${c.default.dynamicAnchors}={}`:l.nil}}={}`}(s)}`,n.$async,()=>e.code(h(r,s)).code(a))}function h(e,t){let r="object"==typeof e&&e[t.schemaId];return r&&(t.code.source||t.code.process)?l._`/*# sourceURL=${r} */`:l.nil}function m({schema:e,self:t}){if("boolean"==typeof e)return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function g(e){return"boolean"!=typeof e.schema}function y(e){(0,d.checkUnknownRules)(e),function(e){let{schema:t,errSchemaPath:r,opts:n,self:s}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}(e)}function v(e,t){if(e.opts.jtd)return b(e,[],!1,t);let n=(0,r.getSchemaTypes)(e.schema);b(e,n,!(0,r.coerceAndCheckDataType)(e,n),t)}function _({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:s}){let a=r.$comment;if(!0===s.$comment)e.code(l._`${c.default.self}.logger.log(${a})`);else if("function"==typeof s.$comment){let r=l.str`${n}/$comment`,s=e.scopeValue("root",{ref:t.root});e.code(l._`${c.default.self}.opts.$comment(${a}, ${r}, ${s}.schema)`)}}function b(e,t,r,a){let{gen:i,schema:o,data:u,allErrors:p,opts:f,self:h}=e,{RULES:m}=h;function g(d){(0,n.shouldUseGroup)(o,d)&&(d.type?(i.if((0,s.checkDataType)(d.type,u,f.strictNumbers)),w(e,d),1===t.length&&t[0]===d.type&&r&&(i.else(),(0,s.reportTypeError)(e)),i.endIf()):w(e,d),p||i.if(l._`${c.default.errors} === ${a||0}`))}!o.$ref||!f.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(o,m)?(f.jtd||function(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(function(e,t){t.length&&(e.dataTypes.length?(t.forEach(t=>{x(e.dataTypes,t)||S(e,`type "${t}" not allowed by context "${e.dataTypes.join(",")}"`)}),function(e,t){let r=[];for(let n of e.dataTypes)x(t,n)?r.push(n):t.includes("integer")&&"number"===n&&r.push("integer");e.dataTypes=r}(e,t)):e.dataTypes=t)}(e,t),e.opts.allowUnionTypes||function(e,t){t.length>1&&(2!==t.length||!t.includes("null"))&&S(e,"use allowUnionTypes to allow union type keyword")}(e,t),function(e,t){let r=e.self.RULES.all;for(let s in r){let a=r[s];if("object"==typeof a&&(0,n.shouldUseRule)(e.schema,a)){let{type:r}=a.definition;r.length&&!r.some(e=>E(t,e))&&S(e,`missing type "${r.join(",")}" for keyword "${s}"`)}}}(e,e.dataTypes))}(e,t),i.block(()=>{for(let e of m.rules)g(e);g(m.post)})):i.block(()=>T(e,"$ref",m.all.$ref.definition))}function w(e,t){let{gen:r,schema:s,opts:{useDefaults:i}}=e;i&&(0,a.assignDefaults)(e,t.type),r.block(()=>{for(let r of t.rules)(0,n.shouldUseRule)(s,r)&&T(e,r.keyword,r.definition,t.type)})}function E(e,t){return e.includes(t)||"number"===t&&e.includes("integer")}function x(e,t){return e.includes(t)||"integer"===t&&e.includes("number")}function S(e,t){t+=` at "${e.schemaEnv.baseId+e.errSchemaPath}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}e.validateFunctionCode=function(e){g(e)&&(y(e),m(e))?function(e){let{schema:t,opts:r,gen:n}=e;f(e,()=>{r.$comment&&t.$comment&&_(e),function(e){let{schema:t,opts:r}=e;void 0!==t.default&&r.useDefaults&&r.strictSchema&&(0,d.checkStrictMode)(e,"default is ignored in the schema root")}(e),n.let(c.default.vErrors,null),n.let(c.default.errors,0),r.unevaluated&&function(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",l._`${r}.evaluated`),t.if(l._`${e.evaluated}.dynamicProps`,()=>t.assign(l._`${e.evaluated}.props`,l._`undefined`)),t.if(l._`${e.evaluated}.dynamicItems`,()=>t.assign(l._`${e.evaluated}.items`,l._`undefined`))}(e),v(e),function(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:s,opts:a}=e;r.$async?t.if(l._`${c.default.errors} === 0`,()=>t.return(c.default.data),()=>t.throw(l._`new ${s}(${c.default.vErrors})`)):(t.assign(l._`${n}.errors`,c.default.vErrors),a.unevaluated&&function({gen:e,evaluated:t,props:r,items:n}){r instanceof l.Name&&e.assign(l._`${t}.props`,r),n instanceof l.Name&&e.assign(l._`${t}.items`,n)}(e),t.return(l._`${c.default.errors} === 0`))}(e)})}(e):f(e,()=>(0,t.topBoolOrEmptySchema)(e))};class k{constructor(e,t,r){if((0,i.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",P(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,i.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:!1!==t.errors)&&(this.errsCount=e.gen.const("_errs",c.default.errors))}result(e,t,r){this.failResult((0,l.not)(e),t,r)}failResult(e,t,r){this.gen.if(e),r?r():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,l.not)(e),void 0,t)}fail(e){if(void 0===e)return this.error(),void(this.allErrors||this.gen.if(!1));this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail(l._`${t} !== undefined && (${(0,l.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t)return this.setParams(t),this._error(e,r),void this.setParams({});this._error(e,r)}_error(e,t){(e?p.reportExtraError:p.reportError)(this,this.def.error,t)}$dataError(){(0,p.reportError)(this,this.def.$dataError||p.keyword$DataError)}reset(){if(void 0===this.errsCount)throw Error('add "trackErrors" to keyword definition');(0,p.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,r=l.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=l.nil,t=l.nil){if(!this.$data)return;let{gen:r,schemaCode:n,schemaType:s,def:a}=this;r.if((0,l.or)(l._`${n} === undefined`,t)),e!==l.nil&&r.assign(e,!0),(s.length||a.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==l.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:n,it:a}=this;return(0,l.or)(function(){if(r.length){if(!(t instanceof l.Name))throw Error("ajv implementation error");let e=Array.isArray(r)?r:[r];return l._`${(0,s.checkDataTypes)(e,t,a.opts.strictNumbers,s.DataType.Wrong)}`}return l.nil}(),function(){if(n.validateSchema){let r=e.scopeValue("validate$data",{ref:n.validateSchema});return l._`!${r}(${t})`}return l.nil}())}subschema(e,r){let n=(0,o.getSubschema)(this.it,e);(0,o.extendSubschemaData)(n,this.it,e),(0,o.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return function(e,r){g(e)&&(y(e),m(e))?function(e,t){let{schema:r,gen:n,opts:s}=e;s.$comment&&r.$comment&&_(e),function(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}(e),function(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error("async schema in sync schema")}(e);let a=n.const("_errs",c.default.errors);v(e,a),n.var(t,l._`${a} === ${c.default.errors}`)}(e,r):(0,t.boolOrEmptySchema)(e,r)}(s,r),s}mergeEvaluated(e,t){let{it:r,gen:n}=this;r.opts.unevaluated&&(!0!==r.props&&void 0!==e.props&&(r.props=d.mergeEvaluated.props(n,e.props,r.props,t)),!0!==r.items&&void 0!==e.items&&(r.items=d.mergeEvaluated.items(n,e.items,r.items,t)))}mergeValidEvaluated(e,t){let{it:r,gen:n}=this;if(r.opts.unevaluated&&(!0!==r.props||!0!==r.items))return n.if(t,()=>this.mergeEvaluated(e,l.Name)),!0}}function T(e,t,r,n){let s=new k(e,r,t);"code"in r?r.code(s,n):s.$data&&r.validate?(0,i.funcKeywordCode)(s,r):"macro"in r?(0,i.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,i.funcKeywordCode)(s,r)}e.KeywordCxt=k;var I=/^\/(?:[^~]|~0|~1)*$/,$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function P(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let s,a;if(""===e)return c.default.rootData;if("/"===e[0]){if(!I.test(e))throw Error(`Invalid JSON-pointer: ${e}`);s=e,a=c.default.rootData}else{let i=$.exec(e);if(!i)throw Error(`Invalid JSON-pointer: ${e}`);let o=+i[1];if(s=i[2],"#"===s){if(o>=t)throw Error(u("property/index",o));return n[t-o]}if(o>t)throw Error(u("data",o));if(a=r[t-o],!s)return a}let i=a,o=s.split("/");for(let e of o)e&&(a=l._`${a}${(0,l.getProperty)((0,d.unescapeJsonPointer)(e))}`,i=l._`${i} && ${a}`);return i;function u(e,r){return`Cannot access ${e} ${r} levels up, current level is ${t}`}}e.getData=P}),xr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});class t extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}}e.default=t}),Sr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=wr();class r extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,t.resolveUrl)(e,r,n),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}e.default=r}),kr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;var t=or(),r=xr(),n=cr(),s=wr(),a=lr(),i=Er();class o{constructor(e){var t;let r;this.refs={},this.dynamicAnchors={},"object"==typeof e.schema&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=null!==(t=e.baseId)&&void 0!==t?t:(0,s.normalizeId)(null==r?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=null==r?void 0:r.$async,this.refs={}}}function l(e){let a=u.call(this,e);if(a)return a;let o,l=(0,s.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:d}=this.opts.code,{ownProperties:p}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:d,ownProperties:p});e.$async&&(o=f.scopeValue("Error",{ref:r.default,code:t._`require("ajv/dist/runtime/validation_error").default`}));let h=f.scopeName("validate");e.validateName=h;let m,g={gen:f,allErrors:this.opts.allErrors,data:n.default.data,parentData:n.default.parentData,parentDataProperty:n.default.parentDataProperty,dataNames:[n.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue("schema",!0===this.opts.code.source?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:h,ValidationError:o,schema:e.schema,schemaEnv:e,rootId:l,baseId:e.baseId||l,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:t._`""`,opts:this.opts,self:this};try{this._compilations.add(e),(0,i.validateFunctionCode)(g),f.optimize(this.opts.code.optimize);let r=f.toString();m=`${f.scopeRefs(n.default.scope)}return ${r}`,this.opts.code.process&&(m=this.opts.code.process(m,e));let s=Function(`${n.default.self}`,`${n.default.scope}`,m)(this,this.scope.get());if(this.scope.value(h,{ref:s}),s.errors=null,s.schema=e.schema,s.schemaEnv=e,e.$async&&(s.$async=!0),!0===this.opts.code.source&&(s.source={validateName:h,validateCode:r,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:r}=g;s.evaluated={props:e instanceof t.Name?void 0:e,items:r instanceof t.Name?void 0:r,dynamicProps:e instanceof t.Name,dynamicItems:r instanceof t.Name},s.source&&(s.source.evaluated=(0,t.stringify)(s.evaluated))}return e.validate=s,e}catch(t){throw delete e.validate,delete e.validateName,m&&this.logger.error("Error compiling schema, function code:",m),t}finally{this._compilations.delete(e)}}function c(e){return(0,s.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:l.call(this,e)}function u(e){for(let t of this._compilations)if(d(t,e))return t}function d(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let r;for(;"string"==typeof(r=this.refs[t]);)t=r;return r||this.schemas[t]||f.call(this,e,t)}function f(e,t){let r=this.opts.uriResolver.parse(t),n=(0,s._getFullPath)(this.opts.uriResolver,r),a=(0,s.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===a)return m.call(this,r,e);let i=(0,s.normalizeId)(n),c=this.refs[i]||this.schemas[i];if("string"==typeof c){let t=f.call(this,e,c);if("object"!=typeof(null==t?void 0:t.schema))return;return m.call(this,r,t)}if("object"==typeof(null==c?void 0:c.schema)){if(c.validate||l.call(this,c),i===(0,s.normalizeId)(t)){let{schema:t}=c,{schemaId:r}=this.opts,n=t[r];return n&&(a=(0,s.resolveUrl)(this.opts.uriResolver,a,n)),new o({schema:t,schemaId:r,root:e,baseId:a})}return m.call(this,r,c)}}e.SchemaEnv=o,e.compileSchema=l,e.resolveRef=function(e,t,r){var n;r=(0,s.resolveUrl)(this.opts.uriResolver,t,r);let a=e.refs[r];if(a)return a;let i=p.call(this,e,r);if(void 0===i){let s=null===(n=e.localRefs)||void 0===n?void 0:n[r],{schemaId:a}=this.opts;s&&(i=new o({schema:s,schemaId:a,root:e,baseId:t}))}return void 0!==i?e.refs[r]=c.call(this,i):void 0},e.getCompilingSchema=u,e.resolveSchema=f;var h=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function m(e,{baseId:t,schema:r,root:n}){var i;if("/"!==(null===(i=e.fragment)||void 0===i?void 0:i[0]))return;for(let n of e.fragment.slice(1).split("/")){if("boolean"==typeof r)return;let e=r[(0,a.unescapeFragment)(n)];if(void 0===e)return;let i="object"==typeof(r=e)&&r[this.opts.schemaId];!h.has(n)&&i&&(t=(0,s.resolveUrl)(this.opts.uriResolver,t,i))}let l;if("boolean"!=typeof r&&r.$ref&&!(0,a.schemaHasRulesButRef)(r,this.RULES)){let e=(0,s.resolveUrl)(this.opts.uriResolver,t,r.$ref);l=f.call(this,n,e)}let{schemaId:c}=this.opts;return l=l||new o({schema:r,schemaId:c,root:n,baseId:t}),l.schema!==l.root.schema?l:void 0}}),Tr=nr((e,t)=>{t.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}}),Ir=nr((e,t)=>{t.exports={HEX:{0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15}}}),$r=nr((e,t)=>{var{HEX:r}=Ir(),n=/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u;function s(e){if(l(e,".")<3)return{host:e,isIPV4:!1};let t=e.match(n)||[],[r]=t;return r?{host:o(r,"."),isIPV4:!0}:{host:e,isIPV4:!1}}function a(e,t=!1){let n="",s=!0;for(let t of e){if(void 0===r[t])return;"0"!==t&&!0===s&&(s=!1),s||(n+=t)}return t&&0===n.length&&(n="0"),n}function i(e){if(l(e,":")<2)return{host:e,isIPV6:!1};let t=function(e){let t=0,r={error:!1,address:"",zone:""},n=[],s=[],i=!1,o=!1,l=!1;function c(){if(s.length){if(!1===i){let e=a(s);if(void 0===e)return r.error=!0,!1;n.push(e)}s.length=0}return!0}for(let a=0;a<e.length;a++){let u=e[a];if("["!==u&&"]"!==u)if(":"!==u)if("%"===u){if(!c())break;i=!0}else s.push(u);else{if(!0===o&&(l=!0),!c())break;if(t++,n.push(":"),t>7){r.error=!0;break}a-1>=0&&":"===e[a-1]&&(o=!0)}}return s.length&&(i?r.zone=s.join(""):l?n.push(s.join("")):n.push(a(s))),r.address=n.join(""),r}(e);if(t.error)return{host:e,isIPV6:!1};{let{address:e,address:r}=t;return t.zone&&(e+="%"+t.zone,r+="%25"+t.zone),{host:e,escapedHost:r,isIPV6:!0}}}function o(e,t){let r="",n=!0,s=e.length;for(let a=0;a<s;a++){let i=e[a];"0"===i&&n?(a+1<=s&&e[a+1]===t||a+1===s)&&(r+=i,n=!1):(n=i===t,r+=i)}return r}function l(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}var c=/^\.\.?\//u,u=/^\/\.(?:\/|$)/u,d=/^\/\.\.(?:\/|$)/u,p=/^\/?(?:.|\n)*?(?=\/|$)/u;t.exports={recomposeAuthority:function(e){let t=[];if(void 0!==e.userinfo&&(t.push(e.userinfo),t.push("@")),void 0!==e.host){let r=unescape(e.host),n=s(r);if(n.isIPV4)r=n.host;else{let t=i(n.host);r=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}t.push(r)}return"number"!=typeof e.port&&"string"!=typeof e.port||(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0},normalizeComponentEncoding:function(e,t){let r=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=r(e.scheme)),void 0!==e.userinfo&&(e.userinfo=r(e.userinfo)),void 0!==e.host&&(e.host=r(e.host)),void 0!==e.path&&(e.path=r(e.path)),void 0!==e.query&&(e.query=r(e.query)),void 0!==e.fragment&&(e.fragment=r(e.fragment)),e},removeDotSegments:function(e){let t=[];for(;e.length;)if(e.match(c))e=e.replace(c,"");else if(e.match(u))e=e.replace(u,"/");else if(e.match(d))e=e.replace(d,"/"),t.pop();else if("."===e||".."===e)e="";else{let r=e.match(p);if(!r)throw Error("Unexpected dot segment condition");{let n=r[0];e=e.slice(n.length),t.push(n)}}return t.join("")},normalizeIPv4:s,normalizeIPv6:i,stringArrayToHexStripped:a}}),Pr=nr((e,t)=>{var r=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu,n=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function s(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}function a(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function i(e){let t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}var o={scheme:"http",domainHost:!0,parse:a,serialize:i},l={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=s(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(s(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}},c={http:o,https:{scheme:"https",domainHost:o.domainHost,parse:a,serialize:i},ws:l,wss:{scheme:"wss",domainHost:l.domainHost,parse:l.parse,serialize:l.serialize},urn:{scheme:"urn",parse:function(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(n);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let s=`${n}:${t.nid||e.nid}`,a=c[s];e.path=void 0,a&&(e=a.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),s=`${r}:${t.nid||n}`,a=c[s];a&&(e=a.serialize(e,t));let i=e,o=e.nss;return i.path=`${n||t.nid}:${o}`,t.skipEscape=!0,i},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(e,t){let n=e;return n.uuid=n.nss,n.nss=void 0,t.tolerant||n.uuid&&r.test(n.uuid)||(n.error=n.error||"UUID is not valid."),n},serialize:function(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};t.exports=c}),Cr=nr((e,t)=>{var{normalizeIPv6:r,normalizeIPv4:n,removeDotSegments:s,recomposeAuthority:a,normalizeComponentEncoding:i}=$r(),o=Pr();function l(e,t,r,n){let a={};return n||(e=p(c(e,r),r),t=p(c(t,r),r)),!(r=r||{}).tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=s(t.path||""),a.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=s(t.path||""),a.query=t.query):(t.path?("/"===t.path.charAt(0)?a.path=s(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:a.path=t.path:a.path="/"+t.path,a.path=s(a.path)),a.query=t.query):(a.path=e.path,void 0!==t.query?a.query=t.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function c(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),i=[],l=o[(n.scheme||r.scheme||"").toLowerCase()];l&&l.serialize&&l.serialize(r,n),void 0!==r.path&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),void 0!==r.scheme&&(r.path=r.path.split("%3A").join(":")))),"suffix"!==n.reference&&r.scheme&&i.push(r.scheme,":");let c=a(r);if(void 0!==c&&("suffix"!==n.reference&&i.push("//"),i.push(c),r.path&&"/"!==r.path.charAt(0)&&i.push("/")),void 0!==r.path){let e=r.path;n.absolutePath||l&&l.absolutePath||(e=s(e)),void 0===c&&(e=e.replace(/^\/\//u,"/%2F")),i.push(e)}return void 0!==r.query&&i.push("?",r.query),void 0!==r.fragment&&i.push("#",r.fragment),i.join("")}var u=Array.from({length:127},(e,t)=>/[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(t))),d=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function p(e,t){let s=Object.assign({},t),a={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=-1!==e.indexOf("%"),l=!1;"suffix"===s.reference&&(e=(s.scheme?s.scheme+":":"")+"//"+e);let c=e.match(d);if(c){if(a.scheme=c[1],a.userinfo=c[3],a.host=c[4],a.port=parseInt(c[5],10),a.path=c[6]||"",a.query=c[7],a.fragment=c[8],isNaN(a.port)&&(a.port=c[5]),a.host){let e=n(a.host);if(!1===e.isIPV4){let t=r(e.host);a.host=t.host.toLowerCase(),l=t.isIPV6}else a.host=e.host,l=!0}void 0!==a.scheme||void 0!==a.userinfo||void 0!==a.host||void 0!==a.port||void 0!==a.query||a.path?void 0===a.scheme?a.reference="relative":void 0===a.fragment?a.reference="absolute":a.reference="uri":a.reference="same-document",s.reference&&"suffix"!==s.reference&&s.reference!==a.reference&&(a.error=a.error||"URI is not a "+s.reference+" reference.");let e=o[(s.scheme||a.scheme||"").toLowerCase()];if(!(s.unicodeSupport||e&&e.unicodeSupport)&&a.host&&(s.domainHost||e&&e.domainHost)&&!1===l&&function(e){let t=0;for(let r=0,n=e.length;r<n;++r)if(t=e.charCodeAt(r),t>126||u[t])return!0;return!1}(a.host))try{a.host=URL.domainToASCII(a.host.toLowerCase())}catch(e){a.error=a.error||"Host's domain name can not be converted to ASCII: "+e}(!e||e&&!e.skipNormalize)&&(i&&void 0!==a.scheme&&(a.scheme=unescape(a.scheme)),i&&void 0!==a.host&&(a.host=unescape(a.host)),a.path&&(a.path=escape(unescape(a.path))),a.fragment&&(a.fragment=encodeURI(decodeURIComponent(a.fragment)))),e&&e.parse&&e.parse(a,s)}else a.error=a.error||"URI can not be parsed.";return a}var f={SCHEMES:o,normalize:function(e,t){return"string"==typeof e?e=c(p(e,t),t):"object"==typeof e&&(e=p(c(e,t),t)),e},resolve:function(e,t,r){let n=Object.assign({scheme:"null"},r);return c(l(p(e,n),p(t,n),n,!0),{...n,skipEscape:!0})},resolveComponents:l,equal:function(e,t,r){return"string"==typeof e?(e=unescape(e),e=c(i(p(e,r),!0),{...r,skipEscape:!0})):"object"==typeof e&&(e=c(i(e,!0),{...r,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=c(i(p(t,r),!0),{...r,skipEscape:!0})):"object"==typeof t&&(t=c(i(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:c,parse:p};t.exports=f,t.exports.default=f,t.exports.fastUri=f}),Rr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Cr();t.code='require("ajv/dist/runtime/uri").default',e.default=t}),Ar=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Er();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=or();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});var n=xr(),s=Sr(),a=pr(),i=kr(),o=or(),l=wr(),c=hr(),u=lr(),d=Tr(),p=Rr(),f=(e,t)=>new RegExp(e,t);f.code="new RegExp";var h=["removeAdditional","useDefaults","coerceTypes"],m=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),g={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},y={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'};function v(e){var t,r,n,s,a,i,o,l,c,u,d,h,m,g,y,v,_,b,w,E,x,S,k,T,I;let $=e.strict,P=null===(t=e.code)||void 0===t?void 0:t.optimize,C=!0===P||void 0===P?1:P||0,R=null!==(n=null===(r=e.code)||void 0===r?void 0:r.regExp)&&void 0!==n?n:f,A=null!==(s=e.uriResolver)&&void 0!==s?s:p.default;return{strictSchema:null===(i=null!==(a=e.strictSchema)&&void 0!==a?a:$)||void 0===i||i,strictNumbers:null===(l=null!==(o=e.strictNumbers)&&void 0!==o?o:$)||void 0===l||l,strictTypes:null!==(u=null!==(c=e.strictTypes)&&void 0!==c?c:$)&&void 0!==u?u:"log",strictTuples:null!==(h=null!==(d=e.strictTuples)&&void 0!==d?d:$)&&void 0!==h?h:"log",strictRequired:null!==(g=null!==(m=e.strictRequired)&&void 0!==m?m:$)&&void 0!==g&&g,code:e.code?{...e.code,optimize:C,regExp:R}:{optimize:C,regExp:R},loopRequired:null!==(y=e.loopRequired)&&void 0!==y?y:200,loopEnum:null!==(v=e.loopEnum)&&void 0!==v?v:200,meta:null===(_=e.meta)||void 0===_||_,messages:null===(b=e.messages)||void 0===b||b,inlineRefs:null===(w=e.inlineRefs)||void 0===w||w,schemaId:null!==(E=e.schemaId)&&void 0!==E?E:"$id",addUsedSchema:null===(x=e.addUsedSchema)||void 0===x||x,validateSchema:null===(S=e.validateSchema)||void 0===S||S,validateFormats:null===(k=e.validateFormats)||void 0===k||k,unicodeRegExp:null===(T=e.unicodeRegExp)||void 0===T||T,int32range:null===(I=e.int32range)||void 0===I||I,uriResolver:A}}class _{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new o.ValueScope({scope:{},prefixes:m,es5:t,lines:r}),this.logger=function(e){if(!1===e)return T;if(void 0===e)return console;if(e.log&&e.warn&&e.error)return e;throw Error("logger must implement log, warn and error methods")}(e.logger);let n=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,"NOT SUPPORTED"),b.call(this,y,e,"DEPRECATED","warn"),this._metaOpts=k.call(this),e.formats&&x.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&S.call(this,e.keywords),"object"==typeof e.meta&&this.addMetaSchema(e.meta),E.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,n=d;"id"===r&&(n={...d},n.id=n.$id,delete n.$id),t&&e&&this.addMetaSchema(n,n[r],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta="object"==typeof e?e[t]||e:void 0}validate(e,t){let r;if("string"==typeof e){if(r=this.getSchema(e),!r)throw Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let n=r(t);return"$async"in r||(this.errors=r.errors),n}compile(e,t){let r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if("function"!=typeof this.opts.loadSchema)throw Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return n.call(this,e,t);async function n(e,t){await a.call(this,e.$schema);let r=this._addSchema(e,t);return r.validate||i.call(this,r)}async function a(e){e&&!this.getSchema(e)&&await n.call(this,{$ref:e},!0)}async function i(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof s.default))throw t;return o.call(this,t),await l.call(this,t.missingSchema),i.call(this,e)}}function o({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function l(e){let r=await c.call(this,e);this.refs[e]||await a.call(this,r.$schema),this.refs[e]||this.addSchema(r,e,t)}async function c(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=r(e))}finally{delete this._loading[e]}}}addSchema(e,t,r,n=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,r,n);return this}let s;if("object"==typeof e){let{schemaId:t}=this.opts;if(s=e[t],void 0!==s&&"string"!=typeof s)throw Error(`schema ${t} must be string`)}return t=(0,l.normalizeId)(t||s),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,n,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if("boolean"==typeof e)return!0;let r;if(r=e.$schema,void 0!==r&&"string"!=typeof r)throw Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let n=this.validate(r,e);if(!n&&t){let e="schema is invalid: "+this.errorsText();if("log"!==this.opts.validateSchema)throw Error(e);this.logger.error(e)}return n}getSchema(e){let t;for(;"string"==typeof(t=w.call(this,e));)e=t;if(void 0===t){let{schemaId:r}=this.opts,n=new i.SchemaEnv({schema:{},schemaId:r});if(t=i.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=w.call(this,e);return"object"==typeof t&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let r=e[this.opts.schemaId];return r&&(r=(0,l.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if("string"==typeof e)r=e,"object"==typeof t&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r);else{if("object"!=typeof e||void 0!==t)throw Error("invalid addKeywords parameters");if(r=(t=e).keyword,Array.isArray(r)&&!r.length)throw Error("addKeywords: keyword must be string or non-empty array")}if($.call(this,r,t),!t)return(0,u.eachItem)(r,e=>P.call(this,e)),this;R.call(this,t);let n={...t,type:(0,c.getJSONTypes)(t.type),schemaType:(0,c.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(r,0===n.type.length?e=>P.call(this,e,n):e=>n.type.forEach(t=>P.call(this,e,n,t))),this}getKeyword(e){let t=this.RULES.all[e];return"object"==typeof t?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let r of t.rules){let t=r.rules.findIndex(t=>t.keyword===e);t>=0&&r.rules.splice(t,1)}return this}addFormat(e,t){return"string"==typeof t&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){return e&&0!==e.length?e.map(e=>`${r}${e.instancePath} ${e.message}`).reduce((e,r)=>e+t+r):"No errors"}$dataMetaSchema(e,t){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let n of t){let t=n.split("/").slice(1),s=e;for(let e of t)s=s[e];for(let e in r){let t=r[e];if("object"!=typeof t)continue;let{$data:n}=t.definition,a=s[e];n&&a&&(s[e]=O(a))}}return e}_removeAllSchemas(e,t){for(let r in e){let n=e[r];t&&!t.test(r)||("string"==typeof n?delete e[r]:n&&!n.meta&&(this._cache.delete(n.schema),delete e[r]))}}_addSchema(e,t,r,n=this.opts.validateSchema,s=this.opts.addUsedSchema){let a,{schemaId:o}=this.opts;if("object"==typeof e)a=e[o];else{if(this.opts.jtd)throw Error("schema must be object");if("boolean"!=typeof e)throw Error("schema must be object or boolean")}let c=this._cache.get(e);if(void 0!==c)return c;r=(0,l.normalizeId)(a||r);let u=l.getSchemaRefs.call(this,e,r);return c=new i.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:r,localRefs:u}),this._cache.set(c.schema,c),s&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=c),n&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):i.compileSchema.call(this,e),!e.validate)throw Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,e)}finally{this.opts=t}}}function b(e,t,r,n="error"){for(let s in e){let a=s;a in t&&this.logger[n](`${r}: option ${s}. ${e[a]}`)}}function w(e){return e=(0,l.normalizeId)(e),this.schemas[e]||this.refs[e]}function E(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function x(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function S(e){if(Array.isArray(e))this.addVocabulary(e);else{this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}}function k(){let e={...this.opts};for(let t of h)delete e[t];return e}_.ValidationError=n.default,_.MissingRefError=s.default,e.default=_;var T={log(){},warn(){},error(){}},I=/^[a-z_$][a-z0-9_$:-]*$/i;function $(e,t){let{RULES:r}=this;if((0,u.eachItem)(e,e=>{if(r.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!I.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!("code"in t)&&!("validate"in t))throw Error('$data keyword must have "code" or "validate" function')}function P(e,t,r){var n;let s=null==t?void 0:t.post;if(r&&s)throw Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,i=s?a.post:a.rules.find(({type:e})=>e===r);if(i||(i={type:r,rules:[]},a.rules.push(i)),a.keywords[e]=!0,!t)return;let o={keyword:e,definition:{...t,type:(0,c.getJSONTypes)(t.type),schemaType:(0,c.getJSONTypes)(t.schemaType)}};t.before?C.call(this,i,o,t.before):i.rules.push(o),a.all[e]=o,null===(n=t.implements)||void 0===n||n.forEach(e=>this.addKeyword(e))}function C(e,t,r){let n=e.rules.findIndex(e=>e.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function R(e){let{metaSchema:t}=e;void 0!==t&&(e.$data&&this.opts.$data&&(t=O(t)),e.validateSchema=this.compile(t,!0))}var A={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function O(e){return{anyOf:[e,A]}}}),Or=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};e.default=t}),Nr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;var t=Sr(),r=gr(),n=or(),s=cr(),a=kr(),i=lr(),o={keyword:"$ref",schemaType:"string",code(e){let{gen:r,schema:s,it:i}=e,{baseId:o,schemaEnv:u,validateName:d,opts:p,self:f}=i,{root:h}=u;if(("#"===s||"#/"===s)&&o===h.baseId)return function(){if(u===h)return c(e,d,u,u.$async);let t=r.scopeValue("root",{ref:h});return c(e,n._`${t}.validate`,h,h.$async)}();let m=a.resolveRef.call(f,h,o,s);if(void 0===m)throw new t.default(i.opts.uriResolver,o,s);return m instanceof a.SchemaEnv?function(t){let r=l(e,t);c(e,r,t,t.$async)}(m):function(t){let a=r.scopeValue("schema",!0===p.code.source?{ref:t,code:(0,n.stringify)(t)}:{ref:t}),i=r.name("valid"),o=e.subschema({schema:t,dataTypes:[],schemaPath:n.nil,topSchemaRef:a,errSchemaPath:s},i);e.mergeEvaluated(o),e.ok(i)}(m)}};function l(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):n._`${r.scopeValue("wrapper",{ref:t})}.validate`}function c(e,t,a,o){let{gen:l,it:c}=e,{allErrors:u,schemaEnv:d,opts:p}=c,f=p.passContext?s.default.this:n.nil;function h(e){let t=n._`${e}.errors`;l.assign(s.default.vErrors,n._`${s.default.vErrors} === null ? ${t} : ${s.default.vErrors}.concat(${t})`),l.assign(s.default.errors,n._`${s.default.vErrors}.length`)}function m(e){var t;if(!c.opts.unevaluated)return;let r=null===(t=null==a?void 0:a.validate)||void 0===t?void 0:t.evaluated;if(!0!==c.props)if(r&&!r.dynamicProps)void 0!==r.props&&(c.props=i.mergeEvaluated.props(l,r.props,c.props));else{let t=l.var("props",n._`${e}.evaluated.props`);c.props=i.mergeEvaluated.props(l,t,c.props,n.Name)}if(!0!==c.items)if(r&&!r.dynamicItems)void 0!==r.items&&(c.items=i.mergeEvaluated.items(l,r.items,c.items));else{let t=l.var("items",n._`${e}.evaluated.items`);c.items=i.mergeEvaluated.items(l,t,c.items,n.Name)}}o?function(){if(!d.$async)throw Error("async schema referenced by sync schema");let s=l.let("valid");l.try(()=>{l.code(n._`await ${(0,r.callValidateCode)(e,t,f)}`),m(t),u||l.assign(s,!0)},e=>{l.if(n._`!(${e} instanceof ${c.ValidationError})`,()=>l.throw(e)),h(e),u||l.assign(s,!1)}),e.ok(s)}():e.result((0,r.callValidateCode)(e,t,f),()=>m(t),()=>h(t))}e.getValidate=l,e.callRef=c,e.default=o}),jr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Or(),r=Nr(),n=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",t.default,r.default];e.default=n}),Dr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=or(),r=t.operators,n={maximum:{okStr:"<=",ok:r.LTE,fail:r.GT},minimum:{okStr:">=",ok:r.GTE,fail:r.LT},exclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},exclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},s={message:({keyword:e,schemaCode:r})=>t.str`must be ${n[e].okStr} ${r}`,params:({keyword:e,schemaCode:r})=>t._`{comparison: ${n[e].okStr}, limit: ${r}}`},a={keyword:Object.keys(n),type:"number",schemaType:"number",$data:!0,error:s,code(e){let{keyword:r,data:s,schemaCode:a}=e;e.fail$data(t._`${s} ${n[r].fail} ${a} || isNaN(${s})`)}};e.default=a}),Ur=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=or(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>t.str`must be multiple of ${e}`,params:({schemaCode:e})=>t._`{multipleOf: ${e}}`},code(e){let{gen:r,data:n,schemaCode:s,it:a}=e,i=a.opts.multipleOfPrecision,o=r.let("res"),l=i?t._`Math.abs(Math.round(${o}) - ${o}) > 1e-${i}`:t._`${o} !== parseInt(${o})`;e.fail$data(t._`(${s} === 0 || (${o} = ${n}/${s}, ${l}))`)}};e.default=r}),Lr=nr(e=>{function t(e){let t,r=e.length,n=0,s=0;for(;s<r;)n++,t=e.charCodeAt(s++),t>=55296&&t<=56319&&s<r&&(t=e.charCodeAt(s),56320==(64512&t)&&s++);return n}Object.defineProperty(e,"__esModule",{value:!0}),e.default=t,t.code='require("ajv/dist/runtime/ucs2length").default'}),Mr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=or(),r=lr(),n=Lr(),s={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:r}){let n="maxLength"===e?"more":"fewer";return t.str`must NOT have ${n} than ${r} characters`},params:({schemaCode:e})=>t._`{limit: ${e}}`},code(e){let{keyword:s,data:a,schemaCode:i,it:o}=e,l="maxLength"===s?t.operators.GT:t.operators.LT,c=!1===o.opts.unicode?t._`${a}.length`:t._`${(0,r.useFunc)(e.gen,n.default)}(${a})`;e.fail$data(t._`${c} ${l} ${i}`)}};e.default=s}),zr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=gr(),r=or(),n={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>r.str`must match pattern "${e}"`,params:({schemaCode:e})=>r._`{pattern: ${e}}`},code(e){let{data:n,$data:s,schema:a,schemaCode:i,it:o}=e,l=o.opts.unicodeRegExp?"u":"",c=s?r._`(new RegExp(${i}, ${l}))`:(0,t.usePattern)(e,a);e.fail$data(r._`!${c}.test(${n})`)}};e.default=n}),Br=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=or(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:r}){let n="maxProperties"===e?"more":"fewer";return t.str`must NOT have ${n} than ${r} properties`},params:({schemaCode:e})=>t._`{limit: ${e}}`},code(e){let{keyword:r,data:n,schemaCode:s}=e,a="maxProperties"===r?t.operators.GT:t.operators.LT;e.fail$data(t._`Object.keys(${n}).length ${a} ${s}`)}};e.default=r}),Fr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=gr(),r=or(),n=lr(),s={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>r.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>r._`{missingProperty: ${e}}`},code(e){let{gen:s,schema:a,schemaCode:i,data:o,$data:l,it:c}=e,{opts:u}=c;if(!l&&0===a.length)return;let d=a.length>=u.loopRequired;if(c.allErrors?function(){if(d||l)e.block$data(r.nil,p);else for(let r of a)(0,t.checkReportMissingProp)(e,r)}():function(){let n=s.let("missing");if(d||l){let a=s.let("valid",!0);e.block$data(a,()=>function(n,a){e.setParams({missingProperty:n}),s.forOf(n,i,()=>{s.assign(a,(0,t.propertyInData)(s,o,n,u.ownProperties)),s.if((0,r.not)(a),()=>{e.error(),s.break()})},r.nil)}(n,a)),e.ok(a)}else s.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),s.else()}(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:r}=e.it;for(let e of a)if(void 0===(null==t?void 0:t[e])&&!r.has(e)){let t=`required property "${e}" is not defined at "${c.schemaEnv.baseId+c.errSchemaPath}" (strictRequired)`;(0,n.checkStrictMode)(c,t,c.opts.strictRequired)}}function p(){s.forOf("prop",i,r=>{e.setParams({missingProperty:r}),s.if((0,t.noPropertyInData)(s,o,r,u.ownProperties),()=>e.error())})}}};e.default=s}),qr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=or(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:r}){let n="maxItems"===e?"more":"fewer";return t.str`must NOT have ${n} than ${r} items`},params:({schemaCode:e})=>t._`{limit: ${e}}`},code(e){let{keyword:r,data:n,schemaCode:s}=e,a="maxItems"===r?t.operators.GT:t.operators.LT;e.fail$data(t._`${n}.length ${a} ${s}`)}};e.default=r}),Hr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=_r();t.code='require("ajv/dist/runtime/equal").default',e.default=t}),Zr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=hr(),r=or(),n=lr(),s=Hr(),a={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>r.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>r._`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:i,$data:o,schema:l,parentSchema:c,schemaCode:u,it:d}=e;if(!o&&!l)return;let p=a.let("valid"),f=c.items?(0,t.getSchemaTypes)(c.items):[];function h(n,s){let o=a.name("item"),l=(0,t.checkDataTypes)(f,o,d.opts.strictNumbers,t.DataType.Wrong),c=a.const("indices",r._`{}`);a.for(r._`;${n}--;`,()=>{a.let(o,r._`${i}[${n}]`),a.if(l,r._`continue`),f.length>1&&a.if(r._`typeof ${o} == "string"`,r._`${o} += "_"`),a.if(r._`typeof ${c}[${o}] == "number"`,()=>{a.assign(s,r._`${c}[${o}]`),e.error(),a.assign(p,!1).break()}).code(r._`${c}[${o}] = ${n}`)})}function m(t,o){let l=(0,n.useFunc)(a,s.default),c=a.name("outer");a.label(c).for(r._`;${t}--;`,()=>a.for(r._`${o} = ${t}; ${o}--;`,()=>a.if(r._`${l}(${i}[${t}], ${i}[${o}])`,()=>{e.error(),a.assign(p,!1).break(c)})))}e.block$data(p,function(){let t=a.let("i",r._`${i}.length`),n=a.let("j");e.setParams({i:t,j:n}),a.assign(p,!0),a.if(r._`${t} > 1`,()=>(f.length>0&&!f.some(e=>"object"===e||"array"===e)?h:m)(t,n))},r._`${u} === false`),e.ok(p)}};e.default=a}),Vr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=or(),r=lr(),n=Hr(),s={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>t._`{allowedValue: ${e}}`},code(e){let{gen:s,data:a,$data:i,schemaCode:o,schema:l}=e;i||l&&"object"==typeof l?e.fail$data(t._`!${(0,r.useFunc)(s,n.default)}(${a}, ${o})`):e.fail(t._`${l} !== ${a}`)}};e.default=s}),Gr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=or(),r=lr(),n=Hr(),s={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>t._`{allowedValues: ${e}}`},code(e){let{gen:s,data:a,$data:i,schema:o,schemaCode:l,it:c}=e;if(!i&&0===o.length)throw Error("enum must have non-empty array");let u,d,p=o.length>=c.opts.loopEnum,f=()=>null!=u?u:u=(0,r.useFunc)(s,n.default);if(p||i)d=s.let("valid"),e.block$data(d,function(){s.assign(d,!1),s.forOf("v",l,e=>s.if(t._`${f()}(${a}, ${e})`,()=>s.assign(d,!0).break()))});else{if(!Array.isArray(o))throw Error("ajv implementation error");let e=s.const("vSchema",l);d=(0,t.or)(...o.map((r,n)=>function(e,r){let n=o[r];return"object"==typeof n&&null!==n?t._`${f()}(${a}, ${e}[${r}])`:t._`${a} === ${n}`}(e,n)))}e.pass(d)}};e.default=s}),Wr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Dr(),r=Ur(),n=Mr(),s=zr(),a=Br(),i=Fr(),o=qr(),l=Zr(),c=Vr(),u=Gr(),d=[t.default,r.default,n.default,s.default,a.default,i.default,o.default,l.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c.default,u.default];e.default=d}),Kr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;var t=or(),r=lr(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:e}})=>t.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>t._`{limit: ${e}}`},code(e){let{parentSchema:t,it:n}=e,{items:a}=t;Array.isArray(a)?s(e,a):(0,r.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas')}};function s(e,n){let{gen:s,schema:a,data:i,keyword:o,it:l}=e;l.items=!0;let c=s.const("len",t._`${i}.length`);if(!1===a)e.setParams({len:n.length}),e.pass(t._`${c} <= ${n.length}`);else if("object"==typeof a&&!(0,r.alwaysValidSchema)(l,a)){let a=s.var("valid",t._`${c} <= ${n.length}`);s.if((0,t.not)(a),()=>function(a){s.forRange("i",n.length,c,n=>{e.subschema({keyword:o,dataProp:n,dataPropType:r.Type.Num},a),l.allErrors||s.if((0,t.not)(a),()=>s.break())})}(a)),e.ok(a)}}e.validateAdditionalItems=s,e.default=n}),Yr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;var t=or(),r=lr(),n=gr(),s={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:s}=e;if(Array.isArray(t))return a(e,"additionalItems",t);s.items=!0,(0,r.alwaysValidSchema)(s,t)||e.ok((0,n.validateArray)(e))}};function a(e,n,s=e.schema){let{gen:a,parentSchema:i,data:o,keyword:l,it:c}=e;(function(e){let{opts:t,errSchemaPath:a}=c,i=s.length,o=i===e.minItems&&(i===e.maxItems||!1===e[n]);if(t.strictTuples&&!o){let e=`"${l}" is ${i}-tuple, but minItems or maxItems/${n} are not specified or different at path "${a}"`;(0,r.checkStrictMode)(c,e,t.strictTuples)}})(i),c.opts.unevaluated&&s.length&&!0!==c.items&&(c.items=r.mergeEvaluated.items(a,s.length,c.items));let u=a.name("valid"),d=a.const("len",t._`${o}.length`);s.forEach((n,s)=>{(0,r.alwaysValidSchema)(c,n)||(a.if(t._`${d} > ${s}`,()=>e.subschema({keyword:l,schemaProp:s,dataProp:s},u)),e.ok(u))})}e.validateTuple=a,e.default=s}),Jr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Yr(),r={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,t.validateTuple)(e,"items")};e.default=r}),Qr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=or(),r=lr(),n=gr(),s=Kr(),a={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>t.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>t._`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:i}=e,{prefixItems:o}=a;i.items=!0,(0,r.alwaysValidSchema)(i,t)||(o?(0,s.validateAdditionalItems)(e,o):e.ok((0,n.validateArray)(e)))}};e.default=a}),Xr=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=or(),r=lr(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:e,max:r}})=>void 0===r?t.str`must contain at least ${e} valid item(s)`:t.str`must contain at least ${e} and no more than ${r} valid item(s)`,params:({params:{min:e,max:r}})=>void 0===r?t._`{minContains: ${e}}`:t._`{minContains: ${e}, maxContains: ${r}}`},code(e){let n,s,{gen:a,schema:i,parentSchema:o,data:l,it:c}=e,{minContains:u,maxContains:d}=o;c.opts.next?(n=void 0===u?1:u,s=d):n=1;let p=a.const("len",t._`${l}.length`);if(e.setParams({min:n,max:s}),void 0===s&&0===n)return void(0,r.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');if(void 0!==s&&n>s)return(0,r.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),void e.fail();if((0,r.alwaysValidSchema)(c,i)){let r=t._`${p} >= ${n}`;return void 0!==s&&(r=t._`${r} && ${p} <= ${s}`),void e.pass(r)}c.items=!0;let f=a.name("valid");function h(){let e=a.name("_valid"),r=a.let("count",0);m(e,()=>a.if(e,()=>function(e){a.code(t._`${e}++`),void 0===s?a.if(t._`${e} >= ${n}`,()=>a.assign(f,!0).break()):(a.if(t._`${e} > ${s}`,()=>a.assign(f,!1).break()),1===n?a.assign(f,!0):a.if(t._`${e} >= ${n}`,()=>a.assign(f,!0)))}(r)))}function m(t,n){a.forRange("i",0,p,s=>{e.subschema({keyword:"contains",dataProp:s,dataPropType:r.Type.Num,compositeRule:!0},t),n()})}void 0===s&&1===n?m(f,()=>a.if(f,()=>a.break())):0===n?(a.let(f,!0),void 0!==s&&a.if(t._`${l}.length > 0`,h)):(a.let(f,!1),h()),e.result(f,()=>e.reset())}};e.default=n}),en=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;var t=or(),r=lr(),n=gr();e.error={message:({params:{property:e,depsCount:r,deps:n}})=>{let s=1===r?"property":"properties";return t.str`must have ${s} ${n} when property ${e} is present`},params:({params:{property:e,depsCount:r,deps:n,missingProperty:s}})=>t._`{property: ${e},
|
|
6
|
+
missingProperty: ${s},
|
|
7
|
+
depsCount: ${r},
|
|
8
|
+
deps: ${n}}`};var s={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(e){let[t,r]=function({schema:e}){let t={},r={};for(let n in e)"__proto__"!==n&&((Array.isArray(e[n])?t:r)[n]=e[n]);return[t,r]}(e);a(e,t),i(e,r)}};function a(e,r=e.schema){let{gen:s,data:a,it:i}=e;if(0===Object.keys(r).length)return;let o=s.let("missing");for(let l in r){let c=r[l];if(0===c.length)continue;let u=(0,n.propertyInData)(s,a,l,i.opts.ownProperties);e.setParams({property:l,depsCount:c.length,deps:c.join(", ")}),i.allErrors?s.if(u,()=>{for(let t of c)(0,n.checkReportMissingProp)(e,t)}):(s.if(t._`${u} && (${(0,n.checkMissingProp)(e,c,o)})`),(0,n.reportMissingProp)(e,o),s.else())}}function i(e,t=e.schema){let{gen:s,data:a,keyword:i,it:o}=e,l=s.name("valid");for(let c in t)(0,r.alwaysValidSchema)(o,t[c])||(s.if((0,n.propertyInData)(s,a,c,o.opts.ownProperties),()=>{let t=e.subschema({keyword:i,schemaProp:c},l);e.mergeValidEvaluated(t,l)},()=>s.var(l,!0)),e.ok(l))}e.validatePropertyDeps=a,e.validateSchemaDeps=i,e.default=s}),tn=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=or(),r=lr(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:e})=>t._`{propertyName: ${e.propertyName}}`},code(e){let{gen:n,schema:s,data:a,it:i}=e;if((0,r.alwaysValidSchema)(i,s))return;let o=n.name("valid");n.forIn("key",a,r=>{e.setParams({propertyName:r}),e.subschema({keyword:"propertyNames",data:r,dataTypes:["string"],propertyName:r,compositeRule:!0},o),n.if((0,t.not)(o),()=>{e.error(!0),i.allErrors||n.break()})}),e.ok(o)}};e.default=n}),rn=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=gr(),r=or(),n=cr(),s=lr(),a={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:e})=>r._`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:i,parentSchema:o,data:l,errsCount:c,it:u}=e;if(!c)throw Error("ajv implementation error");let{allErrors:d,opts:p}=u;if(u.props=!0,"all"!==p.removeAdditional&&(0,s.alwaysValidSchema)(u,i))return;let f=(0,t.allSchemaProperties)(o.properties),h=(0,t.allSchemaProperties)(o.patternProperties);function m(e){a.code(r._`delete ${l}[${e}]`)}function g(t){if("all"===p.removeAdditional||p.removeAdditional&&!1===i)m(t);else{if(!1===i)return e.setParams({additionalProperty:t}),e.error(),void(d||a.break());if("object"==typeof i&&!(0,s.alwaysValidSchema)(u,i)){let n=a.name("valid");"failing"===p.removeAdditional?(y(t,n,!1),a.if((0,r.not)(n),()=>{e.reset(),m(t)})):(y(t,n),d||a.if((0,r.not)(n),()=>a.break()))}}}function y(t,r,n){let a={keyword:"additionalProperties",dataProp:t,dataPropType:s.Type.Str};!1===n&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,r)}a.forIn("key",l,n=>{f.length||h.length?a.if(function(n){let i;if(f.length>8){let e=(0,s.schemaRefOrVal)(u,o.properties,"properties");i=(0,t.isOwnProperty)(a,e,n)}else i=f.length?(0,r.or)(...f.map(e=>r._`${n} === ${e}`)):r.nil;return h.length&&(i=(0,r.or)(i,...h.map(s=>r._`${(0,t.usePattern)(e,s)}.test(${n})`))),(0,r.not)(i)}(n),()=>g(n)):g(n)}),e.ok(r._`${c} === ${n.default.errors}`)}};e.default=a}),nn=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Er(),r=gr(),n=lr(),s=rn(),a={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:a,schema:i,parentSchema:o,data:l,it:c}=e;"all"===c.opts.removeAdditional&&void 0===o.additionalProperties&&s.default.code(new t.KeywordCxt(c,s.default,"additionalProperties"));let u=(0,r.allSchemaProperties)(i);for(let e of u)c.definedProperties.add(e);c.opts.unevaluated&&u.length&&!0!==c.props&&(c.props=n.mergeEvaluated.props(a,(0,n.toHash)(u),c.props));let d=u.filter(e=>!(0,n.alwaysValidSchema)(c,i[e]));if(0===d.length)return;let p=a.name("valid");for(let t of d)f(t)?h(t):(a.if((0,r.propertyInData)(a,l,t,c.opts.ownProperties)),h(t),c.allErrors||a.else().var(p,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(p);function f(e){return c.opts.useDefaults&&!c.compositeRule&&void 0!==i[e].default}function h(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},p)}}};e.default=a}),sn=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=gr(),r=or(),n=lr(),s=lr(),a={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:a,schema:i,data:o,parentSchema:l,it:c}=e,{opts:u}=c,d=(0,t.allSchemaProperties)(i),p=d.filter(e=>(0,n.alwaysValidSchema)(c,i[e]));if(0===d.length||p.length===d.length&&(!c.opts.unevaluated||!0===c.props))return;let f=u.strictSchema&&!u.allowMatchingProperties&&l.properties,h=a.name("valid");!0===c.props||c.props instanceof r.Name||(c.props=(0,s.evaluatedPropsToName)(a,c.props));let{props:m}=c;function g(e){for(let t in f)new RegExp(e).test(t)&&(0,n.checkStrictMode)(c,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function y(n){a.forIn("key",o,i=>{a.if(r._`${(0,t.usePattern)(e,n)}.test(${i})`,()=>{let t=p.includes(n);t||e.subschema({keyword:"patternProperties",schemaProp:n,dataProp:i,dataPropType:s.Type.Str},h),c.opts.unevaluated&&!0!==m?a.assign(r._`${m}[${i}]`,!0):t||c.allErrors||a.if((0,r.not)(h),()=>a.break())})})}!function(){for(let e of d)f&&g(e),c.allErrors?y(e):(a.var(h,!0),y(e),a.if(h))}()}};e.default=a}),an=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=lr(),r={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:r,schema:n,it:s}=e;if((0,t.alwaysValidSchema)(s,n))return void e.fail();let a=r.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};e.default=r}),on=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:gr().validateUnion,error:{message:"must match a schema in anyOf"}};e.default=t}),ln=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=or(),r=lr(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:e})=>t._`{passingSchemas: ${e.passing}}`},code(e){let{gen:n,schema:s,parentSchema:a,it:i}=e;if(!Array.isArray(s))throw Error("ajv implementation error");if(i.opts.discriminator&&a.discriminator)return;let o=s,l=n.let("valid",!1),c=n.let("passing",null),u=n.name("_valid");e.setParams({passing:c}),n.block(function(){o.forEach((s,a)=>{let o;(0,r.alwaysValidSchema)(i,s)?n.var(u,!0):o=e.subschema({keyword:"oneOf",schemaProp:a,compositeRule:!0},u),a>0&&n.if(t._`${u} && ${l}`).assign(l,!1).assign(c,t._`[${c}, ${a}]`).else(),n.if(u,()=>{n.assign(l,!0),n.assign(c,a),o&&e.mergeEvaluated(o,t.Name)})})}),e.result(l,()=>e.reset(),()=>e.error(!0))}};e.default=n}),cn=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=lr(),r={keyword:"allOf",schemaType:"array",code(e){let{gen:r,schema:n,it:s}=e;if(!Array.isArray(n))throw Error("ajv implementation error");let a=r.name("valid");n.forEach((r,n)=>{if((0,t.alwaysValidSchema)(s,r))return;let i=e.subschema({keyword:"allOf",schemaProp:n},a);e.ok(a),e.mergeEvaluated(i)})}};e.default=r}),un=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=or(),r=lr(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:e})=>t.str`must match "${e.ifClause}" schema`,params:({params:e})=>t._`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:n,parentSchema:a,it:i}=e;void 0===a.then&&void 0===a.else&&(0,r.checkStrictMode)(i,'"if" without "then" and "else" is ignored');let o=s(i,"then"),l=s(i,"else");if(!o&&!l)return;let c=n.let("valid",!0),u=n.name("_valid");if(function(){let t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}(),e.reset(),o&&l){let t=n.let("ifClause");e.setParams({ifClause:t}),n.if(u,d("then",t),d("else",t))}else o?n.if(u,d("then")):n.if((0,t.not)(u),d("else"));function d(r,s){return()=>{let a=e.subschema({keyword:r},u);n.assign(c,u),e.mergeValidEvaluated(a,c),s?n.assign(s,t._`${r}`):e.setParams({ifClause:r})}}e.pass(c,()=>e.error(!0))}};function s(e,t){let n=e.schema[t];return void 0!==n&&!(0,r.alwaysValidSchema)(e,n)}e.default=n}),dn=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=lr(),r={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:r,it:n}){void 0===r.if&&(0,t.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};e.default=r}),pn=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Kr(),r=Jr(),n=Yr(),s=Qr(),a=Xr(),i=en(),o=tn(),l=rn(),c=nn(),u=sn(),d=an(),p=on(),f=ln(),h=cn(),m=un(),g=dn();e.default=function(e=!1){let y=[d.default,p.default,f.default,h.default,m.default,g.default,o.default,l.default,i.default,c.default,u.default];return e?y.push(r.default,s.default):y.push(t.default,n.default),y.push(a.default),y}}),fn=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=or(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>t.str`must match format "${e}"`,params:({schemaCode:e})=>t._`{format: ${e}}`},code(e,r){let{gen:n,data:s,$data:a,schema:i,schemaCode:o,it:l}=e,{opts:c,errSchemaPath:u,schemaEnv:d,self:p}=l;c.validateFormats&&(a?function(){let a=n.scopeValue("formats",{ref:p.formats,code:c.code.formats}),i=n.const("fDef",t._`${a}[${o}]`),l=n.let("fType"),u=n.let("format");n.if(t._`typeof ${i} == "object" && !(${i} instanceof RegExp)`,()=>n.assign(l,t._`${i}.type || "string"`).assign(u,t._`${i}.validate`),()=>n.assign(l,t._`"string"`).assign(u,i)),e.fail$data((0,t.or)(!1===c.strictSchema?t.nil:t._`${o} && !${u}`,function(){let e=d.$async?t._`(${i}.async ? await ${u}(${s}) : ${u}(${s}))`:t._`${u}(${s})`,n=t._`(typeof ${u} == "function" ? ${e} : ${u}.test(${s}))`;return t._`${u} && ${u} !== true && ${l} === ${r} && !${n}`}()))}():function(){let a=p.formats[i];if(!a)return void function(){if(!1!==c.strictSchema)throw Error(e());function e(){return`unknown format "${i}" ignored in schema at path "${u}"`}p.logger.warn(e())}();if(!0===a)return;let[o,l,f]=function(e){let r=e instanceof RegExp?(0,t.regexpCode)(e):c.code.formats?t._`${c.code.formats}${(0,t.getProperty)(i)}`:void 0,s=n.scopeValue("formats",{key:i,ref:e,code:r});return"object"!=typeof e||e instanceof RegExp?["string",e,s]:[e.type||"string",e.validate,t._`${s}.validate`]}(a);o===r&&e.pass(function(){if("object"==typeof a&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error("async format in sync schema");return t._`await ${f}(${s})`}return"function"==typeof l?t._`${f}(${s})`:t._`${f}.test(${s})`}())}())}};e.default=r}),hn=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=[fn().default];e.default=t}),mn=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],e.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]}),gn=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=jr(),r=Wr(),n=pn(),s=hn(),a=mn(),i=[t.default,r.default,(0,n.default)(),s.default,a.metadataVocabulary,a.contentVocabulary];e.default=i}),yn=nr(e=>{var t,r;Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0,(r=t||(e.DiscrError=t={})).Tag="tag",r.Mapping="mapping"}),vn=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=or(),r=yn(),n=kr(),s=Sr(),a=lr(),i={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===r.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:r,tagName:n}})=>t._`{error: ${e}, tag: ${n}, tagValue: ${r}}`},code(e){let{gen:i,data:o,schema:l,parentSchema:c,it:u}=e,{oneOf:d}=c;if(!u.opts.discriminator)throw Error("discriminator: requires discriminator option");let p=l.propertyName;if("string"!=typeof p)throw Error("discriminator: requires propertyName");if(l.mapping)throw Error("discriminator: mapping is not supported");if(!d)throw Error("discriminator: requires oneOf keyword");let f=i.let("valid",!1),h=i.const("tag",t._`${o}${(0,t.getProperty)(p)}`);function m(r){let n=i.name("valid"),s=e.subschema({keyword:"oneOf",schemaProp:r},n);return e.mergeEvaluated(s,t.Name),n}i.if(t._`typeof ${h} == "string"`,()=>function(){let o=function(){var e;let t={},r=o(c),i=!0;for(let t=0;t<d.length;t++){let c=d[t];if((null==c?void 0:c.$ref)&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=n.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof n.SchemaEnv&&(c=c.schema),void 0===c)throw new s.default(u.opts.uriResolver,u.baseId,e)}let f=null===(e=null==c?void 0:c.properties)||void 0===e?void 0:e[p];if("object"!=typeof f)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${p}"`);i=i&&(r||o(c)),l(f,t)}if(!i)throw Error(`discriminator: "${p}" must be required`);return t;function o({required:e}){return Array.isArray(e)&&e.includes(p)}function l(e,t){if(e.const)f(e.const,t);else{if(!e.enum)throw Error(`discriminator: "properties/${p}" must have "const" or "enum"`);for(let r of e.enum)f(r,t)}}function f(e,r){if("string"!=typeof e||e in t)throw Error(`discriminator: "${p}" values must be unique strings`);t[e]=r}}();i.if(!1);for(let e in o)i.elseIf(t._`${h} === ${e}`),i.assign(f,m(o[e]));i.else(),e.error(!1,{discrError:r.DiscrError.Mapping,tag:h,tagName:p}),i.endIf()}(),()=>e.error(!1,{discrError:r.DiscrError.Tag,tag:h,tagName:p})),e.ok(f)}};e.default=i}),_n=nr((e,t)=>{t.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}}),bn=nr((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;var r=Ar(),n=gn(),s=vn(),a=_n(),i=["/properties"],o="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(s.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,i):a;this.addMetaSchema(e,o,!1),this.refs["http://json-schema.org/schema"]=o}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(o)?o:void 0)}}e.Ajv=l,t.exports=e=l,t.exports.Ajv=l,Object.defineProperty(e,"__esModule",{value:!0}),e.default=l;var c=Er();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=or();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=xr();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var p=Sr();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return p.default}})}),wn=nr(e=>{function t(e,t){return{validate:e,compare:t}}Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0,e.fullFormats={date:t(s,a),time:t(o(!0),l),"date-time":t(d(!0),p),"iso-time":t(o(),c),"iso-date-time":t(d(),f),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:function(e){return h.test(e)&&m.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:function(e){if(b.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}},uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:function(e){return g.lastIndex=0,g.test(e)},int32:{type:"number",validate:function(e){return Number.isInteger(e)&&e<=v&&e>=y}},int64:{type:"number",validate:function(e){return Number.isInteger(e)}},float:{type:"number",validate:_},double:{type:"number",validate:_},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,c),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,f),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);var r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,n=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(e){let t=r.exec(e);if(!t)return!1;let s=+t[1],a=+t[2],i=+t[3];return a>=1&&a<=12&&i>=1&&i<=(2===a&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(s)?29:n[a])}function a(e,t){if(e&&t)return e>t?1:e<t?-1:0}var i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function o(e){return function(t){let r=i.exec(t);if(!r)return!1;let n=+r[1],s=+r[2],a=+r[3],o=r[4],l="-"===r[5]?-1:1,c=+(r[6]||0),u=+(r[7]||0);if(c>23||u>59||e&&!o)return!1;if(n<=23&&s<=59&&a<60)return!0;let d=s-u*l,p=n-c*l-(d<0?1:0);return(23===p||-1===p)&&(59===d||-1===d)&&a<61}}function l(e,t){if(!e||!t)return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();return r&&n?r-n:void 0}function c(e,t){if(!e||!t)return;let r=i.exec(e),n=i.exec(t);return r&&n?(e=r[1]+r[2]+r[3])>(t=n[1]+n[2]+n[3])?1:e<t?-1:0:void 0}var u=/t|\s/i;function d(e){let t=o(e);return function(e){let r=e.split(u);return 2===r.length&&s(r[0])&&t(r[1])}}function p(e,t){if(!e||!t)return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();return r&&n?r-n:void 0}function f(e,t){if(!e||!t)return;let[r,n]=e.split(u),[s,i]=t.split(u),o=a(r,s);return void 0!==o?o||l(n,i):void 0}var h=/\/|:/,m=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,g=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm,y=-2147483648,v=2147483647;function _(){return!0}var b=/[^\\]\\Z/}),En=nr(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;var t=bn(),r=or(),n=r.operators,s={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},a={message:({keyword:e,schemaCode:t})=>r.str`should be ${s[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>r._`{comparison: ${s[e].okStr}, limit: ${t}}`};e.formatLimitDefinition={keyword:Object.keys(s),type:"string",schemaType:"string",$data:!0,error:a,code(e){let{gen:n,data:a,schemaCode:i,keyword:o,it:l}=e,{opts:c,self:u}=l;if(!c.validateFormats)return;let d=new t.KeywordCxt(l,u.RULES.all.format.definition,"format");function p(e){return r._`${e}.compare(${a}, ${i}) ${s[o].fail} 0`}d.$data?function(){let t=n.scopeValue("formats",{ref:u.formats,code:c.code.formats}),s=n.const("fmt",r._`${t}[${d.schemaCode}]`);e.fail$data((0,r.or)(r._`typeof ${s} != "object"`,r._`${s} instanceof RegExp`,r._`typeof ${s}.compare != "function"`,p(s)))}():function(){let t=d.schema,s=u.formats[t];if(!s||!0===s)return;if("object"!=typeof s||s instanceof RegExp||"function"!=typeof s.compare)throw Error(`"${o}": format "${t}" does not define "compare" function`);let a=n.scopeValue("formats",{key:t,ref:s,code:c.code.formats?r._`${c.code.formats}${(0,r.getProperty)(t)}`:void 0});e.fail$data(p(a))}()},dependencies:["format"]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)}),xn=nr((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var r=wn(),n=En(),s=or(),a=new s.Name("fullFormats"),i=new s.Name("fastFormats"),o=(e,t={keywords:!0})=>{if(Array.isArray(t))return l(e,t,r.fullFormats,a),e;let[s,o]="fast"===t.mode?[r.fastFormats,i]:[r.fullFormats,a];return l(e,t.formats||r.formatNames,s,o),t.keywords&&(0,n.default)(e),e};function l(e,t,r,n){var a,i;null!==(a=(i=e.opts.code).formats)&&void 0!==a||(i.formats=s._`require("ajv-formats/dist/formats").${n}`);for(let n of t)e.addFormat(n,r[n])}o.get=(e,t="full")=>{let n=("fast"===t?r.fastFormats:r.fullFormats)[e];if(!n)throw Error(`Unknown format "${e}"`);return n},t.exports=e=o,Object.defineProperty(e,"__esModule",{value:!0}),e.default=o});function Sn(e=50){let t=new AbortController;return d.setMaxListeners(e,t.signal),t}var kn,Tn="object"==typeof global&&global&&global.Object===Object&&global,In="object"==typeof self&&self&&self.Object===Object&&self,$n=Tn||In||Function("return this")(),Pn=$n.Symbol,Cn=Object.prototype,Rn=Cn.hasOwnProperty,An=Cn.toString,On=Pn?Pn.toStringTag:void 0,Nn=Object.prototype.toString,jn=Pn?Pn.toStringTag:void 0,Dn=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},Un=$n["__core-js_shared__"],Ln=(kn=/[^.]+$/.exec(Un&&Un.keys&&Un.keys.IE_PROTO||""))?"Symbol(src)_1."+kn:"",Mn=Function.prototype.toString,zn=/^\[object .+?Constructor\]$/,Bn=Function.prototype,Fn=Object.prototype,qn=Bn.toString,Hn=Fn.hasOwnProperty,Zn=RegExp("^"+qn.call(Hn).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Vn=function(e){return!(!Dn(e)||function(e){return!!Ln&&Ln in e}(e))&&(function(e){if(!Dn(e))return!1;var t=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":jn&&jn in Object(e)?function(e){var t=Rn.call(e,On),r=e[On];try{e[On]=void 0;var n=!0}catch(e){}var s=An.call(e);return n&&(t?e[On]=r:delete e[On]),s}(e):function(e){return Nn.call(e)}(e)}(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t}(e)?Zn:zn).test(function(e){if(null!=e){try{return Mn.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e))},Gn=function(e,t){var r=function(e,t){return null==e?void 0:e[t]}(e,t);return Vn(r)?r:void 0},Wn=Gn(Object,"create"),Kn=Object.prototype.hasOwnProperty,Yn=Object.prototype.hasOwnProperty;function Jn(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Jn.prototype.clear=function(){this.__data__=Wn?Wn(null):{},this.size=0},Jn.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},Jn.prototype.get=function(e){var t=this.__data__;if(Wn){var r=t[e];return"__lodash_hash_undefined__"===r?void 0:r}return Kn.call(t,e)?t[e]:void 0},Jn.prototype.has=function(e){var t=this.__data__;return Wn?void 0!==t[e]:Yn.call(t,e)},Jn.prototype.set=function(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Wn&&void 0===t?"__lodash_hash_undefined__":t,this};var Qn=Jn,Xn=function(e,t){return e===t||e!=e&&t!=t},es=function(e,t){for(var r=e.length;r--;)if(Xn(e[r][0],t))return r;return-1},ts=Array.prototype.splice;function rs(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}rs.prototype.clear=function(){this.__data__=[],this.size=0},rs.prototype.delete=function(e){var t=this.__data__,r=es(t,e);return!(r<0||(r==t.length-1?t.pop():ts.call(t,r,1),--this.size,0))},rs.prototype.get=function(e){var t=this.__data__,r=es(t,e);return r<0?void 0:t[r][1]},rs.prototype.has=function(e){return es(this.__data__,e)>-1},rs.prototype.set=function(e,t){var r=this.__data__,n=es(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this};var ns=rs,ss=Gn($n,"Map"),as=function(e,t){var r=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?r["string"==typeof t?"string":"hash"]:r.map};function is(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}is.prototype.clear=function(){this.size=0,this.__data__={hash:new Qn,map:new(ss||ns),string:new Qn}},is.prototype.delete=function(e){var t=as(this,e).delete(e);return this.size-=t?1:0,t},is.prototype.get=function(e){return as(this,e).get(e)},is.prototype.has=function(e){return as(this,e).has(e)},is.prototype.set=function(e,t){var r=as(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this};var os=is;function ls(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw TypeError("Expected a function");var r=function(){var n=arguments,s=t?t.apply(this,n):n[0],a=r.cache;if(a.has(s))return a.get(s);var i=e.apply(this,n);return r.cache=a.set(s,i)||a,i};return r.cache=new(ls.Cache||os),r}ls.Cache=os;var cs=ls,us=cs(e=>{if(!e||""===e.trim())return null;let t=e.split(",").map(e=>e.trim()).filter(Boolean);if(0===t.length)return null;let r=t.some(e=>e.startsWith("!")),n=t.some(e=>!e.startsWith("!"));if(r&&n)return null;let s=t.map(e=>e.replace(/^!/,"").toLowerCase());return{include:r?[]:s,exclude:r?s:[],isExclusive:r}});function ds(){return process.env.CLAUDE_CONFIG_DIR??t.join(l.homedir(),".claude")}function ps(e){if(!e)return!1;if("boolean"==typeof e)return e;let t=e.toLowerCase().trim();return["1","true","yes","on"].includes(t)}var fs={name:"BASH_MAX_OUTPUT_LENGTH",default:3e4,validate:e=>{if(!e)return{effective:3e4,status:"valid"};let t=parseInt(e,10);return isNaN(t)||t<=0?{effective:3e4,status:"invalid",message:`Invalid value "${e}" (using default: 30000)`}:t>15e4?{effective:15e4,status:"capped",message:`Capped from ${t} to 150000`}:{effective:t,status:"valid"}}},hs={name:"CLAUDE_CODE_MAX_OUTPUT_TOKENS",default:32e3,validate:e=>{if(!e)return{effective:32e3,status:"valid"};let t=parseInt(e,10);return isNaN(t)||t<=0?{effective:32e3,status:"invalid",message:`Invalid value "${e}" (using default: 32000)`}:t>64e3?{effective:64e3,status:"capped",message:`Capped from ${t} to 64000`}:{effective:t,status:"valid"}}},ms=function(){let e="";return typeof process<"u"&&"function"==typeof process.cwd&&"function"==typeof i.realpathSync&&(e=i.realpathSync(a.cwd())),{originalCwd:e,projectRoot:e,totalCostUSD:0,totalAPIDuration:0,totalAPIDurationWithoutRetries:0,totalToolDuration:0,startTime:Date.now(),lastInteractionTime:Date.now(),totalLinesAdded:0,totalLinesRemoved:0,hasUnknownModelCost:!1,cwd:e,modelUsage:{},mainLoopModelOverride:void 0,initialMainLoopModel:null,modelStrings:null,isInteractive:!1,clientType:"cli",sessionIngressToken:void 0,oauthTokenFromFd:void 0,apiKeyFromFd:void 0,flagSettingsPath:void 0,allowedSettingSources:["userSettings","projectSettings","localSettings","flagSettings","policySettings"],meter:null,sessionCounter:null,locCounter:null,prCounter:null,commitCounter:null,costCounter:null,tokenCounter:null,codeEditToolDecisionCounter:null,activeTimeCounter:null,sessionId:h.randomUUID(),parentSessionId:void 0,loggerProvider:null,eventLogger:null,meterProvider:null,tracerProvider:null,agentColorMap:new Map,agentColorIndex:0,envVarValidators:[fs,hs],lastAPIRequest:null,inMemoryErrorLog:[],inlinePlugins:[],useCoworkPlugins:!1,sessionBypassPermissionsMode:!1,sessionTrustAccepted:!1,sessionPersistenceDisabled:!1,hasExitedPlanMode:!1,needsPlanModeExitAttachment:!1,hasExitedDelegateMode:!1,needsDelegateModeExitAttachment:!1,lspRecommendationShownThisSession:!1,initJsonSchema:null,registeredHooks:null,planSlugCache:new Map,teleportedSessionInfo:null,invokedSkills:new Map,slowOperations:[],promptCacheBreaks:[],sdkBetas:void 0,mainThreadAgentType:void 0,isRemoteMode:!1,directConnectServerUrl:void 0,systemPromptSectionCache:new Map,additionalDirectoriesForClaudeMd:[],resumedTranscriptPath:null}}(),gs=new Set;function ys(e,t){performance.now();try{return t()}finally{performance.now()}}function vs(e,t,r){return function(e){null==e||(Array.isArray(e)?e.length:"object"==typeof e?Object.keys(e).length:"string"==typeof e&&e.length)}(e),ys(0,()=>JSON.stringify(e,t,r))}var _s=(e,t)=>("string"==typeof e&&e.length,ys(0,()=>JSON.parse(e,t))),bs=cs(()=>ps(process.env.DEBUG)||ps(process.env.DEBUG_SDK)||process.argv.includes("--debug")||process.argv.includes("-d")||Es()||process.argv.some(e=>e.startsWith("--debug="))||null!==xs()),ws=cs(()=>{let e=process.argv.find(e=>e.startsWith("--debug="));if(!e)return null;let t=e.substring(8);return us(t)}),Es=cs(()=>process.argv.includes("--debug-to-stderr")||process.argv.includes("-d2e")),xs=cs(()=>{for(let e=0;e<process.argv.length;e++){let t=process.argv[e];if(t.startsWith("--debug-file="))return t.substring(13);if("--debug-file"===t&&e+1<process.argv.length)return process.argv[e+1]}return null}),Ss=null;function ks(e,{level:r}={level:"debug"}){if(!function(e){return!(typeof process>"u"||typeof process.versions>"u"||typeof process.versions.node>"u")&&function(e,t){if(!t)return!0;let r=function(e){let t=[],r=e.match(/^MCP server ["']([^"']+)["']/);if(r&&r[1])t.push("mcp"),t.push(r[1].toLowerCase());else{let r=e.match(/^([^:[]+):/);r&&r[1]&&t.push(r[1].trim().toLowerCase())}let n=e.match(/^\[([^\]]+)]/);n&&n[1]&&t.push(n[1].trim().toLowerCase()),e.toLowerCase().includes("1p event:")&&t.push("1p");let s=e.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/);if(s&&s[1]){let e=s[1].trim().toLowerCase();e.length<30&&!e.includes(" ")&&t.push(e)}return Array.from(new Set(t))}(e);return function(e,t){return!t||0!==e.length&&(t.isExclusive?!e.some(e=>t.exclude.includes(e)):e.some(e=>t.include.includes(e)))}(r,t)}(e,ws())}(e))return;let n=`${(new Date).toISOString()} [${r.toUpperCase()}] ${e.trim()}\n`;Es()?function(e){!function(e,t){e.destroyed||e.write(t)}(process.stderr,e)}(n):(Ss||(Ss=function({writeFn:e,flushIntervalMs:t=1e3,maxBufferSize:r=100,immediateMode:n=!1}){let s=[],a=null;function i(){0!==s.length&&(e(s.join("")),s=[],a&&(clearTimeout(a),a=null))}return{write(o){n?e(o):(s.push(o),a||(a=setTimeout(i,t)),s.length>=r&&i())},flush:i,dispose(){i()}}}({writeFn:e=>{let r=Ts();Rs().existsSync(t.dirname(r))||Rs().mkdirSync(t.dirname(r)),Rs().appendFileSync(r,e),Is()},flushIntervalMs:1e3,maxBufferSize:100,immediateMode:bs()}),gs.add(async()=>Ss?.dispose())),Ss).write(n)}function Ts(){return xs()??process.env.CLAUDE_CODE_DEBUG_LOGS_DIR??t.join(ds(),"debug",`${ms.sessionId}.txt`)}var Is=cs(()=>{if("--ripgrep"!==process.argv[2])try{let e=Ts(),r=t.dirname(e),n=t.join(r,"latest");if(Rs().existsSync(r)||Rs().mkdirSync(r),Rs().existsSync(n))try{Rs().unlinkSync(n)}catch{}Rs().symlinkSync(e,n)}catch{}});function $s(e,t){performance.now();try{return t()}finally{performance.now()}}var Ps={cwd:()=>process.cwd(),existsSync:e=>$s(0,()=>M.existsSync(e)),stat:async e=>f.stat(e),readdir:async e=>f.readdir(e,{withFileTypes:!0}),unlink:async e=>f.unlink(e),rmdir:async e=>f.rmdir(e),rm:async(e,t)=>f.rm(e,t),statSync:e=>$s(0,()=>M.statSync(e)),lstatSync:e=>$s(0,()=>M.lstatSync(e)),readFileSync:(e,t)=>$s(0,()=>M.readFileSync(e,{encoding:t.encoding})),readFileBytesSync:e=>$s(0,()=>M.readFileSync(e)),readSync:(e,t)=>$s(t.length,()=>{let r;try{r=M.openSync(e,"r");let n=Buffer.alloc(t.length);return{buffer:n,bytesRead:M.readSync(r,n,0,t.length,0)}}finally{r&&M.closeSync(r)}}),appendFileSync:(e,t,r)=>$s(t.length,()=>{if(M.existsSync(e)||void 0===r?.mode)M.appendFileSync(e,t);else{let n=M.openSync(e,"a",r.mode);try{M.appendFileSync(n,t)}finally{M.closeSync(n)}}}),copyFileSync:(e,t)=>$s(0,()=>M.copyFileSync(e,t)),unlinkSync:e=>$s(0,()=>M.unlinkSync(e)),renameSync:(e,t)=>$s(0,()=>M.renameSync(e,t)),linkSync:(e,t)=>$s(0,()=>M.linkSync(e,t)),symlinkSync:(e,t)=>$s(0,()=>M.symlinkSync(e,t)),readlinkSync:e=>$s(0,()=>M.readlinkSync(e)),realpathSync:e=>$s(0,()=>M.realpathSync(e)),mkdirSync:(e,t)=>$s(0,()=>{if(!M.existsSync(e)){let r={recursive:!0};void 0!==t?.mode&&(r.mode=t.mode),M.mkdirSync(e,r)}}),readdirSync:e=>$s(0,()=>M.readdirSync(e,{withFileTypes:!0})),readdirStringSync:e=>$s(0,()=>M.readdirSync(e)),isDirEmptySync(e){return $s(0,()=>0===this.readdirSync(e).length)},rmdirSync:e=>$s(0,()=>M.rmdirSync(e)),rmSync:(e,t)=>$s(0,()=>M.rmSync(e,t)),createWriteStream:e=>M.createWriteStream(e)},Cs=Ps;function Rs(){return Cs}var As=class extends Error{};function Os(){return void 0!==process.versions.bun}var Ns=null,js=!1;function Ds(e){let r=function(){if(js)return Ns;if(js=!0,!process.env.DEBUG_CLAUDE_AGENT_SDK)return null;let e=t.join(ds(),"debug");return Ns=t.join(e,`sdk-${h.randomUUID()}.txt`),i.existsSync(e)||i.mkdirSync(e,{recursive:!0}),process.stderr.write(`SDK debug logs: ${Ns}\n`),Ns}();if(!r)return;let n=`${(new Date).toISOString()} ${e}\n`;i.appendFileSync(r,n)}var Us,Ls,Ms=class{options;process;processStdin;processStdout;ready=!1;abortController;exitError;exitListeners=[];processExitHandler;abortHandler;constructor(e){this.options=e,this.abortController=e.abortController||Sn(),this.initialize()}getDefaultExecutable(){return Os()?"bun":"node"}spawnLocalProcess(e){let{command:t,args:r,cwd:n,env:a,signal:i}=e,o=a.DEBUG_CLAUDE_AGENT_SDK||this.options.stderr?"pipe":"ignore",l=s.spawn(t,r,{cwd:n,stdio:["pipe","pipe",o],signal:i,env:a,windowsHide:!0});return(a.DEBUG_CLAUDE_AGENT_SDK||this.options.stderr)&&l.stderr.on("data",e=>{let t=e.toString();Ds(t),this.options.stderr&&this.options.stderr(t)}),{stdin:l.stdin,stdout:l.stdout,get killed(){return l.killed},get exitCode(){return l.exitCode},kill:l.kill.bind(l),on:l.on.bind(l),once:l.once.bind(l),off:l.off.bind(l)}}initialize(){try{let{additionalDirectories:e=[],agent:t,betas:r,cwd:n,executable:s=this.getDefaultExecutable(),executableArgs:a=[],extraArgs:i={},pathToClaudeCodeExecutable:o,env:l={...process.env},maxThinkingTokens:c,maxTurns:u,maxBudgetUsd:d,model:p,fallbackModel:f,jsonSchema:h,permissionMode:m,allowDangerouslySkipPermissions:g,permissionPromptToolName:y,continueConversation:v,resume:_,settingSources:b,allowedTools:w=[],disallowedTools:E=[],tools:x,mcpServers:S,strictMcpConfig:k,canUseTool:T,includePartialMessages:I,plugins:$,sandbox:P}=this.options,C=["--output-format","stream-json","--verbose","--input-format","stream-json"];if(void 0!==c&&C.push("--max-thinking-tokens",c.toString()),u&&C.push("--max-turns",u.toString()),void 0!==d&&C.push("--max-budget-usd",d.toString()),p&&C.push("--model",p),t&&C.push("--agent",t),r&&r.length>0&&C.push("--betas",r.join(",")),h&&C.push("--json-schema",vs(h)),this.options.debugFile?C.push("--debug-file",this.options.debugFile):this.options.debug&&C.push("--debug"),l.DEBUG_CLAUDE_AGENT_SDK&&C.push("--debug-to-stderr"),T){if(y)throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");C.push("--permission-prompt-tool","stdio")}else y&&C.push("--permission-prompt-tool",y);if(v&&C.push("--continue"),_&&C.push("--resume",_),w.length>0&&C.push("--allowedTools",w.join(",")),E.length>0&&C.push("--disallowedTools",E.join(",")),void 0!==x&&(Array.isArray(x)?0===x.length?C.push("--tools",""):C.push("--tools",x.join(",")):C.push("--tools","default")),S&&Object.keys(S).length>0&&C.push("--mcp-config",vs({mcpServers:S})),b&&C.push("--setting-sources",b.join(",")),k&&C.push("--strict-mcp-config"),m&&C.push("--permission-mode",m),g&&C.push("--allow-dangerously-skip-permissions"),f){if(p&&f===p)throw Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");C.push("--fallback-model",f)}I&&C.push("--include-partial-messages");for(let t of e)C.push("--add-dir",t);if($&&$.length>0)for(let e of $){if("local"!==e.type)throw Error(`Unsupported plugin type: ${e.type}`);C.push("--plugin-dir",e.path)}this.options.forkSession&&C.push("--fork-session"),this.options.resumeSessionAt&&C.push("--resume-session-at",this.options.resumeSessionAt),this.options.sessionId&&C.push("--session-id",this.options.sessionId),!1===this.options.persistSession&&C.push("--no-session-persistence");let R=function(e,t){let r={...e};if(t){let e={sandbox:t};if(r.settings)try{e={..._s(r.settings),sandbox:t}}catch{}r.settings=vs(e)}return r}(i??{},P);for(let[e,t]of Object.entries(R))null===t?C.push(`--${e}`):C.push(`--${e}`,t);l.CLAUDE_CODE_ENTRYPOINT||(l.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),delete l.NODE_OPTIONS,l.DEBUG_CLAUDE_AGENT_SDK?l.DEBUG="1":delete l.DEBUG;let A=function(e){return![".js",".mjs",".tsx",".ts",".jsx"].some(t=>e.endsWith(t))}(o),O=A?o:s,N=A?[...a,...C]:[...a,o,...C],j={command:O,args:N,cwd:n,env:l,signal:this.abortController.signal};if(this.options.spawnClaudeCodeProcess)Ds(`Spawning Claude Code (custom): ${O} ${N.join(" ")}`),this.process=this.options.spawnClaudeCodeProcess(j);else{if(!Rs().existsSync(o)){let e=A?`Claude Code native binary not found at ${o}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.`:`Claude Code executable not found at ${o}. Is options.pathToClaudeCodeExecutable set?`;throw ReferenceError(e)}Ds(`Spawning Claude Code: ${O} ${N.join(" ")}`),this.process=this.spawnLocalProcess(j)}this.processStdin=this.process.stdin,this.processStdout=this.process.stdout;let D=()=>{this.process&&!this.process.killed&&this.process.kill("SIGTERM")};this.processExitHandler=D,this.abortHandler=D,process.on("exit",this.processExitHandler),this.abortController.signal.addEventListener("abort",this.abortHandler),this.process.on("error",e=>{this.ready=!1,this.abortController.signal.aborted?this.exitError=new As("Claude Code process aborted by user"):(this.exitError=Error(`Failed to spawn Claude Code process: ${e.message}`),Ds(this.exitError.message))}),this.process.on("exit",(e,t)=>{if(this.ready=!1,this.abortController.signal.aborted)this.exitError=new As("Claude Code process aborted by user");else{let r=this.getProcessExitError(e,t);r&&(this.exitError=r,Ds(r.message))}}),this.ready=!0}catch(e){throw this.ready=!1,e}}getProcessExitError(e,t){return 0!==e&&null!==e?Error(`Claude Code process exited with code ${e}`):t?Error(`Claude Code process terminated by signal ${t}`):void 0}write(e){if(this.abortController.signal.aborted)throw new As("Operation aborted");if(!this.ready||!this.processStdin)throw Error("ProcessTransport is not ready for writing");if(this.process?.killed||null!==this.process?.exitCode)throw Error("Cannot write to terminated process");if(this.exitError)throw Error(`Cannot write to process that exited with error: ${this.exitError.message}`);Ds(`[ProcessTransport] Writing to stdin: ${e.substring(0,100)}`);try{this.processStdin.write(e)||Ds("[ProcessTransport] Write buffer full, data queued")}catch(e){throw this.ready=!1,Error(`Failed to write to process stdin: ${e.message}`)}}close(){this.processStdin&&(this.processStdin.end(),this.processStdin=void 0),this.abortHandler&&(this.abortController.signal.removeEventListener("abort",this.abortHandler),this.abortHandler=void 0);for(let{handler:e}of this.exitListeners)this.process?.off("exit",e);this.exitListeners=[],this.process&&!this.process.killed&&(this.process.kill("SIGTERM"),setTimeout(()=>{this.process&&!this.process.killed&&this.process.kill("SIGKILL")},5e3)),this.ready=!1,this.processExitHandler&&(process.off("exit",this.processExitHandler),this.processExitHandler=void 0)}isReady(){return this.ready}async*readMessages(){if(!this.processStdout)throw Error("ProcessTransport output stream not available");let e=p.createInterface({input:this.processStdout});try{for await(let t of e)if(t.trim())try{yield _s(t)}catch(e){throw Ds(`Non-JSON stdout: ${t}`),Error(`CLI output was not valid JSON. This may indicate an error during startup. Output: ${t.slice(0,200)}${t.length>200?"...":""}`)}await this.waitForExit()}catch(e){throw e}finally{e.close()}}endInput(){this.processStdin&&this.processStdin.end()}getInputStream(){return this.processStdin}onExit(e){if(!this.process)return()=>{};let t=(t,r)=>{let n=this.getProcessExitError(t,r);e(n)};return this.process.on("exit",t),this.exitListeners.push({callback:e,handler:t}),()=>{this.process&&this.process.off("exit",t);let e=this.exitListeners.findIndex(e=>e.handler===t);-1!==e&&this.exitListeners.splice(e,1)}}async waitForExit(){if(this.process){if(null===this.process.exitCode&&!this.process.killed)return new Promise((e,t)=>{let r=(r,n)=>{if(this.abortController.signal.aborted)return void t(new As("Operation aborted"));let s=this.getProcessExitError(r,n);s?t(s):e()};this.process.once("exit",r);let n=e=>{this.process.off("exit",r),t(e)};this.process.once("error",n),this.process.once("exit",()=>{this.process.off("error",n)})});if(this.exitError)throw this.exitError}else if(this.exitError)throw this.exitError}},zs=class{returned;queue=[];readResolve;readReject;isDone=!1;hasError;started=!1;constructor(e){this.returned=e}[Symbol.asyncIterator](){if(this.started)throw Error("Stream can only be iterated once");return this.started=!0,this}next(){return this.queue.length>0?Promise.resolve({done:!1,value:this.queue.shift()}):this.isDone?Promise.resolve({done:!0,value:void 0}):this.hasError?Promise.reject(this.hasError):new Promise((e,t)=>{this.readResolve=e,this.readReject=t})}enqueue(e){if(this.readResolve){let t=this.readResolve;this.readResolve=void 0,this.readReject=void 0,t({done:!1,value:e})}else this.queue.push(e)}done(){if(this.isDone=!0,this.readResolve){let e=this.readResolve;this.readResolve=void 0,this.readReject=void 0,e({done:!0,value:void 0})}}error(e){if(this.hasError=e,this.readReject){let t=this.readReject;this.readResolve=void 0,this.readReject=void 0,t(e)}}return(){return this.isDone=!0,this.returned&&this.returned(),Promise.resolve({done:!0,value:void 0})}},Bs=class{sendMcpMessage;isClosed=!1;constructor(e){this.sendMcpMessage=e}onclose;onerror;onmessage;async start(){}async send(e){if(this.isClosed)throw Error("Transport is closed");this.sendMcpMessage(e)}async close(){this.isClosed||(this.isClosed=!0,this.onclose?.())}},Fs=class{transport;isSingleUserTurn;canUseTool;hooks;abortController;jsonSchema;initConfig;pendingControlResponses=new Map;cleanupPerformed=!1;sdkMessages;inputStream=new zs;initialization;cancelControllers=new Map;hookCallbacks=new Map;nextCallbackId=0;sdkMcpTransports=new Map;sdkMcpServerInstances=new Map;pendingMcpResponses=new Map;firstResultReceivedResolve;firstResultReceived=!1;hasBidirectionalNeeds(){return this.sdkMcpTransports.size>0||void 0!==this.hooks&&Object.keys(this.hooks).length>0||void 0!==this.canUseTool}constructor(e,t,r,n,s,a=new Map,i,o){this.transport=e,this.isSingleUserTurn=t,this.canUseTool=r,this.hooks=n,this.abortController=s,this.jsonSchema=i,this.initConfig=o;for(let[e,t]of a)this.connectSdkMcpServer(e,t);this.sdkMessages=this.readSdkMessages(),this.readMessages(),this.initialization=this.initialize(),this.initialization.catch(()=>{})}setError(e){this.inputStream.error(e)}close(){this.cleanup()}cleanup(e){if(!this.cleanupPerformed){this.cleanupPerformed=!0;try{this.transport.close(),this.pendingControlResponses.clear(),this.pendingMcpResponses.clear(),this.cancelControllers.clear(),this.hookCallbacks.clear();for(let e of this.sdkMcpTransports.values())try{e.close()}catch{}this.sdkMcpTransports.clear(),e?this.inputStream.error(e):this.inputStream.done()}catch(e){}}}next(...[e]){return this.sdkMessages.next(e)}return(e){return this.sdkMessages.return(e)}throw(e){return this.sdkMessages.throw(e)}[Symbol.asyncIterator](){return this.sdkMessages}[Symbol.asyncDispose](){return this.sdkMessages[Symbol.asyncDispose]()}async readMessages(){try{for await(let e of this.transport.readMessages()){if("control_response"===e.type){let t=this.pendingControlResponses.get(e.response.request_id);t&&t(e.response);continue}"control_request"!==e.type?"control_cancel_request"!==e.type?"keep_alive"!==e.type&&"streamlined_text"!==e.type&&"streamlined_tool_use_summary"!==e.type&&("result"===e.type&&(this.firstResultReceived=!0,this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.isSingleUserTurn&&(ks("[Query.readMessages] First result received for single-turn query, closing stdin"),this.transport.endInput())),this.inputStream.enqueue(e)):this.handleControlCancelRequest(e):this.handleControlRequest(e)}this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.inputStream.done(),this.cleanup()}catch(e){this.firstResultReceivedResolve&&this.firstResultReceivedResolve(),this.inputStream.error(e),this.cleanup(e)}}async handleControlRequest(e){let t=new AbortController;this.cancelControllers.set(e.request_id,t);try{let r=await this.processControlRequest(e,t.signal),n={type:"control_response",response:{subtype:"success",request_id:e.request_id,response:r}};await Promise.resolve(this.transport.write(vs(n)+"\n"))}catch(t){let r={type:"control_response",response:{subtype:"error",request_id:e.request_id,error:t.message||String(t)}};await Promise.resolve(this.transport.write(vs(r)+"\n"))}finally{this.cancelControllers.delete(e.request_id)}}handleControlCancelRequest(e){let t=this.cancelControllers.get(e.request_id);t&&(t.abort(),this.cancelControllers.delete(e.request_id))}async processControlRequest(e,t){if("can_use_tool"===e.request.subtype){if(!this.canUseTool)throw Error("canUseTool callback is not provided.");return{...await this.canUseTool(e.request.tool_name,e.request.input,{signal:t,suggestions:e.request.permission_suggestions,blockedPath:e.request.blocked_path,decisionReason:e.request.decision_reason,toolUseID:e.request.tool_use_id,agentID:e.request.agent_id}),toolUseID:e.request.tool_use_id}}if("hook_callback"===e.request.subtype)return await this.handleHookCallbacks(e.request.callback_id,e.request.input,e.request.tool_use_id,t);if("mcp_message"===e.request.subtype){let t=e.request,r=this.sdkMcpTransports.get(t.server_name);if(!r)throw Error(`SDK MCP server not found: ${t.server_name}`);return"method"in t.message&&"id"in t.message&&null!==t.message.id?{mcp_response:await this.handleMcpControlRequest(t.server_name,t,r)}:(r.onmessage&&r.onmessage(t.message),{mcp_response:{jsonrpc:"2.0",result:{},id:0}})}throw Error("Unsupported control request subtype: "+e.request.subtype)}async*readSdkMessages(){for await(let e of this.inputStream)yield e}async initialize(){let e;if(this.hooks){e={};for(let[t,r]of Object.entries(this.hooks))r.length>0&&(e[t]=r.map(e=>{let t=[];for(let r of e.hooks){let e="hook_"+this.nextCallbackId++;this.hookCallbacks.set(e,r),t.push(e)}return{matcher:e.matcher,hookCallbackIds:t,timeout:e.timeout}}))}let t={subtype:"initialize",hooks:e,sdkMcpServers:this.sdkMcpTransports.size>0?Array.from(this.sdkMcpTransports.keys()):void 0,jsonSchema:this.jsonSchema,systemPrompt:this.initConfig?.systemPrompt,appendSystemPrompt:this.initConfig?.appendSystemPrompt,agents:this.initConfig?.agents};return(await this.request(t)).response}async interrupt(){await this.request({subtype:"interrupt"})}async setPermissionMode(e){await this.request({subtype:"set_permission_mode",mode:e})}async setModel(e){await this.request({subtype:"set_model",model:e})}async setMaxThinkingTokens(e){await this.request({subtype:"set_max_thinking_tokens",max_thinking_tokens:e})}async rewindFiles(e,t){return(await this.request({subtype:"rewind_files",user_message_id:e,dry_run:t?.dryRun})).response}async processPendingPermissionRequests(e){for(let t of e)"can_use_tool"===t.request.subtype&&this.handleControlRequest(t).catch(()=>{})}request(e){let t=Math.random().toString(36).substring(2,15),r={request_id:t,type:"control_request",request:e};return new Promise((e,n)=>{this.pendingControlResponses.set(t,t=>{"success"===t.subtype?e(t):(n(Error(t.error)),t.pending_permission_requests&&this.processPendingPermissionRequests(t.pending_permission_requests))}),Promise.resolve(this.transport.write(vs(r)+"\n"))})}async initializationResult(){return this.initialization}async supportedCommands(){return(await this.initialization).commands}async supportedModels(){return(await this.initialization).models}async reconnectMcpServer(e){await this.request({subtype:"mcp_reconnect",serverName:e})}async toggleMcpServer(e,t){await this.request({subtype:"mcp_toggle",serverName:e,enabled:t})}async mcpServerStatus(){return(await this.request({subtype:"mcp_status"})).response.mcpServers}async setMcpServers(e){let t={},r={};for(let[n,s]of Object.entries(e))"sdk"===s.type&&"instance"in s?t[n]=s.instance:r[n]=s;let n=new Set(this.sdkMcpServerInstances.keys()),s=new Set(Object.keys(t));for(let e of n)s.has(e)||await this.disconnectSdkMcpServer(e);for(let[e,r]of Object.entries(t))n.has(e)||this.connectSdkMcpServer(e,r);let a={};for(let e of Object.keys(t))a[e]={type:"sdk",name:e};return(await this.request({subtype:"mcp_set_servers",servers:{...r,...a}})).response}async accountInfo(){return(await this.initialization).account}async streamInput(e){ks("[Query.streamInput] Starting to process input stream");try{let t=0;for await(let r of e){if(t++,ks(`[Query.streamInput] Processing message ${t}: ${r.type}`),this.abortController?.signal.aborted)break;await Promise.resolve(this.transport.write(vs(r)+"\n"))}ks(`[Query.streamInput] Finished processing ${t} messages from input stream`),t>0&&this.hasBidirectionalNeeds()&&(ks("[Query.streamInput] Has bidirectional needs, waiting for first result"),await this.waitForFirstResult()),ks("[Query] Calling transport.endInput() to close stdin to CLI process"),this.transport.endInput()}catch(e){if(!(e instanceof As))throw e}}waitForFirstResult(){return this.firstResultReceived?(ks("[Query.waitForFirstResult] Result already received, returning immediately"),Promise.resolve()):new Promise(e=>{this.abortController?.signal.aborted?e():(this.abortController?.signal.addEventListener("abort",()=>e(),{once:!0}),this.firstResultReceivedResolve=e)})}handleHookCallbacks(e,t,r,n){let s=this.hookCallbacks.get(e);if(!s)throw Error(`No hook callback found for ID: ${e}`);return s(t,r,{signal:n})}connectSdkMcpServer(e,t){let r=new Bs(t=>this.sendMcpServerMessageToCli(e,t));this.sdkMcpTransports.set(e,r),this.sdkMcpServerInstances.set(e,t),t.connect(r)}async disconnectSdkMcpServer(e){let t=this.sdkMcpTransports.get(e);t&&(await t.close(),this.sdkMcpTransports.delete(e)),this.sdkMcpServerInstances.delete(e)}sendMcpServerMessageToCli(e,t){if("id"in t&&null!==t.id&&void 0!==t.id){let r=`${e}:${t.id}`,n=this.pendingMcpResponses.get(r);if(n)return n.resolve(t),void this.pendingMcpResponses.delete(r)}let r={type:"control_request",request_id:h.randomUUID(),request:{subtype:"mcp_message",server_name:e,message:t}};this.transport.write(vs(r)+"\n")}handleMcpControlRequest(e,t,r){let n=`${e}:${"id"in t.message?t.message.id:null}`;return new Promise((e,s)=>{let a=()=>{this.pendingMcpResponses.delete(n)};if(this.pendingMcpResponses.set(n,{resolve:t=>{a(),e(t)},reject:e=>{a(),s(e)}}),!r.onmessage)return a(),void s(Error("No message handler registered"));r.onmessage(t.message)})}};!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw Error()},e.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},e.getValidEnumValues=t=>{let r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),n={};for(let e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(let r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(Us||(Us={})),(Ls||(Ls={})).mergeShapes=(e,t)=>({...e,...t});var qs=Us.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Hs=e=>{switch(typeof e){case"undefined":return qs.undefined;case"string":return qs.string;case"number":return Number.isNaN(e)?qs.nan:qs.number;case"boolean":return qs.boolean;case"function":return qs.function;case"bigint":return qs.bigint;case"symbol":return qs.symbol;case"object":return Array.isArray(e)?qs.array:null===e?qs.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?qs.promise:typeof Map<"u"&&e instanceof Map?qs.map:typeof Set<"u"&&e instanceof Set?qs.set:typeof Date<"u"&&e instanceof Date?qs.date:qs.object;default:return qs.unknown}},Zs=Us.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Vs=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(let s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,n=0;for(;n<s.path.length;){let r=s.path[n];n!==s.path.length-1?e[r]=e[r]||{_errors:[]}:(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))),e=e[r],n++}}};return n(this),r}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Us.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){let t={},r=[];for(let n of this.issues)if(n.path.length>0){let r=n.path[0];t[r]=t[r]||[],t[r].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};Vs.create=e=>new Vs(e);var Gs=(e,t)=>{let r;switch(e.code){case Zs.invalid_type:r=e.received===qs.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Zs.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Us.jsonStringifyReplacer)}`;break;case Zs.unrecognized_keys:r=`Unrecognized key(s) in object: ${Us.joinValues(e.keys,", ")}`;break;case Zs.invalid_union:r="Invalid input";break;case Zs.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Us.joinValues(e.options)}`;break;case Zs.invalid_enum_value:r=`Invalid enum value. Expected ${Us.joinValues(e.options)}, received '${e.received}'`;break;case Zs.invalid_arguments:r="Invalid function arguments";break;case Zs.invalid_return_type:r="Invalid function return type";break;case Zs.invalid_date:r="Invalid date";break;case Zs.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Us.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Zs.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case Zs.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case Zs.custom:r="Invalid input";break;case Zs.invalid_intersection_types:r="Intersection results could not be merged";break;case Zs.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case Zs.not_finite:r="Number must be finite";break;default:r=t.defaultError,Us.assertNever(e)}return{message:r}},Ws=Gs;function Ks(e,t){let r=Ws,n=(e=>{let{data:t,path:r,errorMaps:n,issueData:s}=e,a=[...r,...s.path||[]],i={...s,path:a};if(void 0!==s.message)return{...s,path:a,message:s.message};let o="",l=n.filter(e=>!!e).slice().reverse();for(let e of l)o=e(i,{data:t,defaultError:o}).message;return{...s,path:a,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Gs?void 0:Gs].filter(e=>!!e)});e.common.issues.push(n)}var Ys,Js=class e{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let n of t){if("aborted"===n.status)return Qs;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(t,r){let n=[];for(let e of r){let t=await e.key,r=await e.value;n.push({key:t,value:r})}return e.mergeObjectSync(t,n)}static mergeObjectSync(e,t){let r={};for(let n of t){let{key:t,value:s}=n;if("aborted"===t.status)return Qs;if("aborted"===s.status)return Qs;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"!==t.value&&(typeof s.value<"u"||n.alwaysSet)&&(r[t.value]=s.value)}return{status:e.value,value:r}}},Qs=Object.freeze({status:"aborted"}),Xs=e=>({status:"dirty",value:e}),ea=e=>({status:"valid",value:e}),ta=e=>"aborted"===e.status,ra=e=>"dirty"===e.status,na=e=>"valid"===e.status,sa=e=>typeof Promise<"u"&&e instanceof Promise;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(Ys||(Ys={}));var aa=class{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ia=(e,t)=>{if(na(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new Vs(e.common.issues);return this._error=t,this._error}}};function oa(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:s}:{errorMap:(t,s)=>{let{message:a}=e;return"invalid_enum_value"===t.code?{message:a??s.defaultError}:typeof s.data>"u"?{message:a??n??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:a??r??s.defaultError}},description:s}}var la,ca=class{get description(){return this._def.description}_getType(e){return Hs(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Hs(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Js,ctx:{common:e.parent.common,data:e.data,parsedType:Hs(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(sa(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Hs(e)},n=this._parseSync({data:e,path:r.path,parent:r});return ia(r,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Hs(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return na(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>na(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Hs(e)},n=this._parse({data:e,path:r.path,parent:r}),s=await(sa(n)?n:Promise.resolve(n));return ia(r,s)}refine(e,t){let r=e=>"string"==typeof t||typeof t>"u"?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{let s=e(t),a=()=>n.addIssue({code:Zs.custom,...r(t)});return typeof Promise<"u"&&s instanceof Promise?s.then(e=>!!e||(a(),!1)):!!s||(a(),!1)})}refinement(e,t){return this._refinement((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new ii({schema:this,typeName:pi.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return oi.create(this,this._def)}nullable(){return li.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Za.create(this)}promise(){return ai.create(this,this._def)}or(e){return Wa.create([this,e],this._def)}and(e){return Ya.create(this,e,this._def)}transform(e){return new ii({...oa(this._def),schema:this,typeName:pi.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t="function"==typeof e?e:()=>e;return new ci({...oa(this._def),innerType:this,defaultValue:t,typeName:pi.ZodDefault})}brand(){return new fi({typeName:pi.ZodBranded,type:this,...oa(this._def)})}catch(e){let t="function"==typeof e?e:()=>e;return new ui({...oa(this._def),innerType:this,catchValue:t,typeName:pi.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return hi.create(this,e)}readonly(){return mi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ua=/^c[^\s-]{8,}$/i,da=/^[0-9a-z]+$/,pa=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fa=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ha=/^[a-z0-9_-]{21}$/i,ma=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ga=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ya=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,va=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_a=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ba=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,wa=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ea=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xa=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Sa="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ka=new RegExp(`^${Sa}$`);function Ta(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function Ia(e){return new RegExp(`^${Ta(e)}$`)}function $a(e){let t=`${Sa}T${Ta(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Pa(e,t){return!("v4"!==t&&t||!va.test(e))||!("v6"!==t&&t||!ba.test(e))}function Ca(e,t){if(!ma.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!("object"!=typeof s||null===s||"typ"in s&&"JWT"!==s?.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function Ra(e,t){return!("v4"!==t&&t||!_a.test(e))||!("v6"!==t&&t||!wa.test(e))}var Aa=class e extends ca{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==qs.string){let t=this._getOrReturnCtx(e);return Ks(t,{code:Zs.invalid_type,expected:qs.string,received:t.parsedType}),Qs}let t,r=new Js;for(let n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),r.dirty());else if("max"===n.kind)e.data.length>n.value&&(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),r.dirty());else if("length"===n.kind){let s=e.data.length>n.value,a=e.data.length<n.value;(s||a)&&(t=this._getOrReturnCtx(e,t),s?Ks(t,{code:Zs.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):a&&Ks(t,{code:Zs.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),r.dirty())}else if("email"===n.kind)ya.test(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{validation:"email",code:Zs.invalid_string,message:n.message}),r.dirty());else if("emoji"===n.kind)la||(la=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),la.test(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{validation:"emoji",code:Zs.invalid_string,message:n.message}),r.dirty());else if("uuid"===n.kind)fa.test(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{validation:"uuid",code:Zs.invalid_string,message:n.message}),r.dirty());else if("nanoid"===n.kind)ha.test(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{validation:"nanoid",code:Zs.invalid_string,message:n.message}),r.dirty());else if("cuid"===n.kind)ua.test(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{validation:"cuid",code:Zs.invalid_string,message:n.message}),r.dirty());else if("cuid2"===n.kind)da.test(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{validation:"cuid2",code:Zs.invalid_string,message:n.message}),r.dirty());else if("ulid"===n.kind)pa.test(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{validation:"ulid",code:Zs.invalid_string,message:n.message}),r.dirty());else if("url"===n.kind)try{new URL(e.data)}catch{t=this._getOrReturnCtx(e,t),Ks(t,{validation:"url",code:Zs.invalid_string,message:n.message}),r.dirty()}else"regex"===n.kind?(n.regex.lastIndex=0,n.regex.test(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{validation:"regex",code:Zs.invalid_string,message:n.message}),r.dirty())):"trim"===n.kind?e.data=e.data.trim():"includes"===n.kind?e.data.includes(n.value,n.position)||(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),r.dirty()):"toLowerCase"===n.kind?e.data=e.data.toLowerCase():"toUpperCase"===n.kind?e.data=e.data.toUpperCase():"startsWith"===n.kind?e.data.startsWith(n.value)||(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.invalid_string,validation:{startsWith:n.value},message:n.message}),r.dirty()):"endsWith"===n.kind?e.data.endsWith(n.value)||(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.invalid_string,validation:{endsWith:n.value},message:n.message}),r.dirty()):"datetime"===n.kind?$a(n).test(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.invalid_string,validation:"datetime",message:n.message}),r.dirty()):"date"===n.kind?ka.test(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.invalid_string,validation:"date",message:n.message}),r.dirty()):"time"===n.kind?Ia(n).test(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.invalid_string,validation:"time",message:n.message}),r.dirty()):"duration"===n.kind?ga.test(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{validation:"duration",code:Zs.invalid_string,message:n.message}),r.dirty()):"ip"===n.kind?Pa(e.data,n.version)||(t=this._getOrReturnCtx(e,t),Ks(t,{validation:"ip",code:Zs.invalid_string,message:n.message}),r.dirty()):"jwt"===n.kind?Ca(e.data,n.alg)||(t=this._getOrReturnCtx(e,t),Ks(t,{validation:"jwt",code:Zs.invalid_string,message:n.message}),r.dirty()):"cidr"===n.kind?Ra(e.data,n.version)||(t=this._getOrReturnCtx(e,t),Ks(t,{validation:"cidr",code:Zs.invalid_string,message:n.message}),r.dirty()):"base64"===n.kind?Ea.test(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{validation:"base64",code:Zs.invalid_string,message:n.message}),r.dirty()):"base64url"===n.kind?xa.test(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{validation:"base64url",code:Zs.invalid_string,message:n.message}),r.dirty()):Us.assertNever(n);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:Zs.invalid_string,...Ys.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...Ys.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Ys.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Ys.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Ys.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Ys.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Ys.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Ys.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Ys.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Ys.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Ys.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Ys.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Ys.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Ys.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Ys.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Ys.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Ys.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Ys.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Ys.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Ys.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Ys.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Ys.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Ys.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Ys.errToObj(t)})}nonempty(e){return this.min(1,Ys.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};function Oa(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=r>n?r:n;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}Aa.create=e=>new Aa({checks:[],typeName:pi.ZodString,coerce:e?.coerce??!1,...oa(e)});var Na=class e extends ca{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==qs.number){let t=this._getOrReturnCtx(e);return Ks(t,{code:Zs.invalid_type,expected:qs.number,received:t.parsedType}),Qs}let t,r=new Js;for(let n of this._def.checks)"int"===n.kind?Us.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty()):"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):"multipleOf"===n.kind?0!==Oa(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.not_finite,message:n.message}),r.dirty()):Us.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Ys.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Ys.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Ys.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Ys.toString(t))}setLimit(t,r,n,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Ys.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:Ys.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ys.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ys.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ys.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ys.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Ys.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Ys.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ys.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ys.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&Us.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Na.create=e=>new Na({checks:[],typeName:pi.ZodNumber,coerce:e?.coerce||!1,...oa(e)});var ja=class e extends ca{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==qs.bigint)return this._getInvalidInput(e);let t,r=new Js;for(let n of this._def.checks)"min"===n.kind?(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"max"===n.kind?(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):Us.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return Ks(t,{code:Zs.invalid_type,expected:qs.bigint,received:t.parsedType}),Qs}gte(e,t){return this.setLimit("min",e,!0,Ys.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Ys.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Ys.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Ys.toString(t))}setLimit(t,r,n,s){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Ys.toString(s)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ys.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ys.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ys.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ys.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Ys.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};ja.create=e=>new ja({checks:[],typeName:pi.ZodBigInt,coerce:e?.coerce??!1,...oa(e)});var Da=class extends ca{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==qs.boolean){let t=this._getOrReturnCtx(e);return Ks(t,{code:Zs.invalid_type,expected:qs.boolean,received:t.parsedType}),Qs}return ea(e.data)}};Da.create=e=>new Da({typeName:pi.ZodBoolean,coerce:e?.coerce||!1,...oa(e)});var Ua=class e extends ca{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==qs.date){let t=this._getOrReturnCtx(e);return Ks(t,{code:Zs.invalid_type,expected:qs.date,received:t.parsedType}),Qs}if(Number.isNaN(e.data.getTime()))return Ks(this._getOrReturnCtx(e),{code:Zs.invalid_date}),Qs;let t,r=new Js;for(let n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),r.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(t=this._getOrReturnCtx(e,t),Ks(t,{code:Zs.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),r.dirty()):Us.assertNever(n);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Ys.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Ys.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}};Ua.create=e=>new Ua({checks:[],coerce:e?.coerce||!1,typeName:pi.ZodDate,...oa(e)});var La=class extends ca{_parse(e){if(this._getType(e)!==qs.symbol){let t=this._getOrReturnCtx(e);return Ks(t,{code:Zs.invalid_type,expected:qs.symbol,received:t.parsedType}),Qs}return ea(e.data)}};La.create=e=>new La({typeName:pi.ZodSymbol,...oa(e)});var Ma=class extends ca{_parse(e){if(this._getType(e)!==qs.undefined){let t=this._getOrReturnCtx(e);return Ks(t,{code:Zs.invalid_type,expected:qs.undefined,received:t.parsedType}),Qs}return ea(e.data)}};Ma.create=e=>new Ma({typeName:pi.ZodUndefined,...oa(e)});var za=class extends ca{_parse(e){if(this._getType(e)!==qs.null){let t=this._getOrReturnCtx(e);return Ks(t,{code:Zs.invalid_type,expected:qs.null,received:t.parsedType}),Qs}return ea(e.data)}};za.create=e=>new za({typeName:pi.ZodNull,...oa(e)});var Ba=class extends ca{constructor(){super(...arguments),this._any=!0}_parse(e){return ea(e.data)}};Ba.create=e=>new Ba({typeName:pi.ZodAny,...oa(e)});var Fa=class extends ca{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ea(e.data)}};Fa.create=e=>new Fa({typeName:pi.ZodUnknown,...oa(e)});var qa=class extends ca{_parse(e){let t=this._getOrReturnCtx(e);return Ks(t,{code:Zs.invalid_type,expected:qs.never,received:t.parsedType}),Qs}};qa.create=e=>new qa({typeName:pi.ZodNever,...oa(e)});var Ha=class extends ca{_parse(e){if(this._getType(e)!==qs.undefined){let t=this._getOrReturnCtx(e);return Ks(t,{code:Zs.invalid_type,expected:qs.void,received:t.parsedType}),Qs}return ea(e.data)}};Ha.create=e=>new Ha({typeName:pi.ZodVoid,...oa(e)});var Za=class e extends ca{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==qs.array)return Ks(t,{code:Zs.invalid_type,expected:qs.array,received:t.parsedType}),Qs;if(null!==n.exactLength){let e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(Ks(t,{code:e?Zs.too_big:Zs.too_small,minimum:s?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(Ks(t,{code:Zs.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(Ks(t,{code:Zs.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>n.type._parseAsync(new aa(t,e,t.path,r)))).then(e=>Js.mergeArray(r,e));let s=[...t.data].map((e,r)=>n.type._parseSync(new aa(t,e,t.path,r)));return Js.mergeArray(r,s)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:Ys.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:Ys.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:Ys.toString(r)}})}nonempty(e){return this.min(1,e)}};function Va(e){if(e instanceof Ga){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=oi.create(Va(n))}return new Ga({...e._def,shape:()=>t})}return e instanceof Za?new Za({...e._def,type:Va(e.element)}):e instanceof oi?oi.create(Va(e.unwrap())):e instanceof li?li.create(Va(e.unwrap())):e instanceof Ja?Ja.create(e.items.map(e=>Va(e))):e}Za.create=(e,t)=>new Za({type:e,minLength:null,maxLength:null,exactLength:null,typeName:pi.ZodArray,...oa(t)});var Ga=class e extends ca{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),t=Us.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==qs.object){let t=this._getOrReturnCtx(e);return Ks(t,{code:Zs.invalid_type,expected:qs.object,received:t.parsedType}),Qs}let{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof qa&&"strip"===this._def.unknownKeys))for(let e in r.data)s.includes(e)||a.push(e);let i=[];for(let e of s){let t=n[e],s=r.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new aa(r,s,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof qa){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of a)i.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)a.length>0&&(Ks(r,{code:Zs.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of a){let n=r.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new aa(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of i){let r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e}).then(e=>Js.mergeObjectSync(t,e)):Js.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(t){return Ys.errToObj,new e({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(e,r)=>{let n=this._def.errorMap?.(e,r).message??r.defaultError;return"unrecognized_keys"===e.code?{message:Ys.errToObj(t).message??n}:{message:n}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:pi.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let e of Us.objectKeys(t))t[e]&&this.shape[e]&&(r[e]=this.shape[e]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let e of Us.objectKeys(this.shape))t[e]||(r[e]=this.shape[e]);return new e({...this._def,shape:()=>r})}deepPartial(){return Va(this)}partial(t){let r={};for(let e of Us.objectKeys(this.shape)){let n=this.shape[e];t&&!t[e]?r[e]=n:r[e]=n.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let e of Us.objectKeys(this.shape))if(t&&!t[e])r[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof oi;)t=t._def.innerType;r[e]=t}return new e({...this._def,shape:()=>r})}keyof(){return ri(Us.objectKeys(this.shape))}};Ga.create=(e,t)=>new Ga({shape:()=>e,unknownKeys:"strip",catchall:qa.create(),typeName:pi.ZodObject,...oa(t)}),Ga.strictCreate=(e,t)=>new Ga({shape:()=>e,unknownKeys:"strict",catchall:qa.create(),typeName:pi.ZodObject,...oa(t)}),Ga.lazycreate=(e,t)=>new Ga({shape:e,unknownKeys:"strip",catchall:qa.create(),typeName:pi.ZodObject,...oa(t)});var Wa=class extends ca{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new Vs(e.ctx.common.issues));return Ks(t,{code:Zs.invalid_union,unionErrors:r}),Qs});{let e,n=[];for(let s of r){let r={...t,common:{...t.common,issues:[]},parent:null},a=s._parseSync({data:t.data,path:t.path,parent:r});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let s=n.map(e=>new Vs(e));return Ks(t,{code:Zs.invalid_union,unionErrors:s}),Qs}}get options(){return this._def.options}};function Ka(e,t){let r=Hs(e),n=Hs(t);if(e===t)return{valid:!0,data:e};if(r===qs.object&&n===qs.object){let r=Us.objectKeys(t),n=Us.objectKeys(e).filter(e=>-1!==r.indexOf(e)),s={...e,...t};for(let r of n){let n=Ka(e[r],t[r]);if(!n.valid)return{valid:!1};s[r]=n.data}return{valid:!0,data:s}}if(r===qs.array&&n===qs.array){if(e.length!==t.length)return{valid:!1};let r=[];for(let n=0;n<e.length;n++){let s=Ka(e[n],t[n]);if(!s.valid)return{valid:!1};r.push(s.data)}return{valid:!0,data:r}}return r===qs.date&&n===qs.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}Wa.create=(e,t)=>new Wa({options:e,typeName:pi.ZodUnion,...oa(t)});var Ya=class extends ca{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(ta(e)||ta(n))return Qs;let s=Ka(e.value,n.value);return s.valid?((ra(e)||ra(n))&&t.dirty(),{status:t.value,value:s.data}):(Ks(r,{code:Zs.invalid_intersection_types}),Qs)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Ya.create=(e,t,r)=>new Ya({left:e,right:t,typeName:pi.ZodIntersection,...oa(r)});var Ja=class e extends ca{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==qs.array)return Ks(r,{code:Zs.invalid_type,expected:qs.array,received:r.parsedType}),Qs;if(r.data.length<this._def.items.length)return Ks(r,{code:Zs.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Qs;!this._def.rest&&r.data.length>this._def.items.length&&(Ks(r,{code:Zs.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let n=[...r.data].map((e,t)=>{let n=this._def.items[t]||this._def.rest;return n?n._parse(new aa(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>Js.mergeArray(t,e)):Js.mergeArray(t,n)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ja.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ja({items:e,typeName:pi.ZodTuple,rest:null,...oa(t)})};var Qa=class extends ca{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==qs.map)return Ks(r,{code:Zs.invalid_type,expected:qs.map,received:r.parsedType}),Qs;let n=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([e,t],a)=>({key:n._parse(new aa(r,e,r.path,[a,"key"])),value:s._parse(new aa(r,t,r.path,[a,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of a){let n=await r.key,s=await r.value;if("aborted"===n.status||"aborted"===s.status)return Qs;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of a){let{key:n,value:s}=r;if("aborted"===n.status||"aborted"===s.status)return Qs;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}};Qa.create=(e,t,r)=>new Qa({valueType:t,keyType:e,typeName:pi.ZodMap,...oa(r)});var Xa=class e extends ca{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==qs.set)return Ks(r,{code:Zs.invalid_type,expected:qs.set,received:r.parsedType}),Qs;let n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(Ks(r,{code:Zs.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(Ks(r,{code:Zs.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());let s=this._def.valueType;function a(e){let r=new Set;for(let n of e){if("aborted"===n.status)return Qs;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}let i=[...r.data.values()].map((e,t)=>s._parse(new aa(r,e,r.path,t)));return r.common.async?Promise.all(i).then(e=>a(e)):a(i)}min(t,r){return new e({...this._def,minSize:{value:t,message:Ys.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:Ys.toString(r)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Xa.create=(e,t)=>new Xa({valueType:e,minSize:null,maxSize:null,typeName:pi.ZodSet,...oa(t)});var ei=class extends ca{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ei.create=(e,t)=>new ei({getter:e,typeName:pi.ZodLazy,...oa(t)});var ti=class extends ca{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return Ks(t,{received:t.data,code:Zs.invalid_literal,expected:this._def.value}),Qs}return{status:"valid",value:e.data}}get value(){return this._def.value}};function ri(e,t){return new ni({values:e,typeName:pi.ZodEnum,...oa(t)})}ti.create=(e,t)=>new ti({value:e,typeName:pi.ZodLiteral,...oa(t)});var ni=class e extends ca{_parse(e){if("string"!=typeof e.data){let t=this._getOrReturnCtx(e),r=this._def.values;return Ks(t,{expected:Us.joinValues(r),received:t.parsedType,code:Zs.invalid_type}),Qs}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return Ks(t,{received:t.data,code:Zs.invalid_enum_value,options:r}),Qs}return ea(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...r})}};ni.create=ri;var si=class extends ca{_parse(e){let t=Us.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==qs.string&&r.parsedType!==qs.number){let e=Us.objectValues(t);return Ks(r,{expected:Us.joinValues(e),received:r.parsedType,code:Zs.invalid_type}),Qs}if(this._cache||(this._cache=new Set(Us.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let e=Us.objectValues(t);return Ks(r,{received:r.data,code:Zs.invalid_enum_value,options:e}),Qs}return ea(e.data)}get enum(){return this._def.values}};si.create=(e,t)=>new si({values:e,typeName:pi.ZodNativeEnum,...oa(t)});var ai=class extends ca{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==qs.promise&&!1===t.common.async)return Ks(t,{code:Zs.invalid_type,expected:qs.promise,received:t.parsedType}),Qs;let r=t.parsedType===qs.promise?t.data:Promise.resolve(t.data);return ea(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ai.create=(e,t)=>new ai({type:e,typeName:pi.ZodPromise,...oa(t)});var ii=class extends ca{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===pi.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:e=>{Ks(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===n.type){let e=n.transform(r.data,s);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return Qs;let n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?Qs:"dirty"===n.status||"dirty"===t.value?Xs(n.value):n});{if("aborted"===t.value)return Qs;let n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?Qs:"dirty"===n.status||"dirty"===t.value?Xs(n.value):n}}if("refinement"===n.type){let e=e=>{let t=n.refinement(e,s);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){let n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?Qs:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?Qs:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===n.type){if(!1===r.common.async){let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!na(e))return Qs;let a=n.transform(e.value,s);if(a instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>na(e)?Promise.resolve(n.transform(e.value,s)).then(e=>({status:t.value,value:e})):Qs)}Us.assertNever(n)}};ii.create=(e,t,r)=>new ii({schema:e,typeName:pi.ZodEffects,effect:t,...oa(r)}),ii.createWithPreprocess=(e,t,r)=>new ii({schema:t,effect:{type:"preprocess",transform:e},typeName:pi.ZodEffects,...oa(r)});var oi=class extends ca{_parse(e){return this._getType(e)===qs.undefined?ea(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};oi.create=(e,t)=>new oi({innerType:e,typeName:pi.ZodOptional,...oa(t)});var li=class extends ca{_parse(e){return this._getType(e)===qs.null?ea(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};li.create=(e,t)=>new li({innerType:e,typeName:pi.ZodNullable,...oa(t)});var ci=class extends ca{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===qs.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ci.create=(e,t)=>new ci({innerType:e,typeName:pi.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...oa(t)});var ui=class extends ca{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return sa(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new Vs(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new Vs(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};ui.create=(e,t)=>new ui({innerType:e,typeName:pi.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...oa(t)});var di=class extends ca{_parse(e){if(this._getType(e)!==qs.nan){let t=this._getOrReturnCtx(e);return Ks(t,{code:Zs.invalid_type,expected:qs.nan,received:t.parsedType}),Qs}return{status:"valid",value:e.data}}};di.create=e=>new di({typeName:pi.ZodNaN,...oa(e)});var pi,fi=class extends ca{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},hi=class e extends ca{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?Qs:"dirty"===e.status?(t.dirty(),Xs(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?Qs:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(t,r){return new e({in:t,out:r,typeName:pi.ZodPipeline})}},mi=class extends ca{_parse(e){let t=this._def.innerType._parse(e),r=e=>(na(e)&&(e.value=Object.freeze(e.value)),e);return sa(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}};mi.create=(e,t)=>new mi({innerType:e,typeName:pi.ZodReadonly,...oa(t)}),function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(pi||(pi={})),qa.create,Za.create;var gi=Ga.create;function yi(e,t,r){function n(r,n){var s;Object.defineProperty(r,"_zod",{value:r._zod??{},enumerable:!1}),(s=r._zod).traits??(s.traits=new Set),r._zod.traits.add(e),t(r,n);for(let e in i.prototype)e in r||Object.defineProperty(r,e,{value:i.prototype[e].bind(r)});r._zod.constr=i,r._zod.def=n}let s=r?.Parent??Object;class a extends s{}function i(e){var t;let s=r?.Parent?new a:this;n(s,e),(t=s._zod).deferred??(t.deferred=[]);for(let e of s._zod.deferred)e();return s}return Object.defineProperty(a,"name",{value:e}),Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}Wa.create,Ya.create,Ja.create,ni.create,ai.create,oi.create,li.create;var vi=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},_i={};function bi(e){return e&&Object.assign(_i,e),_i}var wi={};function Ei(e){return e}function xi(e){return e}function Si(e){}function ki(e){throw Error()}function Ti(e){}function Ii(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function $i(e,t="|"){return e.map(e=>Qi(e)).join(t)}function Pi(e,t){return"bigint"==typeof t?t.toString():t}function Ci(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ri(e){return null==e}function Ai(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Oi(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=r>n?r:n;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}function Ni(e,t,r){Object.defineProperty(e,t,{get(){{let n=r();return e[t]=n,n}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function ji(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Di(e,t){return t?t.reduce((e,t)=>e?.[t],e):e}function Ui(e){let t=Object.keys(e),r=t.map(t=>e[t]);return Promise.all(r).then(e=>{let r={};for(let n=0;n<t.length;n++)r[t[n]]=e[n];return r})}function Li(e=10){let t="";for(let r=0;r<e;r++)t+="abcdefghijklmnopqrstuvwxyz"[Math.floor(26*Math.random())];return t}function Mi(e){return JSON.stringify(e)}sr(wi,{unwrapMessage:()=>uo,stringifyPrimitive:()=>Qi,required:()=>oo,randomString:()=>Li,propertyKeyTypes:()=>Vi,promiseAllObject:()=>Ui,primitiveTypes:()=>Gi,prefixIssues:()=>co,pick:()=>ro,partial:()=>io,optionalKeys:()=>Xi,omit:()=>no,numKeys:()=>Hi,nullish:()=>Ri,normalizeParams:()=>Yi,merge:()=>ao,jsonStringifyReplacer:()=>Pi,joinValues:()=>$i,issue:()=>mo,isPlainObject:()=>qi,isObject:()=>Bi,getSizableOrigin:()=>fo,getParsedType:()=>Zi,getLengthableOrigin:()=>ho,getEnumValues:()=>Ii,getElementAtPath:()=>Di,floatSafeRemainder:()=>Oi,finalizeIssue:()=>po,extend:()=>so,escapeRegex:()=>Wi,esc:()=>Mi,defineLazy:()=>Ni,createTransparentProxy:()=>Ji,clone:()=>Ki,cleanRegex:()=>Ai,cleanEnum:()=>go,captureStackTrace:()=>zi,cached:()=>Ci,assignProp:()=>ji,assertNotEqual:()=>xi,assertNever:()=>ki,assertIs:()=>Si,assertEqual:()=>Ei,assert:()=>Ti,allowsEval:()=>Fi,aborted:()=>lo,NUMBER_FORMAT_RANGES:()=>eo,Class:()=>yo,BIGINT_FORMAT_RANGES:()=>to});var zi=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Bi(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Fi=Ci(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function qi(e){if(!1===Bi(e))return!1;let t=e.constructor;if(void 0===t)return!0;let r=t.prototype;return!1!==Bi(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function Hi(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var Zi=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":null===e?"null":e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw Error(`Unknown data type: ${t}`)}},Vi=new Set(["string","number","symbol"]),Gi=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Wi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ki(e,t,r){let n=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(n._zod.parent=e),n}function Yi(e){let t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function Ji(e){let t;return new Proxy({},{get:(r,n,s)=>(t??(t=e()),Reflect.get(t,n,s)),set:(r,n,s,a)=>(t??(t=e()),Reflect.set(t,n,s,a)),has:(r,n)=>(t??(t=e()),Reflect.has(t,n)),deleteProperty:(r,n)=>(t??(t=e()),Reflect.deleteProperty(t,n)),ownKeys:r=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(r,n)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)),defineProperty:(r,n,s)=>(t??(t=e()),Reflect.defineProperty(t,n,s))})}function Qi(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function Xi(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}var eo={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},to={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ro(e,t){let r={},n=e._zod.def;for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&(r[e]=n.shape[e])}return Ki(e,{...e._zod.def,shape:r,checks:[]})}function no(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Ki(e,{...e._zod.def,shape:r,checks:[]})}function so(e,t){if(!qi(t))throw Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let r={...e._zod.def.shape,...t};return ji(this,"shape",r),r},checks:[]};return Ki(e,r)}function ao(e,t){return Ki(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return ji(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function io(e,t,r){let n=t._zod.def.shape,s={...n};if(r)for(let t in r){if(!(t in n))throw Error(`Unrecognized key: "${t}"`);r[t]&&(s[t]=e?new e({type:"optional",innerType:n[t]}):n[t])}else for(let t in n)s[t]=e?new e({type:"optional",innerType:n[t]}):n[t];return Ki(t,{...t._zod.def,shape:s,checks:[]})}function oo(e,t,r){let n=t._zod.def.shape,s={...n};if(r)for(let t in r){if(!(t in s))throw Error(`Unrecognized key: "${t}"`);r[t]&&(s[t]=new e({type:"nonoptional",innerType:n[t]}))}else for(let t in n)s[t]=new e({type:"nonoptional",innerType:n[t]});return Ki(t,{...t._zod.def,shape:s,checks:[]})}function lo(e,t=0){for(let r=t;r<e.issues.length;r++)if(!0!==e.issues[r]?.continue)return!0;return!1}function co(e,t){return t.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function uo(e){return"string"==typeof e?e:e?.message}function po(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let s=uo(e.inst?._zod.def?.error?.(e))??uo(t?.error?.(e))??uo(r.customError?.(e))??uo(r.localeError?.(e))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function fo(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function ho(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function mo(...e){let[t,r,n]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:n}:{...t}}function go(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var yo=class{constructor(...e){}},vo=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get:()=>JSON.stringify(t,Pi,2),enumerable:!0})},_o=yi("$ZodError",vo),bo=yi("$ZodError",vo,{Parent:Error}),wo=e=>(t,r,n,s)=>{let a=n?Object.assign(n,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise)throw new vi;if(i.issues.length){let t=new(s?.Err??e)(i.issues.map(e=>po(e,a,bi())));throw zi(t,s?.callee),t}return i.value},Eo=wo(bo),xo=e=>async(t,r,n,s)=>{let a=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){let t=new(s?.Err??e)(i.issues.map(e=>po(e,a,bi())));throw zi(t,s?.callee),t}return i.value},So=xo(bo),ko=e=>(t,r,n)=>{let s=n?{...n,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new vi;return a.issues.length?{success:!1,error:new(e??_o)(a.issues.map(e=>po(e,s,bi())))}:{success:!0,data:a.value}},To=ko(bo),Io=e=>async(t,r,n)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},a=t._zod.run({value:r,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>po(e,s,bi())))}:{success:!0,data:a.value}},$o=Io(bo),Po=/^[cC][^\s-]{8,}$/,Co=/^[0-9a-z]+$/,Ro=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ao=/^[0-9a-vA-V]{20}$/,Oo=/^[A-Za-z0-9]{27}$/,No=/^[a-zA-Z0-9_-]{21}$/,jo=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Do=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Uo=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Lo=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Mo=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,zo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Bo=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Fo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,qo=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ho=/^[A-Za-z0-9_-]*$/,Zo=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Vo=/^\+(?:[0-9]){6,14}[0-9]$/,Go="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Wo=new RegExp(`^${Go}$`);function Ko(e){return"number"==typeof e.precision?-1===e.precision?"(?:[01]\\d|2[0-3]):[0-5]\\d":0===e.precision?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}var Yo=/^\d+$/,Jo=/^-?\d+(?:\.\d+)?/i,Qo=/true|false/i,Xo=/null/i,el=/^[^A-Z]*$/,tl=/^[^a-z]*$/,rl=yi("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),nl={number:"number",bigint:"bigint",object:"date"},sl=yi("$ZodCheckLessThan",(e,t)=>{rl.init(e,t);let r=nl[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,n=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<n&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),al=yi("$ZodCheckGreaterThan",(e,t)=>{rl.init(e,t);let r=nl[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,n=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>n&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),il=yi("$ZodCheckMultipleOf",(e,t)=>{rl.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value!==BigInt(0):0!==Oi(r.value,t.value))&&r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),ol=yi("$ZodCheckNumberFormat",(e,t)=>{rl.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[s,a]=eo[t.format];e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,n.minimum=s,n.maximum=a,r&&(n.pattern=Yo)}),e._zod.check=i=>{let o=i.value;if(r){if(!Number.isInteger(o))return void i.issues.push({expected:n,format:t.format,code:"invalid_type",input:o,inst:e});if(!Number.isSafeInteger(o))return void(o>0?i.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):i.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}))}o<s&&i.issues.push({origin:"number",input:o,code:"too_small",minimum:s,inclusive:!0,inst:e,continue:!t.abort}),o>a&&i.issues.push({origin:"number",input:o,code:"too_big",maximum:a,inst:e})}}),ll=yi("$ZodCheckMaxLength",(e,t)=>{rl.init(e,t),e._zod.when=e=>{let t=e.value;return!Ri(t)&&void 0!==t.length},e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let n=r.value;if(n.length<=t.maximum)return;let s=ho(n);r.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),cl=yi("$ZodCheckMinLength",(e,t)=>{rl.init(e,t),e._zod.when=e=>{let t=e.value;return!Ri(t)&&void 0!==t.length},e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let n=r.value;if(n.length>=t.minimum)return;let s=ho(n);r.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),ul=yi("$ZodCheckLengthEquals",(e,t)=>{rl.init(e,t),e._zod.when=e=>{let t=e.value;return!Ri(t)&&void 0!==t.length},e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{let n=r.value,s=n.length;if(s===t.length)return;let a=ho(n),i=s>t.length;r.issues.push({origin:a,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),dl=yi("$ZodCheckStringFormat",(e,t)=>{var r,n;rl.init(e,t),e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),pl=yi("$ZodCheckRegex",(e,t)=>{dl.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),fl=yi("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=el),dl.init(e,t)}),hl=yi("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=tl),dl.init(e,t)}),ml=yi("$ZodCheckIncludes",(e,t)=>{rl.init(e,t);let r=Wi(t.includes),n=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),gl=yi("$ZodCheckStartsWith",(e,t)=>{rl.init(e,t);let r=new RegExp(`^${Wi(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),yl=yi("$ZodCheckEndsWith",(e,t)=>{rl.init(e,t);let r=new RegExp(`.*${Wi(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),vl=yi("$ZodCheckOverwrite",(e,t)=>{rl.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),_l=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length)),n=t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e);for(let e of n)this.content.push(e)}compile(){let e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}},bl={major:4,minor:0,patch:0},wl=yi("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=bl;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let t of n)for(let r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,r)=>{let n,s=lo(e);for(let a of t){if(a._zod.when){if(!a._zod.when(e))continue}else if(s)continue;let t=e.issues.length,i=a._zod.check(e);if(i instanceof Promise&&!1===r?.async)throw new vi;if(n||i instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await i,e.issues.length!==t&&(s||(s=lo(e,t)))});else{if(e.issues.length===t)continue;s||(s=lo(e,t))}}return n?n.then(()=>e):e};e._zod.run=(r,s)=>{let a=e._zod.parse(r,s);if(a instanceof Promise){if(!1===s.async)throw new vi;return a.then(e=>t(e,n,s))}return t(a,n,s)}}e["~standard"]={validate:t=>{try{let r=To(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return $o(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),El=yi("$ZodString",(e,t)=>{wl.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(e=>new RegExp(`^${e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*"}$`))(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(e){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),xl=yi("$ZodStringFormat",(e,t)=>{dl.init(e,t),El.init(e,t)}),Sl=yi("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Do),xl.init(e,t)}),kl=yi("$ZodUUID",(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Uo(e))}else t.pattern??(t.pattern=Uo());xl.init(e,t)}),Tl=yi("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Lo),xl.init(e,t)}),Il=yi("$ZodURL",(e,t)=>{xl.init(e,t),e._zod.check=r=>{try{let n=r.value,s=new URL(n),a=s.href;return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(s.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Zo.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),void(!n.endsWith("/")&&a.endsWith("/")?r.value=a.slice(0,-1):r.value=a)}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),$l=yi("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),xl.init(e,t)}),Pl=yi("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=No),xl.init(e,t)}),Cl=yi("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Po),xl.init(e,t)}),Rl=yi("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Co),xl.init(e,t)}),Al=yi("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ro),xl.init(e,t)}),Ol=yi("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Ao),xl.init(e,t)}),Nl=yi("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Oo),xl.init(e,t)}),jl=yi("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){let t=Ko({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Go}T(?:${n})$`)}(t)),xl.init(e,t)}),Dl=yi("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Wo),xl.init(e,t)}),Ul=yi("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=function(e){return new RegExp(`^${Ko(e)}$`)}(t)),xl.init(e,t)}),Ll=yi("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=jo),xl.init(e,t)}),Ml=yi("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Mo),xl.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv4"})}),zl=yi("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=zo),xl.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Bl=yi("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Bo),xl.init(e,t)}),Fl=yi("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Fo),xl.init(e,t),e._zod.check=r=>{let[n,s]=r.value.split("/");try{if(!s)throw Error();let e=Number(s);if(`${e}`!==s)throw Error();if(e<0||e>128)throw Error();new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function ql(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Hl=yi("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=qo),xl.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{ql(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),Zl=yi("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ho),xl.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{(function(e){if(!Ho.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return ql(t.padEnd(4*Math.ceil(t.length/4),"="))})(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Vl=yi("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Vo),xl.init(e,t)}),Gl=yi("$ZodJWT",(e,t)=>{xl.init(e,t),e._zod.check=r=>{(function(e,t=null){try{let r=e.split(".");if(3!==r.length)return!1;let[n]=r;if(!n)return!1;let s=JSON.parse(atob(n));return!("typ"in s&&"JWT"!==s?.typ||!s.alg||t&&(!("alg"in s)||s.alg!==t))}catch{return!1}})(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Wl=yi("$ZodNumber",(e,t)=>{wl.init(e,t),e._zod.pattern=e._zod.bag.pattern??Jo,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}let s=r.value;if("number"==typeof s&&!Number.isNaN(s)&&Number.isFinite(s))return r;let a="number"==typeof s?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:s,inst:e,...a?{received:a}:{}}),r}}),Kl=yi("$ZodNumber",(e,t)=>{ol.init(e,t),Wl.init(e,t)}),Yl=yi("$ZodBoolean",(e,t)=>{wl.init(e,t),e._zod.pattern=Qo,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(e){}let s=r.value;return"boolean"==typeof s||r.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:e}),r}}),Jl=yi("$ZodNull",(e,t)=>{wl.init(e,t),e._zod.pattern=Xo,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{let n=t.value;return null===n||t.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),t}}),Ql=yi("$ZodUnknown",(e,t)=>{wl.init(e,t),e._zod.parse=e=>e}),Xl=yi("$ZodNever",(e,t)=>{wl.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function ec(e,t,r){e.issues.length&&t.issues.push(...co(r,e.issues)),t.value[r]=e.value}var tc=yi("$ZodArray",(e,t)=>{wl.init(e,t),e._zod.parse=(r,n)=>{let s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),r;r.value=Array(s.length);let a=[];for(let e=0;e<s.length;e++){let i=s[e],o=t.element._zod.run({value:i,issues:[]},n);o instanceof Promise?a.push(o.then(t=>ec(t,r,e))):ec(o,r,e)}return a.length?Promise.all(a).then(()=>r):r}});function rc(e,t,r){e.issues.length&&t.issues.push(...co(r,e.issues)),t.value[r]=e.value}function nc(e,t,r,n){e.issues.length?void 0===n[r]?t.value[r]=r in n?void 0:e.value:t.issues.push(...co(r,e.issues)):void 0===e.value?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var sc=yi("$ZodObject",(e,t)=>{wl.init(e,t);let r=Ci(()=>{let e=Object.keys(t.shape);for(let r of e)if(!(t.shape[r]instanceof wl))throw Error(`Invalid element at key "${r}": expected a Zod schema`);let r=Xi(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}});Ni(e._zod,"propValues",()=>{let e=t.shape,r={};for(let t in e){let n=e[t]._zod;if(n.values){r[t]??(r[t]=new Set);for(let e of n.values)r[t].add(e)}}return r});let n,s,a=Bi,i=!_i.jitless,o=i&&Fi.value,l=t.catchall;e._zod.parse=(c,u)=>{s??(s=r.value);let d=c.value;if(!a(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),c;let p=[];if(i&&o&&!1===u?.async&&!0!==u.jitless)n||(n=(e=>{let t=new _l(["shape","payload","ctx"]),n=r.value,s=e=>{let t=Mi(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");let a=Object.create(null),i=0;for(let e of n.keys)a[e]="key_"+i++;t.write("const newResult = {}");for(let e of n.keys)if(n.optionalKeys.has(e)){let r=a[e];t.write(`const ${r} = ${s(e)};`);let n=Mi(e);t.write(`\n if (${r}.issues.length) {\n if (input[${n}] === undefined) {\n if (${n} in input) {\n newResult[${n}] = undefined;\n }\n } else {\n payload.issues = payload.issues.concat(\n ${r}.issues.map((iss) => ({\n ...iss,\n path: iss.path ? [${n}, ...iss.path] : [${n}],\n }))\n );\n }\n } else if (${r}.value === undefined) {\n if (${n} in input) newResult[${n}] = undefined;\n } else {\n newResult[${n}] = ${r}.value;\n }\n `)}else{let r=a[e];t.write(`const ${r} = ${s(e)};`),t.write(`\n if (${r}.issues.length) payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${Mi(e)}, ...iss.path] : [${Mi(e)}]\n })));`),t.write(`newResult[${Mi(e)}] = ${r}.value`)}t.write("payload.value = newResult;"),t.write("return payload;");let o=t.compile();return(t,r)=>o(e,t,r)})(t.shape)),c=n(c,u);else{c.value={};let e=s.shape;for(let t of s.keys){let r=e[t],n=r._zod.run({value:d[t],issues:[]},u),s="optional"===r._zod.optin&&"optional"===r._zod.optout;n instanceof Promise?p.push(n.then(e=>s?nc(e,c,t,d):rc(e,c,t))):s?nc(n,c,t,d):rc(n,c,t)}}if(!l)return p.length?Promise.all(p).then(()=>c):c;let f=[],h=s.keySet,m=l._zod,g=m.def.type;for(let e of Object.keys(d)){if(h.has(e))continue;if("never"===g){f.push(e);continue}let t=m.run({value:d[e],issues:[]},u);t instanceof Promise?p.push(t.then(t=>rc(t,c,e))):rc(t,c,e)}return f.length&&c.issues.push({code:"unrecognized_keys",keys:f,input:d,inst:e}),p.length?Promise.all(p).then(()=>c):c}});function ac(e,t,r,n){for(let r of e)if(0===r.issues.length)return t.value=r.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>po(e,n,bi())))}),t}var ic=yi("$ZodUnion",(e,t)=>{wl.init(e,t),Ni(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),Ni(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Ni(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Ni(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>Ai(e.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let s=!1,a=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},n);if(t instanceof Promise)a.push(t),s=!0;else{if(0===t.issues.length)return t;a.push(t)}}return s?Promise.all(a).then(t=>ac(t,r,e,n)):ac(a,r,e,n)}}),oc=yi("$ZodDiscriminatedUnion",(e,t)=>{ic.init(e,t);let r=e._zod.parse;Ni(e._zod,"propValues",()=>{let e={};for(let r of t.options){let n=r._zod.propValues;if(!n||0===Object.keys(n).length)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let[t,r]of Object.entries(n)){e[t]||(e[t]=new Set);for(let n of r)e[t].add(n)}}return e});let n=Ci(()=>{let e=t.options,r=new Map;for(let n of e){let e=n._zod.propValues[t.discriminator];if(!e||0===e.size)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let t of e){if(r.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,n)}}return r});e._zod.parse=(s,a)=>{let i=s.value;if(!Bi(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),s;let o=n.value.get(i?.[t.discriminator]);return o?o._zod.run(s,a):t.unionFallback?r(s,a):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[t.discriminator],inst:e}),s)}}),lc=yi("$ZodIntersection",(e,t)=>{wl.init(e,t),e._zod.parse=(e,r)=>{let n=e.value,s=t.left._zod.run({value:n,issues:[]},r),a=t.right._zod.run({value:n,issues:[]},r);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([t,r])=>uc(e,t,r)):uc(e,s,a)}});function cc(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(qi(e)&&qi(t)){let r=Object.keys(t),n=Object.keys(e).filter(e=>-1!==r.indexOf(e)),s={...e,...t};for(let r of n){let n=cc(e[r],t[r]);if(!n.valid)return{valid:!1,mergeErrorPath:[r,...n.mergeErrorPath]};s[r]=n.data}return{valid:!0,data:s}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let s=cc(e[n],t[n]);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function uc(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),lo(e))return e;let n=cc(t.value,r.value);if(!n.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}var dc=yi("$ZodRecord",(e,t)=>{wl.init(e,t),e._zod.parse=(r,n)=>{let s=r.value;if(!qi(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),r;let a=[];if(t.keyType._zod.values){let i,o=t.keyType._zod.values;r.value={};for(let e of o)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){let i=t.valueType._zod.run({value:s[e],issues:[]},n);i instanceof Promise?a.push(i.then(t=>{t.issues.length&&r.issues.push(...co(e,t.issues)),r.value[e]=t.value})):(i.issues.length&&r.issues.push(...co(e,i.issues)),r.value[e]=i.value)}for(let e in s)o.has(e)||(i=i??[],i.push(e));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:i})}else{r.value={};for(let i of Reflect.ownKeys(s)){if("__proto__"===i)continue;let o=t.keyType._zod.run({value:i,issues:[]},n);if(o instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(o.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:o.issues.map(e=>po(e,n,bi())),input:i,path:[i],inst:e}),r.value[o.value]=o.value;continue}let l=t.valueType._zod.run({value:s[i],issues:[]},n);l instanceof Promise?a.push(l.then(e=>{e.issues.length&&r.issues.push(...co(i,e.issues)),r.value[o.value]=e.value})):(l.issues.length&&r.issues.push(...co(i,l.issues)),r.value[o.value]=l.value)}}return a.length?Promise.all(a).then(()=>r):r}}),pc=yi("$ZodEnum",(e,t)=>{wl.init(e,t);let r=Ii(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(e=>Vi.has(typeof e)).map(e=>"string"==typeof e?Wi(e):e.toString()).join("|")})$`),e._zod.parse=(t,n)=>{let s=t.value;return e._zod.values.has(s)||t.issues.push({code:"invalid_value",values:r,input:s,inst:e}),t}}),fc=yi("$ZodLiteral",(e,t)=>{wl.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?Wi(e):e?e.toString():String(e)).join("|")})$`),e._zod.parse=(r,n)=>{let s=r.value;return e._zod.values.has(s)||r.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),r}}),hc=yi("$ZodTransform",(e,t)=>{wl.init(e,t),e._zod.parse=(e,r)=>{let n=t.transform(e.value,e);if(r.async)return(n instanceof Promise?n:Promise.resolve(n)).then(t=>(e.value=t,e));if(n instanceof Promise)throw new vi;return e.value=n,e}}),mc=yi("$ZodOptional",(e,t)=>{wl.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ni(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ni(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?new RegExp(`^(${Ai(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>"optional"===t.innerType._zod.optin?t.innerType._zod.run(e,r):void 0===e.value?e:t.innerType._zod.run(e,r)}),gc=yi("$ZodNullable",(e,t)=>{wl.init(e,t),Ni(e._zod,"optin",()=>t.innerType._zod.optin),Ni(e._zod,"optout",()=>t.innerType._zod.optout),Ni(e._zod,"pattern",()=>{let e=t.innerType._zod.pattern;return e?new RegExp(`^(${Ai(e.source)}|null)$`):void 0}),Ni(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),yc=yi("$ZodDefault",(e,t)=>{wl.init(e,t),e._zod.optin="optional",Ni(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if(void 0===e.value)return e.value=t.defaultValue,e;let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(e=>vc(e,t)):vc(n,t)}});function vc(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var _c=yi("$ZodPrefault",(e,t)=>{wl.init(e,t),e._zod.optin="optional",Ni(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),bc=yi("$ZodNonOptional",(e,t)=>{wl.init(e,t),Ni(e._zod,"values",()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,n)=>{let s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(t=>wc(t,e)):wc(s,e)}});function wc(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Ec=yi("$ZodCatch",(e,t)=>{wl.init(e,t),e._zod.optin="optional",Ni(e._zod,"optout",()=>t.innerType._zod.optout),Ni(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>po(e,r,bi()))},input:e.value}),e.issues=[]),e)):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>po(e,r,bi()))},input:e.value}),e.issues=[]),e)}}),xc=yi("$ZodPipe",(e,t)=>{wl.init(e,t),Ni(e._zod,"values",()=>t.in._zod.values),Ni(e._zod,"optin",()=>t.in._zod.optin),Ni(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(e,r)=>{let n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>Sc(e,t,r)):Sc(n,t,r)}});function Sc(e,t,r){return lo(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var kc=yi("$ZodReadonly",(e,t)=>{wl.init(e,t),Ni(e._zod,"propValues",()=>t.innerType._zod.propValues),Ni(e._zod,"values",()=>t.innerType._zod.values),Ni(e._zod,"optin",()=>t.innerType._zod.optin),Ni(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(e,r)=>{let n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(Tc):Tc(n)}});function Tc(e){return e.value=Object.freeze(e.value),e}var Ic=yi("$ZodCustom",(e,t)=>{rl.init(e,t),wl.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{let n=r.value,s=t.fn(n);if(s instanceof Promise)return s.then(t=>$c(t,r,n,e));$c(s,r,n,e)}});function $c(e,t,r,n){if(!e){let e={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(e.params=n._zod.def.params),t.issues.push(mo(e))}}var Pc=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}remove(e){return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}},Cc=new Pc;function Rc(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Yi(t)})}function Ac(e,t){return new sl({check:"less_than",...Yi(t),value:e,inclusive:!1})}function Oc(e,t){return new sl({check:"less_than",...Yi(t),value:e,inclusive:!0})}function Nc(e,t){return new al({check:"greater_than",...Yi(t),value:e,inclusive:!1})}function jc(e,t){return new al({check:"greater_than",...Yi(t),value:e,inclusive:!0})}function Dc(e,t){return new il({check:"multiple_of",...Yi(t),value:e})}function Uc(e,t){return new ll({check:"max_length",...Yi(t),maximum:e})}function Lc(e,t){return new cl({check:"min_length",...Yi(t),minimum:e})}function Mc(e,t){return new ul({check:"length_equals",...Yi(t),length:e})}function zc(e){return new vl({check:"overwrite",tx:e})}var Bc=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Cc,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var r;let n=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(e);if(a)return a.count++,t.schemaPath.includes(e)&&(a.cycle=t.path),a.schema;let i={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,i);let o=e._zod.toJSONSchema?.();if(o)i.schema=o;else{let r={...t,schemaPath:[...t.schemaPath,e],path:t.path},a=e._zod.parent;if(a)i.ref=a,this.process(a,r),this.seen.get(a).isParent=!0;else{let t=i.schema;switch(n.type){case"string":{let r=t;r.type="string";let{minimum:n,maximum:a,format:o,patterns:l,contentEncoding:c}=e._zod.bag;if("number"==typeof n&&(r.minLength=n),"number"==typeof a&&(r.maxLength=a),o&&(r.format=s[o]??o,""===r.format&&delete r.format),c&&(r.contentEncoding=c),l&&l.size>0){let e=[...l];1===e.length?r.pattern=e[0].source:e.length>1&&(i.schema.allOf=[...e.map(e=>({..."draft-7"===this.target?{type:"string"}:{},pattern:e.source}))])}break}case"number":{let r=t,{minimum:n,maximum:s,format:a,multipleOf:i,exclusiveMaximum:o,exclusiveMinimum:l}=e._zod.bag;"string"==typeof a&&a.includes("int")?r.type="integer":r.type="number","number"==typeof l&&(r.exclusiveMinimum=l),"number"==typeof n&&(r.minimum=n,"number"==typeof l&&(l>=n?delete r.minimum:delete r.exclusiveMinimum)),"number"==typeof o&&(r.exclusiveMaximum=o),"number"==typeof s&&(r.maximum=s,"number"==typeof o&&(o<=s?delete r.maximum:delete r.exclusiveMaximum)),"number"==typeof i&&(r.multipleOf=i);break}case"boolean":case"success":t.type="boolean";break;case"bigint":if("throw"===this.unrepresentable)throw Error("BigInt cannot be represented in JSON Schema");break;case"symbol":if("throw"===this.unrepresentable)throw Error("Symbols cannot be represented in JSON Schema");break;case"null":t.type="null";break;case"any":case"unknown":break;case"undefined":case"never":t.not={};break;case"void":if("throw"===this.unrepresentable)throw Error("Void cannot be represented in JSON Schema");break;case"date":if("throw"===this.unrepresentable)throw Error("Date cannot be represented in JSON Schema");break;case"array":{let s=t,{minimum:a,maximum:i}=e._zod.bag;"number"==typeof a&&(s.minItems=a),"number"==typeof i&&(s.maxItems=i),s.type="array",s.items=this.process(n.element,{...r,path:[...r.path,"items"]});break}case"object":{let e=t;e.type="object",e.properties={};let s=n.shape;for(let t in s)e.properties[t]=this.process(s[t],{...r,path:[...r.path,"properties",t]});let a=new Set(Object.keys(s)),i=new Set([...a].filter(e=>{let t=n.shape[e]._zod;return"input"===this.io?void 0===t.optin:void 0===t.optout}));i.size>0&&(e.required=Array.from(i)),"never"===n.catchall?._zod.def.type?e.additionalProperties=!1:n.catchall?n.catchall&&(e.additionalProperties=this.process(n.catchall,{...r,path:[...r.path,"additionalProperties"]})):"output"===this.io&&(e.additionalProperties=!1);break}case"union":t.anyOf=n.options.map((e,t)=>this.process(e,{...r,path:[...r.path,"anyOf",t]}));break;case"intersection":{let e=t,s=this.process(n.left,{...r,path:[...r.path,"allOf",0]}),a=this.process(n.right,{...r,path:[...r.path,"allOf",1]}),i=e=>"allOf"in e&&1===Object.keys(e).length,o=[...i(s)?s.allOf:[s],...i(a)?a.allOf:[a]];e.allOf=o;break}case"tuple":{let s=t;s.type="array";let a=n.items.map((e,t)=>this.process(e,{...r,path:[...r.path,"prefixItems",t]}));if("draft-2020-12"===this.target?s.prefixItems=a:s.items=a,n.rest){let e=this.process(n.rest,{...r,path:[...r.path,"items"]});"draft-2020-12"===this.target?s.items=e:s.additionalItems=e}n.rest&&(s.items=this.process(n.rest,{...r,path:[...r.path,"items"]}));let{minimum:i,maximum:o}=e._zod.bag;"number"==typeof i&&(s.minItems=i),"number"==typeof o&&(s.maxItems=o);break}case"record":{let e=t;e.type="object",e.propertyNames=this.process(n.keyType,{...r,path:[...r.path,"propertyNames"]}),e.additionalProperties=this.process(n.valueType,{...r,path:[...r.path,"additionalProperties"]});break}case"map":if("throw"===this.unrepresentable)throw Error("Map cannot be represented in JSON Schema");break;case"set":if("throw"===this.unrepresentable)throw Error("Set cannot be represented in JSON Schema");break;case"enum":{let e=t,r=Ii(n.entries);r.every(e=>"number"==typeof e)&&(e.type="number"),r.every(e=>"string"==typeof e)&&(e.type="string"),e.enum=r;break}case"literal":{let e=t,r=[];for(let e of n.values)if(void 0===e){if("throw"===this.unrepresentable)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===this.unrepresentable)throw Error("BigInt literals cannot be represented in JSON Schema");r.push(Number(e))}else r.push(e);if(0===r.length);else if(1===r.length){let t=r[0];e.type=null===t?"null":typeof t,e.const=t}else r.every(e=>"number"==typeof e)&&(e.type="number"),r.every(e=>"string"==typeof e)&&(e.type="string"),r.every(e=>"boolean"==typeof e)&&(e.type="string"),r.every(e=>null===e)&&(e.type="null"),e.enum=r;break}case"file":{let r=t,n={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:i}=e._zod.bag;void 0!==s&&(n.minLength=s),void 0!==a&&(n.maxLength=a),i?1===i.length?(n.contentMediaType=i[0],Object.assign(r,n)):r.anyOf=i.map(e=>({...n,contentMediaType:e})):Object.assign(r,n);break}case"transform":if("throw"===this.unrepresentable)throw Error("Transforms cannot be represented in JSON Schema");break;case"nullable":{let e=this.process(n.innerType,r);t.anyOf=[e,{type:"null"}];break}case"nonoptional":case"promise":case"optional":this.process(n.innerType,r),i.ref=n.innerType;break;case"default":this.process(n.innerType,r),i.ref=n.innerType,t.default=JSON.parse(JSON.stringify(n.defaultValue));break;case"prefault":this.process(n.innerType,r),i.ref=n.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(n.defaultValue)));break;case"catch":{let e;this.process(n.innerType,r),i.ref=n.innerType;try{e=n.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}t.default=e;break}case"nan":if("throw"===this.unrepresentable)throw Error("NaN cannot be represented in JSON Schema");break;case"template_literal":{let r=t,n=e._zod.pattern;if(!n)throw Error("Pattern not found in template literal");r.type="string",r.pattern=n.source;break}case"pipe":{let e="input"===this.io?"transform"===n.in._zod.def.type?n.out:n.in:n.out;this.process(e,r),i.ref=e;break}case"readonly":this.process(n.innerType,r),i.ref=n.innerType,t.readOnly=!0;break;case"lazy":{let t=e._zod.innerType;this.process(t,r),i.ref=t;break}case"custom":if("throw"===this.unrepresentable)throw Error("Custom types cannot be represented in JSON Schema")}}}let l=this.metadataRegistry.get(e);return l&&Object.assign(i.schema,l),"input"===this.io&&Fc(e)&&(delete i.schema.examples,delete i.schema.default),"input"===this.io&&i.schema._prefault&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(e).schema}emit(e,t){let r={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},n=this.seen.get(e);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let s=e=>{let t="draft-2020-12"===this.target?"$defs":"definitions";if(r.external){let n=r.external.registry.get(e[0])?.id;if(n)return{ref:r.external.uri(n)};let s=e[1].defId??e[1].schema.id??"schema"+this.counter++;return e[1].defId=s,{defId:s,ref:`${r.external.uri("__shared")}#/${t}/${s}`}}if(e[1]===n)return{ref:"#"};let s=`#/${t}/`,a=e[1].schema.id??"__schema"+this.counter++;return{defId:a,ref:s+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:r,defId:n}=s(e);t.def={...t.schema},n&&(t.defId=n);let a=t.schema;for(let e in a)delete a[e];a.$ref=r};for(let t of this.seen.entries()){let n=t[1];if(e!==t[0]){if(r.external){let n=r.external.registry.get(t[0])?.id;if(e!==t[0]&&n){a(t);continue}}if(this.metadataRegistry.get(t[0])?.id)a(t);else if(n.cycle){if("throw"===r.cycles)throw Error(`Cycle detected: #/${n.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);"ref"===r.cycles&&a(t)}else n.count>1&&"ref"===r.reused&&a(t)}else a(t)}let i=(e,t)=>{let r=this.seen.get(e),n=r.def??r.schema,s={...n};if(null===r.ref)return;let a=r.ref;if(r.ref=null,a){i(a,t);let e=this.seen.get(a).schema;e.$ref&&"draft-7"===t.target?(n.allOf=n.allOf??[],n.allOf.push(e)):(Object.assign(n,e),Object.assign(n,s))}r.isParent||this.override({zodSchema:e,jsonSchema:n,path:r.path??[]})};for(let e of[...this.seen.entries()].reverse())i(e[0],{target:this.target});let o={};"draft-2020-12"===this.target?o.$schema="https://json-schema.org/draft/2020-12/schema":"draft-7"===this.target?o.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),Object.assign(o,n.def);let l=r.external?.defs??{};for(let e of this.seen.entries()){let t=e[1];t.def&&t.defId&&(l[t.defId]=t.def)}!r.external&&Object.keys(l).length>0&&("draft-2020-12"===this.target?o.$defs=l:o.definitions=l);try{return JSON.parse(JSON.stringify(o))}catch(e){throw Error("Error converting schema to JSON.")}}};function Fc(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;switch(n.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":case"custom":case"success":case"catch":return!1;case"array":return Fc(n.element,r);case"object":for(let e in n.shape)if(Fc(n.shape[e],r))return!0;return!1;case"union":for(let e of n.options)if(Fc(e,r))return!0;return!1;case"intersection":return Fc(n.left,r)||Fc(n.right,r);case"tuple":for(let e of n.items)if(Fc(e,r))return!0;return!(!n.rest||!Fc(n.rest,r));case"record":case"map":return Fc(n.keyType,r)||Fc(n.valueType,r);case"set":return Fc(n.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return Fc(n.innerType,r);case"lazy":return Fc(n.getter(),r);case"transform":return!0;case"pipe":return Fc(n.in,r)||Fc(n.out,r)}throw Error(`Unknown schema type: ${n.type}`)}var qc=yi("ZodMiniType",(e,t)=>{if(!e._zod)throw Error("Uninitialized schema in ZodMiniType.");wl.init(e,t),e.def=t,e.parse=(t,r)=>Eo(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>To(e,t,r),e.parseAsync=async(t,r)=>So(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>$o(e,t,r),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>Ki(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e)}),Hc=yi("ZodMiniObject",(e,t)=>{sc.init(e,t),qc.init(e,t),wi.defineLazy(e,"shape",()=>t.shape)});function Zc(e,t){let r={type:"object",get shape(){return wi.assignProp(this,"shape",{...e}),this.shape},...wi.normalizeParams(t)};return new Hc(r)}function Vc(e){return!!e._zod}function Gc(e){let t=Object.values(e);if(0===t.length)return Zc({});let r=t.every(Vc),n=t.every(e=>!Vc(e));if(r)return Zc(e);if(n)return gi(e);throw Error("Mixed Zod versions detected in object shape.")}function Wc(e,t){return Vc(e)?To(e,t):e.safeParse(t)}async function Kc(e,t){return Vc(e)?await $o(e,t):await e.safeParseAsync(t)}function Yc(e){var t,r;if(!e)return;let n;if(n=Vc(e)?null===(r=null===(t=e._zod)||void 0===t?void 0:t.def)||void 0===r?void 0:r.shape:e.shape,n){if("function"==typeof n)try{return n()}catch(e){return}return n}}function Jc(e){var t;if(e){if("object"==typeof e){let t=e;if(!e._def&&!t._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>"object"==typeof e&&null!==e&&(void 0!==e._def||void 0!==e._zod||"function"==typeof e.parse)))return Gc(e)}}if(Vc(e)){let r=null===(t=e._zod)||void 0===t?void 0:t.def;if(r&&("object"===r.type||void 0!==r.shape))return e}else if(void 0!==e.shape)return e}}function Qc(e){if(e&&"object"==typeof e){if("message"in e&&"string"==typeof e.message)return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&"object"==typeof t&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch(t){return String(e)}}return String(e)}function Xc(e){var t;if(Vc(e)){let r=null===(t=e._zod)||void 0===t?void 0:t.def;if(r){if(void 0!==r.value)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}}let r=e._def;if(r){if(void 0!==r.value)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(void 0!==n)return n}var eu={};sr(eu,{time:()=>iu,duration:()=>lu,datetime:()=>ru,date:()=>su,ZodISOTime:()=>au,ZodISODuration:()=>ou,ZodISODateTime:()=>tu,ZodISODate:()=>nu});var tu=yi("ZodISODateTime",(e,t)=>{jl.init(e,t),_u.init(e,t)});function ru(e){return new tu({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Yi(e)})}var nu=yi("ZodISODate",(e,t)=>{Dl.init(e,t),_u.init(e,t)});function su(e){return new nu({type:"string",format:"date",check:"string_format",...Yi(e)})}var au=yi("ZodISOTime",(e,t)=>{Ul.init(e,t),_u.init(e,t)});function iu(e){return new au({type:"string",format:"time",check:"string_format",precision:null,...Yi(e)})}var ou=yi("ZodISODuration",(e,t)=>{Ll.init(e,t),_u.init(e,t)});function lu(e){return new ou({type:"string",format:"duration",check:"string_format",...Yi(e)})}var cu=(e,t)=>{_o.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t){let r=t||function(e){return e.message},n={_errors:[]},s=e=>{for(let t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map(e=>s({issues:e}));else if("invalid_key"===t.code)s({issues:t.issues});else if("invalid_element"===t.code)s({issues:t.issues});else if(0===t.path.length)n._errors.push(r(t));else{let e=n,s=0;for(;s<t.path.length;){let n=t.path[s];s!==t.path.length-1?e[n]=e[n]||{_errors:[]}:(e[n]=e[n]||{_errors:[]},e[n]._errors.push(r(t))),e=e[n],s++}}};return s(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){let r={},n=[];for(let s of e.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(t(s))):n.push(t(s));return{formErrors:n,fieldErrors:r}}(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get:()=>0===e.issues.length}})};yi("ZodError",cu);var uu=yi("ZodError",cu,{Parent:Error}),du=wo(uu),pu=xo(uu),fu=ko(uu),hu=Io(uu),mu=yi("ZodType",(e,t)=>(wl.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>Ki(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>du(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>fu(e,t,r),e.parseAsync=async(t,r)=>pu(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>hu(e,t,r),e.spa=e.safeParseAsync,e.refine=(t,r)=>e.check(function(e,t={}){return function(e,t,r){return new Id({type:"custom",check:"custom",fn:t,...Yi(r)})}(0,e,t)}(t,r)),e.superRefine=t=>e.check(function(e){let t=function(e){let t=new rl({check:"custom",...wi.normalizeParams(void 0)});return t._zod.check=e,t}(r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(wi.issue(e,r.value,t._zod.def));else{let n=e;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),n.continue??(n.continue=!t._zod.def.abort),r.issues.push(wi.issue(n))}},e(r.value,r)));return t}(t)),e.overwrite=t=>e.check(zc(t)),e.optional=()=>yd(e),e.nullable=()=>_d(e),e.nullish=()=>yd(_d(e)),e.nonoptional=t=>function(e,t){return new Ed({type:"nonoptional",innerType:e,...wi.normalizeParams(t)})}(e,t),e.array=()=>Qu(e),e.or=t=>nd([e,t]),e.and=t=>od(e,t),e.transform=t=>kd(e,md(t)),e.default=t=>function(e,t){return new bd({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():t}})}(e,t),e.prefault=t=>function(e,t){return new wd({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof t?t():t}})}(e,t),e.catch=t=>function(e,t){return new xd({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}(e,t),e.pipe=t=>kd(e,t),e.readonly=()=>function(e){return new Td({type:"readonly",innerType:e})}(e),e.describe=t=>{let r=e.clone();return Cc.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>Cc.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Cc.get(e);let r=e.clone();return Cc.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),gu=yi("_ZodString",(e,t)=>{El.init(e,t),mu.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new pl({check:"string_format",format:"regex",...Yi(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new ml({check:"string_format",format:"includes",...Yi(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new gl({check:"string_format",format:"starts_with",...Yi(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new yl({check:"string_format",format:"ends_with",...Yi(t),suffix:e})}(...t)),e.min=(...t)=>e.check(Lc(...t)),e.max=(...t)=>e.check(Uc(...t)),e.length=(...t)=>e.check(Mc(...t)),e.nonempty=(...t)=>e.check(Lc(1,...t)),e.lowercase=t=>e.check(function(e){return new fl({check:"string_format",format:"lowercase",...Yi(e)})}(t)),e.uppercase=t=>e.check(function(e){return new hl({check:"string_format",format:"uppercase",...Yi(e)})}(t)),e.trim=()=>e.check(zc(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return zc(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(zc(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(zc(e=>e.toUpperCase()))}),yu=yi("ZodString",(e,t)=>{El.init(e,t),gu.init(e,t),e.email=t=>e.check(function(e,t){return new bu({type:"string",format:"email",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.url=t=>e.check(function(e,t){return new xu({type:"string",format:"url",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.jwt=t=>e.check(function(e,t){return new Lu({type:"string",format:"jwt",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.emoji=t=>e.check(function(e,t){return new Su({type:"string",format:"emoji",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.guid=t=>e.check(Rc(wu,t)),e.uuid=t=>e.check(function(e,t){return new Eu({type:"string",format:"uuid",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.uuidv4=t=>e.check(function(e,t){return new Eu({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Yi(t)})}(0,t)),e.uuidv6=t=>e.check(function(e,t){return new Eu({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Yi(t)})}(0,t)),e.uuidv7=t=>e.check(function(e,t){return new Eu({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Yi(t)})}(0,t)),e.nanoid=t=>e.check(function(e,t){return new ku({type:"string",format:"nanoid",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.guid=t=>e.check(Rc(wu,t)),e.cuid=t=>e.check(function(e,t){return new Tu({type:"string",format:"cuid",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.cuid2=t=>e.check(function(e,t){return new Iu({type:"string",format:"cuid2",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.ulid=t=>e.check(function(e,t){return new $u({type:"string",format:"ulid",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.base64=t=>e.check(function(e,t){return new ju({type:"string",format:"base64",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.base64url=t=>e.check(function(e,t){return new Du({type:"string",format:"base64url",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.xid=t=>e.check(function(e,t){return new Pu({type:"string",format:"xid",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.ksuid=t=>e.check(function(e,t){return new Cu({type:"string",format:"ksuid",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.ipv4=t=>e.check(function(e,t){return new Ru({type:"string",format:"ipv4",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.ipv6=t=>e.check(function(e,t){return new Au({type:"string",format:"ipv6",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.cidrv4=t=>e.check(function(e,t){return new Ou({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.cidrv6=t=>e.check(function(e,t){return new Nu({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.e164=t=>e.check(function(e,t){return new Uu({type:"string",format:"e164",check:"string_format",abort:!1,...Yi(t)})}(0,t)),e.datetime=t=>e.check(ru(t)),e.date=t=>e.check(su(t)),e.time=t=>e.check(iu(t)),e.duration=t=>e.check(lu(t))});function vu(e){return new yu({type:"string",...Yi(e)})}var _u=yi("ZodStringFormat",(e,t)=>{xl.init(e,t),gu.init(e,t)}),bu=yi("ZodEmail",(e,t)=>{Tl.init(e,t),_u.init(e,t)}),wu=yi("ZodGUID",(e,t)=>{Sl.init(e,t),_u.init(e,t)}),Eu=yi("ZodUUID",(e,t)=>{kl.init(e,t),_u.init(e,t)}),xu=yi("ZodURL",(e,t)=>{Il.init(e,t),_u.init(e,t)}),Su=yi("ZodEmoji",(e,t)=>{$l.init(e,t),_u.init(e,t)}),ku=yi("ZodNanoID",(e,t)=>{Pl.init(e,t),_u.init(e,t)}),Tu=yi("ZodCUID",(e,t)=>{Cl.init(e,t),_u.init(e,t)}),Iu=yi("ZodCUID2",(e,t)=>{Rl.init(e,t),_u.init(e,t)}),$u=yi("ZodULID",(e,t)=>{Al.init(e,t),_u.init(e,t)}),Pu=yi("ZodXID",(e,t)=>{Ol.init(e,t),_u.init(e,t)}),Cu=yi("ZodKSUID",(e,t)=>{Nl.init(e,t),_u.init(e,t)}),Ru=yi("ZodIPv4",(e,t)=>{Ml.init(e,t),_u.init(e,t)}),Au=yi("ZodIPv6",(e,t)=>{zl.init(e,t),_u.init(e,t)}),Ou=yi("ZodCIDRv4",(e,t)=>{Bl.init(e,t),_u.init(e,t)}),Nu=yi("ZodCIDRv6",(e,t)=>{Fl.init(e,t),_u.init(e,t)}),ju=yi("ZodBase64",(e,t)=>{Hl.init(e,t),_u.init(e,t)}),Du=yi("ZodBase64URL",(e,t)=>{Zl.init(e,t),_u.init(e,t)}),Uu=yi("ZodE164",(e,t)=>{Vl.init(e,t),_u.init(e,t)}),Lu=yi("ZodJWT",(e,t)=>{Gl.init(e,t),_u.init(e,t)}),Mu=yi("ZodNumber",(e,t)=>{Wl.init(e,t),mu.init(e,t),e.gt=(t,r)=>e.check(Nc(t,r)),e.gte=(t,r)=>e.check(jc(t,r)),e.min=(t,r)=>e.check(jc(t,r)),e.lt=(t,r)=>e.check(Ac(t,r)),e.lte=(t,r)=>e.check(Oc(t,r)),e.max=(t,r)=>e.check(Oc(t,r)),e.int=t=>e.check(Fu(t)),e.safe=t=>e.check(Fu(t)),e.positive=t=>e.check(Nc(0,t)),e.nonnegative=t=>e.check(jc(0,t)),e.negative=t=>e.check(Ac(0,t)),e.nonpositive=t=>e.check(Oc(0,t)),e.multipleOf=(t,r)=>e.check(Dc(t,r)),e.step=(t,r)=>e.check(Dc(t,r)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function zu(e){return new Mu({type:"number",checks:[],...Yi(e)})}var Bu=yi("ZodNumberFormat",(e,t)=>{Kl.init(e,t),Mu.init(e,t)});function Fu(e){return new Bu({type:"number",check:"number_format",abort:!1,format:"safeint",...Yi(e)})}var qu=yi("ZodBoolean",(e,t)=>{Yl.init(e,t),mu.init(e,t)});function Hu(e){return new qu({type:"boolean",...Yi(e)})}var Zu=yi("ZodNull",(e,t)=>{Jl.init(e,t),mu.init(e,t)});function Vu(e){return new Zu({type:"null",...Yi(e)})}var Gu=yi("ZodUnknown",(e,t)=>{Ql.init(e,t),mu.init(e,t)});function Wu(){return new Gu({type:"unknown"})}var Ku=yi("ZodNever",(e,t)=>{Xl.init(e,t),mu.init(e,t)});function Yu(e){return new Ku({type:"never",...Yi(e)})}var Ju=yi("ZodArray",(e,t)=>{tc.init(e,t),mu.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(Lc(t,r)),e.nonempty=t=>e.check(Lc(1,t)),e.max=(t,r)=>e.check(Uc(t,r)),e.length=(t,r)=>e.check(Mc(t,r)),e.unwrap=()=>e.element});function Qu(e,t){return function(e,t,r){return new Ju({type:"array",element:t,...Yi(r)})}(0,e,t)}var Xu=yi("ZodObject",(e,t)=>{sc.init(e,t),mu.init(e,t),wi.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>dd(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Wu()}),e.loose=()=>e.clone({...e._zod.def,catchall:Wu()}),e.strict=()=>e.clone({...e._zod.def,catchall:Yu()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>wi.extend(e,t),e.merge=t=>wi.merge(e,t),e.pick=t=>wi.pick(e,t),e.omit=t=>wi.omit(e,t),e.partial=(...t)=>wi.partial(gd,e,t[0]),e.required=(...t)=>wi.required(Ed,e,t[0])});function ed(e,t){let r={type:"object",get shape(){return wi.assignProp(this,"shape",{...e}),this.shape},...wi.normalizeParams(t)};return new Xu(r)}function td(e,t){return new Xu({type:"object",get shape(){return wi.assignProp(this,"shape",{...e}),this.shape},catchall:Wu(),...wi.normalizeParams(t)})}var rd=yi("ZodUnion",(e,t)=>{ic.init(e,t),mu.init(e,t),e.options=t.options});function nd(e,t){return new rd({type:"union",options:e,...wi.normalizeParams(t)})}var sd=yi("ZodDiscriminatedUnion",(e,t)=>{rd.init(e,t),oc.init(e,t)});function ad(e,t,r){return new sd({type:"union",options:t,discriminator:e,...wi.normalizeParams(r)})}var id=yi("ZodIntersection",(e,t)=>{lc.init(e,t),mu.init(e,t)});function od(e,t){return new id({type:"intersection",left:e,right:t})}var ld=yi("ZodRecord",(e,t)=>{dc.init(e,t),mu.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function cd(e,t,r){return new ld({type:"record",keyType:e,valueType:t,...wi.normalizeParams(r)})}var ud=yi("ZodEnum",(e,t)=>{pc.init(e,t),mu.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(e,n)=>{let s={};for(let n of e){if(!r.has(n))throw Error(`Key ${n} not found in enum`);s[n]=t.entries[n]}return new ud({...t,checks:[],...wi.normalizeParams(n),entries:s})},e.exclude=(e,n)=>{let s={...t.entries};for(let t of e){if(!r.has(t))throw Error(`Key ${t} not found in enum`);delete s[t]}return new ud({...t,checks:[],...wi.normalizeParams(n),entries:s})}});function dd(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ud({type:"enum",entries:r,...wi.normalizeParams(t)})}var pd=yi("ZodLiteral",(e,t)=>{fc.init(e,t),mu.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function fd(e,t){return new pd({type:"literal",values:Array.isArray(e)?e:[e],...wi.normalizeParams(t)})}var hd=yi("ZodTransform",(e,t)=>{hc.init(e,t),mu.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=n=>{if("string"==typeof n)r.issues.push(wi.issue(n,r.value,t));else{let t=n;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=e),t.continue??(t.continue=!0),r.issues.push(wi.issue(t))}};let s=t.transform(r.value,r);return s instanceof Promise?s.then(e=>(r.value=e,r)):(r.value=s,r)}});function md(e){return new hd({type:"transform",transform:e})}var gd=yi("ZodOptional",(e,t)=>{mc.init(e,t),mu.init(e,t),e.unwrap=()=>e._zod.def.innerType});function yd(e){return new gd({type:"optional",innerType:e})}var vd=yi("ZodNullable",(e,t)=>{gc.init(e,t),mu.init(e,t),e.unwrap=()=>e._zod.def.innerType});function _d(e){return new vd({type:"nullable",innerType:e})}var bd=yi("ZodDefault",(e,t)=>{yc.init(e,t),mu.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),wd=yi("ZodPrefault",(e,t)=>{_c.init(e,t),mu.init(e,t),e.unwrap=()=>e._zod.def.innerType}),Ed=yi("ZodNonOptional",(e,t)=>{bc.init(e,t),mu.init(e,t),e.unwrap=()=>e._zod.def.innerType}),xd=yi("ZodCatch",(e,t)=>{Ec.init(e,t),mu.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),Sd=yi("ZodPipe",(e,t)=>{xc.init(e,t),mu.init(e,t),e.in=t.in,e.out=t.out});function kd(e,t){return new Sd({type:"pipe",in:e,out:t})}var Td=yi("ZodReadonly",(e,t)=>{kc.init(e,t),mu.init(e,t)}),Id=yi("ZodCustom",(e,t)=>{Ic.init(e,t),mu.init(e,t)});function $d(e,t){return kd(md(e),t)}bi({localeError:(()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(t){return e[t]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Invalid input: expected ${e.expected}, received ${(e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${Qi(e.values[0])}`:`Invalid option: expected one of ${$i(e.values,"|")}`;case"too_big":{let r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Too big: expected ${e.origin??"value"} to have ${r}${e.maximum.toString()} ${n.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${r}${e.maximum.toString()}`}case"too_small":{let r=e.inclusive?">=":">",n=t(e.origin);return n?`Too small: expected ${e.origin} to have ${r}${e.minimum.toString()} ${n.unit}`:`Too small: expected ${e.origin} to be ${r}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Invalid string: must start with "${t.prefix}"`:"ends_with"===t.format?`Invalid string: must end with "${t.suffix}"`:"includes"===t.format?`Invalid string: must include "${t.includes}"`:"regex"===t.format?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${r[t.format]??e.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${e.divisor}`;case"unrecognized_keys":return`Unrecognized key${e.keys.length>1?"s":""}: ${$i(e.keys,", ")}`;case"invalid_key":return`Invalid key in ${e.origin}`;case"invalid_union":default:return"Invalid input";case"invalid_element":return`Invalid value in ${e.origin}`}}})()});var Pd,Cd="2025-11-25",Rd=[Cd,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ad="io.modelcontextprotocol/related-task",Od="2.0",Nd=function(e){let t=Yi(void 0);return t.abort??(t.abort=!0),new e({type:"custom",check:"custom",fn:(e=>null!==e&&("object"==typeof e||"function"==typeof e))??(()=>!0),...t})}(Id,0),jd=nd([vu(),zu().int()]),Dd=vu(),Ud=td({ttl:nd([zu(),Vu()]).optional(),pollInterval:zu().optional()}),Ld=td({taskId:vu()}),Md=td({progressToken:jd.optional(),[Ad]:Ld.optional()}),zd=td({task:Ud.optional(),_meta:Md.optional()}),Bd=ed({method:vu(),params:zd.optional()}),Fd=td({_meta:ed({[Ad]:yd(Ld)}).passthrough().optional()}),qd=ed({method:vu(),params:Fd.optional()}),Hd=td({_meta:td({[Ad]:Ld.optional()}).optional()}),Zd=nd([vu(),zu().int()]),Vd=ed({jsonrpc:fd(Od),id:Zd,...Bd.shape}).strict(),Gd=e=>Vd.safeParse(e).success,Wd=ed({jsonrpc:fd(Od),...qd.shape}).strict(),Kd=ed({jsonrpc:fd(Od),id:Zd,result:Hd}).strict(),Yd=e=>Kd.safeParse(e).success;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"}(Pd||(Pd={}));var Jd=ed({jsonrpc:fd(Od),id:Zd,error:ed({code:zu().int(),message:vu(),data:yd(Wu())})}).strict();nd([Vd,Wd,Kd,Jd]);var Qd=Hd.strict(),Xd=Fd.extend({requestId:Zd,reason:vu().optional()}),ep=qd.extend({method:fd("notifications/cancelled"),params:Xd}),tp=ed({src:vu(),mimeType:vu().optional(),sizes:Qu(vu()).optional()}),rp=ed({icons:Qu(tp).optional()}),np=ed({name:vu(),title:vu().optional()}),sp=np.extend({...np.shape,...rp.shape,version:vu(),websiteUrl:vu().optional()}),ap=od(ed({applyDefaults:Hu().optional()}),cd(vu(),Wu())),ip=$d(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,od(ed({form:ap.optional(),url:Nd.optional()}),cd(vu(),Wu()).optional())),op=ed({list:yd(ed({}).passthrough()),cancel:yd(ed({}).passthrough()),requests:yd(ed({sampling:yd(ed({createMessage:yd(ed({}).passthrough())}).passthrough()),elicitation:yd(ed({create:yd(ed({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),lp=ed({list:yd(ed({}).passthrough()),cancel:yd(ed({}).passthrough()),requests:yd(ed({tools:yd(ed({call:yd(ed({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),cp=ed({experimental:cd(vu(),Nd).optional(),sampling:ed({context:Nd.optional(),tools:Nd.optional()}).optional(),elicitation:ip.optional(),roots:ed({listChanged:Hu().optional()}).optional(),tasks:yd(op)}),up=zd.extend({protocolVersion:vu(),capabilities:cp,clientInfo:sp}),dp=Bd.extend({method:fd("initialize"),params:up}),pp=ed({experimental:cd(vu(),Nd).optional(),logging:Nd.optional(),completions:Nd.optional(),prompts:yd(ed({listChanged:yd(Hu())})),resources:ed({subscribe:Hu().optional(),listChanged:Hu().optional()}).optional(),tools:ed({listChanged:Hu().optional()}).optional(),tasks:yd(lp)}).passthrough(),fp=Hd.extend({protocolVersion:vu(),capabilities:pp,serverInfo:sp,instructions:vu().optional()}),hp=qd.extend({method:fd("notifications/initialized")}),mp=Bd.extend({method:fd("ping")}),gp=ed({progress:zu(),total:yd(zu()),message:yd(vu())}),yp=ed({...Fd.shape,...gp.shape,progressToken:jd}),vp=qd.extend({method:fd("notifications/progress"),params:yp}),_p=zd.extend({cursor:Dd.optional()}),bp=Bd.extend({params:_p.optional()}),wp=Hd.extend({nextCursor:yd(Dd)}),Ep=ed({taskId:vu(),status:dd(["working","input_required","completed","failed","cancelled"]),ttl:nd([zu(),Vu()]),createdAt:vu(),lastUpdatedAt:vu(),pollInterval:yd(zu()),statusMessage:yd(vu())}),xp=Hd.extend({task:Ep}),Sp=Fd.merge(Ep),kp=qd.extend({method:fd("notifications/tasks/status"),params:Sp}),Tp=Bd.extend({method:fd("tasks/get"),params:zd.extend({taskId:vu()})}),Ip=Hd.merge(Ep),$p=Bd.extend({method:fd("tasks/result"),params:zd.extend({taskId:vu()})}),Pp=bp.extend({method:fd("tasks/list")}),Cp=wp.extend({tasks:Qu(Ep)}),Rp=Bd.extend({method:fd("tasks/cancel"),params:zd.extend({taskId:vu()})}),Ap=Hd.merge(Ep),Op=ed({uri:vu(),mimeType:yd(vu()),_meta:cd(vu(),Wu()).optional()}),Np=Op.extend({text:vu()}),jp=vu().refine(e=>{try{return atob(e),!0}catch(e){return!1}},{message:"Invalid Base64 string"}),Dp=Op.extend({blob:jp}),Up=ed({audience:Qu(dd(["user","assistant"])).optional(),priority:zu().min(0).max(1).optional(),lastModified:eu.datetime({offset:!0}).optional()}),Lp=ed({...np.shape,...rp.shape,uri:vu(),description:yd(vu()),mimeType:yd(vu()),annotations:Up.optional(),_meta:yd(td({}))}),Mp=ed({...np.shape,...rp.shape,uriTemplate:vu(),description:yd(vu()),mimeType:yd(vu()),annotations:Up.optional(),_meta:yd(td({}))}),zp=bp.extend({method:fd("resources/list")}),Bp=wp.extend({resources:Qu(Lp)}),Fp=bp.extend({method:fd("resources/templates/list")}),qp=wp.extend({resourceTemplates:Qu(Mp)}),Hp=zd.extend({uri:vu()}),Zp=Hp,Vp=Bd.extend({method:fd("resources/read"),params:Zp}),Gp=Hd.extend({contents:Qu(nd([Np,Dp]))}),Wp=qd.extend({method:fd("notifications/resources/list_changed")}),Kp=Hp,Yp=Bd.extend({method:fd("resources/subscribe"),params:Kp}),Jp=Hp,Qp=Bd.extend({method:fd("resources/unsubscribe"),params:Jp}),Xp=Fd.extend({uri:vu()}),ef=qd.extend({method:fd("notifications/resources/updated"),params:Xp}),tf=ed({name:vu(),description:yd(vu()),required:yd(Hu())}),rf=ed({...np.shape,...rp.shape,description:yd(vu()),arguments:yd(Qu(tf)),_meta:yd(td({}))}),nf=bp.extend({method:fd("prompts/list")}),sf=wp.extend({prompts:Qu(rf)}),af=zd.extend({name:vu(),arguments:cd(vu(),vu()).optional()}),of=Bd.extend({method:fd("prompts/get"),params:af}),lf=ed({type:fd("text"),text:vu(),annotations:Up.optional(),_meta:cd(vu(),Wu()).optional()}),cf=ed({type:fd("image"),data:jp,mimeType:vu(),annotations:Up.optional(),_meta:cd(vu(),Wu()).optional()}),uf=ed({type:fd("audio"),data:jp,mimeType:vu(),annotations:Up.optional(),_meta:cd(vu(),Wu()).optional()}),df=ed({type:fd("tool_use"),name:vu(),id:vu(),input:ed({}).passthrough(),_meta:yd(ed({}).passthrough())}).passthrough(),pf=ed({type:fd("resource"),resource:nd([Np,Dp]),annotations:Up.optional(),_meta:cd(vu(),Wu()).optional()}),ff=nd([lf,cf,uf,Lp.extend({type:fd("resource_link")}),pf]),hf=ed({role:dd(["user","assistant"]),content:ff}),mf=Hd.extend({description:yd(vu()),messages:Qu(hf)}),gf=qd.extend({method:fd("notifications/prompts/list_changed")}),yf=ed({title:vu().optional(),readOnlyHint:Hu().optional(),destructiveHint:Hu().optional(),idempotentHint:Hu().optional(),openWorldHint:Hu().optional()}),vf=ed({taskSupport:dd(["required","optional","forbidden"]).optional()}),_f=ed({...np.shape,...rp.shape,description:vu().optional(),inputSchema:ed({type:fd("object"),properties:cd(vu(),Nd).optional(),required:Qu(vu()).optional()}).catchall(Wu()),outputSchema:ed({type:fd("object"),properties:cd(vu(),Nd).optional(),required:Qu(vu()).optional()}).catchall(Wu()).optional(),annotations:yd(yf),execution:yd(vf),_meta:cd(vu(),Wu()).optional()}),bf=bp.extend({method:fd("tools/list")}),wf=wp.extend({tools:Qu(_f)}),Ef=Hd.extend({content:Qu(ff).default([]),structuredContent:cd(vu(),Wu()).optional(),isError:yd(Hu())});Ef.or(Hd.extend({toolResult:Wu()}));var xf=zd.extend({name:vu(),arguments:yd(cd(vu(),Wu()))}),Sf=Bd.extend({method:fd("tools/call"),params:xf}),kf=qd.extend({method:fd("notifications/tools/list_changed")}),Tf=dd(["debug","info","notice","warning","error","critical","alert","emergency"]),If=zd.extend({level:Tf}),$f=Bd.extend({method:fd("logging/setLevel"),params:If}),Pf=Fd.extend({level:Tf,logger:vu().optional(),data:Wu()}),Cf=qd.extend({method:fd("notifications/message"),params:Pf}),Rf=ed({name:vu().optional()}),Af=ed({hints:yd(Qu(Rf)),costPriority:yd(zu().min(0).max(1)),speedPriority:yd(zu().min(0).max(1)),intelligencePriority:yd(zu().min(0).max(1))}),Of=ed({mode:yd(dd(["auto","required","none"]))}),Nf=ed({type:fd("tool_result"),toolUseId:vu().describe("The unique identifier for the corresponding tool call."),content:Qu(ff).default([]),structuredContent:ed({}).passthrough().optional(),isError:yd(Hu()),_meta:yd(ed({}).passthrough())}).passthrough(),jf=ad("type",[lf,cf,uf]),Df=ad("type",[lf,cf,uf,df,Nf]),Uf=ed({role:dd(["user","assistant"]),content:nd([Df,Qu(Df)]),_meta:yd(ed({}).passthrough())}).passthrough(),Lf=zd.extend({messages:Qu(Uf),modelPreferences:Af.optional(),systemPrompt:vu().optional(),includeContext:dd(["none","thisServer","allServers"]).optional(),temperature:zu().optional(),maxTokens:zu().int(),stopSequences:Qu(vu()).optional(),metadata:Nd.optional(),tools:yd(Qu(_f)),toolChoice:yd(Of)}),Mf=Bd.extend({method:fd("sampling/createMessage"),params:Lf}),zf=Hd.extend({model:vu(),stopReason:yd(dd(["endTurn","stopSequence","maxTokens"]).or(vu())),role:dd(["user","assistant"]),content:jf}),Bf=Hd.extend({model:vu(),stopReason:yd(dd(["endTurn","stopSequence","maxTokens","toolUse"]).or(vu())),role:dd(["user","assistant"]),content:nd([Df,Qu(Df)])}),Ff=ed({type:fd("boolean"),title:vu().optional(),description:vu().optional(),default:Hu().optional()}),qf=ed({type:fd("string"),title:vu().optional(),description:vu().optional(),minLength:zu().optional(),maxLength:zu().optional(),format:dd(["email","uri","date","date-time"]).optional(),default:vu().optional()}),Hf=ed({type:dd(["number","integer"]),title:vu().optional(),description:vu().optional(),minimum:zu().optional(),maximum:zu().optional(),default:zu().optional()}),Zf=ed({type:fd("string"),title:vu().optional(),description:vu().optional(),enum:Qu(vu()),default:vu().optional()}),Vf=ed({type:fd("string"),title:vu().optional(),description:vu().optional(),oneOf:Qu(ed({const:vu(),title:vu()})),default:vu().optional()}),Gf=ed({type:fd("string"),title:vu().optional(),description:vu().optional(),enum:Qu(vu()),enumNames:Qu(vu()).optional(),default:vu().optional()}),Wf=nd([Zf,Vf]),Kf=nd([ed({type:fd("array"),title:vu().optional(),description:vu().optional(),minItems:zu().optional(),maxItems:zu().optional(),items:ed({type:fd("string"),enum:Qu(vu())}),default:Qu(vu()).optional()}),ed({type:fd("array"),title:vu().optional(),description:vu().optional(),minItems:zu().optional(),maxItems:zu().optional(),items:ed({anyOf:Qu(ed({const:vu(),title:vu()}))}),default:Qu(vu()).optional()})]),Yf=nd([Gf,Wf,Kf]),Jf=nd([Yf,Ff,qf,Hf]),Qf=nd([zd.extend({mode:fd("form").optional(),message:vu(),requestedSchema:ed({type:fd("object"),properties:cd(vu(),Jf),required:Qu(vu()).optional()})}),zd.extend({mode:fd("url"),message:vu(),elicitationId:vu(),url:vu().url()})]),Xf=Bd.extend({method:fd("elicitation/create"),params:Qf}),eh=Fd.extend({elicitationId:vu()}),th=qd.extend({method:fd("notifications/elicitation/complete"),params:eh}),rh=Hd.extend({action:dd(["accept","decline","cancel"]),content:$d(e=>null===e?void 0:e,cd(vu(),nd([vu(),zu(),Hu(),Qu(vu())])).optional())}),nh=ed({type:fd("ref/resource"),uri:vu()}),sh=ed({type:fd("ref/prompt"),name:vu()}),ah=zd.extend({ref:nd([sh,nh]),argument:ed({name:vu(),value:vu()}),context:ed({arguments:cd(vu(),vu()).optional()}).optional()}),ih=Bd.extend({method:fd("completion/complete"),params:ah}),oh=Hd.extend({completion:td({values:Qu(vu()).max(100),total:yd(zu().int()),hasMore:yd(Hu())})}),lh=ed({uri:vu().startsWith("file://"),name:vu().optional(),_meta:cd(vu(),Wu()).optional()}),ch=Bd.extend({method:fd("roots/list")}),uh=Hd.extend({roots:Qu(lh)}),dh=qd.extend({method:fd("notifications/roots/list_changed")});nd([mp,dp,ih,$f,of,nf,zp,Fp,Vp,Yp,Qp,Sf,bf,Tp,$p,Pp]),nd([ep,vp,hp,dh,kp]),nd([Qd,zf,Bf,rh,uh,Ip,Cp,xp]),nd([mp,Mf,Xf,ch,Tp,$p,Pp]),nd([ep,vp,Cf,ef,Wp,kf,gf,kp,th]),nd([Qd,fp,oh,mf,sf,Bp,qp,Gp,Ef,wf,Ip,Cp,xp]);var ph=class e extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}static fromError(t,r,n){if(t===Pd.UrlElicitationRequired&&n){let e=n;if(e.elicitations)return new fh(e.elicitations,r)}return new e(t,r,n)}},fh=class extends ph{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Pd.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){var e,t;return null!==(t=null===(e=this.data)||void 0===e?void 0:e.elicitations)&&void 0!==t?t:[]}};function hh(e){return"completed"===e||"failed"===e||"cancelled"===e}var mh=Symbol("Let zodToJsonSchema decide on which parser to use"),gh={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"};function yh(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function vh(e,t,r,n,s){e[t]=r,yh(e,t,n,s)}var _h=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function bh(e){if("openAi"!==e.target)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?_h(t,e.currentPath):t.join("/")}}function wh(e,t){return Gh(e.type._def,t)}function Eh(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((r,n)=>Eh(e,t,r))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return xh(e,t)}}var xh=(e,t)=>{let r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(let n of e.checks)switch(n.kind){case"min":vh(r,"minimum",n.value,n.message,t);break;case"max":vh(r,"maximum",n.value,n.message,t)}return r},Sh=void 0,kh=/^[cC][^\s-]{8,}$/,Th=/^[0-9a-z]+$/,Ih=/^[0-9A-HJKMNP-TV-Z]{26}$/,$h=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,Ph=()=>(void 0===Sh&&(Sh=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Sh),Ch=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Rh=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ah=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Oh=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Nh=/^[a-zA-Z0-9_-]{21}$/,jh=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function Dh(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":vh(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":vh(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Mh(r,"email",n.message,t);break;case"format:idn-email":Mh(r,"idn-email",n.message,t);break;case"pattern:zod":zh(r,$h,n.message,t)}break;case"url":Mh(r,"uri",n.message,t);break;case"uuid":Mh(r,"uuid",n.message,t);break;case"regex":zh(r,n.regex,n.message,t);break;case"cuid":zh(r,kh,n.message,t);break;case"cuid2":zh(r,Th,n.message,t);break;case"startsWith":zh(r,RegExp(`^${Uh(n.value,t)}`),n.message,t);break;case"endsWith":zh(r,RegExp(`${Uh(n.value,t)}$`),n.message,t);break;case"datetime":Mh(r,"date-time",n.message,t);break;case"date":Mh(r,"date",n.message,t);break;case"time":Mh(r,"time",n.message,t);break;case"duration":Mh(r,"duration",n.message,t);break;case"length":vh(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t),vh(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":zh(r,RegExp(Uh(n.value,t)),n.message,t);break;case"ip":"v6"!==n.version&&Mh(r,"ipv4",n.message,t),"v4"!==n.version&&Mh(r,"ipv6",n.message,t);break;case"base64url":zh(r,Oh,n.message,t);break;case"jwt":zh(r,jh,n.message,t);break;case"cidr":"v6"!==n.version&&zh(r,Ch,n.message,t),"v4"!==n.version&&zh(r,Rh,n.message,t);break;case"emoji":zh(r,Ph(),n.message,t);break;case"ulid":zh(r,Ih,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":Mh(r,"binary",n.message,t);break;case"contentEncoding:base64":vh(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":zh(r,Ah,n.message,t)}break;case"nanoid":zh(r,Nh,n.message,t)}return r}function Uh(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)Lh.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}var Lh=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Mh(e,t,r,n){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):vh(e,"format",t,r,n)}function zh(e,t,r,n){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:Bh(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):vh(e,"pattern",Bh(t,n),r,n)}function Bh(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r=e.flags.includes("i"),n=e.flags.includes("m"),s=e.flags.includes("s"),a=r?e.source.toLowerCase():e.source,i="",o=!1,l=!1,c=!1;for(let e=0;e<a.length;e++)if(o)i+=a[e],o=!1;else{if(r)if(l){if(a[e].match(/[a-z]/)){c?(i+=a[e],i+=`${a[e-2]}-${a[e]}`.toUpperCase(),c=!1):"-"===a[e+1]&&a[e+2]?.match(/[a-z]/)?(i+=a[e],c=!0):i+=`${a[e]}${a[e].toUpperCase()}`;continue}}else if(a[e].match(/[a-z]/)){i+=`[${a[e]}${a[e].toUpperCase()}]`;continue}if(n){if("^"===a[e]){i+="(^|(?<=[\r\n]))";continue}if("$"===a[e]){i+="($|(?=[\r\n]))";continue}}s&&"."===a[e]?i+=l?`${a[e]}\r\n`:`[${a[e]}\r\n]`:(i+=a[e],"\\"===a[e]?o=!0:l&&"]"===a[e]?l=!1:l||"["!==a[e]||(l=!0))}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Fh(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===pi.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,n)=>({...r,[n]:Gh(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??bh(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Gh(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===pi.ZodString&&e.keyType._def.checks?.length){let{type:n,...s}=Dh(e.keyType._def,t);return{...r,propertyNames:s}}if(e.keyType?._def.typeName===pi.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===pi.ZodBranded&&e.keyType._def.type._def.typeName===pi.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...s}=wh(e.keyType._def,t);return{...r,propertyNames:s}}return r}var qh={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},Hh=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>Gh(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function Zh(e){try{return e.isOptional()}catch{return!0}}var Vh=(e,t,r)=>{switch(t){case pi.ZodString:return Dh(e,r);case pi.ZodNumber:return function(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",yh(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?n.inclusive?vh(r,"minimum",n.value,n.message,t):vh(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),vh(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?vh(r,"maximum",n.value,n.message,t):vh(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),vh(r,"maximum",n.value,n.message,t));break;case"multipleOf":vh(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case pi.ZodObject:return function(e,t){let r="openAi"===t.target,n={type:"object",properties:{}},s=[],a=e.shape();for(let e in a){let i=a[e];if(void 0===i||void 0===i._def)continue;let o=Zh(i);o&&r&&("ZodOptional"===i._def.typeName&&(i=i._def.innerType),i.isNullable()||(i=i.nullable()),o=!1);let l=Gh(i._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==l&&(n.properties[e]=l,o||s.push(e))}s.length&&(n.required=s);let i=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return Gh(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==i&&(n.additionalProperties=i),n}(e,r);case pi.ZodBigInt:return function(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?n.inclusive?vh(r,"minimum",n.value,n.message,t):vh(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),vh(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?vh(r,"maximum",n.value,n.message,t):vh(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),vh(r,"maximum",n.value,n.message,t));break;case"multipleOf":vh(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case pi.ZodBoolean:return{type:"boolean"};case pi.ZodDate:return Eh(e,r);case pi.ZodUndefined:return function(e){return{not:bh(e)}}(r);case pi.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case pi.ZodArray:return function(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==pi.ZodAny&&(r.items=Gh(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&vh(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&vh(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(vh(r,"minItems",e.exactLength.value,e.exactLength.message,t),vh(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case pi.ZodUnion:case pi.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return Hh(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(e=>e._def.typeName in qh&&(!e._def.checks||!e._def.checks.length))){let e=r.reduce((e,t)=>{let r=qh[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(r.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=r.reduce((e,t)=>{let r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===r.length){let t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:r.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(r.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:r.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Hh(e,t)}(e,r);case pi.ZodIntersection:return function(e,t){let r=[Gh(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Gh(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e),n="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0,s=[];return r.forEach(e=>{if((e=>(!("type"in e)||"string"!==e.type)&&"allOf"in e)(e))s.push(...e.allOf),void 0===e.unevaluatedProperties&&(n=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...n}=e;t=n}else n=void 0;s.push(t)}}),s.length?{allOf:s,...n}:void 0}(e,r);case pi.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,r)=>Gh(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:Gh(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,r)=>Gh(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,r);case pi.ZodRecord:return Fh(e,r);case pi.ZodLiteral:return function(e,t){let r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}(e,r);case pi.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case pi.ZodNativeEnum:return function(e){let t=e.values,r=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),n=Array.from(new Set(r.map(e=>typeof e)));return{type:1===n.length?"string"===n[0]?"string":"number":["string","number"],enum:r}}(e);case pi.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:qh[e.innerType._def.typeName],nullable:!0}:{type:[qh[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){let r=Gh(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let r=Gh(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case pi.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Gh(e.innerType._def,t);let r=Gh(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:bh(t)},r]}:bh(t)})(e,r);case pi.ZodMap:return function(e,t){return"record"===t.mapStrategy?Fh(e,t):{type:"array",maxItems:125,items:{type:"array",items:[Gh(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||bh(t),Gh(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||bh(t)],minItems:2,maxItems:2}}}(e,r);case pi.ZodSet:return function(e,t){let r={type:"array",uniqueItems:!0,items:Gh(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&vh(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&vh(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case pi.ZodLazy:return()=>e.getter()._def;case pi.ZodPromise:return function(e,t){return Gh(e.type._def,t)}(e,r);case pi.ZodNaN:case pi.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:bh({...e,currentPath:[...e.currentPath,"not"]})}}(r);case pi.ZodEffects:return function(e,t){return"input"===t.effectStrategy?Gh(e.schema._def,t):bh(t)}(e,r);case pi.ZodAny:return bh(r);case pi.ZodUnknown:return function(e){return bh(e)}(r);case pi.ZodDefault:return function(e,t){return{...Gh(e.innerType._def,t),default:e.defaultValue()}}(e,r);case pi.ZodBranded:return wh(e,r);case pi.ZodReadonly:case pi.ZodCatch:return((e,t)=>Gh(e.innerType._def,t))(e,r);case pi.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return Gh(e.in._def,t);if("output"===t.pipeStrategy)return Gh(e.out._def,t);let r=Gh(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,Gh(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter(e=>void 0!==e)}})(e,r);case pi.ZodFunction:case pi.ZodVoid:case pi.ZodSymbol:default:return}};function Gh(e,t,r=!1){let n=t.seen.get(e);if(t.override){let s=t.override?.(e,t,n,r);if(s!==mh)return s}if(n&&!r){let e=Wh(n,t);if(void 0!==e)return e}let s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);let a=Vh(e,e.typeName,t),i="function"==typeof a?Gh(a(),t):a;if(i&&Kh(e,t,i),t.postProcess){let r=t.postProcess(i,e,t);return s.jsonSchema=i,r}return s.jsonSchema=i,i}var Wh=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:_h(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),bh(t)):"seen"===t.$refStrategy?bh(t):void 0}},Kh=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);function Yh(e){return e?"jsonSchema7"===e||"draft-7"===e?"draft-7":"jsonSchema2019-09"===e||"draft-2020-12"===e?"draft-2020-12":"draft-7":"draft-7"}function Jh(e,t){var r,n,s;return Vc(e)?function(e,t){if(e instanceof Pc){let r=new Bc(t),n={};for(let t of e._idmap.entries()){let[e,n]=t;r.process(n)}let s={},a={registry:e,uri:t?.uri||(e=>e),defs:n};for(let n of e._idmap.entries()){let[e,i]=n;s[e]=r.emit(i,{...t,external:a})}if(Object.keys(n).length>0){let e="draft-2020-12"===r.target?"$defs":"definitions";s.__shared={[e]:n}}return{schemas:s}}let r=new Bc(t);return r.process(e),r.emit(e,t)}(e,{target:Yh(null==t?void 0:t.target),io:null!==(r=null==t?void 0:t.pipeStrategy)&&void 0!==r?r:"input"}):((e,t)=>{let r=(e=>{let t=(e=>"string"==typeof e?{...gh,name:e}:{...gh,...e})(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}})(t),n=t.definitions?Object.entries(t.definitions).reduce((e,[t,n])=>({...e,[t]:Gh(n._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0)??bh(r)}),{}):void 0,s="title"===t?.nameStrategy?void 0:t?.name,a=Gh(e._def,void 0===s?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??bh(r),i=void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==i&&(a.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===r.$refStrategy?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let o=void 0===s?n?{...a,[r.definitionPath]:n}:a:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:a}};return"jsonSchema7"===r.target?o.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==r.target&&"openAi"!==r.target||(o.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o})(e,{strictUnions:null===(n=null==t?void 0:t.strictUnions)||void 0===n||n,pipeStrategy:null!==(s=null==t?void 0:t.pipeStrategy)&&void 0!==s?s:"input"})}function Qh(e){let t=Yc(e),r=null==t?void 0:t.method;if(!r)throw Error("Schema is missing a method literal");let n=Xc(r);if("string"!=typeof n)throw Error("Schema method literal must be a string");return n}function Xh(e,t){let r=Wc(e,t);if(!r.success)throw r.error;return r.data}var em=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ep,e=>{this._oncancel(e)}),this.setNotificationHandler(vp,e=>{this._onprogress(e)}),this.setRequestHandler(mp,e=>({})),this._taskStore=null==e?void 0:e.taskStore,this._taskMessageQueue=null==e?void 0:e.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Tp,async(e,t)=>{let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new ph(Pd.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler($p,async(e,t)=>{let r=async()=>{var n;let s=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(s,t.sessionId);){if("response"===e.type||"error"===e.type){let t=e.message,r=t.id,n=this._requestResolvers.get(r);if(n)if(this._requestResolvers.delete(r),"response"===e.type)n(t);else{let e=t;n(new ph(e.error.code,e.error.message,e.error.data))}else{let t="response"===e.type?"Response":"Error";this._onerror(Error(`${t} handler missing for request ${r}`))}continue}await(null===(n=this._transport)||void 0===n?void 0:n.send(e.message,{relatedRequestId:t.requestId}))}}let a=await this._taskStore.getTask(s,t.sessionId);if(!a)throw new ph(Pd.InvalidParams,`Task not found: ${s}`);if(!hh(a.status))return await this._waitForTaskUpdate(s,t.signal),await r();if(hh(a.status)){let e=await this._taskStore.getTaskResult(s,t.sessionId);return this._clearTaskQueue(s),{...e,_meta:{...e._meta,[Ad]:{taskId:s}}}}return await r()};return await r()}),this.setRequestHandler(Pp,async(e,t)=>{var r;try{let{tasks:n,nextCursor:s}=await this._taskStore.listTasks(null===(r=e.params)||void 0===r?void 0:r.cursor,t.sessionId);return{tasks:n,nextCursor:s,_meta:{}}}catch(e){throw new ph(Pd.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Rp,async(e,t)=>{try{let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new ph(Pd.InvalidParams,`Task not found: ${e.params.taskId}`);if(hh(r.status))throw new ph(Pd.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId);let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new ph(Pd.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...n}}catch(e){if(e instanceof ph)throw e;throw new ph(Pd.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){let t=this._requestHandlerAbortControllers.get(e.params.requestId);null==t||t.abort(e.params.reason)}_setupTimeout(e,t,r,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),ph.fromError(Pd.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var t,r,n;this._transport=e;let s=null===(t=this.transport)||void 0===t?void 0:t.onclose;this._transport.onclose=()=>{null==s||s(),this._onclose()};let a=null===(r=this.transport)||void 0===r?void 0:r.onerror;this._transport.onerror=e=>{null==a||a(e),this._onerror(e)};let i=null===(n=this._transport)||void 0===n?void 0:n.onmessage;this._transport.onmessage=(e,t)=>{null==i||i(e,t),Yd(e)||(e=>Jd.safeParse(e).success)(e)?this._onresponse(e):Gd(e)?this._onrequest(e,t):(e=>Wd.safeParse(e).success)(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){var e;let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=ph.fromError(Pd.ConnectionClosed,"Connection closed");this._transport=void 0,null===(e=this.onclose)||void 0===e||e.call(this);for(let e of t.values())e(r)}_onerror(e){var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}_onnotification(e){var t;let r=null!==(t=this._notificationHandlers.get(e.method))&&void 0!==t?t:this.fallbackNotificationHandler;void 0!==r&&Promise.resolve().then(()=>r(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){var r,n,s,a,i,o;let l=null!==(r=this._requestHandlers.get(e.method))&&void 0!==r?r:this.fallbackRequestHandler,c=this._transport,u=null===(a=null===(s=null===(n=e.params)||void 0===n?void 0:n._meta)||void 0===s?void 0:s[Ad])||void 0===a?void 0:a.taskId;if(void 0===l){let t={jsonrpc:"2.0",id:e.id,error:{code:Pd.MethodNotFound,message:"Method not found"}};return void(u&&this._taskMessageQueue?this._enqueueTaskMessage(u,{type:"error",message:t,timestamp:Date.now()},null==c?void 0:c.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):null==c||c.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`))))}let d=new AbortController;this._requestHandlerAbortControllers.set(e.id,d);let p=null===(i=e.params)||void 0===i?void 0:i.task,f=this._taskStore?this.requestTaskStore(e,null==c?void 0:c.sessionId):void 0,h={signal:d.signal,sessionId:null==c?void 0:c.sessionId,_meta:null===(o=e.params)||void 0===o?void 0:o._meta,sendNotification:async t=>{let r={relatedRequestId:e.id};u&&(r.relatedTask={taskId:u}),await this.notification(t,r)},sendRequest:async(t,r,n)=>{var s,a;let i={...n,relatedRequestId:e.id};u&&!i.relatedTask&&(i.relatedTask={taskId:u});let o=null!==(a=null===(s=i.relatedTask)||void 0===s?void 0:s.taskId)&&void 0!==a?a:u;return o&&f&&await f.updateTaskStatus(o,"input_required"),await this.request(t,r,i)},authInfo:null==t?void 0:t.authInfo,requestId:e.id,requestInfo:null==t?void 0:t.requestInfo,taskId:u,taskStore:f,taskRequestedTtl:null==p?void 0:p.ttl,closeSSEStream:null==t?void 0:t.closeSSEStream,closeStandaloneSSEStream:null==t?void 0:t.closeStandaloneSSEStream};Promise.resolve().then(()=>{p&&this.assertTaskHandlerCapability(e.method)}).then(()=>l(e,h)).then(async t=>{if(d.signal.aborted)return;let r={result:t,jsonrpc:"2.0",id:e.id};u&&this._taskMessageQueue?await this._enqueueTaskMessage(u,{type:"response",message:r,timestamp:Date.now()},null==c?void 0:c.sessionId):await(null==c?void 0:c.send(r))},async t=>{var r;if(d.signal.aborted)return;let n={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Pd.InternalError,message:null!==(r=t.message)&&void 0!==r?r:"Internal error",...void 0!==t.data&&{data:t.data}}};u&&this._taskMessageQueue?await this._enqueueTaskMessage(u,{type:"error",message:n,timestamp:Date.now()},null==c?void 0:c.sessionId):await(null==c?void 0:c.send(n))}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),s=this._progressHandlers.get(n);if(!s)return void this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));let a=this._responseHandlers.get(n),i=this._timeoutInfo.get(n);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(e){return this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),void a(e)}s(r)}_onresponse(e){let t=Number(e.id),r=this._requestResolvers.get(t);if(r)return this._requestResolvers.delete(t),void(Yd(e)?r(e):r(new ph(e.error.code,e.error.message,e.error.data)));let n=this._responseHandlers.get(t);if(void 0===n)return void this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(t),this._cleanupTimeout(t);let s=!1;if(Yd(e)&&e.result&&"object"==typeof e.result){let r=e.result;if(r.task&&"object"==typeof r.task){let e=r.task;"string"==typeof e.taskId&&(s=!0,this._taskProgressTokens.set(e.taskId,t))}}s||this._progressHandlers.delete(t),Yd(e)?n(e):n(ph.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){var e;await(null===(e=this._transport)||void 0===e?void 0:e.close())}async*requestStream(e,t,r){var n,s,a,i;let o,{task:l}=null!=r?r:{};if(l)try{let l=await this.request(e,xp,r);if(!l.task)throw new ph(Pd.InternalError,"Task creation did not return a task");for(o=l.task.taskId,yield{type:"taskCreated",task:l.task};;){let e=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:e},hh(e.status))return void("completed"===e.status?yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)}:"failed"===e.status?yield{type:"error",error:new ph(Pd.InternalError,`Task ${o} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new ph(Pd.InternalError,`Task ${o} was cancelled`)}));if("input_required"===e.status)return void(yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)});let l=null!==(a=null!==(n=e.pollInterval)&&void 0!==n?n:null===(s=this._options)||void 0===s?void 0:s.defaultTaskPollInterval)&&void 0!==a?a:1e3;await new Promise(e=>setTimeout(e,l)),null===(i=null==r?void 0:r.signal)||void 0===i||i.throwIfAborted()}}catch(e){yield{type:"error",error:e instanceof ph?e:new ph(Pd.InternalError,String(e))}}else try{yield{type:"result",result:await this.request(e,t,r)}}catch(e){yield{type:"error",error:e instanceof ph?e:new ph(Pd.InternalError,String(e))}}}request(e,t,r){let{relatedRequestId:n,resumptionToken:s,onresumptiontoken:a,task:i,relatedTask:o}=null!=r?r:{};return new Promise((l,c)=>{var u,d,p,f,h,m,g;let y=e=>{c(e)};if(!this._transport)return void y(Error("Not connected"));if(!0===(null===(u=this._options)||void 0===u?void 0:u.enforceStrictCapabilities))try{this.assertCapabilityForMethod(e.method),i&&this.assertTaskCapability(e.method)}catch(e){return void y(e)}null===(d=null==r?void 0:r.signal)||void 0===d||d.throwIfAborted();let v=this._requestMessageId++,_={...e,jsonrpc:"2.0",id:v};(null==r?void 0:r.onprogress)&&(this._progressHandlers.set(v,r.onprogress),_.params={...e.params,_meta:{...(null===(p=e.params)||void 0===p?void 0:p._meta)||{},progressToken:v}}),i&&(_.params={..._.params,task:i}),o&&(_.params={..._.params,_meta:{...(null===(f=_.params)||void 0===f?void 0:f._meta)||{},[Ad]:o}});let b=e=>{var t;this._responseHandlers.delete(v),this._progressHandlers.delete(v),this._cleanupTimeout(v),null===(t=this._transport)||void 0===t||t.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:v,reason:String(e)}},{relatedRequestId:n,resumptionToken:s,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`)));let r=e instanceof ph?e:new ph(Pd.RequestTimeout,String(e));c(r)};this._responseHandlers.set(v,e=>{var n;if(!(null===(n=null==r?void 0:r.signal)||void 0===n?void 0:n.aborted)){if(e instanceof Error)return c(e);try{let r=Wc(t,e.result);r.success?l(r.data):c(r.error)}catch(e){c(e)}}}),null===(h=null==r?void 0:r.signal)||void 0===h||h.addEventListener("abort",()=>{var e;b(null===(e=null==r?void 0:r.signal)||void 0===e?void 0:e.reason)});let w=null!==(m=null==r?void 0:r.timeout)&&void 0!==m?m:6e4;this._setupTimeout(v,w,null==r?void 0:r.maxTotalTimeout,()=>b(ph.fromError(Pd.RequestTimeout,"Request timed out",{timeout:w})),null!==(g=null==r?void 0:r.resetTimeoutOnProgress)&&void 0!==g&&g);let E=null==o?void 0:o.taskId;if(E){let e=e=>{let t=this._responseHandlers.get(v);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${v}`))};this._requestResolvers.set(v,e),this._enqueueTaskMessage(E,{type:"request",message:_,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(v),c(e)})}else this._transport.send(_,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(v),c(e)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},Ip,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},Cp,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},Ap,t)}async notification(e,t){var r,n,s,a,i;if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let o=null===(r=null==t?void 0:t.relatedTask)||void 0===r?void 0:r.taskId;if(o){let r={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...(null===(n=e.params)||void 0===n?void 0:n._meta)||{},[Ad]:t.relatedTask}}};return void await this._enqueueTaskMessage(o,{type:"notification",message:r,timestamp:Date.now()})}if((null!==(a=null===(s=this._options)||void 0===s?void 0:s.debouncedNotificationMethods)&&void 0!==a?a:[]).includes(e.method)&&!e.params&&!(null==t?void 0:t.relatedRequestId)&&!(null==t?void 0:t.relatedTask)){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{var r,n;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};(null==t?void 0:t.relatedTask)&&(s={...s,params:{...s.params,_meta:{...(null===(r=s.params)||void 0===r?void 0:r._meta)||{},[Ad]:t.relatedTask}}}),null===(n=this._transport)||void 0===n||n.send(s,t).catch(e=>this._onerror(e))})}let l={...e,jsonrpc:"2.0"};(null==t?void 0:t.relatedTask)&&(l={...l,params:{...l.params,_meta:{...(null===(i=l.params)||void 0===i?void 0:i._meta)||{},[Ad]:t.relatedTask}}}),await this._transport.send(l,t)}setRequestHandler(e,t){let r=Qh(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,n)=>{let s=Xh(e,r);return Promise.resolve(t(s,n))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let r=Qh(e);this._notificationHandlers.set(r,r=>{let n=Xh(e,r);return Promise.resolve(t(n))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);void 0!==t&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,r){var n;if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let s=null===(n=this._options)||void 0===n?void 0:n.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,s)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,t);for(let t of r)if("request"===t.type&&Gd(t.message)){let r=t.message.id,n=this._requestResolvers.get(r);n?(n(new ph(Pd.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(r)):this._onerror(Error(`Resolver missing for request ${r} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){var r,n,s;let a=null!==(n=null===(r=this._options)||void 0===r?void 0:r.defaultTaskPollInterval)&&void 0!==n?n:1e3;try{let t=await(null===(s=this._taskStore)||void 0===s?void 0:s.getTask(e));(null==t?void 0:t.pollInterval)&&(a=t.pollInterval)}catch(e){}return new Promise((e,r)=>{if(t.aborted)return void r(new ph(Pd.InvalidRequest,"Request cancelled"));let n=setTimeout(e,a);t.addEventListener("abort",()=>{clearTimeout(n),r(new ph(Pd.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let r=this._taskStore;if(!r)throw Error("No task store configured");return{createTask:async n=>{if(!e)throw Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let n=await r.getTask(e,t);if(!n)throw new ph(Pd.InvalidParams,"Failed to retrieve task: Task not found");return n},storeTaskResult:async(e,n,s)=>{await r.storeTaskResult(e,n,s,t);let a=await r.getTask(e,t);if(a){let t=kp.parse({method:"notifications/tasks/status",params:a});await this.notification(t),hh(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>r.getTaskResult(e,t),updateTaskStatus:async(e,n,s)=>{let a=await r.getTask(e,t);if(!a)throw new ph(Pd.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(hh(a.status))throw new ph(Pd.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${n}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(e,n,s,t);let i=await r.getTask(e,t);if(i){let t=kp.parse({method:"notifications/tasks/status",params:i});await this.notification(t),hh(i.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>r.listTasks(e,t)}}};function tm(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}var rm,nm=rr(bn()),sm=rr(xn()),am=class{constructor(e){this._ajv=null!=e?e:function(){let e=new nm.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return sm.default(e),e}()}getValidator(e){var t;let r="$id"in e&&"string"==typeof e.$id&&null!==(t=this._ajv.getSchema(e.$id))&&void 0!==t?t:this._ajv.compile(e);return e=>r(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}},im=class{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}},om=class extends em{constructor(e,t){var r,n;super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Tf.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let r=this._loggingLevels.get(t);return!!r&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(r)},this._capabilities=null!==(r=null==t?void 0:t.capabilities)&&void 0!==r?r:{},this._instructions=null==t?void 0:t.instructions,this._jsonSchemaValidator=null!==(n=null==t?void 0:t.jsonSchemaValidator)&&void 0!==n?n:new am,this.setRequestHandler(dp,e=>this._oninitialize(e)),this.setNotificationHandler(hp,()=>{var e;return null===(e=this.oninitialized)||void 0===e?void 0:e.call(this)}),this._capabilities.logging&&this.setRequestHandler($f,async(e,t)=>{var r;let n=t.sessionId||(null===(r=t.requestInfo)||void 0===r?void 0:r.headers["mcp-session-id"])||void 0,{level:s}=e.params,a=Tf.safeParse(s);return a.success&&this._loggingLevels.set(n,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new im(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=function(e,t){let r={...e};for(let e in t){let n=e,s=t[n];if(void 0===s)continue;let a=r[n];tm(a)&&tm(s)?r[n]={...a,...s}:r[n]=s}return r}(this._capabilities,e)}setRequestHandler(e,t){var r,n,s;let a,i=Yc(e),o=null==i?void 0:i.method;if(!o)throw Error("Schema is missing a method literal");if(Vc(o)){let e=o,t=null===(r=e._zod)||void 0===r?void 0:r.def;a=null!==(n=null==t?void 0:t.value)&&void 0!==n?n:e.value}else{let e=o,t=e._def;a=null!==(s=null==t?void 0:t.value)&&void 0!==s?s:e.value}if("string"!=typeof a)throw Error("Schema method literal must be a string");if("tools/call"===a){let r=async(e,r)=>{let n=Wc(Sf,e);if(!n.success){let e=n.error instanceof Error?n.error.message:String(n.error);throw new ph(Pd.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:s}=n.data,a=await Promise.resolve(t(e,r));if(s.task){let e=Wc(xp,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new ph(Pd.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let i=Wc(Ef,a);if(!i.success){let e=i.error instanceof Error?i.error.message:String(i.error);throw new ph(Pd.InvalidParams,`Invalid tools/call result: ${e}`)}return i.data};return super.setRequestHandler(e,r)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){var t,r,n;switch(e){case"sampling/createMessage":if(!(null===(t=this._clientCapabilities)||void 0===t?void 0:t.sampling))throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(null===(r=this._clientCapabilities)||void 0===r?void 0:r.elicitation))throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(null===(n=this._clientCapabilities)||void 0===n?void 0:n.roots))throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){var t,r;switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!(null===(r=null===(t=this._clientCapabilities)||void 0===t?void 0:t.elicitation)||void 0===r?void 0:r.url))throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){var t,r;!function(e,t,r){var n,s;if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!(null===(n=e.sampling)||void 0===n?void 0:n.createMessage))throw Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!(null===(s=e.elicitation)||void 0===s?void 0:s.create))throw Error(`${r} does not support task creation for elicitation/create (required for ${t})`)}}(null===(r=null===(t=this._clientCapabilities)||void 0===t?void 0:t.tasks)||void 0===r?void 0:r.requests,e,"Client")}assertTaskHandlerCapability(e){var t;this._capabilities&&function(e,t,r){var n;if(!e)throw Error(`${r} does not support task creation (required for ${t})`);if("tools/call"===t&&!(null===(n=e.tools)||void 0===n?void 0:n.call))throw Error(`${r} does not support task creation for tools/call (required for ${t})`)}(null===(t=this._capabilities.tasks)||void 0===t?void 0:t.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Rd.includes(t)?t:Cd,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Qd)}async createMessage(e,t){var r,n;if((e.tools||e.toolChoice)&&!(null===(n=null===(r=this._clientCapabilities)||void 0===r?void 0:r.sampling)||void 0===n?void 0:n.tools))throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let t=e.messages[e.messages.length-1],r=Array.isArray(t.content)?t.content:[t.content],n=r.some(e=>"tool_result"===e.type),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],i=a.some(e=>"tool_use"===e.type);if(n){if(r.some(e=>"tool_result"!==e.type))throw Error("The last message must contain only tool_result content if any is present");if(!i)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(i){let e=new Set(a.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(r.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Bf,t):this.request({method:"sampling/createMessage",params:e},zf,t)}async elicitInput(e,t){var r,n,s,a,i;switch(null!==(r=e.mode)&&void 0!==r?r:"form"){case"url":{if(!(null===(s=null===(n=this._clientCapabilities)||void 0===n?void 0:n.elicitation)||void 0===s?void 0:s.url))throw Error("Client does not support url elicitation.");let r=e;return this.request({method:"elicitation/create",params:r},rh,t)}case"form":{if(!(null===(i=null===(a=this._clientCapabilities)||void 0===a?void 0:a.elicitation)||void 0===i?void 0:i.form))throw Error("Client does not support form elicitation.");let r="form"===e.mode?e:{...e,mode:"form"},n=await this.request({method:"elicitation/create",params:r},rh,t);if("accept"===n.action&&n.content&&r.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(r.requestedSchema)(n.content);if(!e.valid)throw new ph(Pd.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof ph)throw e;throw new ph(Pd.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return n}}}createElicitationCompletionNotifier(e,t){var r,n;if(!(null===(n=null===(r=this._clientCapabilities)||void 0===r?void 0:r.elicitation)||void 0===n?void 0:n.url))throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},uh,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}},lm=Symbol.for("mcp.completable");(rm||(rm={})).Completable="McpCompletable";var cm=/^[A-Za-z0-9._-]{1,128}$/;function um(e){let t=function(e){let t=[];if(0===e.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!cm.test(e)){let r=e.split("").filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,r)=>r.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${r.map(e=>`"${e}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}(e);return function(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}(e,t.warnings),t.isValid}var dm=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let n={taskSupport:"required",...t.execution};if("forbidden"===n.taskSupport)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,n,t._meta,r)}},pm=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new om(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new dm(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(vm(bf)),this.server.assertCanSetRequestHandler(vm(Sf)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(bf,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=Jc(t.inputSchema);return e?Jh(e,{strictUnions:!0,pipeStrategy:"input"}):fm})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=Jc(t.outputSchema);e&&(r.outputSchema=Jh(e,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Sf,async(e,t)=>{var r;try{let n=this._registeredTools[e.params.name];if(!n)throw new ph(Pd.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new ph(Pd.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,a=null===(r=n.execution)||void 0===r?void 0:r.taskSupport,i="createTask"in n.handler;if(("required"===a||"optional"===a)&&!i)throw new ph(Pd.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if("required"===a&&!s)throw new ph(Pd.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if("optional"===a&&!s&&i)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),l=await this.executeToolHandler(n,o,t);return s||await this.validateToolOutput(n,l,e.params.name),l}catch(e){if(e instanceof ph&&e.code===Pd.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(!e.inputSchema)return;let n=Jc(e.inputSchema),s=null!=n?n:e.inputSchema,a=await Kc(s,t);if(!a.success){let e=Qc("error"in a?a.error:"Unknown error");throw new ph(Pd.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${e}`)}return a.data}async validateToolOutput(e,t,r){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new ph(Pd.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=Jc(e.outputSchema),s=await Kc(n,t.structuredContent);if(!s.success){let e=Qc("error"in s?s.error:"Unknown error");throw new ph(Pd.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${e}`)}}async executeToolHandler(e,t,r){let n=e.handler;if("createTask"in n){if(!r.taskStore)throw Error("No task store provided.");let s={...r,taskStore:r.taskStore};return e.inputSchema?await Promise.resolve(n.createTask(t,s)):await Promise.resolve(n.createTask(s))}return e.inputSchema?await Promise.resolve(n(t,r)):await Promise.resolve(n(r))}async handleAutomaticTaskPolling(e,t,r){var n;if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let s=await this.validateToolInput(e,t.params.arguments,t.params.name),a=e.handler,i={...r,taskStore:r.taskStore},o=s?await Promise.resolve(a.createTask(s,i)):await Promise.resolve(a.createTask(i)),l=o.task.taskId,c=o.task,u=null!==(n=c.pollInterval)&&void 0!==n?n:5e3;for(;"completed"!==c.status&&"failed"!==c.status&&"cancelled"!==c.status;){await new Promise(e=>setTimeout(e,u));let e=await r.taskStore.getTask(l);if(!e)throw new ph(Pd.InternalError,`Task ${l} not found during polling`);c=e}return await r.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(vm(ih)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(ih,async e=>{switch(e.params.ref.type){case"ref/prompt":return function(e){if("ref/prompt"!==e.params.ref.type)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return function(e){if("ref/resource"!==e.params.ref.type)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}(e),this.handleResourceCompletion(e,e.params.ref);default:throw new ph(Pd.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new ph(Pd.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new ph(Pd.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return bm;let n=Yc(r.argsSchema),s=null==n?void 0:n[e.params.argument.name];if(!function(e){return!!e&&"object"==typeof e&&lm in e}(s))return bm;let a=function(e){let t=e[lm];return null==t?void 0:t.complete}(s);return a?_m(await a(e.params.argument.value,e.params.context)):bm}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return bm;throw new ph(Pd.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);return n?_m(await n(e.params.argument.value,e.params.context)):bm}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(vm(zp)),this.server.assertCanSetRequestHandler(vm(Fp)),this.server.assertCanSetRequestHandler(vm(Vp)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(zp,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),n=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let r=await e.resourceTemplate.listCallback(t);for(let t of r.resources)n.push({...e.metadata,...t})}return{resources:[...r,...n]}}),this.server.setRequestHandler(Fp,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(Vp,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new ph(Pd.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let e of Object.values(this._registeredResourceTemplates)){let n=e.resourceTemplate.uriTemplate.match(r.toString());if(n)return e.readCallback(r,n,t)}throw new ph(Pd.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(vm(nf)),this.server.assertCanSetRequestHandler(vm(of)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(nf,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?ym(t.argsSchema):void 0}))})),this.server.setRequestHandler(of,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new ph(Pd.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new ph(Pd.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=Jc(r.argsSchema),s=await Kc(n,e.params.arguments);if(!s.success){let t=Qc("error"in s?s.error:"Unknown error");throw new ph(Pd.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let a=s.data,i=r.callback;return await Promise.resolve(i(a,t))}{let e=r.callback;return await Promise.resolve(e(t))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,t,...r){let n;"object"==typeof r[0]&&(n=r.shift());let s=r[0];if("string"==typeof t){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let r=this._createRegisteredResource(e,void 0,t,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let r=this._createRegisteredResourceTemplate(e,void 0,t,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}}registerResource(e,t,r,n){if("string"==typeof t){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let s=this._createRegisteredResource(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,t,r,n,s){let a={name:e,title:t,metadata:n,readCallback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{typeof e.uri<"u"&&e.uri!==r&&(delete this._registeredResources[r],e.uri&&(this._registeredResources[e.uri]=a)),typeof e.name<"u"&&(a.name=e.name),typeof e.title<"u"&&(a.title=e.title),typeof e.metadata<"u"&&(a.metadata=e.metadata),typeof e.callback<"u"&&(a.readCallback=e.callback),typeof e.enabled<"u"&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=a,a}_createRegisteredResourceTemplate(e,t,r,n,s){let a={resourceTemplate:r,title:t,metadata:n,readCallback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{typeof t.name<"u"&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),typeof t.title<"u"&&(a.title=t.title),typeof t.template<"u"&&(a.resourceTemplate=t.template),typeof t.metadata<"u"&&(a.metadata=t.metadata),typeof t.callback<"u"&&(a.readCallback=t.callback),typeof t.enabled<"u"&&(a.enabled=t.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=a,a}_createRegisteredPrompt(e,t,r,n,s){let a={title:t,description:r,argsSchema:void 0===n?void 0:Gc(n),callback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{typeof t.name<"u"&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),typeof t.title<"u"&&(a.title=t.title),typeof t.description<"u"&&(a.description=t.description),typeof t.argsSchema<"u"&&(a.argsSchema=Gc(t.argsSchema)),typeof t.callback<"u"&&(a.callback=t.callback),typeof t.enabled<"u"&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,a}_createRegisteredTool(e,t,r,n,s,a,i,o,l){um(e);let c={title:t,description:r,inputSchema:gm(n),outputSchema:gm(s),annotations:a,execution:i,_meta:o,handler:l,enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:t=>{typeof t.name<"u"&&t.name!==e&&("string"==typeof t.name&&um(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=c)),typeof t.title<"u"&&(c.title=t.title),typeof t.description<"u"&&(c.description=t.description),typeof t.paramsSchema<"u"&&(c.inputSchema=Gc(t.paramsSchema)),typeof t.callback<"u"&&(c.handler=t.callback),typeof t.annotations<"u"&&(c.annotations=t.annotations),typeof t._meta<"u"&&(c._meta=t._meta),typeof t.enabled<"u"&&(c.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=c,this.setToolRequestHandlers(),this.sendToolListChanged(),c}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r,n,s;if("string"==typeof t[0]&&(r=t.shift()),t.length>1){let e=t[0];mm(e)?(n=t.shift(),t.length>1&&"object"==typeof t[0]&&null!==t[0]&&!mm(t[0])&&(s=t.shift())):"object"==typeof e&&null!==e&&(s=t.shift())}let a=t[0];return this._createRegisteredTool(e,void 0,r,n,void 0,s,{taskSupport:"forbidden"},void 0,a)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:n,description:s,inputSchema:a,outputSchema:i,annotations:o,_meta:l}=t;return this._createRegisteredTool(e,n,s,a,i,o,{taskSupport:"forbidden"},l,r)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let r,n;"string"==typeof t[0]&&(r=t.shift()),t.length>1&&(n=t.shift());let s=t[0],a=this._createRegisteredPrompt(e,void 0,r,n,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:n,description:s,argsSchema:a}=t,i=this._createRegisteredPrompt(e,n,s,a,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},fm={type:"object",properties:{}};function hm(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function mm(e){return"object"==typeof e&&null!==e&&!function(e){return"_def"in e||"_zod"in e||hm(e)}(e)&&(0===Object.keys(e).length||Object.values(e).some(hm))}function gm(e){if(e)return mm(e)?Gc(e):e}function ym(e){let t=Yc(e);return t?Object.entries(t).map(([e,t])=>{let r=function(e){var t,r,n,s;if(Vc(e))return null===(r=null===(t=e._zod)||void 0===t?void 0:t.def)||void 0===r?void 0:r.description;let a=e;return null!==(n=e.description)&&void 0!==n?n:null===(s=a._def)||void 0===s?void 0:s.description}(t),n=function(e){var t,r,n;if(Vc(e))return"optional"===(null===(r=null===(t=e._zod)||void 0===t?void 0:t.def)||void 0===r?void 0:r.type);let s=e;return"function"==typeof e.isOptional?e.isOptional():"ZodOptional"===(null===(n=s._def)||void 0===n?void 0:n.typeName)}(t);return{name:e,description:r,required:!n}}):[]}function vm(e){let t=Yc(e),r=null==t?void 0:t.method;if(!r)throw Error("Schema is missing a method literal");let n=Xc(r);if("string"==typeof n)return n;throw Error("Schema method literal must be a string")}function _m(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var bm={completion:{values:[],hasMore:!1}};function wm(e,t,r,n,s){return{name:e,description:t,inputSchema:r,handler:n,annotations:s?.annotations}}function Em(e){let t=new pm({name:e.name,version:e.version??"1.0.0"},{capabilities:{tools:e.tools?{}:void 0}});return e.tools&&e.tools.forEach(e=>{t.registerTool(e.name,{description:e.description,inputSchema:e.inputSchema,annotations:e.annotations},e.handler)}),{type:"sdk",name:e.name,instance:t}}var xm=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=y.simpleGit({baseDir:e.workingDir,maxConcurrentProcesses:1})}static createLocal({workingDir:t}){return new e({mode:"local",workingDir:t})}static createCloud({workingDir:t,baseBranch:r}){return new e({mode:"cloud",workingDir:t,baseBranch:r})}async captureSnapshot(){if("local"!==this.config.mode)return;this.snapshotIndexPath=t.join(l.tmpdir(),`git-diff-tracker-${h.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=t.join(l.tmpdir(),`git-diff-tracker-${h.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 Sm(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 Sm(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function Sm(e){try{await f.unlink(e)}catch{}}var km="x-stably-org-id",Tm={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},Im=({allowReserved:e,explode:t,name:r,style:n,value:s})=>{if(!t){const t=(e?s:s.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(n));switch(n){case"label":return`.${t}`;case"matrix":return`;${r}=${t}`;case"simple":return t;default:return`${r}=${t}`}}const a=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),i=s.map(t=>"label"===n||"simple"===n?e?t:encodeURIComponent(t):$m({allowReserved:e,name:r,value:t})).join(a);return"label"===n||"matrix"===n?a+i:i},$m=({allowReserved:e,name:t,value:r})=>{if(null==r)return"";if("object"==typeof r)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?r:encodeURIComponent(r)}`},Pm=({allowReserved:e,explode:t,name:r,style:n,value:s,valueOnly:a})=>{if(s instanceof Date)return a?s.toISOString():`${r}=${s.toISOString()}`;if("deepObject"!==n&&!t){let t=[];Object.entries(s).forEach(([r,n])=>{t=[...t,r,e?n:encodeURIComponent(n)]});const a=t.join(",");switch(n){case"form":return`${r}=${a}`;case"label":return`.${a}`;case"matrix":return`;${r}=${a}`;default:return a}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),o=Object.entries(s).map(([t,s])=>$m({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:s})).join(i);return"label"===n||"matrix"===n?i+o:o},Cm=/\{[^{}]+\}/g;function Rm(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 Am,Om=async(e,t)=>{const r="function"==typeof t?await t(e):t;if(r)return"bearer"===e.scheme?`Bearer ${r}`:"basic"===e.scheme?`Basic ${btoa(r)}`:r},Nm=({parameters:e={},...t}={})=>r=>{const n=[];if(r&&"object"==typeof r)for(const s in r){const a=r[s];if(null==a)continue;const i=e[s]||t;if(Array.isArray(a)){const e=Im({allowReserved:i.allowReserved,explode:!0,name:s,style:"form",value:a,...i.array});e&&n.push(e)}else if("object"==typeof a){const e=Pm({allowReserved:i.allowReserved,explode:!0,name:s,style:"deepObject",value:a,...i.object});e&&n.push(e)}else{const e=$m({allowReserved:i.allowReserved,name:s,value:a});e&&n.push(e)}}return n.join("&")},jm=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Dm=e=>(({baseUrl:e,path:t,query:r,querySerializer:n,url:s})=>{let a=(e??"")+(s.startsWith("/")?s:`/${s}`);t&&(a=(({path:e,url:t})=>{let r=t;const n=t.match(Cm);if(n)for(const t of n){let n=!1,s=t.substring(1,t.length-1),a="simple";s.endsWith("*")&&(n=!0,s=s.substring(0,s.length-1)),s.startsWith(".")?(s=s.substring(1),a="label"):s.startsWith(";")&&(s=s.substring(1),a="matrix");const i=e[s];if(null==i)continue;if(Array.isArray(i)){r=r.replace(t,Im({explode:n,name:s,style:a,value:i}));continue}if("object"==typeof i){r=r.replace(t,Pm({explode:n,name:s,style:a,value:i,valueOnly:!0}));continue}if("matrix"===a){r=r.replace(t,`;${$m({name:s,value:i})}`);continue}const o=encodeURIComponent("label"===a?`.${i}`:i);r=r.replace(t,o)}return r})({path:t,url:a}));let i=r?n(r):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(a+=`?${i}`),a})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:Nm(e.querySerializer),url:e.url}),Um=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=Mm(e.headers,t.headers),r},Lm=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},Mm=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?Lm(r):Object.entries(r);for(const[r,n]of e)if(null===n)t.delete(r);else if(Array.isArray(n))for(const e of n)t.append(r,e);else void 0!==n&&t.set(r,"object"==typeof n?JSON.stringify(n):n)}return t},zm=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 r=this.getInterceptorIndex(e);return!!this.fns[r]&&(this.fns[r]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}},Bm=Nm({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Fm={"Content-Type":"application/json"},qm=(e={})=>({...Tm,headers:Fm,parseAs:"auto",querySerializer:Bm,...e}),Hm=(e={})=>{let t=Um(qm(),e);const r=()=>({...t}),n={error:new zm,request:new zm,response:new zm},s=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Mm(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(jm(t,r.name))continue;const e=await Om(r,t.auth);if(!e)continue;const n=r.name??"Authorization";switch(r.in){case"query":t.query||(t.query={}),t.query[n]=e;break;case"cookie":t.headers.append("Cookie",`${n}=${e}`);break;default:t.headers.set(n,e)}}})({...r,security:r.security}),r.requestValidator&&await r.requestValidator(r),void 0!==r.body&&r.bodySerializer&&(r.serializedBody=r.bodySerializer(r.body)),void 0!==r.body&&""!==r.serializedBody||r.headers.delete("Content-Type"),{opts:r,url:Dm(r)}},a=async e=>{const{opts:t,url:r}=await s(e),a={redirect:"follow",...t,body:Rm(t)};let i=new Request(r,a);for(const e of n.request.fns)e&&(i=await e(i,t));const o=t.fetch;let l;try{l=await o(i)}catch(e){let r=e;for(const s of n.error.fns)s&&(r=await s(e,void 0,i,t));if(r=r||{},t.throwOnError)throw r;return"data"===t.responseStyle?void 0:{error:r,request:i,response:void 0}}for(const e of n.response.fns)e&&(l=await e(l,i,t));const c={request:i,response:l};if(l.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})(l.headers.get("Content-Type")):t.parseAs)??"json";if(204===l.status||"0"===l.headers.get("Content-Length")){let r;switch(e){case"arrayBuffer":case"blob":case"text":r=await l[e]();break;case"formData":r=new FormData;break;case"stream":r=l.body;break;default:r={}}return"data"===t.responseStyle?r:{data:r,...c}}let r;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":r=await l[e]();break;case"stream":return"data"===t.responseStyle?l.body:{data:l.body,...c}}return"json"===e&&(t.responseValidator&&await t.responseValidator(r),t.responseTransformer&&(r=await t.responseTransformer(r))),"data"===t.responseStyle?r:{data:r,...c}}const u=await l.text();let d;try{d=JSON.parse(u)}catch{}const p=d??u;let f=p;for(const e of n.error.fns)e&&(f=await e(p,l,i,t));if(f=f||{},t.throwOnError)throw f;return"data"===t.responseStyle?void 0:{error:f,...c}},i=e=>t=>a({...t,method:e}),o=e=>async t=>{const{opts:r,url:a}=await s(t);return(({onRequest:e,onSseError:t,onSseEvent:r,responseTransformer:n,responseValidator:s,sseDefaultRetryDelay:a,sseMaxRetryAttempts:i,sseMaxRetryDelay:o,sseSleepFn:l,url:c,...u})=>{let d;const p=l??(e=>new Promise(t=>setTimeout(t,e))),f=async function*(){let l=a??3e3,f=0;const h=u.signal??(new AbortController).signal;for(;!h.aborted;){f++;const a=u.headers instanceof Headers?u.headers:new Headers(u.headers);void 0!==d&&a.set("Last-Event-ID",d);try{const t={redirect:"follow",...u,body:u.serializedBody,headers:a,signal:h};let i=new Request(c,t);e&&(i=await e(c,t));const o=u.fetch??globalThis.fetch,p=await o(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 a=m.split("\n\n");m=a.pop()??"";for(const e of a){const t=e.split("\n"),a=[];let i,o;for(const e of t)if(e.startsWith("data:"))a.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))i=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))d=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(l=t)}let c=!1;if(a.length){const e=a.join("\n");try{o=JSON.parse(e),c=!0}catch{o=e}}c&&(s&&await s(o),n&&(o=await n(o))),r?.({data:o,event:i,id:d,retry:l}),a.length&&(yield o)}}}finally{h.removeEventListener("abort",g),f.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&f>=i)break;const r=Math.min(l*2**(f-1),o??3e4);await p(r)}}}();return{stream:f}})({...r,body:r.body,headers:r.headers,method:e,onRequest:async(e,t)=>{let s=new Request(e,t);for(const e of n.request.fns)e&&(s=await e(s,r));return s},url:a})};return{buildUrl:Dm,connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),getConfig:r,head:i("HEAD"),interceptors:n,options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),request:a,setConfig:e=>(t=Um(t,e),r()),sse:{connect:o("CONNECT"),delete:o("DELETE"),get:o("GET"),head:o("HEAD"),options:o("OPTIONS"),patch:o("PATCH"),post:o("POST"),put:o("PUT"),trace:o("TRACE")},trace:i("TRACE")}},Zm=Hm(qm({baseUrl:"https://api.stably.ai"})),Vm="4.6.2-rc.1",Gm=process.env.STABLY_API_URL||"https://api.stably.ai",Wm=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},Km=process.env.AUTH_URL||"https://auth.stably.ai",Ym=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",Jm=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",Qm=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",Wm(Gm)).toString(),Xm=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",Wm(Gm)).toString(),eg="http://localhost:9876/auth/callback",tg=()=>Am||(Am=Hm(qm({baseUrl:Gm,headers:{"X-STABLY-CLI-VERSION":Vm,"X-STABLY-SOURCE":"cli"}}))),rg=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:tg()},(n.client??Zm).post({url:"/internal/v1/cli/exchange-token",...n,headers:{"Content-Type":"application/json",...n.headers}}));var n;if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to exchange token: ${r.response.status}`);return r.data},ng=b.z.object({org_id:b.z.string(),org_name:b.z.string()}),sg=b.z.object({email:b.z.string(),org_id_to_org_member_info:b.z.record(b.z.string(),ng).optional(),org_member_info:ng.optional(),user_id:b.z.string()});b.z.object({email:b.z.string(),firstName:b.z.string().optional(),lastName:b.z.string().optional(),organizations:b.z.array(b.z.object({id:b.z.string(),name:b.z.string()})),userId:b.z.string()});var ag,ig,og=e=>{const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf-8");return JSON.parse(n)},lg=e=>{try{const t=sg.parse(og(e)),r=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:r,userId:t.user_id}}catch(e){throw new Error(`Failed to decode token: ${e instanceof Error?e.message:"Unknown error"}`)}},cg=async(e,t)=>{let r=e;const{root:n}=D.default.parse(r);for(;r!==n;){const e=D.default.join(r,t);try{return await f.access(e),e}catch{r=D.default.dirname(r)}}},ug=D.default.join(z.default.homedir(),".stably"),dg=D.default.join(ug,"auth.json"),pg=".stably",fg="project.json",hg=Z.default.object({accessToken:Z.default.string(),expiresAt:Z.default.number(),idToken:Z.default.string().optional(),refreshToken:Z.default.string()}),mg=Z.default.object({orgId:Z.default.string(),orgName:Z.default.string(),projectId:Z.default.string(),projectName:Z.default.string()}),gg=async()=>{try{const e=await f.readFile(dg,"utf-8");return hg.parse(JSON.parse(e))}catch{return}},yg=async e=>{await f.mkdir(ug,{recursive:!0}),await f.writeFile(dg,JSON.stringify(e,null,2),{mode:384})},vg=async()=>{try{await f.unlink(dg)}catch{}},_g=async()=>{try{const e=await cg(process.cwd(),pg);if(!e)return;const t=D.default.join(e,fg),r=await f.readFile(t,"utf-8");return mg.parse(JSON.parse(r))}catch{return}},bg=async()=>{try{const e=await cg(process.cwd(),pg);e&&await f.unlink(D.default.join(e,fg))}catch{}},wg=e=>Date.now()>=e.expiresAt-3e5,Eg=async e=>{const t=new URLSearchParams({client_id:Ym,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${Km}/propelauth/oauth/token`,{body:t.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);const n=await r.json();return{accessToken:n.access_token,expiresAt:Date.now()+1e3*n.expires_in,refreshToken:n.refresh_token}};function xg(){return void 0===ig&&(ig=(()=>{try{return M.default.statSync("/run/.containerenv"),!0}catch{return!1}})()||(void 0===ag&&(ag=function(){try{return M.default.statSync("/.dockerenv"),!0}catch{return!1}}()||function(){try{return M.default.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}()),ag)),ig}var Sg=()=>{if("linux"!==L.default.platform)return!1;if(z.default.release().toLowerCase().includes("microsoft"))return!xg();try{return!!M.default.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")&&!xg()}catch{return!1}},kg=L.default.env.__IS_WSL_TEST__?Sg:Sg(),Tg=u.promisify(U.default.execFile),Ig=()=>`${L.default.env.SYSTEMROOT||L.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,$g=async(e,t={})=>{const{powerShellPath:r,...n}=t,s=$g.encodeCommand(e);return Tg(r??Ig(),[...$g.argumentsPrefix,s],{encoding:"utf8",...n})};$g.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"],$g.encodeCommand=e=>n.Buffer.from(e,"utf16le").toString("base64"),$g.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;var Pg,Cg=u.promisify(U.default.execFile),Rg=(()=>{const e="/mnt/";let t;return async function(){if(t)return t;const r="/etc/wsl.conf";let n=!1;try{await F.default.access(r,f.constants.F_OK),n=!0}catch{}if(!n)return e;const s=await F.default.readFile(r,{encoding:"utf8"}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(s);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith("/")?t:`${t}/`,t):e}})(),Ag=kg?async()=>`${await Rg()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`:Ig;function Og(e,t,r){const n=r=>Object.defineProperty(e,t,{value:r,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){const e=r();return n(e),e},set(e){n(e)}}),e}var Ng=u.promisify(s.execFile),jg=u.promisify(s.execFile);async function Dg(e){return async function(e,{humanReadableOutput:t=!0,signal:r}={}){if("darwin"!==L.default.platform)throw new Error("macOS only");const n=t?[]:["-ss"],s={};r&&(s.signal=r);const{stdout:a}=await jg("osascript",["-e",e,n],s);return a.trim()}(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var Ug=u.promisify(s.execFile),Lg={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},Mg=new Map(Object.entries(Lg)),zg=class extends Error{},Bg=u.promisify(s.execFile),Fg=Boolean(L.default.env.SSH_CONNECTION||L.default.env.SSH_CLIENT||L.default.env.SSH_TTY),qg=Symbol("fallbackAttempt"),Hg=("undefined"==typeof document?require("url").pathToFileURL(__filename).href:R&&"SCRIPT"===R.tagName.toUpperCase()&&R.src||new URL("index.js",document.baseURI).href)?D.default.dirname(o.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:R&&"SCRIPT"===R.tagName.toUpperCase()&&R.src||new URL("index.js",document.baseURI).href)):"",Zg=D.default.join(Hg,"xdg-open"),{platform:Vg,arch:Gg}=L.default,Wg=async(e,t)=>{if(0===e.length)return;const r=[];for(const n of e)try{return await t(n)}catch(e){r.push(e)}throw new AggregateError(r,"Failed to open in all supported apps")},Kg=async e=>{const t=!0===(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e})[qg];if(delete e[qg],Array.isArray(e.app))return Wg(e.app,t=>Kg({...e,app:t,[qg]:!0}));let r,{name:n,arguments:s=[]}=e.app??{};if(s=[...s],Array.isArray(n))return Wg(n,t=>Kg({...e,app:{name:t,arguments:s},[qg]:!0}));if("browser"===n||"browserPrivate"===n){const t={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},r={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"};let a;if(kg){const e=await(async()=>{const e=await Ag(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await $g(t,{powerShellPath:e});return r.trim()})();a=Mg.get(e)??{}}else a=await async function(){if("darwin"===L.default.platform){const e=await async function(){if("darwin"!==L.default.platform)throw new Error("macOS only");const{stdout:e}=await Ng("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e),r=t?.groups.id??"com.apple.Safari";return"com.apple.safari"===r?"com.apple.Safari":r}();return{name:await Dg(e),id:e}}if("linux"===L.default.platform){const{stdout:e}=await Bg("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim(),r=t.replace(/.desktop$/,"").replace("-"," ").toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());return{name:r,id:t}}if("win32"===L.default.platform)return async function(e=Ug){const{stdout:t}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),r=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!r)throw new zg(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);const{id:n}=r.groups,s=Lg[n];if(!s)throw new zg(`Unknown browser ID: ${n}`);return s}();throw new Error("Only macOS, Linux, and Windows are supported")}();if(a.id in t){const i=t[a.id.toLowerCase()];if("browserPrivate"===n){if("safari"===i)throw new Error("Safari doesn't support opening in private mode via command line");s.push(r[i])}return Kg({...e,app:{name:Qg[i],arguments:s}})}throw new Error(`${a.name} is not supported as a default browser`)}const a=[],i={};let o=!1;if(!kg||xg()||Fg||n||(o=await(async()=>(Pg??=(async()=>{try{const e=await Ag();return await F.default.access(e,f.constants.X_OK),!0}catch{return!1}})(),Pg))()),"darwin"===Vg)r="open",e.wait&&a.push("--wait-apps"),e.background&&a.push("--background"),e.newInstance&&a.push("--new"),n&&a.push("-a",n);else if("win32"===Vg||o){r=await Ag(),a.push(...$g.argumentsPrefix),kg||(i.windowsVerbatimArguments=!0),kg&&e.target&&(e.target=await(async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{const{stdout:t}=await Cg("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}})(e.target));const t=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&t.push("-Wait"),n?(t.push($g.escapeArgument(n)),e.target&&s.push(e.target)):e.target&&t.push($g.escapeArgument(e.target)),s.length>0&&(s=s.map(e=>$g.escapeArgument(e)),t.push("-ArgumentList",s.join(","))),e.target=$g.encodeCommand(t.join(" ")),e.wait||(i.stdio="ignore")}else{if(n)r=n;else{const e=!Hg||"/"===Hg;let t=!1;try{await F.default.access(Zg,f.constants.X_OK),t=!0}catch{}r=L.default.versions.electron??("android"===Vg||e||!t)?"xdg-open":Zg}s.length>0&&a.push(...s),e.wait||(i.stdio="ignore",i.detached=!0)}"darwin"===Vg&&s.length>0&&a.push("--args",...s),e.target&&a.push(e.target);const l=U.default.spawn(r,a,i);return e.wait?new Promise((t,r)=>{l.once("error",r),l.once("close",n=>{e.allowNonzeroExitCode||0===n?t(l):r(new Error(`Exited with code ${n}`))})}):t?new Promise((e,t)=>{l.once("error",t),l.once("spawn",()=>{l.once("close",r=>{l.off("error",t),0===r?(l.unref(),e(l)):t(new Error(`Exited with code ${r}`))})})}):(l.unref(),new Promise((e,t)=>{l.once("error",t),l.once("spawn",()=>{l.off("error",t),e(l)})}))};function Yg(e){if("string"==typeof e||Array.isArray(e))return e;const{[Gg]:t}=e;if(!t)throw new Error(`${Gg} is not supported`);return t}function Jg({[Vg]:e},{wsl:t}={}){if(t&&kg)return Yg(t);if(!e)throw new Error(`${Vg} is not supported`);return Yg(e)}var Qg={browser:"browser",browserPrivate:"browserPrivate"};Og(Qg,"chrome",()=>Jg({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}})),Og(Qg,"brave",()=>Jg({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}})),Og(Qg,"firefox",()=>Jg({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"})),Og(Qg,"edge",()=>Jg({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"})),Og(Qg,"safari",()=>Jg({darwin:"Safari"}));var Xg=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`,ey=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},ty=(e,t)=>{const r=new URLSearchParams({client_id:Ym,code_challenge:e,code_challenge_method:"S256",redirect_uri:eg,response_type:"code",state:t});return`${Km}/propelauth/oauth/authorize?${r.toString()}`},ry=async e=>{const t=v.spinner();let r;t.start("Loading user info...");try{r=lg(e.accessToken),t.stop(H.default.green(`✓ Logged in as ${H.default.cyan(r.email)}`))}catch(e){t.stop(H.default.red("✗ Failed to load user info"));const r=e instanceof Error?e.message:"Unknown error";return v.log.error(r),{success:!1}}const n=await(async e=>{if(0===e.length)return void v.log.error("You don't belong to any organizations.");if(1===e.length)return v.log.info(`Using organization: ${H.default.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return v.log.info(`Auto-selecting organization: ${H.default.cyan(e[0].name)}`),e[0];const t=await v.select({message:"Select an organization",options:[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({label:e.name,value:e.id}))});return v.isCancel(t)?void 0:e.find(e=>e.id===t)})(r.organizations);if(!n)return v.log.warn("Organization selection cancelled."),{success:!1};let s;t.start("Getting org credentials...");try{const r=await rg(e.accessToken,n.id);s={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(H.default.green("✓ Credentials obtained"))}catch(e){t.stop(H.default.red("✗ Failed to get org credentials"));const r=e instanceof Error?e.message:"Unknown error";return v.log.error(r),{success:!1}}const a=await(async(e,t)=>{const r=v.spinner();let n;r.start("Loading projects...");try{n=await(async({accessToken:e,orgId:t})=>{const r=await(n={auth:e,client:tg(),path:{orgId:t}},(n.client??Zm).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/orgs/{orgId}/projects",...n}));var n;if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to list projects: ${r.response.status}`);return r.data.projects})({accessToken:e,orgId:t}),r.stop(H.default.green("✓ Projects loaded"))}catch(e){r.stop(H.default.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void v.log.error(t)}if(0===n.length)return v.log.error("No projects found in this organization."),void v.log.info(`Create a project at ${H.default.underline(H.default.cyan("https://app.stably.ai"))}`);if(1===n.length)return v.log.info(`Using project: ${H.default.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return v.log.info(`Auto-selecting project: ${H.default.cyan(n[0].name)}`),n[0];const s=await v.select({message:"Select a project",options:n.map(e=>({label:e.name,value:e.id}))});return v.isCancel(s)?void 0:n.find(e=>e.id===s)})(s.accessToken,n.id);return a?(await(async e=>{const t=D.default.join(process.cwd(),pg),r=D.default.join(t,fg);await f.mkdir(t,{recursive:!0}),await f.writeFile(r,JSON.stringify(e,null,2)),await(async e=>{const t=D.default.join(e,".gitignore"),r="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await f.readFile(t,"utf-8"),n=e.split("\n").map(e=>e.trim());if(n.includes(".stably/*")&&n.includes("!.stably/docs/"))return;const s=/^# Stably CLI\n\.stably\/?$/m,a=/^\.stably\/?$/m;if(s.test(e)){const n=e.replace(s,`\n${r}\n`);await f.writeFile(t,n)}else if(a.test(e)){const n=e.replace(a,`\n${r}\n`);await f.writeFile(t,n)}else await f.appendFile(t,`\n${r}\n`)}catch{await f.writeFile(t,`${r}\n`)}})(process.cwd())})({orgId:n.id,orgName:n.name,projectId:a.id,projectName:a.name}),v.log.info(H.default.dim("Linked this directory to your Stably project.")),{scopedTokens:s,success:!0}):(v.log.warn("Project selection cancelled."),{success:!1})},ny=async()=>{if(xy())return v.log.warn(`Environment variables ${H.default.cyan("STABLY_API_KEY")} and ${H.default.cyan("STABLY_PROJECT_ID")} are set.`),v.log.warn("These will be used for authentication instead of OAuth login."),v.log.warn("To use OAuth login, unset these environment variables first."),void v.outro(H.default.yellow("Login skipped - using environment variable authentication."));const e=await gg();if(e){if(!wg(e)){if(await _g())return void v.outro(H.default.yellow("You are already logged in. Run `stably logout` first to log out."));v.log.info("You are logged in but haven't selected a project yet.");const t=await ry(e);return void(t.success?(await yg(t.scopedTokens),v.outro(H.default.green("Setup complete! You can now use Stably CLI."))):v.outro(H.default.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=v.spinner();t.start("Refreshing session...");try{const r=await Eg(e.refreshToken);t.stop(H.default.green("✓ Session refreshed"));const n=await _g();if(n){t.start("Getting org credentials...");try{const e=await rg(r.accessToken,n.orgId),s={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:r.idToken,refreshToken:r.refreshToken};await yg(s),t.stop(H.default.green("✓ Credentials obtained")),v.outro(H.default.green("Login successful"))}catch{await yg(r),t.stop(H.default.yellow("Using full credentials")),v.outro(H.default.green("Login successful"))}}else{const e=await ry(r);e.success?(await yg(e.scopedTokens),v.outro(H.default.green("Setup complete! You can now use Stably CLI."))):v.outro(H.default.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(H.default.yellow("Session expired, proceeding with fresh login...")),await vg(),await bg()}}const{authorizeUrl:t,serverReady:r,waitForCallback:n}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=q.default.randomBytes(32).toString("base64url"),t=(r=e,q.default.createHash("sha256").update(r).digest("base64url"));var r;const n=q.default.randomBytes(16).toString("base64url");return{authorizeUrl:ty(t,n),codeVerifier:e,state:n}})(),{ready:n,result:s}=(e=>{let t,r;return{ready:new Promise((e,n)=>{t=e,r=n}),result:new Promise((n,s)=>{const a=setTimeout(()=>{l.close(),n({error:"Login timed out",success:!1})},3e5),i=()=>{clearTimeout(a)},l=V.default.createServer((t,r)=>{const s=new o.URL(t.url||"","http://localhost:9876");if("/auth/callback"!==s.pathname)return r.writeHead(404),void r.end("Not found");const a=s.searchParams.get("code"),c=s.searchParams.get("state"),u=s.searchParams.get("error");return u?(ey(r,400,Xg(u)),i(),l.close(),void n({error:u,success:!1})):a&&c?c!==e?(ey(r,400,Xg("Invalid state parameter (possible CSRF attack)")),i(),l.close(),void n({error:"State mismatch",success:!1})):(ey(r,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'),i(),l.close(),void n({code:a,state:c,success:!0})):(ey(r,400,Xg("Missing code or state parameter")),i(),l.close(),void n({error:"Missing code or state parameter",success:!1}))});l.on("error",e=>{if(i(),"EADDRINUSE"===e.code){const e=new Error("Port 9876 is already in use. Please close the application using it and try again.");return r(e),void s(e)}const t=new Error(`Failed to start callback server: ${e.message}`);r(t),s(t)}),l.listen(9876,()=>{t()})})}})(r);return{authorizeUrl:e,serverReady:n,waitForCallback:async()=>{const e=await s;if(!e.success)throw new Error(e.error);return(async(e,t)=>{const r=new URLSearchParams({client_id:Ym,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:eg}),n=await fetch(`${Km}/propelauth/oauth/token`,{body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!n.ok){const e=await n.text();throw new Error(`Token exchange failed: ${n.status} ${e}`)}const s=await n.json();return{accessToken:s.access_token,expiresAt:Date.now()+1e3*s.expires_in,idToken:s.id_token,refreshToken:s.refresh_token}})(e.code,t)}}})();await r,v.log.info("Opening browser for authentication..."),v.log.info(H.default.dim("If browser doesn't open, visit:")),v.log.info(`]8;;${t}${H.default.underline(H.default.cyan(t))}]8;;`);try{await(e=>{if("string"!=typeof e)throw new TypeError("Expected a `target`");return Kg({target:e})})(t)}catch{v.log.warn("Could not open browser automatically. Please open the URL above manually.")}const s=v.spinner();let a;s.start("Waiting for authentication...");try{a=await n(),s.stop(H.default.green("✓ Authentication successful"))}catch(e){s.stop(H.default.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";v.outro(H.default.red(`Login failed: ${t}`)),process.exit(1)}const i=await ry(a);i.success?(await yg(i.scopedTokens),v.outro(H.default.green("Setup complete! You can now use Stably CLI."))):(v.outro(H.default.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},sy={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},ay=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),iy=(new Date).toISOString().split("T")[0],oy=D.default.join(z.default.tmpdir(),"stably-logs",iy);M.default.mkdirSync(oy,{recursive:!0});var ly,cy=process.argv.includes("--verbose")||process.argv.includes("-v"),uy=process.env.STABLY_LOG_LEVEL?.toLowerCase(),dy=cy?"debug":void 0!==(ly=uy)&&ly in sy?uy:"warn",py=sy[dy],fy=null,hy=null,my=null,gy=[],yy=!1,vy=e=>{if(!yy){fy=(e=>{const t=(()=>{const e=new Date;return[e.getHours().toString().padStart(2,"0"),e.getMinutes().toString().padStart(2,"0"),e.getSeconds().toString().padStart(2,"0")].join("-")})(),r=((e,t=100)=>e.replace(/[/\\:*?"<>|]/g,"-").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9\-_]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).toLowerCase()||"session")(e);return D.default.join(oy,`${t}-${r}.log`)})(e),(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${Vm}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${z.default.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${dy}`,"=".repeat(60),""].join("\n");e.write(t)})(hy=new W.default({dest:fy,minLength:4096,sync:!1,append:!0})),my=G.default({level:"debug",timestamp:G.default.stdTimeFunctions.isoTime,base:{version:Vm}},hy);for(const{level:e,msg:t,context:r}of gy)r?my[e](r,t):my[e](t);gy=[],yy=!0,cy&&process.stderr.write(`${H.default.dim(`Debug log: ${fy}`)}\n\n`)}},_y=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&ay.has(e)?e:null})();_y&&vy(_y);var by=e=>(t,r)=>{if(my?r?my[e](r,t):my[e](t):gy.push({level:e,msg:t,context:r}),(e=>sy[e]>=py)(e)){const r=((e,t)=>`${{fatal:H.default.bgRed(H.default.white(" FATAL ")),error:H.default.red("error"),warn:H.default.yellow("warn"),info:H.default.cyan("info"),debug:H.default.dim("debug"),trace:H.default.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${r}\n`)}},wy={fatal:by("fatal"),error:by("error"),warn:by("warn"),info:by("info"),debug:by("debug"),trace:by("trace"),initSession:e=>{yy||vy(e)},getLogFilePath:()=>fy,flush:()=>{if(hy)try{hy.flushSync()}catch{}},printLogFileInfo:()=>{fy&&(process.stderr.write(`\n${H.default.dim("Debug log written to:")}\n`),process.stderr.write(` ${H.default.cyan(fy)}\n`),process.stderr.write(`${H.default.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>my};setInterval(()=>{wy.flush()},3e4).unref(),process.on("beforeExit",()=>{wy.flush()});var Ey=e=>{const t=()=>{wy.flush(),cy&&wy.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",Ey("SIGINT")),process.on("SIGTERM",Ey("SIGTERM"));var xy=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return wy.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};wy.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},Sy=!1,ky=()=>{Sy||(Sy=!0,v.log.warn("Both environment variable auth and stored OAuth login were detected."),v.log.warn(`Honoring environment variables (${H.default.cyan("STABLY_API_KEY")} + ${H.default.cyan("STABLY_PROJECT_ID")}).`),v.log.warn("To use OAuth login instead, unset those environment variables."))},Ty=async()=>{wy.debug("Checking for stored auth tokens");const e=await gg();if(!e)return void wy.debug("No stored auth tokens found");const t=wg(e);if(wy.debug("Auth tokens status",{expired:t}),!t){const t=await _g(),r=(e=>{try{const t=sg.parse(og(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);if(wy.debug("Token scope check",{scope:r,hasContext:!!t}),t&&"full"===r)try{wy.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const r=await rg(e.accessToken,t.orgId),n={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await yg(n),wy.debug("Token exchange successful"),n}catch(t){return wy.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{wy.debug("Attempting token refresh");const t=await Eg(e.refreshToken);wy.debug("Token refresh successful");const r=await _g();if(r)try{wy.debug("Exchanging refreshed token for org-scoped token");const e=await rg(t.accessToken,r.orgId),n={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await yg(n),n}catch{return await yg(t),t}return await yg(t),t}catch(e){return void wy.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},Iy=async(e={})=>{wy.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=xy();if(t){wy.info("Using environment variable authentication");try{await gg()&&ky()}catch{}return{auth:t,type:"env"}}let r=await Ty(),n=r?await _g():void 0;const s=process.stdin.isTTY&&process.stdout.isTTY;if(wy.debug("OAuth auth check",{hasTokens:!!r,hasContext:!!n,canPrompt:s}),(!r||!n)&&e.autoLogin&&s){wy.info("Prompting user to login"),r?v.log.info("You are logged in but need to select an organization and project."):v.log.info("You are not logged in."),v.log.info("Press Enter to log in."),process.stdout.write(`${H.default.dim("Alternatively, set environment variables for an org API key:")}\n${H.default.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=_.createInterface({input:process.stdin,output:process.stdout});try{await e.question(H.default.dim("Press Enter to continue... "))}finally{e.close()}await ny(),r=await Ty(),n=r?await _g():void 0}return r||(wy.warn("Authentication required but no tokens available"),v.outro(H.default.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(wy.warn("Authentication succeeded but no project context selected"),v.outro(H.default.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),wy.info("OAuth authentication successful",{orgId:n.orgId,projectId:n.projectId}),{auth:{accessToken:r.accessToken,context:n},type:"oauth"}},$y=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,Py=e=>e?{...process.env,...e}:process.env,Cy=async()=>{wy.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===Gm)return;const e=Gm.startsWith("http://")?"ws://":"wss://";return`${Gm.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();wy.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=xy();if(t)return wy.info("[test] Using env var auth (STABLY_API_KEY + STABLY_PROJECT_ID)"),{STABLY_API_KEY:t.apiKey,STABLY_PROJECT_ID:t.projectId,...e&&{STABLY_WS_URL:e}};wy.info("[test] No env var auth, attempting OAuth auth");const r=Date.now(),n=await(async()=>{const e=xy();if(e){try{await gg()&&ky()}catch{}return{auth:e,type:"env"}}const t=await Ty(),r=t?await _g():void 0;if(t&&r)return{auth:{accessToken:t.accessToken,context:r},type:"oauth"}})();if(wy.info("[test] OAuth auth resolved",{durationMs:Date.now()-r,hasAuth:!!n,authType:n?.type}),!n||"env"===n.type)return void wy.info("[test] No usable auth found");const s=process.env.STABLY_PROJECT_ID?.trim(),a=s||$y(n);if(!a)return void wy.warn("[test] No project ID available");wy.info("[test] Fetching JWT API key",{projectId:a});const i=Date.now(),o=await(async(e,t)=>{try{wy.debug("Requesting JWT API key",{projectId:t,apiUrl:Gm});const r=await(async({accessToken:e,projectId:t})=>{const r=await(n={auth:e,client:tg(),path:{projectId:t}},(n.client??Zm).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/api-key",...n}));var n;if(r.error){const e=r.error?.error,{status:t}=r.response;throw new Error(e??`Failed to get API key: ${t}`)}return r.data})({accessToken:e,projectId:t});return wy.debug("JWT API key obtained",{keyPrefix:r.apiKey.substring(0,10)}),r.apiKey}catch(e){return void wy.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(n.auth.accessToken,a);wy.info("[test] JWT API key fetch complete",{durationMs:Date.now()-i,success:!!o});const l=o?{STABLY_API_KEY:o,STABLY_PROJECT_ID:a,...e&&{STABLY_WS_URL:e}}:void 0;return wy.info("[test] Stably test env resolved",{hasApiKey:!!l?.STABLY_API_KEY,projectId:l?.STABLY_PROJECT_ID,wsUrl:l?.STABLY_WS_URL??process.env.STABLY_WS_URL??"(default)"}),l},Ry=e=>e?{[km]:e}:void 0,Ay=b.z.object({context:b.z.string().min(1),autohealReportUrl:b.z.string()}),Oy=S.z.object({bucket:S.z.string(),key:S.z.string()}),Ny=S.z.object({diffBucketPath:Oy,expiresInSeconds:S.z.number(),key:S.z.string(),uploadUrl:S.z.string()}),jy=S.z.object({traceBucketPath:Oy,expiresInSeconds:S.z.number(),key:S.z.string(),uploadUrl:S.z.string(),sensitiveValues:S.z.array(S.z.string())}),Dy=async({authHeader:e,contentType:t="text/plain",orgId:r,runId:n})=>{const s=await(a={auth:e,body:{contentType:t},client:tg(),headers:Ry(r),path:{runId:n}},(a.client??Zm).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...a,headers:{"Content-Type":"application/json",...a.headers}}));var a;if(s.error)throw new Error(`Failed to presign diff upload (${s.response.status})`);const i=Ny.parse(s.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}},Uy=async({contentType:e="text/plain",diff:t,uploadUrl:r})=>{const n=await fetch(r,{body:t,headers:{"Content-Type":e},method:"PUT"});if(!n.ok)throw new Error(`Failed to upload diff (${n.status})`)},Ly=async({authHeader:e,diffBucketPath:t,orgId:r,runId:n})=>{const s=(tg().getConfig().baseUrl??"").replace(/\/$/,""),a=await fetch(`${s}/internal/v1/cli/runs/${encodeURIComponent(n)}/autoheal-diff/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json",...Ry(r),authorization:e},body:JSON.stringify(t)});if(!a.ok)throw new Error(`Failed to confirm diff upload (${a.status})`)},My=class{socket;url;authHeader;orgId;runId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=3;reconnectDelay=2e3;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,runId:r,url:n=Qm,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.runId=r,this.url=n,this.onUserMessage=s,wy.info("[ws] Constructing AutohealWebSocketClient",{url:this.url,runId:r})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?runId=${encodeURIComponent(this.runId)}`;wy.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new K.default(t,{headers:e}),this.socket.on("open",()=>{wy.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),r=JSON.parse(t);wy.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(wy.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(wy.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{wy.info("[ws] Connection closed",{code:e,authFailed:1008===e,reconnectAttempts:this.reconnectAttempts,maxReconnect:this.maxReconnectAttempts,isClosed:this._isClosed}),this.isAuthenticated=!1,1008===e&&(this.authenticationFailed=!0),!this._isClosed&&!this.authenticationFailed&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}),this.socket.on("error",e=>{wy.warn("[ws] Connection error",{error:e.message})})}catch(e){wy.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,wy.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===K.default.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void wy.debug("[ws] sendProgress called but client is closed",{phase:e.phase});const t={type:"autoheal_progress",payload:e};return this.pendingEvent=t,this.isConnected()?"complete"===e.phase?(wy.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(wy.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===K.default.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return wy.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{wy.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(wy.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){wy.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;wy.info("[ws] Closing WebSocket client"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.flushPending();const{socket:e}=this;this.socket=void 0,e&&setTimeout(()=>{e.close()},200)}},zy=class{socket;url;authHeader;orgId;sessionId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=3;reconnectDelay=2e3;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,sessionId:r,url:n=Xm,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.sessionId=r,this.url=n,this.onUserMessage=s,wy.info("[ws] Constructing CreateProgressWebSocketClient",{url:this.url,sessionId:r})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?sessionId=${encodeURIComponent(this.sessionId)}`;wy.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new K.default(t,{headers:e}),this.socket.on("open",()=>{wy.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),r=JSON.parse(t);wy.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(wy.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(wy.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{wy.info("[ws] Connection closed",{code:e,authFailed:1008===e,reconnectAttempts:this.reconnectAttempts,maxReconnect:this.maxReconnectAttempts,isClosed:this._isClosed}),this.isAuthenticated=!1,1008===e&&(this.authenticationFailed=!0),!this._isClosed&&!this.authenticationFailed&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}),this.socket.on("error",e=>{wy.warn("[ws] Connection error",{error:e.message})})}catch(e){wy.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,wy.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===K.default.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void wy.debug("[ws] sendProgress called but client is closed",{phase:e.phase});const t={type:"create_progress",payload:e};return this.pendingEvent=t,this.isConnected()?"complete"===e.phase?(wy.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(wy.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===K.default.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return wy.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{wy.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(wy.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){wy.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;wy.info("[ws] Closing WebSocket client"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.flushPending();const{socket:e}=this;this.socket=void 0,e&&setTimeout(()=>{e.close()},200)}},By=/\.(spec|test)\.(c|m)?[jt]sx?$/,Fy=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},qy=e=>null!=e&&"object"==typeof e&&"tool_response"in e,Hy=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},Zy=e=>{const t=Hy(e);if(t)return t.filter(Fy).map(e=>e.text).join("\n")||void 0},Vy=/\u001b\[[0-9;]*m/g,Gy=e=>e.replace(Vy,""),Wy=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function Ky({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 r=t.tool_input,n="string"==typeof r.text?r.text:void 0;if(!n)return{decision:"approve"};const s=n.replace(Wy,(t,r)=>{const n=e[r];return null!=n?n:t});return s===n?{decision:"approve"}:{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser text input.",updatedInput:{...r,text:s}}}}}function Yy({onResult:e}){return async t=>{if(!qy(t))return{decision:"approve"};const r=Zy(t);if(!r)return{decision:"approve"};const n=function(e){const t=Gy(e),r=t.split(/Running \d+ tests? using \d+ workers?/).at(-1)??t,n=parseInt(r.match(/(\d+)\s+passed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0"),s=parseInt(r.match(/(\d+)\s+failed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0");if(0===n&&0===s)return;const a=[n>0?`${n} test${1===n?"":"s"} passed ✓`:void 0,s>0?`${s} test${1===s?"":"s"} failed ✗`:void 0].filter(e=>void 0!==e).join(", ");if(0===s)return a;const i=r.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?a:`${a}\n${i.map(e=>` - ${e}`).join("\n")}`}(r);return n&&e(n),{decision:"approve"}}}function Jy({onResult:e}){return async t=>{if(!qy(t))return{decision:"approve"};const r=Zy(t);if(!r)return{decision:"approve"};const n=function(e){const t=Gy(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 r=t.match(/(\d+)\s+passed/);if(r){const e=parseInt(r[1]);return`${e} test${1===e?"":"s"} passed ✓`}}(r);return n&&e(n),{decision:"approve"}}}var Qy=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function Xy({onFileCreated:e}){return async t=>{const r=(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),n=r?.file_path;return"string"==typeof n&&Qy.test(n)&&e(n),{decision:"approve"}}}var ev=u.promisify(s.exec);async function tv(){try{const{stdout:e}=await ev('pgrep -f "playwright run-test-mcp-server" 2>/dev/null || true'),t=e.trim();if(!t)return;const r=t.split("\n").filter(Boolean);await Promise.allSettled(r.map(async e=>{await ev(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var rv="sha256",nv=/^---\r?\n([\s\S]*?)\r?\n---/;function sv(e){const t=e.replace(nv,"").replace(/^(\r?\n)+/,""),r=q.default.createHash(rv).update(t,"utf8").digest("hex");return`${rv}:${r}`}function av(e){const t=e.match(/^\/\*\*[\s\S]*?@prompt-hash\s+(sha256:[a-f0-9]{64})[\s\S]*?\*\//);return t?.[1]}function iv({builtAt:e=new Date,promptFile:t,promptHash:r}){const n=Array.isArray(t)?t:[t],s=n[0]??"unknown",a=e.toISOString();return["/**"," * @generated by stably build",` * @prompt-hash ${r}`,...n.map(e=>` * @prompt-file ${e}`),` * @built-at ${a}`," *",` * DO NOT EDIT MANUALLY - regenerate with: stably build ${s} --force`," */"].join("\n")}function ov({workDir:e}){return async r=>{if(null==(n=r)||"object"!=typeof n||!("file_path"in n)||"string"!=typeof n.file_path)return{};var n;const s=r.file_path;if(!/\.(spec|test)\.[jt]sx?$/.test(s))return{};const a=t.resolve(e,s);if(!a.startsWith(t.resolve(e)+t.sep))return console.error(`[PromptHash Hook] Path traversal attempt blocked: ${s}`),{};let i;try{i=await f.readFile(a,"utf-8")}catch(e){return console.error(`[PromptHash Hook] Error reading ${s}:`,e),{}}const o=function(e){const t=e.match(/\/\/\s*@stably\.spec\s+(\S+)/);return t?.[1]}(i);if(!o)return{};const l=t.resolve(e,o);if(!l.startsWith(t.resolve(e)+t.sep))return console.error(`[PromptHash Hook] Path traversal attempt blocked: ${o}`),{};let c;try{c=await f.readFile(l,"utf-8")}catch{return{}}const u=sv(c);if(av(i)===u)return{};const d=iv({promptHash:u,promptFile:o});let p;const h=i.match(/\/\*\*[\s\S]*?@prompt-hash[\s\S]*?\*\/\n?/);p=h?i.replace(h[0],`${d}\n`):`${d}\n${i}`;try{await f.writeFile(a,p,"utf-8")}catch(e){console.error(`[PromptHash Hook] Error writing ${s}:`,e)}return{}}}var lv=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())}hasQueuedMessages(){return this.queue.length>0}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()})}};function cv(e){try{const t=s.execSync("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}var uv=[".ts",".js",".mts",".mjs",".cts",".cjs"],dv=10240,pv=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await f.stat(r)).size,n=await f.readFile(r,"utf-8"),s=Buffer.byteLength(n,"utf-8");if(s<=dv)return n;const a=(e=>{const t=e.split("\n"),r=[];let n=!1,s=!1,a=0,i=!1;for(let e=0;e<t.length;e++){const o=t[e],l=o.trim();l.startsWith("/*")&&(n=!0),l.includes("*/")?n=!1:n||l.startsWith("//")&&!l.startsWith("///")||(l.startsWith("import ")||l.startsWith("export ")?(r.push(o),i=!0):i&&""===l?(r.push(o),i=!1):(i=!1,l.startsWith("type ")||l.startsWith("interface ")?r.push(o):l.startsWith("function ")||l.startsWith("const ")||l.startsWith("async function ")||l.startsWith("export function ")||l.startsWith("export const ")||l.startsWith("test.describe(")||l.startsWith("test(")?(r.push(o),s=!0,a=(o.match(/{/g)||[]).length-(o.match(/}/g)||[]).length,0===a&&(l.endsWith(";")||l.endsWith(","))&&(s=!1)):s?(a+=(o.match(/{/g)||[]).length,a-=(o.match(/}/g)||[]).length,0===a&&l.includes("}")?(r.push(o),s=!1):a>0&&" // ... implementation omitted ..."!==r.at(-1)&&r.push(" // ... implementation omitted ...")):l.match(/^[a-zA-Z_]+:/)&&r.push(o)))}return r.join("\n")})(n),i=Buffer.byteLength(a,"utf-8");return i<=dv?a:a.slice(0,dv)+`\n\n... [TRUNCATED: File "${t}" at ${r} was ${e} bytes (${s} bytes as UTF-8), reduced to ~${i} bytes of essential content, then truncated to 10240 bytes] ...`}catch(r){let n;if(r&&"object"==typeof r&&"code"in r){const e=r.code;"string"==typeof e&&(n=e)}return"ENOENT"!==n&&console.warn(`Failed to read ${t}: ${r}`),e}},fv=async({defaultContent:e,dirName:t,dirPath:r})=>{try{const e=await f.readdir(r);return e.length>0?e.join("\n"):"(empty)"}catch(r){let n;if(r&&"object"==typeof r&&"code"in r){const e=r.code;"string"==typeof e&&(n=e)}return"ENOENT"!==n&&console.warn(`Failed to read ${t}: ${r}`),e}},hv=async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n,customHeader:s,maxParallelWorkers:a})=>{const i=tg(),o=cv(r.absolutePath);wy.debug("Requesting system prompt from API",{mode:t,hasGitContext:!!o,envVarCount:e.length});const l=await(c={client:i,auth:n,body:{mode:t,workspaceInfo:r,allowedEnvVars:e,gitContext:o,maxParallelWorkers:a}},(c.client??Zm).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...c,headers:{"Content-Type":"application/json",...c.headers}}));var c;if(401===l.response.status)throw wy.warn("System prompt fetch failed: unauthorized (401)"),await vg(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===l.response.status)throw wy.warn("System prompt fetch failed: forbidden (403)"),await vg(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(l.error)throw wy.warn("System prompt fetch failed",{error:l.error}),new Error(`Failed to fetch system prompt: ${JSON.stringify(l.error)}`);const u=function({customHeader:e,systemPrompt:t}){return e?`${t}\n\nWhen writing or updating the generated test file, prepend this exact header at the top of the file without modification:\n\`\`\`ts\n${e}\n\`\`\``:t}({systemPrompt:l.data.systemPrompt,customHeader:s});return wy.debug("System prompt received",{size:u.length,appendedCustomHeader:!!s,hasPrContext:!!l.data.prContext}),{systemPrompt:u,prContext:l.data.prContext}},mv=".stably-playwright-wrapper.config.*",gv=[".ts",".js",".mts",".mjs",".cts",".cjs"];function yv(e){const r=t.resolve(e);if(i.existsSync(r))for(const e of gv){const n=t.join(r,`playwright.config${e}`);if(i.existsSync(n))return n}}var vv=["tests","e2e","__tests__","test"];function _v(e){try{return i.existsSync(e)&&i.statSync(e).isDirectory()}catch{return!1}}function bv(e,t){const r="output-flag"===t?"--output flag":"playwright.config.ts"===t?"playwright.config.ts":"auto-detected"===t?"auto-detected":"cwd fallback";console.error(H.default.dim(`Using output directory: ${e} (from ${r})`))}var wv,Ev=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__test-doc-sync__","mcp__stably-agent-control__"],xv=["planner_","generator_"],Sv={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools","mcp__session-control__restart_mcp_servers":"Restarting Browser Tools"},kv=(e,t)=>{const r=t.find(t=>e.startsWith(t));return r?e.slice(r.length):e},Tv=e=>{const t=Sv[e];if(t)return t;const r=kv(e,Ev);return kv(r,xv).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")},Iv=(e,t)=>{if(!t||"object"!=typeof t)return;const r=t,n="string"==typeof r.intent?r.intent:void 0;if("Read"!==e&&"Write"!==e&&"Edit"!==e){if("Glob"===e||"Grep"===e)return"string"==typeof r.pattern?r.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=r.test;return"string"==typeof e?.title?e.title:void 0}return"mcp__playwright-test__generator_setup_page"===e||"generator_setup_page"===e?"string"==typeof r.seedFile?r.seedFile:"tests/seed.spec.ts":"mcp__playwright-test__generator_write_test"===e||"generator_write_test"===e?"string"==typeof r.fileName?r.fileName:void 0:"Bash"===e?"string"==typeof r.command?r.command.length>50?`${r.command.slice(0,50)}...`:r.command:void 0:e.includes("browser_navigate")&&!e.includes("back")?"string"==typeof r.url?r.url:n:e.includes("browser_type")?("string"==typeof r.text?`"${r.text}"`:void 0)??n:e.includes("browser_click")?"string"==typeof r.element?r.element:n:e.includes("browser_wait_for")?"string"==typeof r.text?`text: "${r.text}"`:"number"==typeof r.time?`${r.time}ms`:n:e.includes("verify_text")?"string"==typeof r.text?`"${r.text}"`:n:e.includes("verify_element")?"string"==typeof r.accessibleName?r.accessibleName:n:e.includes("screenshot")&&"string"==typeof r.filename?r.filename:n}if(Array.isArray(r.locations)){const e=r.locations.filter(e=>"string"==typeof e);return e.length>0?e.join(", "):void 0}}else if("string"==typeof r.file_path)return r.file_path.split("/").at(-1)??void 0},$v=["test","bug","other"],Pv={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."},Cv=e=>Pv[e],Rv=/[^a-zA-Z0-9-_]/g,Av=e=>{const t=e.trim().replace(Rv,"_");return t.length>0?t.slice(0,80):void 0},Ov=e=>"string"==typeof e?Av(e):void 0,Nv=((e,t,r)=>(r=null!=e?Y(ee(e)):{},((e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of X(t))te.call(e,r)||void 0===r||J(e,r,{get:()=>t[r],enumerable:!(n=Q(t,r))||n.enumerable});return e})(J(r,"default",{value:e,enumerable:!0}),e)))(ne()),jv=$.createRequire("/");try{wv=jv("worker_threads").Worker}catch(e){}var Dv=wv?function(e,t,r,n,s){var a=!1,i=new wv(e+";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global",{eval:!0}).on("error",function(e){return s(e,null)}).on("message",function(e){return s(null,e)}).on("exit",function(e){e&&!a&&s(new Error("exited with code "+e),null)});return i.postMessage(r,n),i.terminate=function(){return a=!0,wv.prototype.terminate.call(i)},i}:function(e,t,r,n,s){setImmediate(function(){return s(new Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"),null)});var a=function(){};return{terminate:a,postMessage:a}},Uv=Uint8Array,Lv=Uint16Array,Mv=Int32Array,zv=new Uv([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Bv=new Uv([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Fv=new Uv([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),qv=function(e,t){for(var r=new Lv(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];var s=new Mv(r[30]);for(n=1;n<30;++n)for(var a=r[n];a<r[n+1];++a)s[a]=a-r[n]<<5|n;return{b:r,r:s}},Hv=qv(zv,2),Zv=Hv.b,Vv=Hv.r;Zv[28]=258,Vv[258]=28;var Gv,Wv=qv(Bv,0),Kv=Wv.b,Yv=Wv.r,Jv=new Lv(32768);for(e_=0;e_<32768;++e_)Gv=(61680&(Gv=(52428&(Gv=(43690&e_)>>1|(21845&e_)<<1))>>2|(13107&Gv)<<2))>>4|(3855&Gv)<<4,Jv[e_]=((65280&Gv)>>8|(255&Gv)<<8)>>1;var Qv=function(e,t,r){for(var n=e.length,s=0,a=new Lv(t);s<n;++s)e[s]&&++a[e[s]-1];var i,o=new Lv(t);for(s=1;s<t;++s)o[s]=o[s-1]+a[s-1]<<1;if(r){i=new Lv(1<<t);var l=15-t;for(s=0;s<n;++s)if(e[s])for(var c=s<<4|e[s],u=t-e[s],d=o[e[s]-1]++<<u,p=d|(1<<u)-1;d<=p;++d)i[Jv[d]>>l]=c}else for(i=new Lv(n),s=0;s<n;++s)e[s]&&(i[s]=Jv[o[e[s]-1]++]>>15-e[s]);return i},Xv=new Uv(288);for(e_=0;e_<144;++e_)Xv[e_]=8;for(e_=144;e_<256;++e_)Xv[e_]=9;for(e_=256;e_<280;++e_)Xv[e_]=7;for(e_=280;e_<288;++e_)Xv[e_]=8;var e_,t_=new Uv(32);for(e_=0;e_<32;++e_)t_[e_]=5;var r_=Qv(Xv,9,0),n_=Qv(Xv,9,1),s_=Qv(t_,5,0),a_=Qv(t_,5,1),i_=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},o_=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},l_=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},c_=function(e){return(e+7)/8|0},u_=function(e,t,r){return(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length),new Uv(e.subarray(t,r))},d_=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],p_=function(e,t,r){var n=new Error(t||d_[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,p_),!r)throw n;return n},f_=function(e,t,r,n){var s=e.length,a=n?n.length:0;if(!s||t.f&&!t.l)return r||new Uv(0);var i=!r,o=i||2!=t.i,l=t.i;i&&(r=new Uv(3*s));var c=function(e){var t=r.length;if(e>t){var n=new Uv(Math.max(2*t,e));n.set(r),r=n}},u=t.f||0,d=t.p||0,p=t.b||0,f=t.l,h=t.d,m=t.m,g=t.n,y=8*s;do{if(!f){u=o_(e,d,1);var v=o_(e,d+1,3);if(d+=3,!v){var _=e[(C=c_(d)+4)-4]|e[C-3]<<8,b=C+_;if(b>s){l&&p_(0);break}o&&c(p+_),r.set(e.subarray(C,b),p),t.b=p+=_,t.p=d=8*b,t.f=u;continue}if(1==v)f=n_,h=a_,m=9,g=5;else if(2==v){var w=o_(e,d,31)+257,E=o_(e,d+10,15)+4,x=w+o_(e,d+5,31)+1;d+=14;for(var S=new Uv(x),k=new Uv(19),T=0;T<E;++T)k[Fv[T]]=o_(e,d+3*T,7);d+=3*E;var I=i_(k),$=(1<<I)-1,P=Qv(k,I,1);for(T=0;T<x;){var C,R=P[o_(e,d,$)];if(d+=15&R,(C=R>>4)<16)S[T++]=C;else{var A=0,O=0;for(16==C?(O=3+o_(e,d,3),d+=2,A=S[T-1]):17==C?(O=3+o_(e,d,7),d+=3):18==C&&(O=11+o_(e,d,127),d+=7);O--;)S[T++]=A}}var N=S.subarray(0,w),j=S.subarray(w);m=i_(N),g=i_(j),f=Qv(N,m,1),h=Qv(j,g,1)}else p_(1);if(d>y){l&&p_(0);break}}o&&c(p+131072);for(var D=(1<<m)-1,U=(1<<g)-1,L=d;;L=d){var M=(A=f[l_(e,d)&D])>>4;if((d+=15&A)>y){l&&p_(0);break}if(A||p_(2),M<256)r[p++]=M;else{if(256==M){L=d,f=null;break}var z=M-254;if(M>264){var B=zv[T=M-257];z=o_(e,d,(1<<B)-1)+Zv[T],d+=B}var F=h[l_(e,d)&U],q=F>>4;if(F||p_(3),d+=15&F,j=Kv[q],q>3&&(B=Bv[q],j+=l_(e,d)&(1<<B)-1,d+=B),d>y){l&&p_(0);break}o&&c(p+131072);var H=p+z;if(p<j){var Z=a-j,V=Math.min(j,H);for(Z+p<0&&p_(3);p<V;++p)r[p]=n[Z+p]}for(;p<H;++p)r[p]=r[p-j]}}t.l=f,t.p=L,t.b=p,t.f=u,f&&(u=1,t.m=m,t.d=h,t.n=g)}while(!u);return p!=r.length&&i?u_(r,0,p):r.subarray(0,p)},h_=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},m_=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8,e[n+2]|=r>>16},g_=function(e,t){for(var r=[],n=0;n<e.length;++n)e[n]&&r.push({s:n,f:e[n]});var s=r.length,a=r.slice();if(!s)return{t:x_,l:0};if(1==s){var i=new Uv(r[0].s+1);return i[r[0].s]=1,{t:i,l:1}}r.sort(function(e,t){return e.f-t.f}),r.push({s:-1,f:25001});var o=r[0],l=r[1],c=0,u=1,d=2;for(r[0]={s:-1,f:o.f+l.f,l:o,r:l};u!=s-1;)o=r[r[c].f<r[d].f?c++:d++],l=r[c!=u&&r[c].f<r[d].f?c++:d++],r[u++]={s:-1,f:o.f+l.f,l:o,r:l};var p=a[0].s;for(n=1;n<s;++n)a[n].s>p&&(p=a[n].s);var f=new Lv(p+1),h=y_(r[u-1],f,0);if(h>t){n=0;var m=0,g=h-t,y=1<<g;for(a.sort(function(e,t){return f[t.s]-f[e.s]||e.f-t.f});n<s;++n){var v=a[n].s;if(!(f[v]>t))break;m+=y-(1<<h-f[v]),f[v]=t}for(m>>=g;m>0;){var _=a[n].s;f[_]<t?m-=1<<t-f[_]++-1:++n}for(;n>=0&&m;--n){var b=a[n].s;f[b]==t&&(--f[b],++m)}h=t}return{t:new Uv(f),l:h}},y_=function(e,t,r){return-1==e.s?Math.max(y_(e.l,t,r+1),y_(e.r,t,r+1)):t[e.s]=r},v_=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new Lv(++t),n=0,s=e[0],a=1,i=function(e){r[n++]=e},o=1;o<=t;++o)if(e[o]==s&&o!=t)++a;else{if(!s&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(s),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(s);a=1,s=e[o]}return{c:r.subarray(0,n),n:t}},__=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},b_=function(e,t,r){var n=r.length,s=c_(t+2);e[s]=255&n,e[s+1]=n>>8,e[s+2]=255^e[s],e[s+3]=255^e[s+1];for(var a=0;a<n;++a)e[s+a+4]=r[a];return 8*(s+4+n)},w_=function(e,t,r,n,s,a,i,o,l,c,u){h_(t,u++,r),++s[256];for(var d=g_(s,15),p=d.t,f=d.l,h=g_(a,15),m=h.t,g=h.l,y=v_(p),v=y.c,_=y.n,b=v_(m),w=b.c,E=b.n,x=new Lv(19),S=0;S<v.length;++S)++x[31&v[S]];for(S=0;S<w.length;++S)++x[31&w[S]];for(var k=g_(x,7),T=k.t,I=k.l,$=19;$>4&&!T[Fv[$-1]];--$);var P,C,R,A,O=c+5<<3,N=__(s,Xv)+__(a,t_)+i,j=__(s,p)+__(a,m)+i+14+3*$+__(x,T)+2*x[16]+3*x[17]+7*x[18];if(l>=0&&O<=N&&O<=j)return b_(t,u,e.subarray(l,l+c));if(h_(t,u,1+(j<N)),u+=2,j<N){P=Qv(p,f,0),C=p,R=Qv(m,g,0),A=m;var D=Qv(T,I,0);for(h_(t,u,_-257),h_(t,u+5,E-1),h_(t,u+10,$-4),u+=14,S=0;S<$;++S)h_(t,u+3*S,T[Fv[S]]);u+=3*$;for(var U=[v,w],L=0;L<2;++L){var M=U[L];for(S=0;S<M.length;++S){var z=31&M[S];h_(t,u,D[z]),u+=T[z],z>15&&(h_(t,u,M[S]>>5&127),u+=M[S]>>12)}}}else P=r_,C=Xv,R=s_,A=t_;for(S=0;S<o;++S){var B=n[S];if(B>255){m_(t,u,P[257+(z=B>>18&31)]),u+=C[z+257],z>7&&(h_(t,u,B>>23&31),u+=zv[z]);var F=31&B;m_(t,u,R[F]),u+=A[F],F>3&&(m_(t,u,B>>5&8191),u+=Bv[F])}else m_(t,u,P[B]),u+=C[B]}return m_(t,u,P[256]),u+C[256]},E_=new Mv([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),x_=new Uv(0),S_=function(e,t,r,n,s,a){var i=a.z||e.length,o=new Uv(n+i+5*(1+Math.ceil(i/7e3))+s),l=o.subarray(n,o.length-s),c=a.l,u=7&(a.r||0);if(t){u&&(l[0]=a.r>>3);for(var d=E_[t-1],p=d>>13,f=8191&d,h=(1<<r)-1,m=a.p||new Lv(32768),g=a.h||new Lv(h+1),y=Math.ceil(r/3),v=2*y,_=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<v)&h},b=new Mv(25e3),w=new Lv(288),E=new Lv(32),x=0,S=0,k=a.i||0,T=0,I=a.w||0,$=0;k+2<i;++k){var P=_(k),C=32767&k,R=g[P];if(m[C]=R,g[P]=C,I<=k){var A=i-k;if((x>7e3||T>24576)&&(A>423||!c)){u=w_(e,l,0,b,w,E,S,T,$,k-$,u),T=x=S=0,$=k;for(var O=0;O<286;++O)w[O]=0;for(O=0;O<30;++O)E[O]=0}var N=2,j=0,D=f,U=C-R&32767;if(A>2&&P==_(k-U))for(var L=Math.min(p,A)-1,M=Math.min(32767,k),z=Math.min(258,A);U<=M&&--D&&C!=R;){if(e[k+N]==e[k+N-U]){for(var B=0;B<z&&e[k+B]==e[k+B-U];++B);if(B>N){if(N=B,j=U,B>L)break;var F=Math.min(U,B-2),q=0;for(O=0;O<F;++O){var H=k-U+O&32767,Z=H-m[H]&32767;Z>q&&(q=Z,R=H)}}}U+=(C=R)-(R=m[C])&32767}if(j){b[T++]=268435456|Vv[N]<<18|Yv[j];var V=31&Vv[N],G=31&Yv[j];S+=zv[V]+Bv[G],++w[257+V],++E[G],I=k+N,++x}else b[T++]=e[k],++w[e[k]]}}for(k=Math.max(k,I);k<i;++k)b[T++]=e[k],++w[e[k]];u=w_(e,l,c,b,w,E,S,T,$,k-$,u),c||(a.r=7&u|l[u/8|0]<<3,u-=7,a.h=g,a.p=m,a.i=k,a.w=I)}else{for(k=a.w||0;k<i+c;k+=65535){var W=k+65535;W>=i&&(l[u/8|0]=c,W=i),u=b_(l,u+1,e.subarray(k,W))}a.i=i}return u_(o,0,n+c_(u)+s)},k_=function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var r=t,n=9;--n;)r=(1&r&&-306674912)^r>>>1;e[t]=r}return e}(),T_=function(e,t,r,n,s){if(!s&&(s={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),i=new Uv(a.length+e.length);i.set(a),i.set(e,a.length),e=i,s.w=a.length}return S_(e,null==t.level?6:t.level,null==t.mem?s.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):20:12+t.mem,r,n,s)},I_=function(e,t){var r={};for(var n in e)r[n]=e[n];for(var n in t)r[n]=t[n];return r},$_=function(e,t,r){for(var n=e(),s=e.toString(),a=s.slice(s.indexOf("[")+1,s.lastIndexOf("]")).replace(/\s+/g,"").split(","),i=0;i<n.length;++i){var o=n[i],l=a[i];if("function"==typeof o){t+=";"+l+"=";var c=o.toString();if(o.prototype)if(-1!=c.indexOf("[native code]")){var u=c.indexOf(" ",8)+1;t+=c.slice(u,c.indexOf("(",u))}else for(var d in t+=c,o.prototype)t+=";"+l+".prototype."+d+"="+o.prototype[d].toString();else t+=c}else r[l]=o}return t},P_=[],C_=function(){return[Uv,Lv,Mv,zv,Bv,Fv,Zv,Kv,n_,a_,Jv,d_,Qv,i_,o_,l_,c_,u_,p_,f_,z_,A_,O_]},R_=function(){return[Uv,Lv,Mv,zv,Bv,Fv,Vv,Yv,r_,Xv,s_,t_,Jv,E_,x_,Qv,h_,m_,g_,y_,v_,__,b_,w_,c_,u_,S_,T_,M_,A_]},A_=function(e){return postMessage(e,[e.buffer])},O_=function(e){return e&&{out:e.size&&new Uv(e.size),dictionary:e.dictionary}},N_=function(e,t,r,n,s,a){var i=function(e,t,r,n){if(!P_[r]){for(var s="",a={},i=e.length-1,o=0;o<i;++o)s=$_(e[o],s,a);P_[r]={c:$_(e[i],s,a),e:a}}var l=I_({},P_[r].e);return Dv(P_[r].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+t.toString()+"}",r,l,function(e){var t=[];for(var r in e)e[r].buffer&&t.push((e[r]=new e[r].constructor(e[r])).buffer);return t}(l),n)}(r,n,s,function(e,t){i.terminate(),a(e,t)});return i.postMessage([e,t],t.consume?[e.buffer]:[]),function(){i.terminate()}},j_=function(e,t){return e[t]|e[t+1]<<8},D_=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},U_=function(e,t){return D_(e,t)+4294967296*D_(e,t+4)},L_=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8};function M_(e,t){return T_(e,t||{},0,0)}function z_(e,t){return f_(e,{i:2},t&&t.out,t&&t.dictionary)}var B_=function(e,t,r,n){for(var s in e){var a=e[s],i=t+s,o=n;Array.isArray(a)&&(o=I_(n,a[1]),a=a[0]),a instanceof Uv?r[i]=[a,o]:(r[i+="/"]=[new Uv(0),o],B_(a,i,r,n))}},F_="undefined"!=typeof TextEncoder&&new TextEncoder,q_="undefined"!=typeof TextDecoder&&new TextDecoder;try{q_.decode(x_,{stream:!0})}catch(e){}function H_(e,t){if(F_)return F_.encode(e);for(var r=e.length,n=new Uv(e.length+(e.length>>1)),s=0,a=function(e){n[s++]=e},i=0;i<r;++i){if(s+5>n.length){var o=new Uv(s+8+(r-i<<1));o.set(n),n=o}var l=e.charCodeAt(i);l<128||t?a(l):l<2048?(a(192|l>>6),a(128|63&l)):l>55295&&l<57344?(a(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++i))>>18),a(128|l>>12&63),a(128|l>>6&63),a(128|63&l)):(a(224|l>>12),a(128|l>>6&63),a(128|63&l))}return u_(n,0,s)}var Z_=function(e){var t=0;if(e)for(var r in e){var n=e[r].length;n>65535&&p_(9),t+=n+4}return t},V_=function(e,t,r,n,s,a,i,o){var l=n.length,c=r.extra,u=o&&o.length,d=Z_(c);L_(e,t,null!=i?33639248:67324752),t+=4,null!=i&&(e[t++]=20,e[t++]=r.os),e[t]=20,t+=2,e[t++]=r.flag<<1|(a<0&&8),e[t++]=s&&8,e[t++]=255&r.compression,e[t++]=r.compression>>8;var p=new Date(null==r.mtime?Date.now():r.mtime),f=p.getFullYear()-1980;if((f<0||f>119)&&p_(10),L_(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=a&&(L_(e,t,r.crc),L_(e,t+4,a<0?-a-2:a),L_(e,t+8,r.size)),L_(e,t+12,l),L_(e,t+14,d),t+=16,null!=i&&(L_(e,t,u),L_(e,t+6,r.attrs),L_(e,t+10,i),t+=14),e.set(n,t),t+=l,d)for(var h in c){var m=c[h],g=m.length;L_(e,t,+h),L_(e,t+2,g),e.set(m,t+4),t+=4+g}return u&&(e.set(o,t),t+=u),t},G_="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()},W_=[/^\/$/,/^\*+$/,/^[0-9]+$/],K_=["/artifact/","https://","http://","*********"],Y_=new Set(["sha1","_sha1","pageref","downloadsPath","tracesDir","pageId"]);function J_({sensitiveValues:e,str:t}){return e.reduce((e,t)=>e.replaceAll(t,"[REDACTED]"),t)}function Q_({sensitiveValues:e,value:t}){return"string"==typeof t?J_({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>Q_({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?eb({obj:t,sensitiveValues:e}):t}function X_(e){return!!Y_.has(e)||e.toLowerCase().endsWith("sha1")}function eb({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,X_(e)?r:Q_({sensitiveValues:t,value:r})]))}function tb({error:e,sensitiveValues:t}){return e?{...e,message:J_({sensitiveValues:t,str:e.message})}:void 0}function rb({content:e,sensitiveValues:t}){const r=new u.TextDecoder,n=new u.TextEncoder,s=J_({sensitiveValues:t,str:r.decode(e)});return n.encode(s)}var nb=u.promisify(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&p_(7);var n=[],s=function(){for(var e=0;e<n.length;++e)n[e]()},a={},i=function(e,t){G_(function(){r(e,t)})};G_(function(){i=r});for(var o=e.length-22;101010256!=D_(e,o);--o)if(!o||e.length-o>65558)return i(p_(13,0,1),null),s;var l=j_(e,o+8);if(l){var c=l,u=D_(e,o+16),d=4294967295==u||65535==c;if(d){var p=D_(e,o-12);(d=101075792==D_(e,p))&&(c=l=D_(e,p+32),u=D_(e,p+48))}for(var f=t&&t.filter,h=function(t){var r=function(e,t,r){var n=j_(e,t+28),s=function(e,t){if(t){for(var r="",n=0;n<e.length;n+=16384)r+=String.fromCharCode.apply(null,e.subarray(n,n+16384));return r}if(q_)return q_.decode(e);var s=function(e){for(var t="",r=0;;){var n=e[r++],s=(n>127)+(n>223)+(n>239);if(r+s>e.length)return{s:t,r:u_(e,r-1)};s?3==s?(n=((15&n)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t+=String.fromCharCode(55296|n>>10,56320|1023&n)):t+=1&s?String.fromCharCode((31&n)<<6|63&e[r++]):String.fromCharCode((15&n)<<12|(63&e[r++])<<6|63&e[r++]):t+=String.fromCharCode(n)}}(e),a=s.s;return(r=s.r).length&&p_(8),a}(e.subarray(t+46,t+46+n),!(2048&j_(e,t+8))),a=t+46+n,i=D_(e,t+20),o=r&&4294967295==i?function(e,t){for(;1!=j_(e,t);t+=4+j_(e,t+2));return[U_(e,t+12),U_(e,t+4),U_(e,t+20)]}(e,a):[i,D_(e,t+24),D_(e,t+42)],l=o[0],c=o[1],u=o[2];return[j_(e,t+10),l,c,s,a+j_(e,t+30)+j_(e,t+32),u]}(e,u,d),o=r[0],c=r[1],p=r[2],h=r[3],m=r[4],g=r[5],y=function(e,t){return t+30+j_(e,t+26)+j_(e,t+28)}(e,g);u=m;var v=function(e,t){e?(s(),i(e,null)):(t&&(a[h]=t),--l||i(null,a))};if(!f||f({name:h,size:c,originalSize:p,compression:o}))if(o)if(8==o){var _=e.subarray(y,y+c);if(p<524288||c>.8*p)try{v(null,z_(_,{out:new Uv(p)}))}catch(e){v(e,null)}else n.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&p_(7),N_(e,t,[C_],function(e){return A_(z_(e.data[0],O_(e.data[1])))},1,r)}(_,{size:p},v))}else v(p_(14,"unknown compression type "+o,1),null);else v(null,u_(e,y,y+c));else v(null,null)},m=0;m<c;++m)h()}else i(null,{});return s}),sb=u.promisify(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&p_(7);var n={};B_(e,"",n,t);var s=Object.keys(n),a=s.length,i=0,o=0,l=a,c=new Array(a),u=[],d=function(){for(var e=0;e<u.length;++e)u[e]()},p=function(e,t){G_(function(){r(e,t)})};G_(function(){p=r});var f=function(){var e=new Uv(o+22),t=i,r=o-i;o=0;for(var n=0;n<l;++n){var s=c[n];try{var a=s.c.length;V_(e,o,s,s.f,s.u,a);var u=30+s.f.length+Z_(s.extra),d=o+u;e.set(s.c,d),V_(e,i,s,s.f,s.u,a,o,s.m),i+=16+u+(s.m?s.m.length:0),o=d+a}catch(e){return p(e,null)}}!function(e,t,r,n,s){L_(e,t,101010256),L_(e,t+8,r),L_(e,t+10,r),L_(e,t+12,n),L_(e,t+16,s)}(e,i,c.length,r,t),p(null,e)};a||f();for(var h=function(e){var t=s[e],r=n[t],l=r[0],h=r[1],m=function(){var e=-1;return{p:function(t){for(var r=e,n=0;n<t.length;++n)r=k_[255&r^t[n]]^r>>>8;e=r},d:function(){return~e}}}(),g=l.length;m.p(l);var y=H_(t),v=y.length,_=h.comment,b=_&&H_(_),w=b&&b.length,E=Z_(h.extra),x=0==h.level?0:8,S=function(r,n){if(r)d(),p(r,null);else{var s=n.length;c[e]=I_(h,{size:g,crc:m.d(),c:n,f:y,m:b,u:v!=t.length||b&&_.length!=w,compression:x}),i+=30+v+E+s,o+=76+2*(v+E)+(w||0)+s,--a||f()}};if(v>65535&&S(p_(11,0,1),null),x)if(g<16e4)try{S(null,M_(l,h))}catch(e){S(e,null)}else u.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&p_(7),N_(e,t,[R_],function(e){return A_(M_(e.data[0],e.data[1]))},0,r)}(l,h,S));else S(null,l)},m=0;m<l;++m)h(m);return d});async function ab({content:e,filename:t,sensitiveValues:r}){const n=t.toLowerCase();return n.endsWith(".trace")||n.endsWith(".network")?function({content:e,sensitiveValues:t}){const r=new u.TextDecoder,n=new u.TextEncoder,s=r.decode(e).split("\n").map(e=>{if(!e.trim())return e;try{const r=function({event:e,sensitiveValues:t}){return m.match(e).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:J_({sensitiveValues:t,str:e.preview}),value:Q_({sensitiveValues:t,value:e.value})})),text:J_({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:eb({obj:e.params,sensitiveValues:t}),title:e.title?J_({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:tb({error:e.error,sensitiveValues:t}),result:void 0!==e.result?Q_({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:tb({error:e.error,sensitiveValues:t}),params:eb({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?Q_({sensitiveValues:t,value:e.result}):void 0,title:e.title?J_({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:eb({obj:e.params,sensitiveValues:t})})).with({type:"stdout"},{type:"stderr"},e=>({...e,text:void 0!==e.text?J_({sensitiveValues:t,str:e.text}):void 0})).with({type:"error"},e=>({...e,message:J_({sensitiveValues:t,str:e.message})})).with({type:"log"},e=>({...e,message:J_({sensitiveValues:t,str:e.message})})).with({type:"context-options"},e=>({...e,options:eb({obj:e.options,sensitiveValues:t}),title:e.title?J_({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:eb({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:eb({obj:e.snapshot,sensitiveValues:t})})).with({type:"screencast-frame"},{type:"input"},e=>e).exhaustive()}({event:JSON.parse(e),sensitiveValues:t});return JSON.stringify(r)}catch{return J_({sensitiveValues:t,str:e})}});return n.encode(s.join("\n"))}({content:e,sensitiveValues:r}):n.endsWith(".html")||n.endsWith(".dat")||n.endsWith(".json")?rb({content:e,sensitiveValues:r}):n.startsWith("resources/")?async function({content:e,sensitiveValues:t}){return await(0,Nv.isBinaryFile)(Buffer.from(e))?e:rb({content:e,sensitiveValues:t})}({content:e,sensitiveValues:r}):e}function ib(e=process.cwd()){let r=t.resolve(e);for(;;){const e=ob(r);if(e){const n={...e.dependencies,...e.devDependencies},s="@playwright/test"in n?"@playwright/test":"playwright"in n?"playwright":void 0;if(s){const e=lb(r);let n=!1,a=r;for(;;){const e=t.join(a,"node_modules"),r=t.join(e,s);if(i.existsSync(r)){n=!0;break}const o=t.dirname(a);if(o===a)break;a=o}return{inNodeModules:n,installed:!0,packageManager:e,packageName:s}}}const n=t.dirname(r);if(n===r)return{inNodeModules:!1,installed:!1,packageManager:void 0};r=n}}function ob(e){const r=t.join(e,"package.json");let n;try{n=i.readFileSync(r,"utf-8")}catch{return}try{return JSON.parse(n)}catch{return}}function lb(e){const r=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];let n=e;for(;;){for(const[e,s]of r)if(i.existsSync(t.join(n,s)))return e;const e=t.dirname(n);if(e===n)return;n=e}}function cb(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 ub=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),db=e=>(e instanceof Error?e.message:String(e)).slice(0,400),pb=({outputDir:e,representativeTest:t})=>{const r=["test","--trace=on","--workers=1","--retries=0","--output",e];return t.filePath&&r.push(t.filePath),t.testIdentifier?r.push("--grep",`^${ub(t.testIdentifier)}$`):t.testTitle&&r.push("--grep",ub(t.testTitle)),r},fb=async e=>{const t=await f.readdir(e,{withFileTypes:!0}),r=[];for(const n of t){const t=D.default.join(e,n.name);if(n.isDirectory())r.push(...await fb(t));else if(n.isFile()&&"trace.zip"===n.name){const e=await f.stat(t);r.push({path:t,mtimeMs:e.mtimeMs})}}return r},{zSuiteAutoHealReport:hb,zRepresentativeTest:mb}=function(e){const t=e.enum($v),r=["Classification of the root cause:","",`- test: ${Cv("test")}`,`- bug: ${Cv("bug")}`,`- other: ${Cv("other")}`].join("\n"),n=e.object({filePath:e.string().optional(),testIdentifier:e.string().optional(),testTitle:e.string().optional()}),s=e.object({status:e.enum(["captured","capture_failed","upload_failed"]),representativeTest:n,storage:e.object({bucket:e.string(),key:e.string()}).optional(),signedUrl:e.string().optional(),error:e.string().optional()}),a=s.extend({testCaseId:e.string().min(1).describe("Test case ID this trace proof corresponds to.")}),i=e.object({erroredUrl:e.string().optional(),issueType:t.describe(r),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",[i.extend({fixApplied:e.string().describe("What fix was applied (brief, specific)."),result:e.literal("fixed"),traceProof:s.optional().describe("Optional trace proof metadata for fixed issues."),traceProofs:e.array(a).min(1).optional().describe("Optional per-test trace proof metadata for fixed issues.")}),i.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,zRepresentativeTest:n,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.")}),zTraceProof:s,zTraceProofByTest:a}}(S.z),gb=({authHeader:e,diffTracker:t,orgId:r,runId:n,workingDir:a})=>Em({name:"auto-heal-report",tools:[wm("capture-trace-proof",["Capture and upload a Playwright trace proof for a fixed issue or fixed test case.","","Use this only for fixed results. Pass representative test info from the worker.","Pass testCaseId and call once per fixed test case.","testCaseId is for per-test mapping/storage metadata; representativeTest selects the runnable test."].join("\n"),{issueId:S.z.string().min(1).describe("Issue identifier for deterministic output paths and storage key naming."),proofId:S.z.string().min(1).optional().describe("Optional id for deterministic proof naming and deduplication."),representativeTest:mb.optional().default({}),testCaseId:S.z.string().min(1).optional().describe("Optional test case ID when capturing per-test trace proofs.")},async({issueId:t,proofId:o,representativeTest:l,testCaseId:c})=>{const u=S.z.string().min(1).parse(t),d=null==o?void 0:S.z.string().min(1).parse(o),p=null==c?void 0:S.z.string().min(1).parse(c),h=await(async({authHeader:e,issueId:t,orgId:r,proofId:n,representativeTest:a,runId:o,testCaseId:l,workingDir:c})=>{if(!(e=>null!=e.filePath||null!=e.testTitle||null!=e.testIdentifier)(a))return{status:"capture_failed",representativeTest:a,error:"Representative test info is missing (need filePath, testTitle, or testIdentifier)."};const u=ib(c);if(!u.installed||!u.inNodeModules||!u.packageManager)return{status:"capture_failed",representativeTest:a,error:"Playwright is not installed in the current workspace."};const d=(e=>Av(e)??"issue")(t),p=(({proofId:e,testCaseId:t})=>Ov(t)??Ov(e))({testCaseId:l,proofId:n}),h=D.default.join(c,".stably","autoheal-proof",d,p??"issue"),[m,...g]=cb(u.packageManager),y=[...g,...pb({outputDir:h,representativeTest:a})];try{await f.rm(h,{force:!0,recursive:!0}),await f.mkdir(h,{recursive:!0});const{code:u,stderr:d,timedOut:p}=await(async({args:e,command:t,cwd:r,env:n,timeoutMs:a})=>await new Promise((i,o)=>{const l=s.spawn(t,e,{cwd:r,env:n??process.env,stdio:["ignore","ignore","pipe"]});let c="",u=!1;l.stderr.on("data",e=>{c+=e.toString()});const d=setTimeout(()=>{u=!0,l.kill("SIGTERM")},a);l.on("error",e=>{clearTimeout(d),o(e)}),l.on("close",e=>{clearTimeout(d),i({code:e,stderr:c,timedOut:u})})}))({args:y,command:m,cwd:c,env:{...process.env,STABLY_INTERNAL_DISABLE_REPORTING:"1"},timeoutMs:3e5});if(p)return{status:"capture_failed",representativeTest:a,error:"Trace proof run timed out while executing Playwright verification."};if(0!==u)return{status:"capture_failed",representativeTest:a,error:`Trace proof run failed (exit code ${u??"unknown"}): ${d.trim().slice(0,280)}`};const g=await(async e=>{const t=await fb(e);if(0!==t.length)return t.sort((e,t)=>t.mtimeMs-e.mtimeMs),t[0]?.path})(h);if(!g)return{status:"capture_failed",representativeTest:a,error:"Trace proof run completed, but no trace.zip was produced."};const{traceBucketPath:v,uploadUrl:_,sensitiveValues:b}=await(async({authHeader:e,issueId:t,proofId:r,testCaseId:n,contentType:s="application/zip",orgId:a,runId:i})=>{const o=await(l={auth:e,body:{contentType:s,issueId:t,proofId:r,testCaseId:n},client:tg(),headers:Ry(a),path:{runId:i}},(l.client??Zm).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-trace/upload-url",...l,headers:{"Content-Type":"application/json",...l.headers}}));var l;if(o.error)throw new Error(`Failed to presign trace upload (${o.response.status})`);const c=jy.parse(o.data);return{traceBucketPath:c.traceBucketPath,expiresInSeconds:c.expiresInSeconds,key:c.key,uploadUrl:c.uploadUrl,sensitiveValues:c.sensitiveValues}})({authHeader:e,issueId:t,proofId:n,orgId:r,runId:o,testCaseId:l}),w=await async function({tracePath:e,sensitiveValues:t}){const r=[],n=i.createReadStream(e);for await(const e of n)r.push(e);return async function({sensitiveValues:e,traceBuffer:t}){const r=e.filter(e=>!(e.length<3||W_.some(t=>t.test(e))||K_.some(t=>e.includes(t))));if(0===r.length)return new Uint8Array(t);const n=[...r].sort((e,t)=>t.length-e.length),s=await nb(new Uint8Array(t)),a=Object.entries(s),i=await Promise.all(a.map(async([e,t])=>[e,await ab({content:t,filename:e,sensitiveValues:n})])),o=Object.fromEntries(i);return sb(o)}({traceBuffer:new Uint8Array(Buffer.concat(r)),sensitiveValues:t})}({tracePath:g,sensitiveValues:b});try{await(async({contentType:e="application/zip",traceBuffer:t,uploadUrl:r})=>{const n=await fetch(r,{body:Buffer.from(t),headers:{"Content-Type":e},method:"PUT"});if(!n.ok)throw new Error(`Failed to upload trace (${n.status})`)})({traceBuffer:w,uploadUrl:_})}catch(e){return{status:"upload_failed",representativeTest:a,error:db(e)}}return{status:"captured",representativeTest:a,storage:v}}catch(e){return{status:"capture_failed",representativeTest:a,error:db(e)}}})({authHeader:e,issueId:u,orgId:r,proofId:d,representativeTest:mb.parse(l??{}),runId:n,testCaseId:p,workingDir:a}),m="string"==typeof p?{testCaseId:p,...h}:h;return{content:[{text:JSON.stringify(m),type:"text"}]}}),wm("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:hb},async({report:s})=>{const a=await t.computeDiff(),i=(e=>{if(!e||"object"!=typeof e)return e;const t=e;if(!Array.isArray(t.issues))return e;const r=t.issues.map(e=>{if(!e||"object"!=typeof e)return e;const t=e;if("fixed"!==t.result||null!=t.traceProof||!Array.isArray(t.traceProofs))return e;const[r]=t.traceProofs;if(!r||"object"!=typeof r)return e;const n={...r};return delete n.testCaseId,{...t,traceProof:n}});return{...t,issues:r}})(s),o=hb.parse(i);try{await(async({authHeader:e,orgId:t,report:r,runId:n})=>{const s=await(a={auth:e,body:{report:JSON.stringify(r)},client:tg(),headers:Ry(t),path:{runId:n}},(a.client??Zm).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...a,headers:{"Content-Type":"application/json",...a.headers}}));var a;if(s.error)throw new Error(`Failed to upload auto-heal report (${s.response.status})`)})({authHeader:e,orgId:r,report:o,runId:n});const{diffBucketPath:t,uploadUrl:s}=await Dy({authHeader:e,contentType:"text/plain",orgId:r,runId:n});await Uy({contentType:"text/plain",diff:a,uploadUrl:s}),await Ly({authHeader:e,diffBucketPath:t,orgId:r,runId:n})}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. ${e instanceof Error?e.message:String(e)} 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"}),yb=({onComplete:e,onRestartRequested:t})=>Em(e?{name:"session-control",tools:[wm("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:S.z.string().describe("A brief summary of what was accomplished")},({summary:t})=>{const r="string"==typeof t?t:String(t);return e(),Promise.resolve(`Session complete: ${r}`)})]}:{name:"stably-agent-control",version:"1.0.0",tools:[wm("restart_mcp_servers",'Restart the MCP servers to reinitialize browser tools after dependency changes.\n\nWHEN TO USE:\n- After installing or updating @playwright/test to version 1.56.x\n- When browser tools fail due to version mismatch errors\n- When the user has fixed a dependency issue and you need to reinitialize\n\nIMPORTANT: The restart happens at the END of your current turn.\n- Do NOT call any browser tools (setup_page, navigate, etc.) after this tool in the same turn - they will use the OLD servers\n- After calling this tool, END your turn naturally (no more tool calls)\n- The system will automatically continue in a new turn once the tools are restarted\n- Do NOT ask the user to reply again just to resume (only ask if you truly need additional input)\n\nEnd your turn briefly. You may say something like:\n- "Restarting browser tools now…"\n- "Tools are restarting to pick up the dependency changes…"',{},()=>(t(),Promise.resolve({content:[{type:"text",text:"MCP servers are being restarted. Browser tools will be reinitialized."}]})))]}),vb=S.z.object({commentUrl:S.z.string()}),_b=({prContext:e,authHeader:t,orgId:r,onReportPosted:n})=>Em({name:"create-report",tools:[wm("post_create_report",`Post a test creation report as a GitHub comment on PR #${e.prNumber}.\nCall this tool at the end of test creation to summarize what was created.\nThe report will be posted to: ${e.prUrl}\n\nWHEN TO USE:\n- After you have finished creating test files\n- To provide a summary of the tests created on the PR for visibility\n\nThe report will include:\n- A list of all test files created\n- Your summary of what was tested`,{summary:S.z.string().describe("A summary of the tests created. Include what features/flows are tested and any important notes."),filesCreated:S.z.array(S.z.string()).describe("List of test file paths that were created (relative to workspace root)")},async({summary:s,filesCreated:a})=>{const i=Array.isArray(a)?a:[];wy.info("[create-report] Posting report to GitHub PR",{prNumber:e.prNumber,filesCount:i.length});try{const a={summary:"string"==typeof s?s:String(s),filesCreated:i.map(String)},o=await async function({authHeader:e,orgId:t,prNumber:r,owner:n,repo:s,report:a}){const i=new URL("/internal/v1/cli/create-report",Gm).toString(),o={Authorization:e,"Content-Type":"application/json"};t&&(o["x-stably-org-id"]=t),wy.debug("Posting create report to GitHub",{prNumber:r,owner:n,repo:s,filesCount:a.filesCreated.length});const l=await fetch(i,{method:"POST",headers:o,body:JSON.stringify({prNumber:r,owner:n,repo:s,report:a}),signal:AbortSignal.timeout(3e4)});if(!l.ok){const e=await l.text().catch(()=>"");throw wy.error("Failed to post create report",{status:l.status,error:e.slice(0,500)}),new Error(`Failed to post create report: ${l.status} ${e.slice(0,200)}`)}const c=vb.parse(await l.json());return wy.info("Create report posted successfully",{commentUrl:c.commentUrl}),c}({authHeader:t,orgId:r,prNumber:e.prNumber,owner:e.owner,repo:e.repo,report:a});return n?.(o),wy.info("[create-report] Report posted successfully",{commentUrl:o.commentUrl}),{content:[{type:"text",text:`✅ Test creation report posted to PR #${e.prNumber}\n\nView the comment: ${o.commentUrl}`}]}}catch(e){const t=e instanceof Error?e.message:String(e);return wy.error("[create-report] Failed to post report",{error:t}),{content:[{type:"text",text:`❌ Failed to post report to GitHub: ${t}\n\nThe tests were still created successfully, but the PR comment could not be posted.`}],isError:!0}}})]}),bb=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]"),wb=(e,t)=>({message:bb(e),status:t?.status,statusText:t?.statusText}),Eb=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"]),xb=async({authHeader:e,mode:t,maxTurnsOverride:r})=>{const n=tg();wy.debug("Requesting subagent definitions from API",{mode:t,maxTurnsOverride:r});const s=await(a={client:n,auth:e,body:{mode:t,maxTurnsOverride:r}},(a.client??Zm).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/subagents",...a,headers:{"Content-Type":"application/json",...a.headers}}));var a;if(401===s.response.status)throw wy.warn("Subagent definitions fetch failed: unauthorized (401)"),await vg(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===s.response.status)throw wy.warn("Subagent definitions fetch failed: forbidden (403)"),await vg(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(s.error)throw wy.warn("Subagent definitions fetch failed",{error:s.error}),new Error(`Failed to fetch subagent definitions: ${JSON.stringify(s.error)}`);const{subagents:i}=s.data;return wy.debug("Subagent definitions received",{count:Object.keys(i).length}),i},{zStablyYaml:Sb}=function(e){const t=e.object({cron:e.string(),stablyTestArgs:e.string().optional(),timezone:e.string().optional()}),r=e.object({maxTurnsPerIssue:e.number().int().positive().optional(),maxParallelWorkers:e.number().int().positive().optional(),rules:e.string().optional()}),n=e.object({fix:r.optional()});return{zStablyYaml:e.object({schedules:e.record(e.string(),t).optional(),agent:n.optional()}),zAgentConfig:n,zAgentFixConfig:r,zScheduleEntry:t}}(b.z),kb=async(e,t)=>{try{const r=await cg(e,t);if(!r)return void wy.debug(`No ${t} found`);const n=await f.readFile(r,"utf-8");if(!n.trim())return;return n.length>1e4?(wy.warn(`${t} exceeds max length (${n.length} > 10000), truncating`,{path:r}),{content:n.slice(0,1e4),path:r}):(wy.debug(`Loaded ${t} rules`,{path:r,contentLength:n.length}),{content:n,path:r})}catch(e){return void wy.warn(`Failed to read ${t}`,{error:e})}},Tb=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],Ib=["Task","mcp__playwright-test","Skill"],$b=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],Pb=e=>{if("EPIPE"!==e.code)throw e},Cb="__main__",Rb=e=>"mcp__auto-heal-report__generate-report"===e,Ab=e=>"mcp__auto-heal-report__capture-trace-proof"===e?"Verify Test Run":"mcp__auto-heal-report__generate-report"===e?"Generate Report":Tv(e);async function Ob(e,t){return!!e&&(!!e.hasQueuedMessages()||new Promise(r=>{const n=setTimeout(()=>{clearInterval(s),r(!1)},t),s=setInterval(()=>{e.hasQueuedMessages()&&(clearTimeout(n),clearInterval(s),r(!0))},200)}))}var Nb=async r=>{if("single"===r.mode||"build"===r.mode){const e=Array.isArray(r.prompt)?r.prompt.join(" "):r.prompt;wy.initSession(e||"create-from-diff")}else"fix"===r.mode&&wy.initSession(`fix-${r.runId}`);wy.info("Agent session starting",{mode:r.mode}),process.stdout.on("error",Pb),process.stderr.on("error",Pb);const n=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",n),wy.debug("Checking authentication");const s=await Iy({autoLogin:"chat"===r.mode||"init"===r.mode}),a=(e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken)(s);wy.debug("Authentication resolved",{authType:s.type});const l="oauth"===s.type?s.auth.context.orgId:void 0,c=D.default.resolve(process.cwd()),u=D.default.join(c,".env"),d=M.default.existsSync(u)&&M.default.statSync(u).isFile(),p=d?e.parse(M.default.readFileSync(u,"utf8")):{};wy.debug("Environment file",{path:u,exists:d,variableCount:Object.keys(p).length});const h="chat"!==r.mode&&"init"!==r.mode,g="chat"===r.mode;let y=new lv;const v="chat"===r.mode?r.getHelpText:void 0,_={log:[],promptDisplay:m.match(r).with({mode:"chat"},()=>"Ask Stably to build tests for you").with({mode:"init"},()=>"Setting up Playwright and Stably SDK").with({mode:"fix"},()=>"Fixing broken tests").with({mode:"build"},()=>"Building tests from specifications").with({mode:"single"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Creating tests from PR/branch changes"}).exhaustive(),status:"running"};let b,w,E,x,S=h,k=!1,$=!1,C=0,A=0,O=!1;const N=[];let j,U,L=[],z=!1,B=!1,F=0;const Z=new Map;let V=null,G=!1,W=!1;const K=Date.now();let Y,J="fix"===r.mode?{suiteId:r.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:K,endedAt:null,isError:!1,updatedAt:K,recentActivity:[],workers:[{id:Cb,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:K,endedAt:null,activity:[]}]}:null;const Q=new Set,X=(e,t)=>{if(!J)return;const r=J.workers.map(r=>{if(r.id!==e)return r;const n=[...r.activity,{...t,timestamp:Date.now()}].slice(-15);return{...r,activity:n}});re({workers:r})},ee=e=>{if(!J)return;const t=[...J.recentActivity,{...e,timestamp:Date.now()}].slice(-10);re({recentActivity:t})},te=e=>(J?.workers??[]).map(t=>t.id===Cb?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),re=e=>{J&&!Y?.isClosed&&(J={...J,...e,updatedAt:Date.now()},Y?.sendProgress(J))},ne=async e=>{if("fix"===r.mode){if("STARTED"===e){if(G)return;G=!0}else{if(W)return;W=!0}try{await(async({authHeader:e,orgId:t,runId:r,status:n})=>{const s=await(a={auth:e,body:{status:n},client:tg(),headers:Ry(t),path:{runId:r}},(a.client??Zm).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-status",...a,headers:{"Content-Type":"application/json",...a.headers}}));var a;if(s.error)throw new Error(`Failed to update autoheal status (${s.response.status})`)})({authHeader:a,orgId:l,runId:r.runId,status:e})}catch{}}},se="single"===r.mode||"build"===r.mode,ae=Date.now();let ie,oe=null;const le=e=>{oe&&!ie?.isClosed&&(oe={...oe,...e,updatedAt:Date.now()},ie?.sendProgress(oe))},ce=e=>{if(!oe)return;const t=[...oe.recentActivity,{...e,timestamp:Date.now()}].slice(-10);le({recentActivity:t})};if(se||"fix"===r.mode)try{const e=new URL("/internal/v1/cli/progress",Gm).toString(),t={Authorization:a,"Content-Type":"application/json"};l&&(t["x-stably-org-id"]=l);const n="single"===r.mode?"create":"build"===r.mode?"build":"fix",i=await fetch(e,{method:"POST",headers:t,body:JSON.stringify({mode:n,projectId:$y(s),agentId:q.default.randomUUID(),..."fix"===r.mode?{playwrightSuiteRunId:r.runId}:{}}),signal:AbortSignal.timeout(1e4)});if(i.ok){const{sessionId:e}=await i.json();if(se){const t="single"===r.mode||"build"===r.mode?Array.isArray(r.prompt)?r.prompt.join(" "):r.prompt:null,n=cv(c);oe={sessionId:e,phase:"initializing",startedAt:ae,endedAt:null,isError:!1,updatedAt:ae,currentActivity:null,filesCreated:[],recentActivity:[],prompt:t||null,environment:{gitBranch:n?.branch??null,workingDirectory:c,nodeVersion:process.version,cliVersion:Vm}},ie=new zy({authHeader:a,orgId:l,sessionId:e,onUserMessage:e=>{y&&(wy.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),ce({type:"user_message",summary:e}),ye({text:`[Web] ${e}`}),y.pushText(`[Message from web UI user]: ${e}`),S||(S=!0,ke({status:"running"})))}}),ie.start(),le({phase:"initializing"})}wy.info(`[${n}] Progress session created`,{sessionId:e})}else{const t=await i.text().catch(()=>"");wy.warn(`[${n}] Failed to create progress session: ${i.status} ${e} — ${t.slice(0,300)}`)}}catch(e){const t=e instanceof Error?e.message:String(e);wy.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const ue={current:e=>{}},de={current:async()=>{}},{addSubagentActivity:pe,addSubagentStart:fe,addTool:he,addToolResult:me,appendText:ge,appendUserMessage:ye,cleanup:ve,setExiting:_e,setRunningLabel:be,setStatus:we,setSubagentStatus:Ee,updateFixProgress:xe}=await(async(e,t)=>{const{Box:r,Static:n,Text:s,render:a,useInput:i}=await import("ink"),o=!!process.stdin.isTTY,l=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],c=()=>I.jsx(s,{inverse:!0,children:" "}),u=(({Box:e,Text:t,useInput:r},n,s)=>function({onChoice:a,prompt:i}){const[o,l]=T.useState(0),[c,u]=T.useState(!1),[d,p]=T.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"}];r((e,t)=>{if(c)return t.return?void a("deny_with_message",d||"User denied this action"):t.escape?(u(!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 l(e=>e>0?e-1:f.length-1);if(t.downArrow)return void l(e=>e<f.length-1?e+1:0);if(t.return){const e=f[o];return"deny_with_message"===e.value?void u(!0):void a(e.value)}const r=parseInt(e,10);if(r>=1&&r<=f.length){const e=f[r-1];if("deny_with_message"===e.value)return void u(!0);a(e.value)}},{isActive:s});const h=Tv(i.toolName),m=Iv(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]})}),c?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:">"})," ",d,I.jsx(n,{})]})]}):I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,r)=>I.jsx(t,{children:I.jsxs(t,{color:r===o?"cyan":void 0,children:[r===o?"❯":" "," ",r+1,". ",e.label]})},e.value))]})]})})({Box:r,Text:s,useInput:i},c,o),d=(({Cursor:e,inkComponents:{Box:t,Static:r,Text:n,useInput:s},isRawModeSupported:a,PermissionPrompt:i,Spinner:o})=>{const l=({progress:e})=>{const[r,s]=T.useState(Date.now());T.useEffect(()=>{const e=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(e)},[]);const a=r-e.startedAt,i=Math.floor(a/1e3),o=Math.floor(i/60),l=i%60,c=o>0?`${o}m ${l.toString().padStart(2,"0")}s`:`${l}s`,{label:u,color:d}={initializing:{label:"Fetching test results",color:"gray"},triage:{label:"Triaging failures",color:"yellow"},fixing:{label:"Fixing tests",color:"cyan"},validation:{label:"Validating fixes",color:"blue"},complete:{label:"Complete",color:"green"}}[e.phase],p=e.fixedTests+e.failedTests,f="fixing"===e.phase&&p>0?null!==e.totalTests?` (fixed ${e.fixedTests}/${e.totalTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:` (fixed ${e.fixedTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:"";return I.jsx(t,{flexDirection:"column",children:I.jsxs(n,{children:[I.jsx(n,{color:d,bold:!0,children:u}),I.jsx(n,{color:"gray",children:f}),I.jsxs(n,{color:"gray",children:[" [",c,"]"]})]})})},c=({progress:e})=>{const r=e.endedAt??Date.now(),s=Math.floor((r-e.startedAt)/1e3),a=Math.floor(s/60),i=s%60,o=a>0?`${a}m ${i.toString().padStart(2,"0")}s`:`${i}s`,l=e.isError?"yellow":"green",c=e.isError?"Fix stopped":"Fix complete";return I.jsxs(t,{flexDirection:"column",children:[I.jsxs(n,{color:l,bold:!0,children:[c," in ",o]}),null!==e.totalTests&&I.jsxs(n,{color:"gray",children:[e.fixedTests,"/",e.totalTests," tests fixed",e.failedTests>0?`, ${e.failedTests} failed`:""]})]})},u=e=>{if("subagent"===e.kind&&e.subagent){const{subagent:r}=e,s="complete"===r.status?"green":"error"===r.status?"red":"yellow";return I.jsxs(t,{flexDirection:"column",marginTop:1,children:[I.jsxs(n,{children:[I.jsx(n,{color:s,bold:!0,children:"Agent"}),r.description?I.jsxs(n,{color:"gray",children:[" (",r.description,")"]}):null]}),r.activities.length>0&&I.jsx(t,{flexDirection:"column",marginLeft:2,children:r.activities.map(e=>(e=>"tool"===e.kind?I.jsxs(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?I.jsx(n,{color:"gray",children:e.content},e.id):null)(e))})]},e.id)}return"tool"===e.kind?I.jsxs(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?I.jsx(n,{color:"gray",children:e.content},e.id):"user"===e.kind?I.jsxs(n,{color:"cyan",children:["You: ",e.content]},e.id):I.jsx(n,{children:e.content},e.id)},d="vscode"===process.env.TERM_PROGRAM,p=(e,t)=>{if(t<=0)return 0;let r=t-1;for(;r>0&&/\s/.test(e[r]);)r--;for(;r>0&&!/\s/.test(e[r-1]);)r--;return r},f=(e,t)=>{if(t>=e.length)return e.length;let r=t;for(;r<e.length&&!/\s/.test(e[r]);)r++;for(;r<e.length&&/\s/.test(e[r]);)r++;return r},h=(e,t)=>{if(t<=0)return 0;const r=e.lastIndexOf("\n",t-1);return-1===r?0:r+1},m=(e,t)=>{const r=e.indexOf("\n",t);return-1===r?e.length:r};return function({onExit:g,onPermissionChoice:y,onSend:v,showSpinnerImmediately:_,state:b}){const[w,E]=T.useState({value:"",cursor:0}),x=w.value,S=w.cursor,k=T.useRef(!1),$=T.useRef(void 0),[P,C]=T.useState(!1),R=T.useRef(0),A=b.log.at(-1),O="text"===A?.kind&&"running"===b.status,N=b.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),j=d?0:-1!==N?N:O?b.log.length-1:b.log.length;T.useEffect(()=>{b.log.length<R.current&&(R.current=0),j>R.current&&(R.current=j)},[b.log.length,j]);const D=b.log.slice(0,R.current),U=b.log.slice(R.current),L=!!b.permissionPrompt,M=T.useCallback(async()=>{k.current?($.current&&clearTimeout($.current),await(g?.()),process.exit(0)):(k.current=!0,C(!0),$.current=setTimeout(()=>{k.current=!1,C(!1)},2e3))},[g]);s((e,t)=>{t.ctrl&&"c"===e&&M().catch(()=>process.exit(1))},{isActive:a}),T.useEffect(()=>{if(L||!v)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,cursor:m(e.value,e.cursor)})):E(e=>({...e,cursor:h(e.value,e.cursor)})):E(e=>({...e,cursor:e.value.length})):E(e=>({...e,cursor:0}))};return process.stdin.on("data",e),()=>{process.stdin.off("data",e)}},[L,v,x]),s((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){const e=x.trim();return e&&v?.(e),void E({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?E(e=>{const t=p(e.value,e.cursor);return{value:e.value.slice(0,t)+e.value.slice(e.cursor),cursor:t}}):!t.backspace&&!t.delete||t.ctrl?t.ctrl&&t.leftArrow||t.meta&&"b"===e?E(e=>({...e,cursor:p(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?E(e=>({...e,cursor:f(e.value,e.cursor)})):t.leftArrow?E(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?E(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?E(e=>({...e,cursor:0})):t.ctrl&&"e"===e?E(e=>({...e,cursor:e.value.length})):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||E(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):E(e=>e.cursor>0?{value:e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor),cursor:e.cursor-1}:e)}},{isActive:a&&!!v&&!L});const z=T.useMemo(()=>"running"===b.status?I.jsx(o,{label:b.runningLabel??"Working"}):"success"!==b.status?I.jsx(n,{color:"red",children:"✖ Failed"}):void 0,[b.runningLabel,b.status]),B=!(_||!v||"running"!==b.status||0!==b.log.length||b.resultText||b.errorText),F="running"===b.status&&!B||b.log.length>0||b.resultText||b.errorText||"running"!==b.status;return I.jsxs(t,{flexDirection:"column",children:[I.jsx(r,{items:["header"],children:()=>I.jsxs(t,{flexDirection:"column",flexShrink:0,children:[I.jsx(n,{color:"cyan",bold:!0,children:"Stably Agent"}),I.jsx(t,{flexDirection:"column",marginTop:1,children:I.jsx(n,{color:"gray",children:b.promptDisplay})})]},"header")}),D.length>0&&I.jsx(r,{items:D,children:e=>u(e)}),U.length>0&&I.jsx(t,{flexDirection:"column",children:U.map(e=>u(e))}),"error"===b.status&&b.errorText&&I.jsx(t,{marginTop:1,children:I.jsx(n,{color:"red",children:b.errorText})}),"success"===b.status&&b.resultText&&I.jsx(t,{marginTop:1,children:I.jsx(n,{children:b.resultText})}),F&&I.jsx(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===b.status&&b.fixProgress?I.jsxs(t,{flexDirection:"column",children:[I.jsxs(t,{children:[I.jsx(o,{}),I.jsx(n,{children:" "}),I.jsx(l,{progress:b.fixProgress})]}),"fixing"===b.fixProgress.phase&&b.log.flatMap(e=>{const{subagent:r}=e;if("subagent"!==e.kind||"fix-worker"!==r?.subagentType||"running"!==r.status)return[];const{activities:s}=r,a=s.filter(e=>"tool"===e.kind).length,i=s.at(-1),l=s.filter(e=>"tool"===e.kind).at(-1),c=(()=>{if(!i)return null;if("tool"===i.kind)return null;if("text"===i.kind){const e=i.content.trim().split("\n").at(-1)?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}if("tool_result"===i.kind){const e=i.content.trim().split("\n")[0]?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}return null})();return I.jsxs(t,{flexDirection:"column",children:[I.jsxs(n,{children:[" ",I.jsx(o,{}),I.jsxs(n,{color:"gray",children:[r.description||"fix-worker",a>0?` (${a} ${1===a?"cycle":"cycles"})`:""]})]}),l&&I.jsxs(n,{color:"gray",dimColor:!0,children:[" • ",l.content]}),c&&I.jsxs(n,{color:"gray",dimColor:!0,children:[" ",c]})]},e.id)})]}):"success"!==b.status&&"error"!==b.status||!b.fixProgress?z:I.jsx(c,{progress:b.fixProgress})}),null!=b.permissionPrompt&&null!=y&&I.jsx(i,{onChoice:y,prompt:b.permissionPrompt}),null!=v&&null==b.permissionPrompt&&!b.isExiting&&I.jsxs(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[I.jsx(n,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),I.jsxs(n,{children:[I.jsx(n,{color:"yellow",children:">"})," ",x.slice(0,S),I.jsx(e,{}),x.slice(S)]})]}),P&&I.jsxs(t,{marginTop:1,flexDirection:"column",children:[I.jsx(n,{color:"yellow",children:"Press Ctrl+C again to exit"}),cy&&I.jsxs(n,{color:"gray",children:["Debug log: ",fy]})]})]})}})({Cursor:c,inkComponents:{Box:r,Static:n,Text:s,useInput:i},isRawModeSupported:o,PermissionPrompt:u,Spinner:({label:e})=>{const[t,r]=T.useState(0);return T.useEffect(()=>{const e=setInterval(()=>r(e=>(e+1)%l.length),80);return()=>clearInterval(e)},[]),I.jsxs(s,{color:"yellow",children:[l[t]," ",e]})}});let p=e;t?.isFixMode&&(p.fixProgress={phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:Date.now(),endedAt:null,isError:!1});const f={current:(e,t)=>{}},h=a(I.jsx(d,{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(d,{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())},y=new Map;return{addSubagentActivity:({toolUseId:e,kind:t,content:r})=>{const n=y.get(e);if(void 0===n)return void console.error("[addSubagentActivity] No entry index for toolUseId:",e);const s=p.log[n];if(s&&"subagent"===s.kind&&s.subagent){if("text"===t){const e=s.subagent.activities.at(-1);e&&"text"===e.kind?e.content+=r:s.subagent.activities.push({id:s.subagent.activities.length,kind:"text",content:r.replace(/^\s*\n+/,"")})}else s.subagent.activities.push({id:s.subagent.activities.length,kind:t,content:r});p.log=[...p.log],m()}else console.error("[addSubagentActivity] Entry not found or not subagent:",{entryIndex:n,entryKind:s?.kind})},addSubagentStart:({toolUseId:e,subagentType:t,description:r})=>{const n=p.log.length;if(y.set(e,n),p.log=[...p.log,{content:"",id:n,kind:"subagent",subagent:{toolUseId:e,subagentType:t,description:r,status:"running",activities:[]}}],p.fixProgress)if("triage"===t&&"initializing"===p.fixProgress.phase)p.fixProgress={...p.fixProgress,phase:"triage"};else if("fix-worker"===t){const e=(p.fixProgress.totalTests??0)+1,t=r||null;p.fixProgress={...p.fixProgress,phase:"fixing",totalTests:e,currentTestDescription:t,lastTestDescription:t??p.fixProgress.lastTestDescription}}else"validation"===t?p.fixProgress={...p.fixProgress,phase:"validation",currentTestDescription:null}:"context"===t&&(p.fixProgress={...p.fixProgress,currentTestDescription:r||p.fixProgress.currentTestDescription});m()},addTool:({rawName:e,toolInput:t})=>{const r=Tv(e),n=Iv(e,t),s=n?`${r} (${n})`:r;p.log=[...p.log,{content:s,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),r=t&&"text"===t.kind?e:e.replace(/^\s*\n+/,"");t&&"text"===t.kind?p.log=[...p.log.slice(0,-1),{...t,content:`${t.content}${r}`}]:p.log=[...p.log,{content:r,id:p.log.length,kind:"text"}],m()},appendUserMessage:g,cleanup:async()=>{const e=h.waitUntilExit();h.unmount(),await e},setExiting:()=>{p.isExiting=!0,m()},setRunningLabel:({label:e})=>{p.runningLabel=e,m()},setStatus:({error:e,result:t,status:r})=>{p.errorText=e,p.resultText=t,p.status=r,m()},setSubagentStatus:({toolUseId:e,status:t})=>{const r=y.get(e);if(void 0===r)return;const n=p.log[r];n&&"subagent"===n.kind&&n.subagent&&(n.subagent.status=t,p.fixProgress&&"fix-worker"===n.subagent.subagentType&&("complete"===t?p.fixProgress={...p.fixProgress,fixedTests:p.fixProgress.fixedTests+1,currentTestDescription:null}:"error"===t&&(p.fixProgress={...p.fixProgress,failedTests:p.fixProgress.failedTests+1,currentTestDescription:null})),p.log=[...p.log],m(),"complete"!==t&&"error"!==t||y.delete(e))},showPermissionPrompt:e=>new Promise(t=>{f.current=(r,n)=>{if(p.permissionPrompt=void 0,m(),"allow"===r)t({behavior:"allow",updatedInput:e.input});else if("always"===r)t({behavior:"allow",updatedInput:e.input,updatedPermissions:e.suggestions});else{const e=n??"User denied this action";g({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},p.permissionPrompt={...e,resolve:t},m()}),updateFixProgress:t?.isFixMode?e=>{p.fixProgress&&(p.fixProgress={...p.fixProgress,...e},m())}:void 0}})(_,"chat"===r.mode||"init"===r.mode?{onExit:()=>de.current(),onSend:e=>ue.current(e),showSpinnerImmediately:"init"===r.mode}:"fix"===r.mode?{onExit:()=>de.current(),isFixMode:!0}:void 0);let Se=_.status;const ke=({error:e,result:t,status:r})=>{Se=r,we({error:e,result:t,status:r})};let Te;ue.current=e=>{const t=e.trim();if(g&&!wy.getLogFilePath()&&wy.initSession(t||"chat"),wy.debug("User message",{text:t}),"/help"===t){S&&y&&(k=!0,b?.interrupt?.(),y.allowNextTurn(),S=!1),"running"===Se&&ke({status:"success"}),ye({text:e});const t=v?.();return void ge({text:t??"Help is not available in this session."})}const r=E||$&&S;if(g&&(C+=1,x=void 0,r||(O=!1,be({label:void 0}))),y){if(r)return ke({status:"running"}),ye({text:e}),void N.push(e);if(!$||S||E||($=!1),S)return ke({status:"running"}),ye({text:e}),y.pushText(e),void(A+=1);ke({status:"running"}),ye({text:e}),y.pushText(e),S=!0}};const Ie=[];let $e;const Pe=await(async()=>{if("single"===r.mode||"build"===r.mode){const n=await async function(e,r){const n=t.resolve(e);if(r){const e=t.resolve(n,r);return bv(e,"output-flag"),{path:e,source:"output-flag"}}const s=yv(n);if(s){const e=await async function(e){try{const t=(await f.readFile(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(s);if(e){const r=t.resolve(t.dirname(s),e);if(_v(r))return bv(r,"playwright.config.ts"),{path:r,source:"playwright.config.ts"}}}for(const e of vv){const r=t.join(n,e);if(_v(r))return bv(r,"auto-detected"),{path:r,source:"auto-detected"}}return bv(n,"cwd-fallback"),{path:n,source:"cwd-fallback"}}(c,r.outputDir);return $e=n.path,e=r.prompt,`${(Array.isArray(e)?e.join(" "):e).trim()||"Create tests based on the changes in the current PR or branch. If the user references a specific PR number or branch name, first checkout that PR/branch using `gh pr checkout <number>` or `git checkout <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 stably test` or the repo's test command) and iterate until the new tests pass."}\n\n[Output directory: ${$e}]`}var e;if("fix"===r.mode)try{wy.info("[fix] Fetching autoheal context",{runId:r.runId});const e=Date.now(),{context:t,autohealReportUrl:n}=await(async({authHeader:e,orgId:t,runId:r})=>{wy.debug("Fetching autoheal context",{runId:r});const n=await(s={auth:e,client:tg(),headers:Ry(t),path:{runId:r}},(s.client??Zm).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...s}));var s;if(404===n.response.status)throw wy.warn("Autoheal context not found",{runId:r,status:404}),new Error(`Run ID "${r}" was not found.`);if(401===n.response.status)throw wy.warn("Autoheal context fetch unauthorized",{runId:r,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===n.response.status)throw wy.warn("Autoheal context fetch invalid request",{runId:r,status:422,error:n.error?.error}),new Error(n.error?.error??"Failed to fetch autoheal context (422).");if(!n.error){const e=Ay.safeParse(n.data);if(e.success)return wy.debug("Autoheal context fetched successfully",{runId:r,contextSize:e.data.context.length}),{context:e.data.context,autohealReportUrl:e.data.autohealReportUrl};throw wy.warn("Autoheal context response invalid",{runId:r}),new Error("Autoheal context response missing or invalid context.")}throw wy.warn("Autoheal context fetch failed",{runId:r,error:n.error}),new Error("Failed to fetch autoheal context")})({authHeader:a,orgId:l,runId:r.runId});return wy.info("[fix] Autoheal context fetched",{runId:r.runId,durationMs:Date.now()-e,contextLength:t.length}),Te=n,Y||(wy.info("[fix] Creating WebSocket progress reporter"),Y=new My({authHeader:a,orgId:l,runId:r.runId,onUserMessage:e=>{if(wy.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),X(Cb,{type:"user_message",summary:e}),ee({type:"user_message",summary:e}),ye({text:`[Web] ${e}`}),!S)return y.pushText(`[Message from web UI user]: ${e}`),S=!0,void y.allowNextTurn();z||Date.now()-F<2e3?y.pushText(`[Message from web UI user]: ${e}`):(L.push(e),j&&clearTimeout(j),j=setTimeout(()=>{j=void 0;const e=[...L];L=[],F=Date.now(),Et(e)},500))}}),Y.start(),re({phase:"initializing"})),ne("STARTED"),t}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";wy.error("[fix] Failed to fetch autoheal context",{error:t}),ke({error:t,status:"error"}),await ve(),process.exit(1)}return"init"===r.mode?"Please analyze this project and set up Playwright with the Stably SDK. Check for existing configurations and install the necessary dependencies.":""})(),Ce=await async function(e){const t=D.default.resolve(e),r=D.default.join(t,"tests"),n=D.default.join(r,"helpers"),s=D.default.join(r,"assets"),a=function(e){const t=D.default.resolve(e);if(i.existsSync(t))for(const e of uv){const r=D.default.join(t,`playwright.config${e}`);if(i.existsSync(r))return r}}(t)??D.default.join(t,"playwright.config.ts"),o=D.default.basename(a),l=D.default.join(r,"seed.spec.ts"),[c,u,d,p,f,h]=await Promise.all([fv({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),fv({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:r}),fv({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:n}),fv({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:s}),pv({defaultContent:"File does not exist or could not be read",fileName:o,filePath:a}),pv({defaultContent:"File does not exist or could not be read",fileName:"seed.spec.ts",filePath:l})]);return{absolutePath:t,directories:{assets:p,helpers:d,root:c,tests:u},files:{playwrightConfig:f,playwrightConfigFilename:o,seedSpec:h}}}(c),Re=await(async e=>{try{const t=await cg(e,"stably.yaml");if(!t)return void wy.debug("No stably.yaml found");const r=await f.readFile(t,"utf-8");if(!r.trim())return;const n=P.parseDocument(r),s=Sb.parse(n.toJS()),a=s.agent?.fix?.maxTurnsPerIssue,i=s.agent?.fix?.maxParallelWorkers,o=!!s.agent?.fix?.rules;return wy.debug(`Loaded stably.yaml: maxTurnsPerIssue=${a??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${o}`,{path:t,config:s.agent}),s}catch(e){return void wy.warn("Failed to parse stably.yaml",{error:e})}})(c),Ae=Re?.agent?.fix?.maxTurnsPerIssue,Oe=Re?.agent?.fix?.maxParallelWorkers,Ne=Re?.agent?.fix?.rules,je="fix"===r.mode||"single"===r.mode||"build"===r.mode,De="single"===r.mode||"build"===r.mode?await(async e=>{const t=await kb(e,"STABLY-CREATE.md");return t?.content})(c):void 0,Ue=await(e=>kb(e,"STABLY.md"))(c),Le=Ue?.content;wy.info("[fix] Fetching system prompt and subagent definitions",{mode:r.mode,maxTurnsOverride:Ae,hasCustomRules:!!Ne,hasCreateRules:!!De,hasStablyMd:!!Le,stablyMdPath:Ue?.path}),Ue&&wy.info(`STABLY.md loaded (${Ue.content.length} chars)`,{path:Ue.path});const Me=Date.now(),[{systemPrompt:ze,prContext:Be},Fe]=await Promise.all([hv({allowedEnvVars:Object.keys(p),mode:r.mode,workspaceInfo:Ce,authHeader:a,customHeader:"single"===r.mode||"build"===r.mode?r.customHeader:void 0,maxParallelWorkers:"fix"===r.mode?Oe:void 0}),je?xb({authHeader:a,mode:r.mode,maxTurnsOverride:Ae}):Promise.resolve({})]);wy.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-Me,systemPromptSize:ze.length,subagentCount:Object.keys(Fe).length,maxTurnsOverride:Ae??"default",hasPrContext:!!Be});const qe={...p,...process.env},He={};for(const[e,t]of Object.entries(qe))Eb.has(e)||void 0===t||(He[e]=t);const Ze=!0;wy.debug("AI proxy configuration",{useStablyAiProxy:Ze,wantsBypassProxy:!1,wantsUseOllama:!1}),wy.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:Ze});const Ve=Date.now(),Ge=await async function({auth:e,client:t,source:r,metadata:n,duration:s}){try{const i=await(a={auth:e,client:t,body:{source:r,metadata:n??{},duration:s}},(a.client??Zm).post({security:[{scheme:"bearer",type:"http"}],url:"/v1/proxy/api-key",...a,headers:{"Content-Type":"application/json",...a.headers}})),o=i.response;if(i.error){const e="object"==typeof i.error&&"error"in i.error?i.error.error:"Unknown error";return{error:wb(e,o)}}return i.data?{key:i.data.key}:{error:wb("No data in response",o)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:wb(t)}}var a}({auth:a,client:tg(),source:"cli"}),We=Ge?.key;if(wy.info("[fix] AI proxy key acquired",{durationMs:Date.now()-Ve,success:!!We,hasError:!!Ge?.error}),!We){const e=Ge?.error?.message?`Unable to make AI calls: ${Ge.error.message}`:"Unable to make AI calls. Check if you are authenticated.";wy.warn("Failed to get proxy API key",{error:Ge?.error?.message}),ke({error:e,status:"error"}),await ve(),wy.flush(),wy.printLogFileInfo(),process.exit(1)}wy.debug("Proxy API key acquired",{success:!!We});const Ke=await Cy(),Ye=Ke?Object.fromEntries(Object.entries(Py(Ke)).filter(e=>null!=e[1])):void 0,Je="init"===r.mode,Qe="fix"===r.mode,Xe=Qe?xm.createLocal({workingDir:c}):void 0;Xe&&await Xe.captureSnapshot();const et=Je?yb({onComplete:()=>{ke({status:"success"}),_e(),y?.finish(),process.exit(0)}}):g?yb({onRestartRequested:()=>{g&&($=!0,ke({status:"running"}),be({label:"Restarting browser tools..."}),x={createdAtUserMessageSeq:C,attempts:0})}}):void 0,tt=et?g?{"stably-agent-control":et}:{"session-control":et}:{},rt=se&&Be?["mcp__create-report"]:[],nt=Je?$b:[...Tb,...Qe?["mcp__auto-heal-report"]:[],...rt],st=Je?$b:g?[...Ib,"mcp__stably-agent-control"]:[...Ib,...rt],at=se&&Be?{"create-report":_b({prContext:Be,authHeader:a,orgId:l,onReportPosted:e=>{le({githubComment:{url:e.commentUrl,prNumber:Be.prNumber}})}})}:{},it=Je?tt:Qe&&Xe?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:Ye},"auto-heal-report":gb({authHeader:a,diffTracker:Xe,orgId:l,runId:r.runId,workingDir:c}),...tt}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:Ye},...tt,...at},ot="single"===r.mode||"build"===r.mode,lt=Je?[]:[{hooks:[async e=>{const t=Hy(e);if(!t)return{decision:"approve"};let r=!1;const n=t.map(e=>Fy(e)?e.text.length<=4e4?e:(r=!0,{...e,text:`${e.text.slice(0,4e4)}...[truncated to 40000 characters]`}):e);return r?{decision:"approve",hookSpecificOutput:{hookEventName:"PostToolUse",updatedMCPToolOutput:n}}:{decision:"approve"}}],matcher:"mcp__playwright-test__.*"},{matcher:"mcp__playwright-test__test_run",hooks:[Yy({onResult:e=>me({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[Jy({onResult:e=>me({message:e})})]},...ot?[{matcher:"Write",hooks:[Xy({onFileCreated:e=>{Ie.push(e),oe&&le({filesCreated:[...oe.filesCreated,e]})}})]}]:[],{matcher:"Write",hooks:[ov({workDir:c})]},{matcher:"Edit",hooks:[ov({workDir:c})]}],ct=Je?[]:[{matcher:"mcp__playwright-test__browser_type",hooks:[Ky({envVars:p})]}],ut=Object.keys(Fe).length>0?Fe:void 0,dt={...He};dt.MCP_TOOL_TIMEOUT=String(6e5),We&&(dt.ANTHROPIC_API_KEY=We,dt.ANTHROPIC_BASE_URL=Jm,dt.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1");const pt=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6",ft=Ne?`\n\n## Custom Rules\n${Ne}`:"",ht=De?`\n\n## Custom Test Generation Rules\n${De}`:"",mt=Le?`\n\n## Project Rules (STABLY.md)\n${Le}`:"",gt=ze+ft+ht+mt;wy.debug("[fix] Final system prompt assembled",{baseSize:ze.length,fixRulesSize:ft.length,createRulesSize:ht.length,stablyMdSize:mt.length,finalSize:gt.length});const yt=D.default.join(__dirname,"stably-plugin"),vt=M.default.existsSync(yt)?{type:"local",path:yt}:function(){const e=function(){try{if(!("undefined"==typeof document?require("url").pathToFileURL(e).href:R&&"SCRIPT"===R.tagName.toUpperCase()&&R.src||new URL("index.js",document.baseURI).href))return;const e=o.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(e).href:R&&"SCRIPT"===R.tagName.toUpperCase()&&R.src||new URL("index.js",document.baseURI).href),r=t.dirname(e);return t.join(r,"..","stably-plugin")}catch{return}}();if(e&&i.existsSync(e))return{type:"local",path:e}}(),_t=()=>(wy.info("[fix] Starting SDK query",{model:pt,tools:nt,mcpServers:Object.keys(it),resumeSessionId:w??null,subagentsEnabled:!!ut,subagentCount:Object.keys(Fe).length,useStablyAiProxy:Ze,aiProxyUrl:Jm,anthropicBaseUrl:void 0,stablyPluginPath:vt?.path,stablyPluginExists:!!vt}),function({prompt:e,options:r}){let n,s,{systemPrompt:a,settingSources:i,sandbox:l,...c}=r??{};void 0===a?n="":"string"==typeof a?n=a:"preset"===a.type&&(s=a.append);let u=c.pathToClaudeCodeExecutable;if(!u){let e=o.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:R&&"SCRIPT"===R.tagName.toUpperCase()&&R.src||new URL("index.js",document.baseURI).href),r=t.join(e,"..");u=t.join(r,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.2.34";let{abortController:d=Sn(),additionalDirectories:p=[],agent:f,agents:h,allowedTools:m=[],betas:g,canUseTool:y,continue:v,cwd:_,debug:b,debugFile:w,disallowedTools:E=[],tools:x,env:S,executable:k=(Os()?"bun":"node"),executableArgs:T=[],extraArgs:I={},fallbackModel:$,enableFileCheckpointing:P,forkSession:C,hooks:A,includePartialMessages:O,persistSession:N,maxThinkingTokens:j,maxTurns:D,maxBudgetUsd:U,mcpServers:L,model:M,outputFormat:z,permissionMode:B="default",allowDangerouslySkipPermissions:F=!1,permissionPromptToolName:q,plugins:H,resume:Z,resumeSessionAt:V,sessionId:G,stderr:W,strictMcpConfig:K}=c,Y="json_schema"===z?.type?z.schema:void 0,J=S;if(J||(J={...process.env}),J.CLAUDE_CODE_ENTRYPOINT||(J.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),P&&(J.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true"),!u)throw Error("pathToClaudeCodeExecutable is required");let Q={},X=new Map;if(L)for(let[e,t]of Object.entries(L))"sdk"===t.type&&"instance"in t?(X.set(e,t.instance),Q[e]={type:"sdk",name:e}):Q[e]=t;let ee="string"==typeof e,te=new Ms({abortController:d,additionalDirectories:p,agent:f,betas:g,cwd:_,debug:b,debugFile:w,executable:k,executableArgs:T,extraArgs:I,pathToClaudeCodeExecutable:u,env:J,forkSession:C,stderr:W,maxThinkingTokens:j,maxTurns:D,maxBudgetUsd:U,model:M,fallbackModel:$,jsonSchema:Y,permissionMode:B,allowDangerouslySkipPermissions:F,permissionPromptToolName:q,continueConversation:v,resume:Z,resumeSessionAt:V,sessionId:G,settingSources:i??[],allowedTools:m,disallowedTools:E,tools:x,mcpServers:Q,strictMcpConfig:K,canUseTool:!!y,hooks:!!A,includePartialMessages:O,persistSession:N,plugins:H,sandbox:l,spawnClaudeCodeProcess:c.spawnClaudeCodeProcess}),re=new Fs(te,ee,y,A,d,X,Y,{systemPrompt:n,appendSystemPrompt:s,agents:h});return"string"==typeof e?te.write(vs({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:e}]},parent_tool_use_id:null})+"\n"):re.streamInput(e),re}({options:{executableArgs:["--max-old-space-size=4096"],tools:nt,allowedTools:st,betas:[],canUseTool:(e,t)=>(wy.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:c,env:dt,hooks:{PostToolUse:lt,PreToolUse:ct},includePartialMessages:!0,agents:ut,mcpServers:it,model:pt,permissionMode:"default",plugins:vt?[vt]:void 0,systemPrompt:gt,...w?{resume:w}:{}},prompt:y??Pe})),bt=()=>{if(y&&0!==N.length){for(const e of N)y.pushText(e);N.length=0,S=!0,ke({status:"running"})}},wt=async()=>{g&&(E||(E=(async()=>{wy.info("Restarting MCP servers for chat mode"),ke({status:"running"}),be({label:"Restarting browser tools..."});try{await(b?.interrupt?.())}catch(e){wy.warn("Failed to interrupt response during MCP restart",{error:e instanceof Error?e.message:String(e)})}await tv(),y?.finish(),y=new lv,A=0,S=!1,k=!1,Z.clear(),b=_t(),O=!0,be({label:"Restarting browser tools..."}),g&&y&&x&&(x.createdAtUserMessageSeq===C?x.attempts>=1||N.length>0?x=void 0:(x.attempts+=1,y.pushText(["[SYSTEM] MCP servers were restarted successfully.","Continue the task using existing conversation context.","Do not ask the user to resend their message unless new input is required."].join("\n")),x=void 0,S=!0,ke({status:"running"})):x=void 0),bt()})().finally(()=>{E=void 0,bt()})),await E)},Et=async e=>{if(h&&S&&!z&&!U)U=(async()=>{wy.info("[fix] Interrupting for user message",{messageCount:e.length,phase:J?.phase});try{await(b?.interrupt?.())}catch(e){wy.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await tv(),y?.finish(),y=new lv,Z.clear(),b=_t();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");y.pushText(`[SYSTEM] The user sent a message while you were working. Read their message below, incorporate their feedback, and continue your task. Do not restart from scratch unless the user explicitly asks.\n\n${t}`),B=!0,S=!0})().finally(()=>{U=void 0}),await U;else for(const t of e)y?.pushText(`[Message from web UI user]: ${t}`)};if(We){const e=Jm,t=`${e.replace(/\/$/,"")}/v1/messages`;wy.debug(`[fix] Pre-flight: POST ${t}`);const r=Date.now();try{const e=await fetch(t,{method:"POST",signal:AbortSignal.timeout(1e4),headers:{"x-api-key":We,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),n=await e.text().catch(()=>""),s=Date.now()-r;wy.debug(`[fix] Pre-flight: ${e.status} in ${s}ms — ${n.slice(0,300)}`),401===e.status||403===e.status?wy.error(`[fix] Pre-flight: AI proxy key rejected (${e.status}) at ${t}`):wy.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:s})}catch(t){wy.error("[fix] Pre-flight: AI proxy unreachable",{error:t instanceof Error?t.message:String(t),durationMs:Date.now()-r,url:e})}}wy.info("[fix] Creating initial agent query"),wy.flush(),b=_t(),wy.info("[fix] Agent query created, entering message loop"),"chat"!==r.mode&&y.pushText(Pe),de.current=async()=>{V="CANCELED",await ne("CANCELED"),re({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:te(!0)}),Y?.close(),le({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),ie?.close(),j&&(clearTimeout(j),j=void 0),wy.flush(),_e();try{await(b?.interrupt?.())}catch{}y?.finish(),ve()};let xt=0,St=null;const kt=setInterval(()=>{const e=Date.now()-K;St?wy.info("[fix] Watchdog: message loop active",{messageCount:xt,elapsed:e}):wy.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),wy.flush()},15e3);kt.unref();try{let e=!1;for(;;){if(!b){wy.info("[fix] No response object, exiting message loop");break}e=!1,wy.info("[fix] Entering for-await on SDK response");for await(const t of b){xt++,St||(St=Date.now(),wy.info("[fix] First SDK message received",{waitDurationMs:St-K,messageType:t.type,messageSubtype:"subtype"in t?t.subtype:void 0}));const n="session_id"in t&&"string"==typeof t.session_id?t.session_id:void 0;if(n&&n!==w&&(w=n,wy.debug("Captured Claude session id",{sessionId:w})),"stream_event"===t.type){const{event:e}=t;(xt<=5||xt%200==0)&&wy.debug("[fix] Stream event",{msgNum:xt,eventType:e?.type});const r=e&&"object"==typeof e&&"parent_tool_use_id"in e&&"string"==typeof e.parent_tool_use_id?e.parent_tool_use_id:void 0;if("content_block_delta"===e?.type){const{delta:t}=e;if("text_delta"===t?.type&&t.text){if(g&&$&&!r)continue;O&&(O=!1,be({label:void 0})),r&&Z.has(r)?pe({toolUseId:r,kind:"text",content:t.text}):ge({text:t.text})}}"message_stop"===e?.type&&y&&(z=!1,y.allowNextTurn());continue}if("assistant"===t.type){const e="parent_tool_use_id"in t&&"string"==typeof t.parent_tool_use_id?t.parent_tool_use_id:void 0,{content:n}=t.message??{};if(Array.isArray(n)&&!e){const e=n.filter(e=>e&&"object"==typeof e&&"type"in e&&"text"===e.type).map(e=>e&&"object"==typeof e&&"text"in e&&"string"==typeof e.text?e.text:void 0).filter(Boolean).join("");e&&(wy.debug("Assistant message",{text:e}),"fix"===r.mode&&(X(Cb,{type:"ai_message",summary:e.slice(0,200)}),ee({type:"ai_message",summary:e.slice(0,200)})),se&&ce({type:"ai_message",summary:e.slice(0,200)}))}if(Z.size>0){const r=Array.isArray(n)?n.filter(e=>e&&"object"==typeof e&&"type"in e&&"tool_use"===e.type).map(e=>e&&"object"==typeof e&&"name"in e&&"string"==typeof e.name?e.name:void 0):[];wy.debug("Assistant message with active subagents",{hasParentToolUseId:!!e,parentToolUseId:e,activeSubagentIds:Array.from(Z.keys()),toolNames:r,fullMessageKeys:Object.keys(t),rawMessage:JSON.stringify(t).slice(0,500)})}if(Array.isArray(n))for(const t of n){if("tool_use"===t?.type){if("mcp__auto-heal-report__generate-report"===t.name&&(z=!0),"mcp__session-control__restart_mcp_servers"===t.name||"mcp__stably-agent-control__restart_mcp_servers"===t.name){he({rawName:t.name,toolInput:t.input});continue}if(t.name.startsWith("mcp__session-control__")||t.name.startsWith("mcp__stably-agent-control__"))continue;if(Rb(t.name))continue;if(Z.size>0&&wy.debug("Tool use detected with active subagents",{toolName:t.name,hasParentToolUseId:!!e,parentToolUseId:e,wouldRouteToSubagent:!!e&&Z.has(e),activeSubagentIds:Array.from(Z.keys())}),"Task"===t.name){const e=t.input,n=e&&"object"==typeof e?e:void 0,s=n&&"subagent_type"in n&&"string"==typeof n.subagent_type?n.subagent_type:"subagent",a=n&&"description"in n&&"string"==typeof n.description?n.description.trim():"";if(wy.info("[fix] Subagent started",{subagentType:s,description:a,toolUseId:t.id,activeSubagentCount:Z.size+1}),Z.set(t.id,{subagentType:s,description:a}),fe({toolUseId:t.id,subagentType:s,description:a}),"fix"===r.mode){if("triage"===s){xe?.({phase:"triage"});const e={id:t.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};re({phase:"triage",workers:[...J?.workers??[],e]})}else if("fix-worker"===s){Q.add(a||t.id);const e={id:t.id,testDescription:a||t.id,workerType:"fix-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};xe?.({phase:"fixing",totalTests:Q.size,currentTestDescription:a||null}),re({phase:"fixing",totalTests:Q.size,currentTestDescription:a||null,lastTestDescription:a||J?.lastTestDescription||null,workers:[...J?.workers??[],e]})}else"validation"===s?(xe?.({phase:"validation",currentTestDescription:null}),re({phase:"validation",currentTestDescription:null})):"context"===s&&re({currentTestDescription:a||null});ee({type:"tool_call",summary:`[${s}] ${a}`.trim()})}continue}if(e&&Z.has(e)){const n=Ab(t.name),s=Iv(t.name,t.input),a=s?`${n} (${s})`:n;if(wy.debug("Subagent tool called",{tool:t.name,parentToolUseId:e}),pe({toolUseId:e,kind:"tool",content:a}),"fix"===r.mode){ee({type:"tool_call",summary:a});const t=Z.get(e);"fix-worker"!==t?.subagentType&&"triage"!==t?.subagentType||X(e,{type:"tool_call",summary:a})}continue}if(e&&wy.debug("Tool with parent_tool_use_id but no matching subagent",{tool:t.name,parentToolUseId:e,activeSubagentIds:Array.from(Z.keys())}),wy.debug("Tool called",{tool:t.name,input:t.input}),he({rawName:t.name,toolInput:t.input}),"fix"===r.mode){const e=Ab(t.name),r=Iv(t.name,t.input),n=r?`${e} (${r})`:e;X(Cb,{type:"tool_call",summary:n}),ee({type:"tool_call",summary:n})}if(se){const e=Ab(t.name),r=Iv(t.name,t.input),n=r?`${e} (${r})`:e;"initializing"===oe?.phase?le({phase:"generating",currentActivity:n}):"mcp__playwright-test__test_run"===t.name&&"generating"===oe?.phase?le({phase:"testing",currentActivity:n}):le({currentActivity:n}),ce({type:"tool_call",summary:n})}}if("text"===t?.type&&e&&Z.has(e)){const n="string"==typeof t.text?t.text:"";if(n&&(pe({toolUseId:e,kind:"text",content:n}),"fix"===r.mode)){const t=Z.get(e);"fix-worker"!==t?.subagentType&&"triage"!==t?.subagentType||X(e,{type:"ai_message",summary:n.slice(0,200)})}}}continue}if("user"===t.type){const e="message"in t&&t.message&&"object"==typeof t.message&&"content"in t.message?t.message.content:void 0;if(Array.isArray(e))for(const t of e)if(t&&"object"==typeof t&&"type"in t&&"tool_result"===t.type&&"tool_use_id"in t){const e="string"==typeof t.tool_use_id?t.tool_use_id:void 0,n="is_error"in t&&!0===t.is_error,s="content"in t&&"string"==typeof t.content?t.content:void 0;if(wy.debug("Tool result",{toolUseId:e,isError:n,output:s?.slice(0,500)}),e&&Z.has(e)){const t=Z.get(e);if(wy.info("[fix] Subagent completed",{toolUseId:e,isError:n,subagentType:t?.subagentType,description:t?.description,activeSubagentCount:Z.size-1}),Ee({toolUseId:e,status:n?"error":"complete"}),"fix"===r.mode&&"triage"===t?.subagentType){const t=n?"failed":"succeeded",r=s?s.slice(0,500):null,a=(J?.workers??[]).map(n=>n.id===e?{...n,status:t,summary:r,endedAt:Date.now()}:n);re({workers:a})}if("fix"===r.mode&&"fix-worker"===t?.subagentType){const t=n?"failed":"succeeded",r=s?s.slice(0,500):null,a=(J?.workers??[]).map(n=>n.id===e?{...n,status:t,summary:r,endedAt:Date.now()}:n);n?(xe?.({failedTests:(J?.failedTests??0)+1,currentTestDescription:null}),re({failedTests:(J?.failedTests??0)+1,currentTestDescription:null,workers:a})):(xe?.({fixedTests:(J?.fixedTests??0)+1,currentTestDescription:null}),re({fixedTests:(J?.fixedTests??0)+1,currentTestDescription:null,workers:a}))}Z.delete(e)}}continue}if("result"===t.type){if(wy.info("[fix] Agent result received",{subtype:t.subtype,messageCount:xt,elapsed:Date.now()-K,activeSubagents:Z.size,fixedTests:J?.fixedTests,failedTests:J?.failedTests,phase:J?.phase}),h){if("success"===t.subtype){j&&(clearTimeout(j),j=void 0);for(const e of L)y?.pushText(`[Message from web UI user]: ${e}`);if(L=[],(se||"fix"===r.mode)&&y){if(y.hasQueuedMessages()){wy.info("[ws] Queued web UI messages found, continuing agent"),S=!0,y.allowNextTurn();continue}if(await Ob(y,3e3)){wy.info("[ws] Web UI message received during grace period, continuing agent"),S=!0,y.allowNextTurn();continue}y.finish()}if(xe?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),re({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:te(!1)}),le({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null}),ot&&Ie.length>0){H.default.green("Created files:");for(const e of Ie)H.default.green(`- ${e}`)}const e=(e,t)=>`]8;;${e}${t}]8;;`,t=Te?H.default.cyan(`📊 View Autoheal Report:\n ${e(Te,H.default.cyan(H.default.bold(H.default.underline(Te))))}`):void 0;ke({status:"success",result:t}),V="COMPLETED"}else U||B?wy.info("[fix] Suppressing error status: user-message interrupt in progress"):k?(V="CANCELED",re({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:te(!0)}),le({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(xe?.({endedAt:Date.now(),isError:!0}),re({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:te(!0)}),le({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),ke({error:"Run failed.",status:"error"}),process.exitCode=1,V="FAILED");k=!1;break}const n=g&&$;if("success"!==t.subtype?k||(ke({error:"Run failed.",status:"error"}),process.exitCode=1):ke(n?{status:"running"}:{status:"success"}),S=!1,k=!1,n){$=!1,wy.info("Processing deferred MCP restart request in chat mode"),await wt(),e=!0;break}O=!1,be({label:void 0}),y?.allowNextTurn(),g&&A>0&&(A-=1,S=!0,ke({status:"running"}));continue}}if(U&&await U,B&&(B=!1,e=!0,ke({status:"running"}),wy.info("[fix] Resuming after user-message interrupt")),!e)break}}catch(e){k?(V="CANCELED",re({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:te(!0)}),le({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(wy.error("[fix] Agent encountered an error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,elapsed:Date.now()-K}),ke({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,V="FAILED",re({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:te(!0)}),le({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),wy.flush(),wy.printLogFileInfo())}finally{if(clearInterval(kt),j&&(clearTimeout(j),j=void 0),wy.info("[fix] Agent session ending",{finalStatus:V,elapsed:Date.now()-K,totalMessages:xt}),S=!1,k=!1,process.off("uncaughtException",n),y?.finish(),V){wy.info("[fix] Reporting final autoheal status",{status:V});const e=Date.now();await ne(V),wy.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(wy.info("[fix] Closing WebSocket progress reporter"),Y?.close(),ie?.close(),Qe&&Xe){const e=Date.now();try{wy.info("[fix] Computing diff...");const t=await Xe.computeDiff();if(t&&t.trim().length>0){wy.info("[fix] Uploading diff...",{diffLength:t.length});const{diffBucketPath:n,uploadUrl:s}=await Dy({authHeader:a,contentType:"text/plain",orgId:l,runId:r.runId});await Uy({contentType:"text/plain",diff:t,uploadUrl:s}),await Ly({authHeader:a,diffBucketPath:n,orgId:l,runId:r.runId}),wy.info("[fix] Diff uploaded",{durationMs:Date.now()-e})}else wy.info("[fix] No diff to upload (empty or no changes)")}catch(t){wy.warn("[fix] Failed to upload diff",{error:t instanceof Error?t.message:String(t),durationMs:Date.now()-e})}}wy.info("[fix] Cleaning up diff tracker"),await(Xe?.cleanup()),wy.info("[fix] Running final cleanup"),await ve(),wy.info("[fix] Cleanup complete")}},jb=Z.default.object({runId:Z.default.string(),timestamp:Z.default.number()}),Db=class{entries=[];warnings=[];runId;command;executionMode;constructor(e){this.runId=e.runId,this.command=e.command,this.executionMode=e.executionMode}phaseStart(e,t){this.addEntry({phase:e,level:"info",message:t}),v.log.info(function(e,t){return`${H.default.bold(H.default.cyan(`[${e}]`))} ${t}`}(e,t))}phaseEnd(e,t){this.addEntry({phase:e,level:"info",message:t})}info(e){this.addEntry({phase:e.phase,level:"info",message:e.message,fields:e.fields})}warn(e){this.addEntry({phase:e.phase,level:"warn",message:e.message,fields:e.fields}),v.log.warn(H.default.yellow(` warn: ${e.message}`))}error(e){this.addEntry({phase:e.phase,level:"error",message:e.message,fields:e.fields}),v.log.error(H.default.red(` error: ${e.message}`))}emitWarning(e){this.warnings.push(e),this.addEntry({phase:"summary",level:"warn",message:e.message,fields:{warningCode:e.code,...e.details}}),v.log.warn(function(e){return H.default.yellow(` warning: ${e.code} - ${e.message}`)}(e))}getEntries(){return[...this.entries]}getWarnings(){return[...this.warnings]}getRunId(){return this.runId}getCommand(){return this.command}getExecutionMode(){return this.executionMode}addEntry(e){this.entries.push({runId:this.runId,command:this.command,executionMode:this.executionMode,phase:e.phase,timestamp:(new Date).toISOString(),level:e.level,message:e.message,...e.fields?{fields:e.fields}:{}})}};function Ub(e){return 0===e.length?[]:[H.default.yellow(H.default.bold("Warnings:")),...e.map(e=>H.default.yellow(` ${e.code}: ${e.message}`)),""]}function Lb(e){return e?[H.default.dim(`Next action: ${e}`),""]:[]}function Mb(e){const t=[],r="fix"===e.command?"Fix":"Build";if(t.push(""),"success"===e.status){const n=e.changedPaths.length;t.push(H.default.green(H.default.bold(`${r} succeeded`))+(n>0?H.default.green(` (${n} path${1!==n?"s":""} changed)`):"")),t.push(""),t.push(...Ub(e.warnings))}else if("failure"===e.status)t.push(H.default.red(H.default.bold(`${r} failed`))),e.errorCode&&t.push(H.default.red(` Error: ${e.errorCode}`)),t.push(""),t.push(...Ub(e.warnings)),t.push(...Lb(e.nextAction));else{const n=e.changedPaths.length,s=e.failedPaths.length,a=e.partialPaths.length;t.push(H.default.yellow(H.default.bold(`${r} partially succeeded`))+H.default.yellow(` (${n} changed, ${s} failed, ${a} partial)`)),t.push(""),t.push(...Ub(e.warnings)),t.push(...Lb(e.nextAction))}return t.push(H.default.dim(`Run ID: ${e.runId}`)),t.join("\n")}var zb=/^\/\*\*\r?\n \* @generated by stably build[\s\S]*?\*\/(?:\r?\n)*/;function Bb(e){return!!e&&"object"==typeof e&&"code"in e}async function Fb({errorMessage:e,filePath:t}){try{return await F.default.readFile(t,"utf8")}catch(t){if(Bb(t)&&"ENOENT"===t.code)throw new Error(e);throw t}}function qb(e){return e.split(D.default.sep).join("/")}async function Hb(e){const t=[];return await async function e(r){let n;try{n=await F.default.readdir(r,{withFileTypes:!0})}catch{return}for(const s of n){const n=D.default.join(r,s.name);s.isDirectory()&&!s.isSymbolicLink()?await e(n):s.isFile()&&s.name.endsWith(".stably.md")&&t.push(n)}}(e),t.sort()}var Zb=/^---\r?\n([\s\S]*?)\r?\n---/;function Vb(e,t){const r=[],n=Zb.exec(e);let s,a={};if(n){try{const e=P.parse(n[1]??"");a=e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{v.log.warn(`Warning: Failed to parse YAML frontmatter in ${t}, treating as empty`),a={}}s=e.slice(n[0].length).replace(/^(\r?\n)+/,"")}else s=e;if(!s.trim())return{updated:e,addedFields:r};if(!a.name){const e=s.slice(0,1e4).replace(/```[\s\S]*?```/g,""),n=/^#\s+(.+)$/m.exec(e),i=D.default.basename(t).replace(/\.stably\.md$/,"").replace(/\.md$/,"");a.name=n?.[1]?.trim()??i,r.push("name")}return a.priority||(a.priority="medium",r.push("priority")),0===r.length?{updated:e,addedFields:r}:{updated:`---\n${P.stringify(a).trimEnd()}\n---\n\n${s}`,addedFields:r}}async function Gb(e){try{return(await F.default.readdir(e)).filter(e=>By.test(e)).map(t=>D.default.join(e,t))}catch(e){if(Bb(e)&&"ENOENT"===e.code)return[];throw e}}function Wb({runId:e,warnings:t,changedPaths:r=[],failedPaths:n=[],...s}){return{runId:e,command:"build",executionMode:"cli",warnings:t,changedPaths:r,failedPaths:n,partialPaths:[],...s}}async function Kb({force:e,inputFilePath:t}){const r=`build-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,n=new Db({runId:r,command:"build",executionMode:"cli"});n.phaseStart("preflight","Validating workspace and arguments");const s=process.cwd();n.info({phase:"preflight",message:"Input resolved",fields:{input:t}}),n.phaseEnd("preflight","Preflight complete"),n.phaseStart("scope","Resolving scope");const a=await Fb({filePath:t,errorMessage:`Prompt file not found: ${t}`});if(!a.trim())throw new Error(`Prompt file is empty: ${t}`);const i=sv(a),o=qb(D.default.relative(s,t)),l=D.default.dirname(t),c=(u=t,D.default.basename(u).replace(/\.stably\.md$/,"").replace(/\.md$/,"").replace(/\.txt$/,""));var u;const d=await async function(e,t){return(await Gb(e)).find(e=>{const r=D.default.basename(e);return r.startsWith(`${t}.spec`)||r.startsWith(`${t}.test`)})}(l,c);if(!e&&d&&await async function({outputFilePath:e,promptHash:t}){try{return av(await F.default.readFile(e,"utf8"))===t}catch(e){if(Bb(e)&&"ENOENT"===e.code)return!1;throw e}}({outputFilePath:d,promptHash:i})){n.info({phase:"scope",message:"Hash unchanged, skipping build"});const e={code:"STABLY_WARNING_NO_CHANGES",message:"Test code is up to date (hash unchanged)"};n.emitWarning(e);const t=Wb({runId:r,status:"success",warnings:[e]});return n.phaseStart("summary","Build summary"),v.log.info(Mb(t)),n.phaseEnd("summary","Done"),v.log.success(H.default.green(`Skipped build: ${o} (hash unchanged)`)),"skipped"}n.info({phase:"scope",message:"Scope resolved",fields:{promptFile:o,promptHash:i,resolvedScopeCount:1,unmappedPaths:[],baseSource:"prompt-file",baseRef:o}}),n.phaseEnd("scope","Scope complete"),n.phaseStart("plan","Preparing prompt");const p=new Set(await Gb(l));await F.default.mkdir(l,{recursive:!0});const f=iv({promptFile:o,promptHash:i}),h=qb(D.default.relative(s,l)||l),m=function({outputDir:e,promptContent:t,sourceSpecFile:r}){return["Compile this test specification into a Playwright test file.","",`Output directory: ${e}`,"","Choose output filename:",`- Look at existing test files in ${e} to determine the naming convention.`,"- Use the same extension pattern as existing tests (e.g., .test.ts or .spec.ts).","- If no existing tests, default to .spec.ts.","- Base the filename on the prompt content (e.g., login.spec.ts for login tests).","","File creation rules:","- Create your test file in the output directory with your chosen filename.","- You MAY create shared helper files (e.g., lib/auth.ts) if the prompt explicitly requests reusable components.","- Prefer single-file output unless shared helpers would significantly improve maintainability.","- Never modify unrelated existing files.","","Sync workflow for existing files:","1. Examine existing test files in the workspace and preserve hand edits where possible.","2. If a matching test file already exists, read it first and compare against the prompt specification.","3. Apply sync rules:"," - If file does not exist: CREATE from scratch."," - If file exists and already satisfies the prompt: KEEP behavior and make minimal edits only when needed."," - If file exists but only partially matches: UPDATE only changed scenarios so code aligns with prompt."," - If file structure conflicts heavily with prompt: REGENERATE the file content completely.","4. Prompt specification is the source of truth for final test behavior.","","Test verification:","After generating the test file, run the tests locally to verify they work correctly.","Use the appropriate test command (e.g., `pnpm stably test` or the repository's test command).","If tests fail, analyze the errors and iterate on the test code until all tests pass.","","Spec file linking:",`- Add \`// @stably.spec ${r}\` after the import statements.`,"- This links the test back to its source .md specification.","- If different test.describe()/test() blocks come from different .md files, add per-block @stably.spec instead.","","Prompt specification:",t].join("\n")}({outputDir:h,promptContent:a,sourceSpecFile:o});n.info({phase:"plan",message:"Agent prompt assembled",fields:{outputTarget:h,plannedPathCount:1,plannedPaths:[h],mode:"directory"}}),n.phaseEnd("plan","Plan complete"),n.phaseStart("execute","Running agent session"),process.exitCode=void 0;const g=Date.now();await Nb({mode:"build",prompt:m,outputDir:l,customHeader:f});const y=Date.now()-g,_=process.exitCode;if("number"==typeof _&&0!==_){n.error({phase:"execute",message:`Build generation failed for: ${o}`,fields:{toolName:"runAgentSession",durationMs:y}});const e=Wb({runId:r,status:"failure",warnings:n.getWarnings(),failedPaths:[o],nextAction:"open_agent_session",errorCode:"STABLY_WRITE_FAILED"});throw n.phaseStart("summary","Build summary"),n.info({phase:"summary",message:"Run failed",fields:{errorCode:e.errorCode,nextAction:e.nextAction}}),v.log.info(Mb(e)),n.phaseEnd("summary","Done"),new Error(`Build generation failed for: ${o}`)}n.info({phase:"execute",message:"Agent session completed",fields:{toolName:"runAgentSession",durationMs:y}}),n.phaseEnd("execute","Agent session complete"),n.phaseStart("finalize","Applying results");const b=[];let w=d;if(!w&&(w=(await Gb(l)).find(e=>!p.has(e)),!w)){const e={path:o,status:"failed",error:"No new test file created"};b.push(e),n.info({phase:"finalize",message:"Write failed",fields:{path:e.path,writeStatus:e.status,error:e.error}});const t=Wb({runId:r,status:"failure",warnings:n.getWarnings(),failedPaths:[o],nextAction:"open_agent_session",errorCode:"STABLY_WRITE_FAILED"});throw n.phaseStart("summary","Build summary"),n.info({phase:"summary",message:"Run failed",fields:{errorCode:t.errorCode,nextAction:t.nextAction}}),v.log.info(Mb(t)),n.phaseEnd("summary","Done"),new Error(`Build finished but no new test file was created for: ${o}`)}const E=await Fb({filePath:w,errorMessage:`Build finished but output file was not created for: ${o}`}),x=function(e){return e.replace(zb,"")}(E),S=E.startsWith(f)?E:`${f}\n\n${x}`;S!==E&&await F.default.writeFile(w,S,"utf8");const k=qb(D.default.relative(s,w)),T={path:k,status:"success"};b.push(T),n.info({phase:"finalize",message:"Write succeeded",fields:{path:T.path,writeStatus:T.status}}),n.phaseEnd("finalize","Finalize complete"),n.phaseStart("summary","Build summary");const I=b.filter(e=>"success"===e.status).map(e=>e.path),$=b.filter(e=>"failed"===e.status).map(e=>e.path);let P;P=$.length>0?I.length>0?"partial":"failure":"success";const C=$.length>0,R=Wb({runId:r,status:P,warnings:n.getWarnings(),changedPaths:I,failedPaths:$,nextAction:C?"inspect_failed_paths":void 0,errorCode:C?"STABLY_WRITE_FAILED":void 0});return n.info({phase:"summary",message:"Run completed",fields:{status:R.status,changedPathCount:I.length,failedPathCount:$.length,...R.errorCode?{errorCode:R.errorCode}:{},...R.nextAction?{nextAction:R.nextAction}:{}}}),v.log.info(Mb(R)),n.phaseEnd("summary","Done"),v.log.success(H.default.green(`Built: ${k}`)),"built"}var Yb=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],Jb=["You have two different versions of @playwright/test"];function Qb(e){const[t,...r]=cb(e),n=[t,...r.slice(0,-1)].join(" ");return(t,r)=>{let s=t.toString();for(const e of Yb)s=s.replaceAll(`${n} playwright ${e.name}`,`${n} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===e){const e=s.split("\n");return e.length>0&&e[0].includes("/.bin/playwright")&&e.shift(),void r.write(e.join("\n"))}r.write(s)}}async function Xb({overrideArgs:e,subcommand:r}){wy.info("[test] forwardToPlaywright starting",{subcommand:r,overrideArgs:e});const n=process.argv,a=n.findIndex((e,t)=>t>1&&e===r),o=-1===a?[]:n.slice(a+1),l="--"===o[0],c=l?o.slice(1):o;if(!l&&("--help"===c[0]||"-h"===c[0]))return async function({subcommand:e}){const t=Yb.find(t=>t.name===e),r=e=>process.stdout.write(`${e}\n`);r(`stably ${e} - ${t?.description??""}`),r(""),"test"===e&&(r('IMPORTANT: Always use "stably" commands instead of "playwright" directly.'),r(""),r("Stably commands:"),r(" stably test [file] Run tests (auto-enables tracing and analytics)"),r(" stably fix [file] Auto-fix failing tests using AI"),r(" stably create <url> Generate new tests from a URL using AI"),r(""),r("Why use Stably?"),r(' - "stably fix" automatically repairs broken tests'),r(' - "stably test" enables --trace=on and test analytics'),r(' - "stably create" generates tests from prompt'),r(""));const n=ib();if(!n.installed||!n.inNodeModules)return void r('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:a}=n;if(!a)return void r("Could not determine package manager.");r("Playwright options:"),r("");const[i,...o]=cb(a),l=Qb(a);return new Promise(t=>{const r=s.spawn(i,[...o,e,"--help"],{stdio:["inherit","pipe","pipe"],env:{...process.env,...process.env.CI?{}:{FORCE_COLOR:"1"}}});r.stdout?.on("data",e=>{l(e,process.stdout)}),r.stderr?.on("data",e=>{l(e,process.stderr)}),r.on("close",()=>{t()})})}({subcommand:r});const u=e??[],d=new Set(u.map(e=>{const[t]=e.split("=");return t})),p=[];for(let e=0;e<c.length;e++){const t=c[e],[r]=t.split("=");d.has(r)?!t.includes("=")&&e+1<c.length&&!c[e+1].startsWith("-")&&e++:p.push(t)}const f=[r,...u,...p];wy.info("[test] Forwarded args computed",{forwardedArgs:f}),wy.info("[test] Resolving Stably test environment");const h=Date.now(),m="test"===r?await Cy():void 0;wy.info("[test] Stably test environment resolved",{durationMs:Date.now()-h,hasCredentials:null!=m,hasWsUrl:!!m?.STABLY_WS_URL}),wy.info("[test] Setting up Stably reporter injection");const g="test"===r?function({forwardedArgs:e,hasCredentials:r}){if(!r)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 n=process.cwd(),a=e=>{const r=function(e){let r=t.resolve(e);for(;;){if([t.join(r,"node_modules","@stablyai","playwright-test"),t.join(r,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>i.existsSync(e)))return!0;const e=t.dirname(r);if(e===r)return!1;r=e}}(e);return r||(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: ]8;;https://docs.stably.ai/getting-started/sdk-setup-guidehttps://docs.stably.ai/getting-started/sdk-setup-guide]8;;[0m\n")),r},o=(e,r)=>{try{return function({baseConfigPath:e,projectDir:r}){const n=function(e){try{const t=s.execSync("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return"module"===JSON.parse(t.trim())}catch{return!1}}(r),a=n?"mts":"ts",o=t.dirname(t.resolve(e)),l=t.basename(e),c=t.join(o,`.stably-playwright-wrapper.config.${a}`),u=`\n// Auto-generated wrapper config by Stably CLI\n// This file injects the Stably reporter and ensures trace is enabled\nimport baseConfig from './${l}';\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 isStablyReporter = (reporter: unknown): boolean => {\n // Only match @stablyai npm scope to avoid false positives on unrelated reporters\n // that might contain "stably" substring (e.g., "unstably-runner")\n if (typeof reporter === 'string') {\n return reporter.includes('@stablyai');\n }\n if (Array.isArray(reporter) && typeof reporter[0] === 'string') {\n return reporter[0].includes('@stablyai');\n }\n return false;\n};\n\nconst getStablyReporterOptions = (reporters: unknown[]): Record<string, unknown> | undefined => {\n for (const reporter of reporters) {\n if (Array.isArray(reporter) && typeof reporter[0] === 'string' && reporter[0].includes('@stablyai')) {\n return (reporter[1] as Record<string, unknown>) ?? {};\n }\n }\n return undefined;\n};\n\nconst filterOutStablyReporter = (reporters: unknown[]): unknown[] => {\n return reporters.filter((reporter) => !isStablyReporter(reporter));\n};\n\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\n\n // Resolve errorSummary: env var STABLY_ERROR_SUMMARY=0 disables it\n const resolveErrorSummary = (existingValue?: unknown): boolean | undefined => {\n if (process.env.STABLY_ERROR_SUMMARY === '0') return false;\n if (typeof existingValue === 'boolean') return existingValue;\n return undefined; // let the reporter default (true)\n };\n\n // No existing reporters - create fresh stably reporter\n if (!existingReporters) {\n return [stablyReporter({\n apiKey: process.env.STABLY_API_KEY,\n projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(),\n })];\n }\n\n // Normalize to array\n const reportersArray: unknown[] = Array.isArray(existingReporters)\n ? existingReporters\n : [[existingReporters, {}]];\n\n // If user has a stably reporter, take their options but override credentials\n const existingOptions = getStablyReporterOptions(reportersArray);\n const stablyReporterEntry = stablyReporter({\n ...existingOptions,\n apiKey: process.env.STABLY_API_KEY,\n projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(existingOptions?.errorSummary),\n });\n\n // Keep all non-stably reporters, add our (merged or fresh) stably reporter\n const otherReporters = filterOutStablyReporter(reportersArray);\n return [...otherReporters, stablyReporterEntry];\n};\n\nexport default defineConfig({\n ...baseConfig,\n use: {\n ...baseConfig.use,\n trace: 'on',\n },\n reporter: buildReporterList(),\n});\n`.trim();return i.existsSync(o)||i.mkdirSync(o,{recursive:!0}),i.writeFileSync(c,u,"utf-8"),function(e){const r=t.join(e,".gitignore");try{if(i.existsSync(r)){const e=i.readFileSync(r,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(mv))return;const t=e.length>0&&!e.endsWith("\n");i.appendFileSync(r,`${t?"\n":""}${mv}\n`)}else i.writeFileSync(r,`${mv}\n`)}catch{}}(o),c}({baseConfigPath:e,projectDir:r})}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 r=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==r&&e[r+1]){const s=t.resolve(n,e[r+1]),i=t.dirname(s);if(!a(i))return;const l=o(s,i);if(!l)return;return e[r+1]=l,l}const s=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==s){const r=t.resolve(n,e[s].split("=")[1]),i=t.dirname(r);if(!a(i))return;const l=o(r,i);if(!l)return;const c=e[s].startsWith("--config=")?"--config=":"-c=";return e[s]=`${c}${l}`,l}}const l=yv(n);if(!l)return;const c=t.dirname(l);if(!a(c))return;const u=o(l,c);return u?(e.push("--config",u),u):void 0}({forwardedArgs:f,hasCredentials:null!=m}):void 0;wy.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!g}),wy.info("[test] Spawning Playwright process"),await function(e,t={}){wy.info("[test] Detecting Playwright installation");const r=ib();wy.info("[test] Playwright installation check",{installed:r.installed,inNodeModules:r.inNodeModules,packageManager:r.packageManager,packageName:r.packageName}),r.installed||(console.error('Playwright is not installed. Please run "stably init" to install it.'),process.exit(1)),r.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:n}=r;n||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[a,...i]=cb(n),o=Py(t.env),l=[a,...i,...e];wy.info("[test] Spawning Playwright process",{command:l.join(" "),pid:process.pid});const c=Date.now(),u=s.spawn(a,[...i,...e],{stdio:["inherit","pipe","pipe"],env:{...o,...process.env.CI?{}:{FORCE_COLOR:"1"}}});wy.info("[test] Playwright process spawned",{childPid:u.pid});const d=Qb(n),p=function(){let e=!1,t="";return(r,n)=>{if(!e){t+=r,t.length>1024&&(t=t.slice(-1024));for(const r of Jb)if(t.includes(r))return n.write("\n[stably] Hint: This is a Playwright error, not caused by @stablyai/playwright-test.\n Common causes: running from the wrong directory (especially in monorepos),\n or a dependency pulling in a conflicting @playwright/test version.\n"),void(e=!0)}}}();u.stdout?.on("data",e=>{d(e,process.stdout)}),u.stderr?.on("data",e=>{const t=e.toString();d(e,process.stderr),p(t,process.stderr)});const f=new AbortController,h=()=>!f.signal.aborted&&(f.abort(),t.onClose?.(),process.removeListener("SIGINT",m),process.removeListener("SIGTERM",m),!0),m=e=>{wy.info("[test] Signal received, killing Playwright process",{signal:e,childPid:u.pid}),h(),u.kill(e);const t="SIGINT"===e?130:143;process.exit(t)};return process.on("SIGINT",m),process.on("SIGTERM",m),new Promise((e,t)=>{u.on("error",e=>{h()&&(wy.error("[test] Playwright process error",{error:e.message,childPid:u.pid}),t(e))}),u.on("close",t=>{if(!h())return;wy.info("[test] Playwright process exited",{exitCode:t,durationMs:Date.now()-c});const r=[process.stdout,process.stderr].filter(e=>e.writableNeedDrain).map(e=>new Promise(t=>e.once("drain",t)));Promise.race([Promise.all(r),new Promise(e=>setTimeout(e,5e3))]).then(()=>{process.exitCode=t??0,e(t??0)})})})}(f,{env:m,onClose:()=>{var e;wy.info("[test] Playwright process closed, cleaning up wrapper config"),(e=g)&&i.existsSync(e)&&i.rmSync(e)}})}function ew(e=""){process.stdout.write(`${e}\n`)}function tw(...e){process.stderr.write(`${e.join(" ")}\n`)}var rw="stably",nw=`https://registry.npmjs.org/${rw}/latest`,sw=b.z.object({version:b.z.string()});function aw(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 iw(e,t){const r=aw(e),n=aw(t);return!(!r||!n)&&(n.major>r.major||!(n.major<r.major)&&(n.minor>r.minor||!(n.minor<r.minor)&&n.patch>r.patch))}var ow=D.default.join(z.default.homedir(),".stably"),lw=D.default.join(ow,"update-check.json"),cw=`https://registry.npmjs.org/${rw}/latest`,uw=b.z.object({lastCheck:b.z.number(),latestVersion:b.z.string()}),dw=!1,pw=!1,fw=async()=>{if(pw)try{const{shutdown:e}=await import("@hyperdx/node-opentelemetry"),t=process.stderr.write.bind(process.stderr),r=process.stdout.write.bind(process.stdout),n=(e,...t)=>{const r=t[0];return!("string"!=typeof r||!r.includes("OpenTelemetry"))||!(!Buffer.isBuffer(r)||!r.toString().includes("OpenTelemetry"))||e(...t)};process.stderr.write=(...e)=>n(t,...e),process.stdout.write=(...e)=>n(r,...e);try{await e()}finally{process.stderr.write=t,process.stdout.write=r}}catch{}};!function(){const e=function(){try{const e=M.default.readFileSync(lw,"utf-8");return uw.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 = '${cw}';\n const cacheFile = ${JSON.stringify(lw)};\n const cacheDir = ${JSON.stringify(ow)};\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{s.spawn(process.execPath,["-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&iw(Vm,e.latestVersion)){if(dw)return;dw=!0;let t=!1;const r=()=>{if(t)return;t=!0;const r=`${H.default.yellow(`update available (${Vm} → ${e.latestVersion})`)} - run \`${rw} upgrade\` to get the latest version\n`;try{M.default.writeSync(2,r)}catch{}};process.once("beforeExit",r),process.once("exit",r)}}(),se.cwdChanged&&wy.debug("Changed working directory",{cwd:se.newCwd});for(const e of se.envFilesLoaded)wy.debug("Loaded env file",{path:e});for(const e of se.envFileErrors)wy.warn(e);var hw=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==hw&&process.argv.splice(hw,1);var mw=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==mw&&process.argv.splice(mw,1),wy.info("CLI starting",{version:Vm,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{wy.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),wy.flush(),wy.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(wy.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),wy.flush(),wy.printLogFileInfo())});var gw=new r.Command;gw.name("stably").description("AI-assisted Playwright testing CLI").version(Vm),gw.enablePositionalOptions(),gw.showHelpAfterError(),gw.exitOverride(),gw.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}});var yw=[];gw.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{yw.push(e)}});var vw=()=>{const e=gw.helpInformation().trimEnd();return e?`${e}\n`:""},_w=(e,t)=>{let r=e;for(const e of t){const t=r.commands.find(t=>t.name()===e||t.aliases().includes(e));if(!t)return;r=t}return r},bw=()=>{process.stdout.write(vw())};gw.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void bw();const t=_w(gw,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),bw(),void(process.exitCode=1);var r;r=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(r))}),gw.action(()=>Nb({mode:"chat",getHelpText:vw})),gw.command("login").description("Authenticate with Stably in your browser").action(ny),gw.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=xy();e&&(v.log.warn(`Environment variables ${H.default.cyan("STABLY_API_KEY")} and ${H.default.cyan("STABLY_PROJECT_ID")} are set.`),v.log.warn("They will continue to be used for authentication even after logout."),v.log.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await gg();if(!t)return void v.outro(e?H.default.yellow("No stored OAuth login found to clear."):H.default.yellow("You are not logged in."));const r=v.spinner();r.start("Logging out..."),await(async e=>{try{await fetch(`${Km}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await vg(),await bg(),r.stop(H.default.green("✓ Logged out")),v.outro(H.default.green("You have been logged out successfully."))}),gw.command("whoami").description("Show auth status and current project").action(async()=>{v.log.info(`${H.default.bold("CLI Version:")} ${H.default.cyan(Vm)}`);const e=xy();if(e){v.log.info(H.default.dim("Authentication: Environment variables")),v.log.info(` ${H.default.bold("API Key:")} ${H.default.cyan(e.apiKey.slice(0,8))}...`),v.log.info(` ${H.default.bold("Project ID:")} ${H.default.cyan(e.projectId)}`);const t=await gg();if(t){let e;try{e=lg(t.accessToken).email}catch{e=void 0}v.log.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&v.log.info(` ${H.default.bold("OAuth Email:")} ${H.default.cyan(e)}`),v.log.info(` ${H.default.bold("Tip:")} Unset env vars to use OAuth`)}return void v.outro(H.default.green("Authenticated via environment variables"))}const t=await gg();if(!t)return void v.outro(H.default.yellow("Not logged in. Run `stably login` to authenticate."));let r;try{r=lg(t.accessToken).email}catch{r=void 0}const n=await _g();if(!n)return v.log.info(H.default.dim("Authentication: OAuth (not linked to a project)")),r&&v.log.info(` ${H.default.bold("Email:")} ${H.default.cyan(r)}`),void v.outro(H.default.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const s=await(async()=>cg(process.cwd(),pg))(),a=s?D.default.dirname(s):process.cwd(),i=D.default.relative(process.cwd(),a)||".";v.log.info(H.default.dim("Authentication: OAuth")),r&&v.log.info(` ${H.default.bold("Email:")} ${H.default.cyan(r)}`),v.log.info(` ${H.default.bold("Organization:")} ${H.default.cyan(n.orgName)}`),v.log.info(` ${H.default.bold("Project:")} ${H.default.cyan(n.projectName)}`),v.log.info(` ${H.default.bold("Linked at:")} ${H.default.dim(i)}`),v.outro(H.default.green("Authenticated"))}),gw.command("build [input...]").description("Compile test specification files (.stably.md) into Playwright tests").option("--force","Force regeneration even if prompt is unchanged").action(async(e,t)=>{try{await async function(e){const{inputs:t,force:r}=e,n=process.cwd();let a;if(0===t.length){const e=function(e){try{return s.execSync('git ls-files --cached --others --exclude-standard "*.stably.md"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).split("\n").map(e=>e.trim()).filter(Boolean)}catch{return[]}}(n);a=e.map(e=>D.default.resolve(n,e))}else a=await async function(e,t){const r=[];for(const n of e){const e=D.default.resolve(t,n);let s;try{s=await F.default.stat(e)}catch{r.push(e);continue}if(s.isDirectory()){const t=await Hb(e);r.push(...t)}else r.push(e)}const n=new Set,s=[];for(const e of r){const t=D.default.resolve(e);n.has(t)||(n.add(t),s.push(t))}return s}(t,n);if(0===a.length)throw new Error("No .stably.md files found. Create a test specification file (e.g., login.stably.md) and try again.");const{fixedFiles:i}=await async function(e,t){const r=[],n=[];for(const s of e){let e=s;try{await F.default.stat(e)}catch{n.push(e);continue}if(e.endsWith(".md")&&!e.endsWith(".stably.md")){const n=e.replace(/\.md$/,".stably.md");try{await F.default.rename(e,n);const s=qb(D.default.relative(t,e)),a=qb(D.default.relative(t,n)),i={code:"STABLY_WARNING_FILE_RENAMED",message:`Renamed ${s} → ${a} (test specs must use .stably.md extension)`,details:{oldPath:s,newPath:a}};r.push(i),v.log.warn(H.default.yellow(` ⚠ ${i.message}`)),e=n}catch(t){if(!(t instanceof Error&&"code"in t)||"EEXIST"!==t.code&&"ENOTEMPTY"!==t.code)throw t;v.log.warn(H.default.yellow(` ⚠ Skipping rename: ${n} already exists`)),e=n}}if(!e.endsWith(".stably.md")){n.push(e);continue}const a=await F.default.readFile(e,"utf8"),{updated:i,addedFields:o}=Vb(a,e);if(o.length>0){await F.default.writeFile(e,i,"utf8");const n=qb(D.default.relative(t,e)),s={code:"STABLY_WARNING_FRONTMATTER_ADDED",message:`Added missing frontmatter fields to ${n}: ${o.join(", ")}`,details:{path:n,addedFields:o}};r.push(s),v.log.warn(H.default.yellow(` ⚠ ${s.message}`))}n.push(e)}return{fixedFiles:n,warnings:r}}(a,n);a=i,v.log.info(H.default.bold(`Found ${a.length} test specification${1!==a.length?"s":""}`));for(const e of a){const t=qb(D.default.relative(n,e));v.log.info(H.default.dim(` ${t}`))}v.log.info("");const o={built:[],skipped:[],failed:[]};for(const e of a){const t=qb(D.default.relative(n,e));try{"built"===await Kb({force:r,inputFilePath:e})?o.built.push(t):o.skipped.push(t)}catch(e){const r=e instanceof Error?e.message:String(e);v.log.error(H.default.red(`Failed to build ${t}: ${r}`)),o.failed.push(t)}}return function(e){if(v.log.info(""),v.log.info(H.default.bold("Build Summary")),v.log.info(` ${H.default.green(`${e.built.length} built`)} ${H.default.dim(`${e.skipped.length} skipped (unchanged)`)} ${e.failed.length>0?H.default.red(`${e.failed.length} failed`):H.default.dim("0 failed")}`),e.failed.length>0){v.log.info(""),v.log.error(H.default.red("Failed files:"));for(const t of e.failed)v.log.error(H.default.red(` - ${t}`))}}(o),o.failed.length>0&&(process.exitCode=1),o}({inputs:e,force:t.force??!1})}catch(e){const t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}\n`),process.exitCode=1}}),gw.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=>{v.intro(`Starting development server for port ${e.port}...`);const t=await Iy(),r="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),n=v.spinner();n.start("Starting development server...");const s=await C.startTunnel(`http://localhost:${e.port}`,{subdomain:r});n.stop(`Your local environment is available at: ]8;;${s.url}${H.default.underline(H.default.cyan(s.url))}]8;;`)}),gw.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(async(e,t)=>{const r=e.length>0&&"test"===e[0]?e.slice(1):e;return Nb({mode:"single",prompt:r,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(async(e,t)=>Nb({mode:"single",prompt:e,outputDir:t.output})),gw.command("fix [runId]").description("Fix failing tests from a run (auto-detects from last test run or CI)").action(async e=>{(function(e){try{return s.execSync("git rev-parse --is-inside-work-tree",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}})(process.cwd())||(wy.error('Not a git repository. The "stably fix" command requires a git repository to track changes made during the fix. Please run this command from inside a git repository.'),process.stderr.write('Error: Not a git repository.\nThe "stably fix" command requires a git repository to track changes made during the fix.\nPlease run this command from inside a git repository.\n'),process.exit(1));const t=await(async e=>{const t=e=>e.replace(/\//g,"_");if(e)return wy.debug("Run ID provided explicitly",{runId:e}),t(e);const r=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 r of Object.keys(Yt))if(Yt[r].detect({env:e,cwd:t}))return{isCi:!0,...Yt[r].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(r={env:e,cwd:t},{commit:bt(r),branch:wt(r)})};var r})();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),r=[e.service,"slug"in e?e.slug?.replace(/\//g,"_"):void 0,"build"in e?String(e.build):void 0,"job"in e?String(e.job):void 0,t&&String(t)].filter(Boolean);return r.length>0?r.join("-"):void 0}();if(r)return wy.debug("Run ID detected from CI environment",{runId:r}),t(r);wy.debug("No explicit run ID or CI environment detected, checking last-run.json");const n=await(async()=>{try{const e=await cg(process.cwd(),".stably/last-run.json");if(!e)return;const t=await f.readFile(e,"utf-8");return{...jb.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(n){const e=(Date.now()-n.timestamp)/36e5;return wy.debug("Run ID found in last-run.json",{runId:n.runId,timestamp:n.timestamp,filePath:n.filePath,ageHours:Math.round(e)}),e>24&&wy.warn(`Using run ID from ${Math.round(e)} hours ago (${n.filePath}). Provide an explicit run ID if this is not the run you want to fix.`),t(n.runId)}wy.debug("No run ID found in last-run.json")})(e);return t||(process.stderr.write('Run ID is required. Either:\n 1. Run "stably test" first (run ID will be auto-detected)\n 2. Provide a run ID: stably fix <runId>\n 3. Run in CI (auto-detected from environment)\n'),process.exit(1)),Nb({mode:"fix",runId:t})}),gw.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>Nb({mode:"init"})),gw.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 r;ew(H.default.cyan("Checking for updates...\n"));try{r=await async function(){const e=await async function(){const e=new AbortController,t=setTimeout(()=>e.abort(),1e4);t.unref();try{const t=await fetch(nw,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return sw.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:Vm,latest:e,isOutdated:iw(Vm,e)}}()}catch(e){return tw(H.default.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(ew(`Current version: ${H.default.yellow(r.current)}`),ew(`Latest version: ${H.default.green(r.latest)}`),ew(),!r.isOutdated)return void ew(H.default.green("✓ You are already on the latest version!"));if(ew(H.default.yellow(`⚠ A new version is available: ${r.current} → ${r.latest}`)),ew(),t)return ew(H.default.dim("Exiting with code 1 to indicate update available (useful for CI).")),void(process.exitCode=1);const n=function(){const e=process.argv[1]||"";if(e.includes("_npx")||e.includes(".npm/_cacache"))return"npx";try{const t=s.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=s.execSync("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=s.execSync("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=s.execSync("yarn config get globalFolder",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-berry"}catch{}return"unknown"}(),a=function(e){switch(e){case"global-npm":case"global-yarn-berry":case"unknown":return{command:"npm",args:["install","-g",`${rw}@latest`],description:`npm install -g ${rw}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${rw}@latest`],description:`pnpm add -g ${rw}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${rw}@latest`],description:`yarn global add ${rw}@latest`};case"npx":return{command:"npx",args:[`${rw}@latest`],description:`npx ${rw}@latest (always uses latest)`}}}(n);if("npx"===n)return ew(H.default.dim("You are running via npx, which always fetches the latest version.")),void ew(H.default.dim(`Simply run: ${H.default.white("npx stably")} to use the latest version.`));"unknown"===n?(ew(H.default.yellow("Could not detect installation method. Falling back to npm.")),ew()):"global-yarn-berry"===n&&(ew(H.default.yellow("Yarn Berry does not support global packages. Falling back to npm.")),ew()),ew(`Upgrade command: ${H.default.cyan(a.description)}`),ew(),ew(H.default.cyan("Upgrading...")),ew();try{await(i=a.command,o=a.args,new Promise((e,t)=>{const r=s.spawn(i,o,{stdio:"inherit",shell:"win32"===process.platform});r.on("close",r=>{0===r?e():t(new Error(`Upgrade command exited with code ${r}`))}),r.on("error",e=>{t(e)})})),ew(),ew(H.default.green("✓ Upgrade complete!")),ew(H.default.dim(`Run ${H.default.white("stably --version")} to verify.`))}catch(e){tw(H.default.red("Upgrade failed:"),e instanceof Error?e.message:e),ew(),ew(H.default.dim("You can try manually running:")),ew(H.default.cyan(` ${a.description}`)),process.exitCode=1}var i,o}(e)),Yb.forEach(({args:e,description:t,name:r})=>{gw.command(r).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>Xb({overrideArgs:e,subcommand:r}))});var ww=()=>{0!==yw.length&&(process.stderr.write(yw.join("")),yw=[])};(async()=>{await(async()=>{if(!pw&&"1"!==process.env.STABLY_DISABLE_TELEMETRY&&"1"!==process.env.DO_NOT_TRACK&&!process.argv.includes("--no-telemetry"))try{const{init:e}=await import("@hyperdx/node-opentelemetry");e({apiKey:"61d10b50-9534-47be-a732-95bfe461adb7",service:"stably-cli",consoleCapture:!0,disableTracing:!0,disableMetrics:!0,disableStartupLogs:!0,additionalResourceAttributes:{"cli.version":Vm,"node.version":process.version,"os.platform":process.platform}}),pw=!0}catch{}})();try{await gw.parseAsync(process.argv),wy.info("CLI completed successfully")}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e))throw wy.error("Unexpected CLI error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),ww(),wy.flush(),wy.printLogFileInfo(),await fw(),e;const t="number"==typeof e.exitCode?e.exitCode:1,r=process.argv.slice(2).find(e=>!e.startsWith("-")),n=!!r&&!!_w(gw,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return yw=[],wy.warn("Unknown command",{command:r}),process.stderr.write(`command '${r}' not found\n`),bw(),void(process.exitCode=t);wy.debug("Commander error",{code:e.code,exitCode:t}),ww(),process.exitCode=t}finally{wy.flush(),await fw()}})();
|