aicommits 2.0.0-develop.23 → 2.0.0-develop.25

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.
@@ -19,12 +19,12 @@ var TD=Object.defineProperty;var i=(e,t)=>TD(e,"name",{value:t,configurable:!0})
19
19
  `:"")+(n?this.indentText({text:this.render(n),spaces:r}):"")}
20
20
  `}table({tableData:t,tableOptions:n,tableBreakpoints:r}){return Ag(t.map(o=>o.map(s=>this.render(s))),r?Sg(r):n)}flagParameter(t){return t===Boolean?"":t===String?"<string>":t===Number?"<number>":Array.isArray(t)?this.flagParameter(t[0]):"<value>"}flagOperator(t){return" "}flagName(t){const{flag:n,flagFormatted:r,aliasesEnabled:o,aliasFormatted:s}=t;let a="";if(s?a+=`${s}, `:o&&(a+=" "),a+=r,"placeholder"in n&&typeof n.placeholder=="string")a+=`${this.flagOperator(t)}${n.placeholder}`;else{const u=this.flagParameter("type"in n?n.type:n);u&&(a+=`${this.flagOperator(t)}${u}`)}return a}flagDefault(t){return JSON.stringify(t)}flagDescription({flag:t}){let n="description"in t?t.description??"":"";if("default"in t){let{default:r}=t;typeof r=="function"&&(r=r()),r&&(n+=` (default: ${this.flagDefault(r)})`)}return n}render(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>this.render(n)).join(`
21
21
  `);if("type"in t&&this[t.type]){const n=this[t.type];if(typeof n=="function")return n.call(this,t.data)}throw new Error(`Invalid node type: ${JSON.stringify(t)}`)}},i(Hn,"_z"),Hn);ke(ic,"Renderers");let jg=ic;const fs=ke(e=>e.length>0&&!e.includes(" "),"isValidScriptName"),{stringify:Tt}=JSON,zg=/[|\\{}()[\]^$+*?.]/;function qo(e){const t=[];let n,r;for(const o of e){if(r)throw new Error(`Invalid parameter: Spread parameter ${Tt(r)} must be last`);const s=o[0],a=o.at(-1);let u;if(s==="<"&&a===">"&&(u=!0,n))throw new Error(`Invalid parameter: Required parameter ${Tt(o)} cannot come after optional parameter ${Tt(n)}`);if(s==="["&&a==="]"&&(u=!1,n=o),u===void 0)throw new Error(`Invalid parameter: ${Tt(o)}. Must be wrapped in <> (required parameter) or [] (optional parameter)`);let l=o.slice(1,-1);const c=l.slice(-3)==="...";c&&(r=o,l=l.slice(0,-3));const d=l.match(zg);if(d)throw new Error(`Invalid parameter: ${Tt(o)}. Invalid character found ${Tt(d[0])}`);t.push({name:l,required:u,spread:c})}return t}i(qo,"b$1"),ke(qo,"parseParameters");function Uo(e,t,n,r){for(let o=0;o<t.length;o+=1){const{name:s,required:a,spread:u}=t[o],l=Og(s);if(l in e)throw new Error(`Invalid parameter: ${Tt(s)} is used more than once.`);const c=u?n.slice(o):n[o];if(u&&(o=t.length),a&&(!c||u&&c.length===0))return console.error(`Error: Missing required parameter ${Tt(s)}
22
- `),r(),process.exit(1);e[l]=c}}i(Uo,"v"),ke(Uo,"mapParametersToArguments");function uc(e){return e===void 0||e!==!1}i(uc,"G$2"),ke(uc,"helpEnabled");function ms(e,t,n,r){const o={...t.flags},s=t.version&&!("version"in o);s&&(o.version={type:Boolean,description:"Show version"});const{help:a}=t,u=uc(a);u&&!("help"in o)&&(o.help={type:Boolean,alias:"h",description:"Show help"});const l=ug(o,r,{ignore:t.ignoreArgv}),c=ke(()=>{console.log(t.version)},"showVersion");if(s&&l.flags.version===!0)return c(),process.exit(0);const d=new jg,f=u&&a?.render?a.render:v=>d.render(v),h=ke(v=>{const y=Pg({...t,...v?{help:v}:{},flags:o});console.log(f(y,d))},"showHelp");if(u&&l.flags.help===!0)return h(),process.exit(0);if(t.parameters){let{parameters:v}=t,y=l._;const b=v.indexOf("--"),w=v.slice(b+1),C=Object.create(null);if(b>-1&&w.length>0){v=v.slice(0,b);const x=l._["--"];y=y.slice(0,-x.length||void 0),Uo(C,qo(v),y,h),Uo(C,qo(w),x,h)}else Uo(C,qo(v),y,h);Object.assign(l._,C)}const D={...l,showVersion:c,showHelp:h},m={command:e,...D};if(typeof n=="function"){const v=n(D);if(v&&"then"in v)return Object.assign(Promise.resolve(v),m)}return m}i(ms,"j"),ke(ms,"cliBase");function lc(e,t){const n=new Map;for(const r of t){const o=[r.options.name],{alias:s}=r.options;s&&(Array.isArray(s)?o.push(...s):o.push(s));for(const a of o){if(n.has(a))throw new Error(`Duplicate command name found: ${Tt(a)}`);n.set(a,r)}}return n.get(e)}i(lc,"K$1"),ke(lc,"getCommand");function cc(e,t,n=process.argv.slice(2)){if(!e)throw new Error("Options is required");if("name"in e&&(!e.name||!fs(e.name)))throw new Error(`Invalid script name: ${Tt(e.name)}`);const r=n[0];if(e.commands&&r&&fs(r)){const o=lc(r,e.commands);if(o)return ms(o.options.name,{...o.options,parent:e},o.callback,n.slice(1))}return ms(void 0,e,t,n)}i(cc,"Q"),ke(cc,"cli");function An(e,t){if(!e)throw new Error("Command options are required");const{name:n}=e;if(n===void 0)throw new Error("Command name is required");if(!fs(n))throw new Error(`Invalid command name ${JSON.stringify(n)}. Command names must be one word.`);return{options:e,callback:t}}i(An,"X"),ke(An,"command");var Lg="aicommits",qg="2.0.0-develop.23",Ug="Writes your git commit messages for you with AI",Zg=["ai","git","commit","code changes"],Vg="MIT",Gg={type:"git",url:"git+https://github.com/Nutlope/aicommits.git"},Wg="Hassan El Mghari (@nutlope)",Hg="module",Jg=["dist"],Kg={aicommits:"dist/cli.mjs",aic:"dist/cli.mjs"},Yg={build:"pkgroll --minify",lint:"","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json"},Xg={"@clack/prompts":"^0.11.0","@types/ini":"^1.3.31","@types/node":"^24.10.1","clean-pkg-json":"^1.3.0",cleye:"^2.0.0",execa:"^7.0.0","fs-fixture":"^1.2.0",ini:"^3.0.1",kolorist:"^1.8.0",manten:"^0.7.0",ai:"^6.0.97","@ai-sdk/openai":"^3.0.30","@ai-sdk/openai-compatible":"^2.0.30",pkgroll:"^2.20.1",tsx:"^4.21.0",typescript:"^5.9.3"},Qg={branches:["main",{name:"develop",prerelease:!0}]},hs={name:Lg,version:qg,description:Ug,keywords:Zg,license:Vg,repository:Gg,author:Wg,type:Hg,files:Jg,bin:Kg,scripts:Yg,devDependencies:Xg,release:Qg},Zt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function rn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}i(rn,"getDefaultExportFromCjs");var on={exports:{}},Ds,dc;function ev(){if(dc)return Ds;dc=1,Ds=r,r.sync=o;var e=as;function t(s,a){var u=a.pathExt!==void 0?a.pathExt:process.env.PATHEXT;if(!u||(u=u.split(";"),u.indexOf("")!==-1))return!0;for(var l=0;l<u.length;l++){var c=u[l].toLowerCase();if(c&&s.substr(-c.length).toLowerCase()===c)return!0}return!1}i(t,"checkPathExt");function n(s,a,u){return!s.isSymbolicLink()&&!s.isFile()?!1:t(a,u)}i(n,"checkStat");function r(s,a,u){e.stat(s,function(l,c){u(l,l?!1:n(c,s,a))})}i(r,"isexe");function o(s,a){return n(e.statSync(s),s,a)}return i(o,"sync"),Ds}i(ev,"requireWindows");var gs,pc;function tv(){if(pc)return gs;pc=1,gs=t,t.sync=n;var e=as;function t(s,a,u){e.stat(s,function(l,c){u(l,l?!1:r(c,a))})}i(t,"isexe");function n(s,a){return r(e.statSync(s),a)}i(n,"sync");function r(s,a){return s.isFile()&&o(s,a)}i(r,"checkStat");function o(s,a){var u=s.mode,l=s.uid,c=s.gid,d=a.uid!==void 0?a.uid:process.getuid&&process.getuid(),f=a.gid!==void 0?a.gid:process.getgid&&process.getgid(),h=parseInt("100",8),D=parseInt("010",8),m=parseInt("001",8),v=h|D,y=u&m||u&D&&c===f||u&h&&l===d||u&v&&d===0;return y}return i(o,"checkMode"),gs}i(tv,"requireMode");var vs,fc;function nv(){if(fc)return vs;fc=1;var e;process.platform==="win32"||Zt.TESTING_WINDOWS?e=ev():e=tv(),vs=t,t.sync=n;function t(r,o,s){if(typeof o=="function"&&(s=o,o={}),!s){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(a,u){t(r,o||{},function(l,c){l?u(l):a(c)})})}e(r,o||{},function(a,u){a&&(a.code==="EACCES"||o&&o.ignoreErrors)&&(a=null,u=!1),s(a,u)})}i(t,"isexe");function n(r,o){try{return e.sync(r,o||{})}catch(s){if(o&&o.ignoreErrors||s.code==="EACCES")return!1;throw s}}return i(n,"sync"),vs}i(nv,"requireIsexe");var ys,mc;function rv(){if(mc)return ys;mc=1;const e=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",t=bt,n=e?";":":",r=nv(),o=i(l=>Object.assign(new Error(`not found: ${l}`),{code:"ENOENT"}),"getNotFoundError"),s=i((l,c)=>{const d=c.colon||n,f=l.match(/\//)||e&&l.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(c.path||process.env.PATH||"").split(d)],h=e?c.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",D=e?h.split(d):[""];return e&&l.indexOf(".")!==-1&&D[0]!==""&&D.unshift(""),{pathEnv:f,pathExt:D,pathExtExe:h}},"getPathInfo"),a=i((l,c,d)=>{typeof c=="function"&&(d=c,c={}),c||(c={});const{pathEnv:f,pathExt:h,pathExtExe:D}=s(l,c),m=[],v=i(b=>new Promise((w,C)=>{if(b===f.length)return c.all&&m.length?w(m):C(o(l));const x=f[b],T=/^".*"$/.test(x)?x.slice(1,-1):x,O=t.join(T,l),$=!T&&/^\.[\\\/]/.test(l)?l.slice(0,2)+O:O;w(y($,b,0))}),"step"),y=i((b,w,C)=>new Promise((x,T)=>{if(C===h.length)return x(v(w+1));const O=h[C];r(b+O,{pathExt:D},($,I)=>{if(!$&&I)if(c.all)m.push(b+O);else return x(b+O);return x(y(b,w,C+1))})}),"subStep");return d?v(0).then(b=>d(null,b),d):v(0)},"which"),u=i((l,c)=>{c=c||{};const{pathEnv:d,pathExt:f,pathExtExe:h}=s(l,c),D=[];for(let m=0;m<d.length;m++){const v=d[m],y=/^".*"$/.test(v)?v.slice(1,-1):v,b=t.join(y,l),w=!y&&/^\.[\\\/]/.test(l)?l.slice(0,2)+b:b;for(let C=0;C<f.length;C++){const x=w+f[C];try{if(r.sync(x,{pathExt:h}))if(c.all)D.push(x);else return x}catch{}}}if(c.all&&D.length)return D;if(c.nothrow)return null;throw o(l)},"whichSync");return ys=a,a.sync=u,ys}i(rv,"requireWhich");var Zo={exports:{}},hc;function ov(){if(hc)return Zo.exports;hc=1;const e=i((t={})=>{const n=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(n).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"},"pathKey");return Zo.exports=e,Zo.exports.default=e,Zo.exports}i(ov,"requirePathKey");var _s,Dc;function av(){if(Dc)return _s;Dc=1;const e=bt,t=rv(),n=ov();function r(s,a){const u=s.options.env||process.env,l=process.cwd(),c=s.options.cwd!=null,d=c&&process.chdir!==void 0&&!process.chdir.disabled;if(d)try{process.chdir(s.options.cwd)}catch{}let f;try{f=t.sync(s.command,{path:u[n({env:u})],pathExt:a?e.delimiter:void 0})}catch{}finally{d&&process.chdir(l)}return f&&(f=e.resolve(c?s.options.cwd:"",f)),f}i(r,"resolveCommandAttempt");function o(s){return r(s)||r(s,!0)}return i(o,"resolveCommand"),_s=o,_s}i(av,"requireResolveCommand");var Vo={},gc;function sv(){if(gc)return Vo;gc=1;const e=/([()\][%!^"`<>&|;, *?])/g;function t(r){return r=r.replace(e,"^$1"),r}i(t,"escapeCommand");function n(r,o){return r=`${r}`,r=r.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),r=r.replace(/(?=(\\+?)?)\1$/,"$1$1"),r=`"${r}"`,r=r.replace(e,"^$1"),o&&(r=r.replace(e,"^$1")),r}return i(n,"escapeArgument"),Vo.command=t,Vo.argument=n,Vo}i(sv,"require_escape");var bs,vc;function iv(){return vc||(vc=1,bs=/^#!(.*)/),bs}i(iv,"requireShebangRegex");var Cs,yc;function uv(){if(yc)return Cs;yc=1;const e=iv();return Cs=i((t="")=>{const n=t.match(e);if(!n)return null;const[r,o]=n[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s},"shebangCommand"),Cs}i(uv,"requireShebangCommand");var ws,_c;function lv(){if(_c)return ws;_c=1;const e=as,t=uv();function n(r){const s=Buffer.alloc(150);let a;try{a=e.openSync(r,"r"),e.readSync(a,s,0,150,0),e.closeSync(a)}catch{}return t(s.toString())}return i(n,"readShebang"),ws=n,ws}i(lv,"requireReadShebang");var Fs,bc;function cv(){if(bc)return Fs;bc=1;const e=bt,t=av(),n=sv(),r=lv(),o=process.platform==="win32",s=/\.(?:com|exe)$/i,a=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function u(d){d.file=t(d);const f=d.file&&r(d.file);return f?(d.args.unshift(d.file),d.command=f,t(d)):d.file}i(u,"detectShebang");function l(d){if(!o)return d;const f=u(d),h=!s.test(f);if(d.options.forceShell||h){const D=a.test(f);d.command=e.normalize(d.command),d.command=n.command(d.command),d.args=d.args.map(v=>n.argument(v,D));const m=[d.command].concat(d.args).join(" ");d.args=["/d","/s","/c",`"${m}"`],d.command=process.env.comspec||"cmd.exe",d.options.windowsVerbatimArguments=!0}return d}i(l,"parseNonShell");function c(d,f,h){f&&!Array.isArray(f)&&(h=f,f=null),f=f?f.slice(0):[],h=Object.assign({},h);const D={command:d,args:f,options:h,file:void 0,original:{command:d,args:f}};return h.shell?D:l(D)}return i(c,"parse"),Fs=c,Fs}i(cv,"requireParse");var Es,Cc;function dv(){if(Cc)return Es;Cc=1;const e=process.platform==="win32";function t(s,a){return Object.assign(new Error(`${a} ${s.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${a} ${s.command}`,path:s.command,spawnargs:s.args})}i(t,"notFoundError");function n(s,a){if(!e)return;const u=s.emit;s.emit=function(l,c){if(l==="exit"){const d=r(c,a);if(d)return u.call(s,"error",d)}return u.apply(s,arguments)}}i(n,"hookChildProcess");function r(s,a){return e&&s===1&&!a.file?t(a.original,"spawn"):null}i(r,"verifyENOENT");function o(s,a){return e&&s===1&&!a.file?t(a.original,"spawnSync"):null}return i(o,"verifyENOENTSync"),Es={hookChildProcess:n,verifyENOENT:r,verifyENOENTSync:o,notFoundError:t},Es}i(dv,"requireEnoent");var wc;function pv(){if(wc)return on.exports;wc=1;const e=RD,t=cv(),n=dv();function r(s,a,u){const l=t(s,a,u),c=e.spawn(l.command,l.args,l.options);return n.hookChildProcess(c,l),c}i(r,"spawn");function o(s,a,u){const l=t(s,a,u),c=e.spawnSync(l.command,l.args,l.options);return c.error=c.error||n.verifyENOENTSync(c.status,l),c}return i(o,"spawnSync"),on.exports=r,on.exports.spawn=r,on.exports.sync=o,on.exports._parse=t,on.exports._enoent=n,on.exports}i(pv,"requireCrossSpawn");var fv=pv(),mv=rn(fv);function hv(e){const t=typeof e=="string"?`
22
+ `),r(),process.exit(1);e[l]=c}}i(Uo,"v"),ke(Uo,"mapParametersToArguments");function uc(e){return e===void 0||e!==!1}i(uc,"G$2"),ke(uc,"helpEnabled");function ms(e,t,n,r){const o={...t.flags},s=t.version&&!("version"in o);s&&(o.version={type:Boolean,description:"Show version"});const{help:a}=t,u=uc(a);u&&!("help"in o)&&(o.help={type:Boolean,alias:"h",description:"Show help"});const l=ug(o,r,{ignore:t.ignoreArgv}),c=ke(()=>{console.log(t.version)},"showVersion");if(s&&l.flags.version===!0)return c(),process.exit(0);const d=new jg,f=u&&a?.render?a.render:v=>d.render(v),h=ke(v=>{const y=Pg({...t,...v?{help:v}:{},flags:o});console.log(f(y,d))},"showHelp");if(u&&l.flags.help===!0)return h(),process.exit(0);if(t.parameters){let{parameters:v}=t,y=l._;const b=v.indexOf("--"),C=v.slice(b+1),F=Object.create(null);if(b>-1&&C.length>0){v=v.slice(0,b);const E=l._["--"];y=y.slice(0,-E.length||void 0),Uo(F,qo(v),y,h),Uo(F,qo(C),E,h)}else Uo(F,qo(v),y,h);Object.assign(l._,F)}const D={...l,showVersion:c,showHelp:h},m={command:e,...D};if(typeof n=="function"){const v=n(D);if(v&&"then"in v)return Object.assign(Promise.resolve(v),m)}return m}i(ms,"j"),ke(ms,"cliBase");function lc(e,t){const n=new Map;for(const r of t){const o=[r.options.name],{alias:s}=r.options;s&&(Array.isArray(s)?o.push(...s):o.push(s));for(const a of o){if(n.has(a))throw new Error(`Duplicate command name found: ${Tt(a)}`);n.set(a,r)}}return n.get(e)}i(lc,"K$1"),ke(lc,"getCommand");function cc(e,t,n=process.argv.slice(2)){if(!e)throw new Error("Options is required");if("name"in e&&(!e.name||!fs(e.name)))throw new Error(`Invalid script name: ${Tt(e.name)}`);const r=n[0];if(e.commands&&r&&fs(r)){const o=lc(r,e.commands);if(o)return ms(o.options.name,{...o.options,parent:e},o.callback,n.slice(1))}return ms(void 0,e,t,n)}i(cc,"Q"),ke(cc,"cli");function An(e,t){if(!e)throw new Error("Command options are required");const{name:n}=e;if(n===void 0)throw new Error("Command name is required");if(!fs(n))throw new Error(`Invalid command name ${JSON.stringify(n)}. Command names must be one word.`);return{options:e,callback:t}}i(An,"X"),ke(An,"command");var Lg="aicommits",qg="2.0.0-develop.25",Ug="Writes your git commit messages for you with AI",Zg=["ai","git","commit","code changes"],Vg="MIT",Gg={type:"git",url:"git+https://github.com/Nutlope/aicommits.git"},Wg="Hassan El Mghari (@nutlope)",Hg="module",Jg=["dist"],Kg={aicommits:"dist/cli.mjs",aic:"dist/cli.mjs"},Yg={build:"pkgroll --minify",lint:"","type-check":"tsc",test:"tsx tests",prepack:"pnpm build && clean-pkg-json"},Xg={"@clack/prompts":"^0.11.0","@types/ini":"^1.3.31","@types/node":"^24.10.1","clean-pkg-json":"^1.3.0",cleye:"^2.0.0",execa:"^7.0.0","fs-fixture":"^1.2.0",ini:"^3.0.1",kolorist:"^1.8.0",manten:"^0.7.0",ai:"^6.0.97","@ai-sdk/openai":"^3.0.30","@ai-sdk/openai-compatible":"^2.0.30",pkgroll:"^2.20.1",tsx:"^4.21.0",typescript:"^5.9.3"},Qg={branches:["main",{name:"develop",prerelease:!0}]},hs={name:Lg,version:qg,description:Ug,keywords:Zg,license:Vg,repository:Gg,author:Wg,type:Hg,files:Jg,bin:Kg,scripts:Yg,devDependencies:Xg,release:Qg},Zt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function rn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}i(rn,"getDefaultExportFromCjs");var on={exports:{}},Ds,dc;function ev(){if(dc)return Ds;dc=1,Ds=r,r.sync=o;var e=as;function t(s,a){var u=a.pathExt!==void 0?a.pathExt:process.env.PATHEXT;if(!u||(u=u.split(";"),u.indexOf("")!==-1))return!0;for(var l=0;l<u.length;l++){var c=u[l].toLowerCase();if(c&&s.substr(-c.length).toLowerCase()===c)return!0}return!1}i(t,"checkPathExt");function n(s,a,u){return!s.isSymbolicLink()&&!s.isFile()?!1:t(a,u)}i(n,"checkStat");function r(s,a,u){e.stat(s,function(l,c){u(l,l?!1:n(c,s,a))})}i(r,"isexe");function o(s,a){return n(e.statSync(s),s,a)}return i(o,"sync"),Ds}i(ev,"requireWindows");var gs,pc;function tv(){if(pc)return gs;pc=1,gs=t,t.sync=n;var e=as;function t(s,a,u){e.stat(s,function(l,c){u(l,l?!1:r(c,a))})}i(t,"isexe");function n(s,a){return r(e.statSync(s),a)}i(n,"sync");function r(s,a){return s.isFile()&&o(s,a)}i(r,"checkStat");function o(s,a){var u=s.mode,l=s.uid,c=s.gid,d=a.uid!==void 0?a.uid:process.getuid&&process.getuid(),f=a.gid!==void 0?a.gid:process.getgid&&process.getgid(),h=parseInt("100",8),D=parseInt("010",8),m=parseInt("001",8),v=h|D,y=u&m||u&D&&c===f||u&h&&l===d||u&v&&d===0;return y}return i(o,"checkMode"),gs}i(tv,"requireMode");var vs,fc;function nv(){if(fc)return vs;fc=1;var e;process.platform==="win32"||Zt.TESTING_WINDOWS?e=ev():e=tv(),vs=t,t.sync=n;function t(r,o,s){if(typeof o=="function"&&(s=o,o={}),!s){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(a,u){t(r,o||{},function(l,c){l?u(l):a(c)})})}e(r,o||{},function(a,u){a&&(a.code==="EACCES"||o&&o.ignoreErrors)&&(a=null,u=!1),s(a,u)})}i(t,"isexe");function n(r,o){try{return e.sync(r,o||{})}catch(s){if(o&&o.ignoreErrors||s.code==="EACCES")return!1;throw s}}return i(n,"sync"),vs}i(nv,"requireIsexe");var ys,mc;function rv(){if(mc)return ys;mc=1;const e=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",t=bt,n=e?";":":",r=nv(),o=i(l=>Object.assign(new Error(`not found: ${l}`),{code:"ENOENT"}),"getNotFoundError"),s=i((l,c)=>{const d=c.colon||n,f=l.match(/\//)||e&&l.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(c.path||process.env.PATH||"").split(d)],h=e?c.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",D=e?h.split(d):[""];return e&&l.indexOf(".")!==-1&&D[0]!==""&&D.unshift(""),{pathEnv:f,pathExt:D,pathExtExe:h}},"getPathInfo"),a=i((l,c,d)=>{typeof c=="function"&&(d=c,c={}),c||(c={});const{pathEnv:f,pathExt:h,pathExtExe:D}=s(l,c),m=[],v=i(b=>new Promise((C,F)=>{if(b===f.length)return c.all&&m.length?C(m):F(o(l));const E=f[b],T=/^".*"$/.test(E)?E.slice(1,-1):E,O=t.join(T,l),$=!T&&/^\.[\\\/]/.test(l)?l.slice(0,2)+O:O;C(y($,b,0))}),"step"),y=i((b,C,F)=>new Promise((E,T)=>{if(F===h.length)return E(v(C+1));const O=h[F];r(b+O,{pathExt:D},($,I)=>{if(!$&&I)if(c.all)m.push(b+O);else return E(b+O);return E(y(b,C,F+1))})}),"subStep");return d?v(0).then(b=>d(null,b),d):v(0)},"which"),u=i((l,c)=>{c=c||{};const{pathEnv:d,pathExt:f,pathExtExe:h}=s(l,c),D=[];for(let m=0;m<d.length;m++){const v=d[m],y=/^".*"$/.test(v)?v.slice(1,-1):v,b=t.join(y,l),C=!y&&/^\.[\\\/]/.test(l)?l.slice(0,2)+b:b;for(let F=0;F<f.length;F++){const E=C+f[F];try{if(r.sync(E,{pathExt:h}))if(c.all)D.push(E);else return E}catch{}}}if(c.all&&D.length)return D;if(c.nothrow)return null;throw o(l)},"whichSync");return ys=a,a.sync=u,ys}i(rv,"requireWhich");var Zo={exports:{}},hc;function ov(){if(hc)return Zo.exports;hc=1;const e=i((t={})=>{const n=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(n).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"},"pathKey");return Zo.exports=e,Zo.exports.default=e,Zo.exports}i(ov,"requirePathKey");var _s,Dc;function av(){if(Dc)return _s;Dc=1;const e=bt,t=rv(),n=ov();function r(s,a){const u=s.options.env||process.env,l=process.cwd(),c=s.options.cwd!=null,d=c&&process.chdir!==void 0&&!process.chdir.disabled;if(d)try{process.chdir(s.options.cwd)}catch{}let f;try{f=t.sync(s.command,{path:u[n({env:u})],pathExt:a?e.delimiter:void 0})}catch{}finally{d&&process.chdir(l)}return f&&(f=e.resolve(c?s.options.cwd:"",f)),f}i(r,"resolveCommandAttempt");function o(s){return r(s)||r(s,!0)}return i(o,"resolveCommand"),_s=o,_s}i(av,"requireResolveCommand");var Vo={},gc;function sv(){if(gc)return Vo;gc=1;const e=/([()\][%!^"`<>&|;, *?])/g;function t(r){return r=r.replace(e,"^$1"),r}i(t,"escapeCommand");function n(r,o){return r=`${r}`,r=r.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),r=r.replace(/(?=(\\+?)?)\1$/,"$1$1"),r=`"${r}"`,r=r.replace(e,"^$1"),o&&(r=r.replace(e,"^$1")),r}return i(n,"escapeArgument"),Vo.command=t,Vo.argument=n,Vo}i(sv,"require_escape");var bs,vc;function iv(){return vc||(vc=1,bs=/^#!(.*)/),bs}i(iv,"requireShebangRegex");var Cs,yc;function uv(){if(yc)return Cs;yc=1;const e=iv();return Cs=i((t="")=>{const n=t.match(e);if(!n)return null;const[r,o]=n[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return s==="env"?o:o?`${s} ${o}`:s},"shebangCommand"),Cs}i(uv,"requireShebangCommand");var ws,_c;function lv(){if(_c)return ws;_c=1;const e=as,t=uv();function n(r){const s=Buffer.alloc(150);let a;try{a=e.openSync(r,"r"),e.readSync(a,s,0,150,0),e.closeSync(a)}catch{}return t(s.toString())}return i(n,"readShebang"),ws=n,ws}i(lv,"requireReadShebang");var Fs,bc;function cv(){if(bc)return Fs;bc=1;const e=bt,t=av(),n=sv(),r=lv(),o=process.platform==="win32",s=/\.(?:com|exe)$/i,a=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function u(d){d.file=t(d);const f=d.file&&r(d.file);return f?(d.args.unshift(d.file),d.command=f,t(d)):d.file}i(u,"detectShebang");function l(d){if(!o)return d;const f=u(d),h=!s.test(f);if(d.options.forceShell||h){const D=a.test(f);d.command=e.normalize(d.command),d.command=n.command(d.command),d.args=d.args.map(v=>n.argument(v,D));const m=[d.command].concat(d.args).join(" ");d.args=["/d","/s","/c",`"${m}"`],d.command=process.env.comspec||"cmd.exe",d.options.windowsVerbatimArguments=!0}return d}i(l,"parseNonShell");function c(d,f,h){f&&!Array.isArray(f)&&(h=f,f=null),f=f?f.slice(0):[],h=Object.assign({},h);const D={command:d,args:f,options:h,file:void 0,original:{command:d,args:f}};return h.shell?D:l(D)}return i(c,"parse"),Fs=c,Fs}i(cv,"requireParse");var Es,Cc;function dv(){if(Cc)return Es;Cc=1;const e=process.platform==="win32";function t(s,a){return Object.assign(new Error(`${a} ${s.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${a} ${s.command}`,path:s.command,spawnargs:s.args})}i(t,"notFoundError");function n(s,a){if(!e)return;const u=s.emit;s.emit=function(l,c){if(l==="exit"){const d=r(c,a);if(d)return u.call(s,"error",d)}return u.apply(s,arguments)}}i(n,"hookChildProcess");function r(s,a){return e&&s===1&&!a.file?t(a.original,"spawn"):null}i(r,"verifyENOENT");function o(s,a){return e&&s===1&&!a.file?t(a.original,"spawnSync"):null}return i(o,"verifyENOENTSync"),Es={hookChildProcess:n,verifyENOENT:r,verifyENOENTSync:o,notFoundError:t},Es}i(dv,"requireEnoent");var wc;function pv(){if(wc)return on.exports;wc=1;const e=RD,t=cv(),n=dv();function r(s,a,u){const l=t(s,a,u),c=e.spawn(l.command,l.args,l.options);return n.hookChildProcess(c,l),c}i(r,"spawn");function o(s,a,u){const l=t(s,a,u),c=e.spawnSync(l.command,l.args,l.options);return c.error=c.error||n.verifyENOENTSync(c.status,l),c}return i(o,"spawnSync"),on.exports=r,on.exports.spawn=r,on.exports.sync=o,on.exports._parse=t,on.exports._enoent=n,on.exports}i(pv,"requireCrossSpawn");var fv=pv(),mv=rn(fv);function hv(e){const t=typeof e=="string"?`
23
23
  `:10,n=typeof e=="string"?"\r":13;return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===n&&(e=e.slice(0,-1)),e}i(hv,"stripFinalNewline");function Fc(e={}){const{env:t=process.env,platform:n=process.platform}=e;return n!=="win32"?"PATH":Object.keys(t).reverse().find(r=>r.toUpperCase()==="PATH")||"Path"}i(Fc,"pathKey");const Dv=i(({cwd:e=Le.cwd(),path:t=Le.env[Fc()],preferLocal:n=!0,execPath:r=Le.execPath,addExecPath:o=!0}={})=>{const s=e instanceof URL?Cl(e):e,a=In.resolve(s),u=[];return n&&gv(u,a),o&&vv(u,r,a),[...u,t].join(In.delimiter)},"npmRunPath"),gv=i((e,t)=>{let n;for(;n!==t;)e.push(In.join(t,"node_modules/.bin")),n=t,t=In.resolve(t,"..")},"applyPreferLocal"),vv=i((e,t,n)=>{const r=t instanceof URL?Cl(t):t;e.push(In.resolve(n,r,".."))},"applyExecPath"),yv=i(({env:e=Le.env,...t}={})=>{e={...e};const n=Fc({env:e});return t.path=e[n],e[n]=Dv(t),e},"npmRunPathEnv"),_v=i((e,t,n,r)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;const o=Object.getOwnPropertyDescriptor(e,n),s=Object.getOwnPropertyDescriptor(t,n);!bv(o,s)&&r||Object.defineProperty(e,n,s)},"copyProperty"),bv=i(function(e,t){return e===void 0||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},"canCopyProperty"),Cv=i((e,t)=>{const n=Object.getPrototypeOf(t);n!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,n)},"changePrototype"),wv=i((e,t)=>`/* Wrapped ${e}*/
24
- ${t}`,"wrappedToString"),Fv=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Ev=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),xv=i((e,t,n)=>{const r=n===""?"":`with ${n.trim()}() `,o=wv.bind(null,r,t.toString());Object.defineProperty(o,"name",Ev),Object.defineProperty(e,"toString",{...Fv,value:o})},"changeToString");function kv(e,t,{ignoreNonConfigurable:n=!1}={}){const{name:r}=e;for(const o of Reflect.ownKeys(t))_v(e,t,o,n);return Cv(e,t),xv(e,t,r),e}i(kv,"mimicFunction");const Go=new WeakMap,Ec=i((e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,r=0;const o=e.displayName||e.name||"<anonymous>",s=i(function(...a){if(Go.set(s,++r),r===1)n=e.apply(this,a),e=null;else if(t.throw===!0)throw new Error(`Function \`${o}\` can only be called once`);return n},"onetime2");return kv(s,e),Go.set(s,r),s},"onetime");Ec.callCount=e=>{if(!Go.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Go.get(e)};const Iv=i(()=>{const e=kc-xc+1;return Array.from({length:e},Av)},"getRealtimeSignals"),Av=i((e,t)=>({name:`SIGRT${t+1}`,number:xc+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),"getRealtimeSignal"),xc=34,kc=64,$v=[{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"}],Ic=i(()=>{const e=Iv();return[...$v,...e].map(Tv)},"getSignals"),Tv=i(({name:e,number:t,description:n,action:r,forced:o=!1,standard:s})=>{const{signals:{[e]:a}}=wl,u=a!==void 0;return{name:e,number:u?a:t,description:n,supported:u,action:r,forced:o,standard:s}},"normalizeSignal"),Sv=i(()=>{const e=Ic();return Object.fromEntries(e.map(Bv))},"getSignalsByName"),Bv=i(({name:e,number:t,description:n,supported:r,action:o,forced:s,standard:a})=>[e,{name:e,number:t,description:n,supported:r,action:o,forced:s,standard:a}],"getSignalByName"),Ov=Sv(),Rv=i(()=>{const e=Ic(),t=kc+1,n=Array.from({length:t},(r,o)=>Nv(o,e));return Object.assign({},...n)},"getSignalsByNumber"),Nv=i((e,t)=>{const n=Pv(e,t);if(n===void 0)return{};const{name:r,description:o,supported:s,action:a,forced:u,standard:l}=n;return{[e]:{name:r,number:e,description:o,supported:s,action:a,forced:u,standard:l}}},"getSignalByNumber"),Pv=i((e,t)=>{const n=t.find(({name:r})=>wl.signals[r]===e);return n!==void 0?n:t.find(r=>r.number===e)},"findSignalByNumber");Rv();const Mv=i(({timedOut:e,timeout:t,errorCode:n,signal:r,signalDescription:o,exitCode:s,isCanceled:a})=>e?`timed out after ${t} milliseconds`:a?"was canceled":n!==void 0?`failed with ${n}`:r!==void 0?`was killed with ${r} (${o})`:s!==void 0?`failed with exit code ${s}`:"failed","getErrorPrefix"),Ac=i(({stdout:e,stderr:t,all:n,error:r,signal:o,exitCode:s,command:a,escapedCommand:u,timedOut:l,isCanceled:c,killed:d,parsed:{options:{timeout:f,cwd:h=Le.cwd()}}})=>{s=s===null?void 0:s,o=o===null?void 0:o;const D=o===void 0?void 0:Ov[o].description,m=r&&r.code,y=`Command ${Mv({timedOut:l,timeout:f,errorCode:m,signal:o,signalDescription:D,exitCode:s,isCanceled:c})}: ${a}`,b=Object.prototype.toString.call(r)==="[object Error]",w=b?`${y}
25
- ${r.message}`:y,C=[w,t,e].filter(Boolean).join(`
26
- `);return b?(r.originalMessage=r.message,r.message=C):r=new Error(C),r.shortMessage=w,r.command=a,r.escapedCommand=u,r.exitCode=s,r.signal=o,r.signalDescription=D,r.stdout=e,r.stderr=t,r.cwd=h,n!==void 0&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!l,r.isCanceled=c,r.killed=d&&!l,r},"makeError"),Wo=["stdin","stdout","stderr"],jv=i(e=>Wo.some(t=>e[t]!==void 0),"hasAlias"),zv=i(e=>{if(!e)return;const{stdio:t}=e;if(t===void 0)return Wo.map(r=>e[r]);if(jv(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Wo.map(r=>`\`${r}\``).join(", ")}`);if(typeof t=="string")return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const n=Math.max(t.length,Wo.length);return Array.from({length:n},(r,o)=>t[o])},"normalizeStdio");var an={exports:{}},xs={exports:{}},$c;function Lv(){return $c||($c=1,(function(e){e.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&e.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&e.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")})(xs)),xs.exports}i(Lv,"requireSignals");var Tc;function qv(){if(Tc)return an.exports;Tc=1;var e=Zt.process;const t=i(function(y){return y&&typeof y=="object"&&typeof y.removeListener=="function"&&typeof y.emit=="function"&&typeof y.reallyExit=="function"&&typeof y.listeners=="function"&&typeof y.kill=="function"&&typeof y.pid=="number"&&typeof y.on=="function"},"processOk");if(!t(e))an.exports=function(){return function(){}};else{var n=PD,r=Lv(),o=/^win/i.test(e.platform),s=MD;typeof s!="function"&&(s=s.EventEmitter);var a;e.__signal_exit_emitter__?a=e.__signal_exit_emitter__:(a=e.__signal_exit_emitter__=new s,a.count=0,a.emitted={}),a.infinite||(a.setMaxListeners(1/0),a.infinite=!0),an.exports=function(y,b){if(!t(Zt.process))return function(){};n.equal(typeof y,"function","a callback must be provided for exit handler"),d===!1&&f();var w="exit";b&&b.alwaysLast&&(w="afterexit");var C=i(function(){a.removeListener(w,y),a.listeners("exit").length===0&&a.listeners("afterexit").length===0&&u()},"remove");return a.on(w,y),C};var u=i(function(){!d||!t(Zt.process)||(d=!1,r.forEach(function(b){try{e.removeListener(b,c[b])}catch{}}),e.emit=m,e.reallyExit=h,a.count-=1)},"unload2");an.exports.unload=u;var l=i(function(b,w,C){a.emitted[b]||(a.emitted[b]=!0,a.emit(b,w,C))},"emit2"),c={};r.forEach(function(y){c[y]=i(function(){if(t(Zt.process)){var w=e.listeners(y);w.length===a.count&&(u(),l("exit",null,y),l("afterexit",null,y),o&&y==="SIGHUP"&&(y="SIGINT"),e.kill(e.pid,y))}},"listener")}),an.exports.signals=function(){return r};var d=!1,f=i(function(){d||!t(Zt.process)||(d=!0,a.count+=1,r=r.filter(function(b){try{return e.on(b,c[b]),!0}catch{return!1}}),e.emit=v,e.reallyExit=D)},"load2");an.exports.load=f;var h=e.reallyExit,D=i(function(b){t(Zt.process)&&(e.exitCode=b||0,l("exit",e.exitCode,null),l("afterexit",e.exitCode,null),h.call(e,e.exitCode))},"processReallyExit2"),m=e.emit,v=i(function(b,w){if(b==="exit"&&t(Zt.process)){w!==void 0&&(e.exitCode=w);var C=m.apply(this,arguments);return l("exit",e.exitCode,null),l("afterexit",e.exitCode,null),C}else return m.apply(this,arguments)},"processEmit2")}return an.exports}i(qv,"requireSignalExit");var Uv=qv(),Zv=rn(Uv);const Vv=1e3*5,Gv=i((e,t="SIGTERM",n={})=>{const r=e(t);return Wv(e,t,n,r),r},"spawnedKill"),Wv=i((e,t,n,r)=>{if(!Hv(t,n,r))return;const o=Kv(n),s=setTimeout(()=>{e("SIGKILL")},o);s.unref&&s.unref()},"setKillTimeout"),Hv=i((e,{forceKillAfterTimeout:t},n)=>Jv(e)&&t!==!1&&n,"shouldForceKill"),Jv=i(e=>e===ND.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM","isSigterm"),Kv=i(({forceKillAfterTimeout:e=!0})=>{if(e===!0)return Vv;if(!Number.isFinite(e)||e<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`);return e},"getForceKillAfterTimeout"),Yv=i((e,t)=>{e.kill()&&(t.isCanceled=!0)},"spawnedCancel"),Xv=i((e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},"timeoutKill"),Qv=i((e,{timeout:t,killSignal:n="SIGTERM"},r)=>{if(t===0||t===void 0)return r;let o;const s=new Promise((u,l)=>{o=setTimeout(()=>{Xv(e,n,l)},t)}),a=r.finally(()=>{clearTimeout(o)});return Promise.race([s,a])},"setupTimeout"),ey=i(({timeout:e})=>{if(e!==void 0&&(!Number.isFinite(e)||e<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`)},"validateTimeout"),ty=i(async(e,{cleanup:t,detached:n},r)=>{if(!t||n)return r;const o=Zv(()=>{e.kill()});return r.finally(()=>{o()})},"setExitHandler");function Sc(e){return e!==null&&typeof e=="object"&&typeof e.pipe=="function"}i(Sc,"isStream");function Bc(e){return Sc(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object"}i(Bc,"isWritableStream");const ny=i(e=>e instanceof OD&&typeof e.then=="function","isExecaChildProcess"),ks=i((e,t,n)=>{if(typeof n=="string")return e[t].pipe(jD(n)),e;if(Bc(n))return e[t].pipe(n),e;if(!ny(n))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Bc(n.stdin))throw new TypeError("The target child process's stdin must be available.");return e[t].pipe(n.stdin),n},"pipeToTarget"),ry=i(e=>{e.stdout!==null&&(e.pipeStdout=ks.bind(void 0,e,"stdout")),e.stderr!==null&&(e.pipeStderr=ks.bind(void 0,e,"stderr")),e.all!==void 0&&(e.pipeAll=ks.bind(void 0,e,"all"))},"addPipeMethods");var $n={exports:{}},Is,Oc;function oy(){if(Oc)return Is;Oc=1;const{PassThrough:e}=ss;return Is=i(t=>{t={...t};const{array:n}=t;let{encoding:r}=t;const o=r==="buffer";let s=!1;n?s=!(r||o):r=r||"utf8",o&&(r=null);const a=new e({objectMode:s});r&&a.setEncoding(r);let u=0;const l=[];return a.on("data",c=>{l.push(c),s?u=l.length:u+=c.length}),a.getBufferedValue=()=>n?l:o?Buffer.concat(l,u):l.join(""),a.getBufferedLength=()=>u,a},"bufferStream"),Is}i(oy,"requireBufferStream");var Rc;function ay(){if(Rc)return $n.exports;Rc=1;const{constants:e}=LD,t=ss,{promisify:n}=qD,r=oy(),o=n(t.pipeline),u=class u extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};i(u,"MaxBufferError");let s=u;async function a(l,c){if(!l)throw new Error("Expected a stream");c={maxBuffer:1/0,...c};const{maxBuffer:d}=c,f=r(c);return await new Promise((h,D)=>{const m=i(v=>{v&&f.getBufferedLength()<=e.MAX_LENGTH&&(v.bufferedData=f.getBufferedValue()),D(v)},"rejectPromise");(async()=>{try{await o(l,f),h()}catch(v){m(v)}})(),f.on("data",()=>{f.getBufferedLength()>d&&m(new s)})}),f.getBufferedValue()}return i(a,"getStream"),$n.exports=a,$n.exports.buffer=(l,c)=>a(l,{...c,encoding:"buffer"}),$n.exports.array=(l,c)=>a(l,{...c,array:!0}),$n.exports.MaxBufferError=s,$n.exports}i(ay,"requireGetStream");var sy=ay(),Nc=rn(sy),As,Pc;function iy(){if(Pc)return As;Pc=1;const{PassThrough:e}=ss;return As=i(function(){var t=[],n=new e({objectMode:!0});return n.setMaxListeners(0),n.add=r,n.isEmpty=o,n.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(r),n;function r(a){return Array.isArray(a)?(a.forEach(r),this):(t.push(a),a.once("end",s.bind(null,a)),a.once("error",n.emit.bind(n,"error")),a.pipe(n,{end:!1}),this)}i(r,"add");function o(){return t.length==0}i(o,"isEmpty");function s(a){t=t.filter(function(u){return u!==a}),!t.length&&n.readable&&n.end()}i(s,"remove")},"mergeStream$1"),As}i(iy,"requireMergeStream");var uy=iy(),ly=rn(uy);const cy=i(e=>{if(e!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},"validateInputOptions"),dy=i(({input:e,inputFile:t})=>typeof t!="string"?e:(cy(e),zD(t)),"getInput"),py=i((e,t)=>{const n=dy(t);n!==void 0&&(Sc(n)?n.pipe(e.stdin):e.stdin.end(n))},"handleInput"),fy=i((e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const n=ly();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},"makeAllStream"),$s=i(async(e,t)=>{if(!(!e||t===void 0)){e.destroy();try{return await t}catch(n){return n.bufferedData}}},"getBufferedData"),Ts=i((e,{encoding:t,buffer:n,maxBuffer:r})=>{if(!(!e||!n))return t?Nc(e,{encoding:t,maxBuffer:r}):Nc.buffer(e,{maxBuffer:r})},"getStreamPromise"),my=i(async({stdout:e,stderr:t,all:n},{encoding:r,buffer:o,maxBuffer:s},a)=>{const u=Ts(e,{encoding:r,buffer:o,maxBuffer:s}),l=Ts(t,{encoding:r,buffer:o,maxBuffer:s}),c=Ts(n,{encoding:r,buffer:o,maxBuffer:s*2});try{return await Promise.all([a,u,l,c])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},$s(e,u),$s(t,l),$s(n,c)])}},"getSpawnedResult"),hy=(async()=>{})().constructor.prototype,Dy=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(hy,e)]),Mc=i((e,t)=>{for(const[n,r]of Dy){const o=typeof t=="function"?(...s)=>Reflect.apply(r.value,t(),s):r.value.bind(t);Reflect.defineProperty(e,n,{...r,value:o})}},"mergePromise"),gy=i(e=>new Promise((t,n)=>{e.on("exit",(r,o)=>{t({exitCode:r,signal:o})}),e.on("error",r=>{n(r)}),e.stdin&&e.stdin.on("error",r=>{n(r)})}),"getSpawnedPromise"),jc=i((e,t=[])=>Array.isArray(t)?[e,...t]:[e],"normalizeArgs"),vy=/^[\w.-]+$/,yy=/"/g,_y=i(e=>typeof e!="string"||vy.test(e)?e:`"${e.replace(yy,'\\"')}"`,"escapeArg"),by=i((e,t)=>jc(e,t).join(" "),"joinCommand"),Cy=i((e,t)=>jc(e,t).map(n=>_y(n)).join(" "),"getEscapedCommand"),wy=ZD("execa").enabled,Ho=i((e,t)=>String(e).padStart(t,"0"),"padField"),Fy=i(()=>{const e=new Date;return`${Ho(e.getHours(),2)}:${Ho(e.getMinutes(),2)}:${Ho(e.getSeconds(),2)}.${Ho(e.getMilliseconds(),3)}`},"getTimestamp"),Ey=i((e,{verbose:t})=>{t&&Le.stderr.write(`[${Fy()}] ${e}
27
- `)},"logCommand"),xy=1e3*1e3*100,ky=i(({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:o})=>{const s=t?{...Le.env,...e}:e;return n?yv({env:s,cwd:r,execPath:o}):s},"getEnv"),Iy=i((e,t,n={})=>{const r=mv._parse(e,t,n);return e=r.command,t=r.args,n=r.options,n={maxBuffer:xy,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:n.cwd||Le.cwd(),execPath:Le.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:wy,...n},n.env=ky(n),n.stdio=zv(n),Le.platform==="win32"&&In.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},"handleArguments"),Ss=i((e,t,n)=>typeof t!="string"&&!BD.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?hv(t):t,"handleOutput");function Je(e,t,n){const r=Iy(e,t,n),o=by(e,t),s=Cy(e,t);Ey(s,r.options),ey(r.options);let a;try{a=vl.spawn(r.file,r.args,r.options)}catch(D){const m=new vl.ChildProcess,v=Promise.reject(Ac({error:D,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return Mc(m,v),m}const u=gy(a),l=Qv(a,r.options,u),c=ty(a,r.options,l),d={isCanceled:!1};a.kill=Gv.bind(null,a.kill.bind(a)),a.cancel=Yv.bind(null,a,d);const h=Ec(i(async()=>{const[{error:D,exitCode:m,signal:v,timedOut:y},b,w,C]=await my(a,r.options,c),x=Ss(r.options,b),T=Ss(r.options,w),O=Ss(r.options,C);if(D||m!==0||v!==null){const $=Ac({error:D,exitCode:m,signal:v,stdout:x,stderr:T,all:O,command:o,escapedCommand:s,parsed:r,timedOut:y,isCanceled:d.isCanceled||(r.options.signal?r.options.signal.aborted:!1),killed:a.killed});if(!r.options.reject)return $;throw $}return{command:o,escapedCommand:s,exitCode:0,stdout:x,stderr:T,all:O,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},"handlePromise"));return py(a,r.options),a.all=fy(a,r.options),ry(a),Mc(a,h),a}i(Je,"execa");let sn=!0;const Tn=typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{};let to=0;if(Tn.process&&Tn.process.env&&Tn.process.stdout){const{FORCE_COLOR:e,NODE_DISABLE_COLORS:t,NO_COLOR:n,TERM:r,COLORTERM:o}=Tn.process.env;t||n||e==="0"?sn=!1:e==="1"||e==="2"||e==="3"?sn=!0:r==="dumb"?sn=!1:"CI"in Tn.process.env&&["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(s=>s in Tn.process.env)?sn=!0:sn=process.stdout.isTTY,sn&&(process.platform==="win32"||o&&(o==="truecolor"||o==="24bit")?to=3:r&&(r.endsWith("-256color")||r.endsWith("256"))?to=2:to=1)}let Bs={enabled:sn,supportLevel:to};function Sn(e,t,n=1){const r=`\x1B[${e}m`,o=`\x1B[${t}m`,s=new RegExp(`\\x1b\\[${t}m`,"g");return a=>Bs.enabled&&Bs.supportLevel>=n?r+(""+a).replace(s,r)+o:""+a}i(Sn,"kolorist");const Os=Sn(2,22),Jo=Sn(30,39),Rs=Sn(31,39),St=Sn(32,39),Ns=Sn(33,39),Ko=Sn(46,49);var Ay=Object.freeze({__proto__:null,bgCyan:Ko,black:Jo,dim:Os,green:St,options:Bs,red:Rs,yellow:Ns});async function zc(e){try{return process.platform==="darwin"?await Je("pbcopy",{input:e}):process.platform==="win32"?await Je("clip",{input:e}):await Je("xclip",["-selection","clipboard"],{input:e}).catch(()=>Je("xsel",["--clipboard","--input"],{input:e})),!0}catch{return!1}}i(zc,"copyToClipboard");var Ps,Lc;function $y(){if(Lc)return Ps;Lc=1;const e="\x1B",t=`${e}[`,n="\x07",r={to(a,u){return u?`${t}${u+1};${a+1}H`:`${t}${a+1}G`},move(a,u){let l="";return a<0?l+=`${t}${-a}D`:a>0&&(l+=`${t}${a}C`),u<0?l+=`${t}${-u}A`:u>0&&(l+=`${t}${u}B`),l},up:i((a=1)=>`${t}${a}A`,"up"),down:i((a=1)=>`${t}${a}B`,"down"),forward:i((a=1)=>`${t}${a}C`,"forward"),backward:i((a=1)=>`${t}${a}D`,"backward"),nextLine:i((a=1)=>`${t}E`.repeat(a),"nextLine"),prevLine:i((a=1)=>`${t}F`.repeat(a),"prevLine"),left:`${t}G`,hide:`${t}?25l`,show:`${t}?25h`,save:`${e}7`,restore:`${e}8`},o={up:i((a=1)=>`${t}S`.repeat(a),"up"),down:i((a=1)=>`${t}T`.repeat(a),"down")},s={screen:`${t}2J`,up:i((a=1)=>`${t}1J`.repeat(a),"up"),down:i((a=1)=>`${t}J`.repeat(a),"down"),line:`${t}2K`,lineEnd:`${t}K`,lineStart:`${t}1K`,lines(a){let u="";for(let l=0;l<a;l++)u+=this.line+(l<a-1?r.up():"");return a&&(u+=r.left),u}};return Ps={cursor:r,scroll:o,erase:s,beep:n},Ps}i($y,"requireSrc");var Xe=$y(),Yo={exports:{}},qc;function Ty(){if(qc)return Yo.exports;qc=1;let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes("--no-color"))&&(!!n.FORCE_COLOR||t.includes("--color")||e.platform==="win32"||(e.stdout||{}).isTTY&&n.TERM!=="dumb"||!!n.CI),o=i((u,l,c=u)=>d=>{let f=""+d,h=f.indexOf(l,u.length);return~h?u+s(f,l,c,h)+l:u+f+l},"formatter"),s=i((u,l,c,d)=>{let f="",h=0;do f+=u.substring(h,d)+c,h=d+l.length,d=u.indexOf(l,h);while(~d);return f+u.substring(h)},"replaceClose"),a=i((u=r)=>{let l=u?o:()=>String;return{isColorSupported:u,reset:l("\x1B[0m","\x1B[0m"),bold:l("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:l("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:l("\x1B[3m","\x1B[23m"),underline:l("\x1B[4m","\x1B[24m"),inverse:l("\x1B[7m","\x1B[27m"),hidden:l("\x1B[8m","\x1B[28m"),strikethrough:l("\x1B[9m","\x1B[29m"),black:l("\x1B[30m","\x1B[39m"),red:l("\x1B[31m","\x1B[39m"),green:l("\x1B[32m","\x1B[39m"),yellow:l("\x1B[33m","\x1B[39m"),blue:l("\x1B[34m","\x1B[39m"),magenta:l("\x1B[35m","\x1B[39m"),cyan:l("\x1B[36m","\x1B[39m"),white:l("\x1B[37m","\x1B[39m"),gray:l("\x1B[90m","\x1B[39m"),bgBlack:l("\x1B[40m","\x1B[49m"),bgRed:l("\x1B[41m","\x1B[49m"),bgGreen:l("\x1B[42m","\x1B[49m"),bgYellow:l("\x1B[43m","\x1B[49m"),bgBlue:l("\x1B[44m","\x1B[49m"),bgMagenta:l("\x1B[45m","\x1B[49m"),bgCyan:l("\x1B[46m","\x1B[49m"),bgWhite:l("\x1B[47m","\x1B[49m"),blackBright:l("\x1B[90m","\x1B[39m"),redBright:l("\x1B[91m","\x1B[39m"),greenBright:l("\x1B[92m","\x1B[39m"),yellowBright:l("\x1B[93m","\x1B[39m"),blueBright:l("\x1B[94m","\x1B[39m"),magentaBright:l("\x1B[95m","\x1B[39m"),cyanBright:l("\x1B[96m","\x1B[39m"),whiteBright:l("\x1B[97m","\x1B[39m"),bgBlackBright:l("\x1B[100m","\x1B[49m"),bgRedBright:l("\x1B[101m","\x1B[49m"),bgGreenBright:l("\x1B[102m","\x1B[49m"),bgYellowBright:l("\x1B[103m","\x1B[49m"),bgBlueBright:l("\x1B[104m","\x1B[49m"),bgMagentaBright:l("\x1B[105m","\x1B[49m"),bgCyanBright:l("\x1B[106m","\x1B[49m"),bgWhiteBright:l("\x1B[107m","\x1B[49m")}},"createColors");return Yo.exports=a(),Yo.exports.createColors=a,Yo.exports}i(Ty,"requirePicocolors");var Sy=Ty(),L=rn(Sy);function By({onlyFirst:e=!1}={}){const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(t,e?void 0:"g")}i(By,"DD");const Oy=By();function Uc(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(Oy,"")}i(Uc,"P$1");function Zc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}i(Zc,"L$1");var Vc={exports:{}};(function(e){var t={};e.exports=t,t.eastAsianWidth=function(r){var o=r.charCodeAt(0),s=r.length==2?r.charCodeAt(1):0,a=o;return 55296<=o&&o<=56319&&56320<=s&&s<=57343&&(o&=1023,s&=1023,a=o<<10|s,a+=65536),a==12288||65281<=a&&a<=65376||65504<=a&&a<=65510?"F":a==8361||65377<=a&&a<=65470||65474<=a&&a<=65479||65482<=a&&a<=65487||65490<=a&&a<=65495||65498<=a&&a<=65500||65512<=a&&a<=65518?"H":4352<=a&&a<=4447||4515<=a&&a<=4519||4602<=a&&a<=4607||9001<=a&&a<=9002||11904<=a&&a<=11929||11931<=a&&a<=12019||12032<=a&&a<=12245||12272<=a&&a<=12283||12289<=a&&a<=12350||12353<=a&&a<=12438||12441<=a&&a<=12543||12549<=a&&a<=12589||12593<=a&&a<=12686||12688<=a&&a<=12730||12736<=a&&a<=12771||12784<=a&&a<=12830||12832<=a&&a<=12871||12880<=a&&a<=13054||13056<=a&&a<=19903||19968<=a&&a<=42124||42128<=a&&a<=42182||43360<=a&&a<=43388||44032<=a&&a<=55203||55216<=a&&a<=55238||55243<=a&&a<=55291||63744<=a&&a<=64255||65040<=a&&a<=65049||65072<=a&&a<=65106||65108<=a&&a<=65126||65128<=a&&a<=65131||110592<=a&&a<=110593||127488<=a&&a<=127490||127504<=a&&a<=127546||127552<=a&&a<=127560||127568<=a&&a<=127569||131072<=a&&a<=194367||177984<=a&&a<=196605||196608<=a&&a<=262141?"W":32<=a&&a<=126||162<=a&&a<=163||165<=a&&a<=166||a==172||a==175||10214<=a&&a<=10221||10629<=a&&a<=10630?"Na":a==161||a==164||167<=a&&a<=168||a==170||173<=a&&a<=174||176<=a&&a<=180||182<=a&&a<=186||188<=a&&a<=191||a==198||a==208||215<=a&&a<=216||222<=a&&a<=225||a==230||232<=a&&a<=234||236<=a&&a<=237||a==240||242<=a&&a<=243||247<=a&&a<=250||a==252||a==254||a==257||a==273||a==275||a==283||294<=a&&a<=295||a==299||305<=a&&a<=307||a==312||319<=a&&a<=322||a==324||328<=a&&a<=331||a==333||338<=a&&a<=339||358<=a&&a<=359||a==363||a==462||a==464||a==466||a==468||a==470||a==472||a==474||a==476||a==593||a==609||a==708||a==711||713<=a&&a<=715||a==717||a==720||728<=a&&a<=731||a==733||a==735||768<=a&&a<=879||913<=a&&a<=929||931<=a&&a<=937||945<=a&&a<=961||963<=a&&a<=969||a==1025||1040<=a&&a<=1103||a==1105||a==8208||8211<=a&&a<=8214||8216<=a&&a<=8217||8220<=a&&a<=8221||8224<=a&&a<=8226||8228<=a&&a<=8231||a==8240||8242<=a&&a<=8243||a==8245||a==8251||a==8254||a==8308||a==8319||8321<=a&&a<=8324||a==8364||a==8451||a==8453||a==8457||a==8467||a==8470||8481<=a&&a<=8482||a==8486||a==8491||8531<=a&&a<=8532||8539<=a&&a<=8542||8544<=a&&a<=8555||8560<=a&&a<=8569||a==8585||8592<=a&&a<=8601||8632<=a&&a<=8633||a==8658||a==8660||a==8679||a==8704||8706<=a&&a<=8707||8711<=a&&a<=8712||a==8715||a==8719||a==8721||a==8725||a==8730||8733<=a&&a<=8736||a==8739||a==8741||8743<=a&&a<=8748||a==8750||8756<=a&&a<=8759||8764<=a&&a<=8765||a==8776||a==8780||a==8786||8800<=a&&a<=8801||8804<=a&&a<=8807||8810<=a&&a<=8811||8814<=a&&a<=8815||8834<=a&&a<=8835||8838<=a&&a<=8839||a==8853||a==8857||a==8869||a==8895||a==8978||9312<=a&&a<=9449||9451<=a&&a<=9547||9552<=a&&a<=9587||9600<=a&&a<=9615||9618<=a&&a<=9621||9632<=a&&a<=9633||9635<=a&&a<=9641||9650<=a&&a<=9651||9654<=a&&a<=9655||9660<=a&&a<=9661||9664<=a&&a<=9665||9670<=a&&a<=9672||a==9675||9678<=a&&a<=9681||9698<=a&&a<=9701||a==9711||9733<=a&&a<=9734||a==9737||9742<=a&&a<=9743||9748<=a&&a<=9749||a==9756||a==9758||a==9792||a==9794||9824<=a&&a<=9825||9827<=a&&a<=9829||9831<=a&&a<=9834||9836<=a&&a<=9837||a==9839||9886<=a&&a<=9887||9918<=a&&a<=9919||9924<=a&&a<=9933||9935<=a&&a<=9953||a==9955||9960<=a&&a<=9983||a==10045||a==10071||10102<=a&&a<=10111||11093<=a&&a<=11097||12872<=a&&a<=12879||57344<=a&&a<=63743||65024<=a&&a<=65039||a==65533||127232<=a&&a<=127242||127248<=a&&a<=127277||127280<=a&&a<=127337||127344<=a&&a<=127386||917760<=a&&a<=917999||983040<=a&&a<=1048573||1048576<=a&&a<=1114109?"A":"N"},t.characterLength=function(r){var o=this.eastAsianWidth(r);return o=="F"||o=="W"||o=="A"?2:1};function n(r){return r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}i(n,"t"),t.length=function(r){for(var o=n(r),s=0,a=0;a<o.length;a++)s=s+this.characterLength(o[a]);return s},t.slice=function(r,o,s){textLen=t.length(r),o=o||0,s=s||1,o<0&&(o=textLen+o),s<0&&(s=textLen+s);for(var a="",u=0,l=n(r),c=0;c<l.length;c++){var d=l[c],f=t.length(d);if(u>=o-(f==2?1:0))if(u+f<=s)a+=d;else break;u+=f}return a}})(Vc);var Ry=Vc.exports;const Ny=Zc(Ry);var Py=i(function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g},"FD");const My=Zc(Py);function no(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=Uc(e),e.length===0))return 0;e=e.replace(My()," ");const n=t.ambiguousIsNarrow?1:2;let r=0;for(const o of e){const s=o.codePointAt(0);if(!(s<=31||s>=127&&s<=159||s>=768&&s<=879))switch(Ny.eastAsianWidth(o)){case"F":case"W":r+=2;break;case"A":r+=n;break;default:r+=1}}return r}i(no,"p");const Ms=10,Gc=i((e=0)=>t=>`\x1B[${t+e}m`,"N"),Wc=i((e=0)=>t=>`\x1B[${38+e};5;${t}m`,"I"),Hc=i((e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,"R"),Te={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(Te.modifier);const jy=Object.keys(Te.color),zy=Object.keys(Te.bgColor);[...jy,...zy];function Ly(){const e=new Map;for(const[t,n]of Object.entries(Te)){for(const[r,o]of Object.entries(n))Te[r]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[r]=Te[r],e.set(o[0],o[1]);Object.defineProperty(Te,t,{value:n,enumerable:!1})}return Object.defineProperty(Te,"codes",{value:e,enumerable:!1}),Te.color.close="\x1B[39m",Te.bgColor.close="\x1B[49m",Te.color.ansi=Gc(),Te.color.ansi256=Wc(),Te.color.ansi16m=Hc(),Te.bgColor.ansi=Gc(Ms),Te.bgColor.ansi256=Wc(Ms),Te.bgColor.ansi16m=Hc(Ms),Object.defineProperties(Te,{rgbToAnsi256:{value:i((t,n,r)=>t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5),"value"),enumerable:!1},hexToRgb:{value:i(t=>{const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));const o=Number.parseInt(r,16);return[o>>16&255,o>>8&255,o&255]},"value"),enumerable:!1},hexToAnsi256:{value:i(t=>Te.rgbToAnsi256(...Te.hexToRgb(t)),"value"),enumerable:!1},ansi256ToAnsi:{value:i(t=>{if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,o;if(t>=232)n=((t-232)*10+8)/255,r=n,o=n;else{t-=16;const u=t%36;n=Math.floor(t/36)/5,r=Math.floor(u/6)/5,o=u%6/5}const s=Math.max(n,r,o)*2;if(s===0)return 30;let a=30+(Math.round(o)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(a+=60),a},"value"),enumerable:!1},rgbToAnsi:{value:i((t,n,r)=>Te.ansi256ToAnsi(Te.rgbToAnsi256(t,n,r)),"value"),enumerable:!1},hexToAnsi:{value:i(t=>Te.ansi256ToAnsi(Te.hexToAnsi256(t)),"value"),enumerable:!1}}),Te}i(Ly,"rD");const qy=Ly(),Xo=new Set(["\x1B","\x9B"]),Uy=39,js="\x07",Jc="[",Zy="]",Kc="m",zs=`${Zy}8;;`,Yc=i(e=>`${Xo.values().next().value}${Jc}${e}${Kc}`,"z"),Xc=i(e=>`${Xo.values().next().value}${zs}${e}${js}`,"K"),Vy=i(e=>e.split(" ").map(t=>no(t)),"aD"),Ls=i((e,t,n)=>{const r=[...t];let o=!1,s=!1,a=no(Uc(e[e.length-1]));for(const[u,l]of r.entries()){const c=no(l);if(a+c<=n?e[e.length-1]+=l:(e.push(l),a=0),Xo.has(l)&&(o=!0,s=r.slice(u+1).join("").startsWith(zs)),o){s?l===js&&(o=!1,s=!1):l===Kc&&(o=!1);continue}a+=c,a===n&&u<r.length-1&&(e.push(""),a=0)}!a&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},"k$1"),Gy=i(e=>{const t=e.split(" ");let n=t.length;for(;n>0&&!(no(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},"hD"),Wy=i((e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",o,s;const a=Vy(e);let u=[""];for(const[c,d]of e.split(" ").entries()){n.trim!==!1&&(u[u.length-1]=u[u.length-1].trimStart());let f=no(u[u.length-1]);if(c!==0&&(f>=t&&(n.wordWrap===!1||n.trim===!1)&&(u.push(""),f=0),(f>0||n.trim===!1)&&(u[u.length-1]+=" ",f++)),n.hard&&a[c]>t){const h=t-f,D=1+Math.floor((a[c]-h-1)/t);Math.floor((a[c]-1)/t)<D&&u.push(""),Ls(u,d,t);continue}if(f+a[c]>t&&f>0&&a[c]>0){if(n.wordWrap===!1&&f<t){Ls(u,d,t);continue}u.push("")}if(f+a[c]>t&&n.wordWrap===!1){Ls(u,d,t);continue}u[u.length-1]+=d}n.trim!==!1&&(u=u.map(c=>Gy(c)));const l=[...u.join(`
24
+ ${t}`,"wrappedToString"),Fv=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Ev=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),xv=i((e,t,n)=>{const r=n===""?"":`with ${n.trim()}() `,o=wv.bind(null,r,t.toString());Object.defineProperty(o,"name",Ev),Object.defineProperty(e,"toString",{...Fv,value:o})},"changeToString");function kv(e,t,{ignoreNonConfigurable:n=!1}={}){const{name:r}=e;for(const o of Reflect.ownKeys(t))_v(e,t,o,n);return Cv(e,t),xv(e,t,r),e}i(kv,"mimicFunction");const Go=new WeakMap,Ec=i((e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,r=0;const o=e.displayName||e.name||"<anonymous>",s=i(function(...a){if(Go.set(s,++r),r===1)n=e.apply(this,a),e=null;else if(t.throw===!0)throw new Error(`Function \`${o}\` can only be called once`);return n},"onetime2");return kv(s,e),Go.set(s,r),s},"onetime");Ec.callCount=e=>{if(!Go.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Go.get(e)};const Iv=i(()=>{const e=kc-xc+1;return Array.from({length:e},Av)},"getRealtimeSignals"),Av=i((e,t)=>({name:`SIGRT${t+1}`,number:xc+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),"getRealtimeSignal"),xc=34,kc=64,$v=[{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"}],Ic=i(()=>{const e=Iv();return[...$v,...e].map(Tv)},"getSignals"),Tv=i(({name:e,number:t,description:n,action:r,forced:o=!1,standard:s})=>{const{signals:{[e]:a}}=wl,u=a!==void 0;return{name:e,number:u?a:t,description:n,supported:u,action:r,forced:o,standard:s}},"normalizeSignal"),Sv=i(()=>{const e=Ic();return Object.fromEntries(e.map(Bv))},"getSignalsByName"),Bv=i(({name:e,number:t,description:n,supported:r,action:o,forced:s,standard:a})=>[e,{name:e,number:t,description:n,supported:r,action:o,forced:s,standard:a}],"getSignalByName"),Ov=Sv(),Rv=i(()=>{const e=Ic(),t=kc+1,n=Array.from({length:t},(r,o)=>Nv(o,e));return Object.assign({},...n)},"getSignalsByNumber"),Nv=i((e,t)=>{const n=Pv(e,t);if(n===void 0)return{};const{name:r,description:o,supported:s,action:a,forced:u,standard:l}=n;return{[e]:{name:r,number:e,description:o,supported:s,action:a,forced:u,standard:l}}},"getSignalByNumber"),Pv=i((e,t)=>{const n=t.find(({name:r})=>wl.signals[r]===e);return n!==void 0?n:t.find(r=>r.number===e)},"findSignalByNumber");Rv();const Mv=i(({timedOut:e,timeout:t,errorCode:n,signal:r,signalDescription:o,exitCode:s,isCanceled:a})=>e?`timed out after ${t} milliseconds`:a?"was canceled":n!==void 0?`failed with ${n}`:r!==void 0?`was killed with ${r} (${o})`:s!==void 0?`failed with exit code ${s}`:"failed","getErrorPrefix"),Ac=i(({stdout:e,stderr:t,all:n,error:r,signal:o,exitCode:s,command:a,escapedCommand:u,timedOut:l,isCanceled:c,killed:d,parsed:{options:{timeout:f,cwd:h=Le.cwd()}}})=>{s=s===null?void 0:s,o=o===null?void 0:o;const D=o===void 0?void 0:Ov[o].description,m=r&&r.code,y=`Command ${Mv({timedOut:l,timeout:f,errorCode:m,signal:o,signalDescription:D,exitCode:s,isCanceled:c})}: ${a}`,b=Object.prototype.toString.call(r)==="[object Error]",C=b?`${y}
25
+ ${r.message}`:y,F=[C,t,e].filter(Boolean).join(`
26
+ `);return b?(r.originalMessage=r.message,r.message=F):r=new Error(F),r.shortMessage=C,r.command=a,r.escapedCommand=u,r.exitCode=s,r.signal=o,r.signalDescription=D,r.stdout=e,r.stderr=t,r.cwd=h,n!==void 0&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!l,r.isCanceled=c,r.killed=d&&!l,r},"makeError"),Wo=["stdin","stdout","stderr"],jv=i(e=>Wo.some(t=>e[t]!==void 0),"hasAlias"),zv=i(e=>{if(!e)return;const{stdio:t}=e;if(t===void 0)return Wo.map(r=>e[r]);if(jv(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Wo.map(r=>`\`${r}\``).join(", ")}`);if(typeof t=="string")return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const n=Math.max(t.length,Wo.length);return Array.from({length:n},(r,o)=>t[o])},"normalizeStdio");var an={exports:{}},xs={exports:{}},$c;function Lv(){return $c||($c=1,(function(e){e.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"],process.platform!=="win32"&&e.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),process.platform==="linux"&&e.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")})(xs)),xs.exports}i(Lv,"requireSignals");var Tc;function qv(){if(Tc)return an.exports;Tc=1;var e=Zt.process;const t=i(function(y){return y&&typeof y=="object"&&typeof y.removeListener=="function"&&typeof y.emit=="function"&&typeof y.reallyExit=="function"&&typeof y.listeners=="function"&&typeof y.kill=="function"&&typeof y.pid=="number"&&typeof y.on=="function"},"processOk");if(!t(e))an.exports=function(){return function(){}};else{var n=PD,r=Lv(),o=/^win/i.test(e.platform),s=MD;typeof s!="function"&&(s=s.EventEmitter);var a;e.__signal_exit_emitter__?a=e.__signal_exit_emitter__:(a=e.__signal_exit_emitter__=new s,a.count=0,a.emitted={}),a.infinite||(a.setMaxListeners(1/0),a.infinite=!0),an.exports=function(y,b){if(!t(Zt.process))return function(){};n.equal(typeof y,"function","a callback must be provided for exit handler"),d===!1&&f();var C="exit";b&&b.alwaysLast&&(C="afterexit");var F=i(function(){a.removeListener(C,y),a.listeners("exit").length===0&&a.listeners("afterexit").length===0&&u()},"remove");return a.on(C,y),F};var u=i(function(){!d||!t(Zt.process)||(d=!1,r.forEach(function(b){try{e.removeListener(b,c[b])}catch{}}),e.emit=m,e.reallyExit=h,a.count-=1)},"unload2");an.exports.unload=u;var l=i(function(b,C,F){a.emitted[b]||(a.emitted[b]=!0,a.emit(b,C,F))},"emit2"),c={};r.forEach(function(y){c[y]=i(function(){if(t(Zt.process)){var C=e.listeners(y);C.length===a.count&&(u(),l("exit",null,y),l("afterexit",null,y),o&&y==="SIGHUP"&&(y="SIGINT"),e.kill(e.pid,y))}},"listener")}),an.exports.signals=function(){return r};var d=!1,f=i(function(){d||!t(Zt.process)||(d=!0,a.count+=1,r=r.filter(function(b){try{return e.on(b,c[b]),!0}catch{return!1}}),e.emit=v,e.reallyExit=D)},"load2");an.exports.load=f;var h=e.reallyExit,D=i(function(b){t(Zt.process)&&(e.exitCode=b||0,l("exit",e.exitCode,null),l("afterexit",e.exitCode,null),h.call(e,e.exitCode))},"processReallyExit2"),m=e.emit,v=i(function(b,C){if(b==="exit"&&t(Zt.process)){C!==void 0&&(e.exitCode=C);var F=m.apply(this,arguments);return l("exit",e.exitCode,null),l("afterexit",e.exitCode,null),F}else return m.apply(this,arguments)},"processEmit2")}return an.exports}i(qv,"requireSignalExit");var Uv=qv(),Zv=rn(Uv);const Vv=1e3*5,Gv=i((e,t="SIGTERM",n={})=>{const r=e(t);return Wv(e,t,n,r),r},"spawnedKill"),Wv=i((e,t,n,r)=>{if(!Hv(t,n,r))return;const o=Kv(n),s=setTimeout(()=>{e("SIGKILL")},o);s.unref&&s.unref()},"setKillTimeout"),Hv=i((e,{forceKillAfterTimeout:t},n)=>Jv(e)&&t!==!1&&n,"shouldForceKill"),Jv=i(e=>e===ND.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM","isSigterm"),Kv=i(({forceKillAfterTimeout:e=!0})=>{if(e===!0)return Vv;if(!Number.isFinite(e)||e<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`);return e},"getForceKillAfterTimeout"),Yv=i((e,t)=>{e.kill()&&(t.isCanceled=!0)},"spawnedCancel"),Xv=i((e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},"timeoutKill"),Qv=i((e,{timeout:t,killSignal:n="SIGTERM"},r)=>{if(t===0||t===void 0)return r;let o;const s=new Promise((u,l)=>{o=setTimeout(()=>{Xv(e,n,l)},t)}),a=r.finally(()=>{clearTimeout(o)});return Promise.race([s,a])},"setupTimeout"),ey=i(({timeout:e})=>{if(e!==void 0&&(!Number.isFinite(e)||e<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`)},"validateTimeout"),ty=i(async(e,{cleanup:t,detached:n},r)=>{if(!t||n)return r;const o=Zv(()=>{e.kill()});return r.finally(()=>{o()})},"setExitHandler");function Sc(e){return e!==null&&typeof e=="object"&&typeof e.pipe=="function"}i(Sc,"isStream");function Bc(e){return Sc(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object"}i(Bc,"isWritableStream");const ny=i(e=>e instanceof OD&&typeof e.then=="function","isExecaChildProcess"),ks=i((e,t,n)=>{if(typeof n=="string")return e[t].pipe(jD(n)),e;if(Bc(n))return e[t].pipe(n),e;if(!ny(n))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!Bc(n.stdin))throw new TypeError("The target child process's stdin must be available.");return e[t].pipe(n.stdin),n},"pipeToTarget"),ry=i(e=>{e.stdout!==null&&(e.pipeStdout=ks.bind(void 0,e,"stdout")),e.stderr!==null&&(e.pipeStderr=ks.bind(void 0,e,"stderr")),e.all!==void 0&&(e.pipeAll=ks.bind(void 0,e,"all"))},"addPipeMethods");var $n={exports:{}},Is,Oc;function oy(){if(Oc)return Is;Oc=1;const{PassThrough:e}=ss;return Is=i(t=>{t={...t};const{array:n}=t;let{encoding:r}=t;const o=r==="buffer";let s=!1;n?s=!(r||o):r=r||"utf8",o&&(r=null);const a=new e({objectMode:s});r&&a.setEncoding(r);let u=0;const l=[];return a.on("data",c=>{l.push(c),s?u=l.length:u+=c.length}),a.getBufferedValue=()=>n?l:o?Buffer.concat(l,u):l.join(""),a.getBufferedLength=()=>u,a},"bufferStream"),Is}i(oy,"requireBufferStream");var Rc;function ay(){if(Rc)return $n.exports;Rc=1;const{constants:e}=LD,t=ss,{promisify:n}=qD,r=oy(),o=n(t.pipeline),u=class u extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};i(u,"MaxBufferError");let s=u;async function a(l,c){if(!l)throw new Error("Expected a stream");c={maxBuffer:1/0,...c};const{maxBuffer:d}=c,f=r(c);return await new Promise((h,D)=>{const m=i(v=>{v&&f.getBufferedLength()<=e.MAX_LENGTH&&(v.bufferedData=f.getBufferedValue()),D(v)},"rejectPromise");(async()=>{try{await o(l,f),h()}catch(v){m(v)}})(),f.on("data",()=>{f.getBufferedLength()>d&&m(new s)})}),f.getBufferedValue()}return i(a,"getStream"),$n.exports=a,$n.exports.buffer=(l,c)=>a(l,{...c,encoding:"buffer"}),$n.exports.array=(l,c)=>a(l,{...c,array:!0}),$n.exports.MaxBufferError=s,$n.exports}i(ay,"requireGetStream");var sy=ay(),Nc=rn(sy),As,Pc;function iy(){if(Pc)return As;Pc=1;const{PassThrough:e}=ss;return As=i(function(){var t=[],n=new e({objectMode:!0});return n.setMaxListeners(0),n.add=r,n.isEmpty=o,n.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(r),n;function r(a){return Array.isArray(a)?(a.forEach(r),this):(t.push(a),a.once("end",s.bind(null,a)),a.once("error",n.emit.bind(n,"error")),a.pipe(n,{end:!1}),this)}i(r,"add");function o(){return t.length==0}i(o,"isEmpty");function s(a){t=t.filter(function(u){return u!==a}),!t.length&&n.readable&&n.end()}i(s,"remove")},"mergeStream$1"),As}i(iy,"requireMergeStream");var uy=iy(),ly=rn(uy);const cy=i(e=>{if(e!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},"validateInputOptions"),dy=i(({input:e,inputFile:t})=>typeof t!="string"?e:(cy(e),zD(t)),"getInput"),py=i((e,t)=>{const n=dy(t);n!==void 0&&(Sc(n)?n.pipe(e.stdin):e.stdin.end(n))},"handleInput"),fy=i((e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;const n=ly();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},"makeAllStream"),$s=i(async(e,t)=>{if(!(!e||t===void 0)){e.destroy();try{return await t}catch(n){return n.bufferedData}}},"getBufferedData"),Ts=i((e,{encoding:t,buffer:n,maxBuffer:r})=>{if(!(!e||!n))return t?Nc(e,{encoding:t,maxBuffer:r}):Nc.buffer(e,{maxBuffer:r})},"getStreamPromise"),my=i(async({stdout:e,stderr:t,all:n},{encoding:r,buffer:o,maxBuffer:s},a)=>{const u=Ts(e,{encoding:r,buffer:o,maxBuffer:s}),l=Ts(t,{encoding:r,buffer:o,maxBuffer:s}),c=Ts(n,{encoding:r,buffer:o,maxBuffer:s*2});try{return await Promise.all([a,u,l,c])}catch(d){return Promise.all([{error:d,signal:d.signal,timedOut:d.timedOut},$s(e,u),$s(t,l),$s(n,c)])}},"getSpawnedResult"),hy=(async()=>{})().constructor.prototype,Dy=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(hy,e)]),Mc=i((e,t)=>{for(const[n,r]of Dy){const o=typeof t=="function"?(...s)=>Reflect.apply(r.value,t(),s):r.value.bind(t);Reflect.defineProperty(e,n,{...r,value:o})}},"mergePromise"),gy=i(e=>new Promise((t,n)=>{e.on("exit",(r,o)=>{t({exitCode:r,signal:o})}),e.on("error",r=>{n(r)}),e.stdin&&e.stdin.on("error",r=>{n(r)})}),"getSpawnedPromise"),jc=i((e,t=[])=>Array.isArray(t)?[e,...t]:[e],"normalizeArgs"),vy=/^[\w.-]+$/,yy=/"/g,_y=i(e=>typeof e!="string"||vy.test(e)?e:`"${e.replace(yy,'\\"')}"`,"escapeArg"),by=i((e,t)=>jc(e,t).join(" "),"joinCommand"),Cy=i((e,t)=>jc(e,t).map(n=>_y(n)).join(" "),"getEscapedCommand"),wy=ZD("execa").enabled,Ho=i((e,t)=>String(e).padStart(t,"0"),"padField"),Fy=i(()=>{const e=new Date;return`${Ho(e.getHours(),2)}:${Ho(e.getMinutes(),2)}:${Ho(e.getSeconds(),2)}.${Ho(e.getMilliseconds(),3)}`},"getTimestamp"),Ey=i((e,{verbose:t})=>{t&&Le.stderr.write(`[${Fy()}] ${e}
27
+ `)},"logCommand"),xy=1e3*1e3*100,ky=i(({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:o})=>{const s=t?{...Le.env,...e}:e;return n?yv({env:s,cwd:r,execPath:o}):s},"getEnv"),Iy=i((e,t,n={})=>{const r=mv._parse(e,t,n);return e=r.command,t=r.args,n=r.options,n={maxBuffer:xy,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:n.cwd||Le.cwd(),execPath:Le.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:wy,...n},n.env=ky(n),n.stdio=zv(n),Le.platform==="win32"&&In.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},"handleArguments"),Ss=i((e,t,n)=>typeof t!="string"&&!BD.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?hv(t):t,"handleOutput");function Je(e,t,n){const r=Iy(e,t,n),o=by(e,t),s=Cy(e,t);Ey(s,r.options),ey(r.options);let a;try{a=vl.spawn(r.file,r.args,r.options)}catch(D){const m=new vl.ChildProcess,v=Promise.reject(Ac({error:D,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return Mc(m,v),m}const u=gy(a),l=Qv(a,r.options,u),c=ty(a,r.options,l),d={isCanceled:!1};a.kill=Gv.bind(null,a.kill.bind(a)),a.cancel=Yv.bind(null,a,d);const h=Ec(i(async()=>{const[{error:D,exitCode:m,signal:v,timedOut:y},b,C,F]=await my(a,r.options,c),E=Ss(r.options,b),T=Ss(r.options,C),O=Ss(r.options,F);if(D||m!==0||v!==null){const $=Ac({error:D,exitCode:m,signal:v,stdout:E,stderr:T,all:O,command:o,escapedCommand:s,parsed:r,timedOut:y,isCanceled:d.isCanceled||(r.options.signal?r.options.signal.aborted:!1),killed:a.killed});if(!r.options.reject)return $;throw $}return{command:o,escapedCommand:s,exitCode:0,stdout:E,stderr:T,all:O,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}},"handlePromise"));return py(a,r.options),a.all=fy(a,r.options),ry(a),Mc(a,h),a}i(Je,"execa");let sn=!0;const Tn=typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{};let to=0;if(Tn.process&&Tn.process.env&&Tn.process.stdout){const{FORCE_COLOR:e,NODE_DISABLE_COLORS:t,NO_COLOR:n,TERM:r,COLORTERM:o}=Tn.process.env;t||n||e==="0"?sn=!1:e==="1"||e==="2"||e==="3"?sn=!0:r==="dumb"?sn=!1:"CI"in Tn.process.env&&["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(s=>s in Tn.process.env)?sn=!0:sn=process.stdout.isTTY,sn&&(process.platform==="win32"||o&&(o==="truecolor"||o==="24bit")?to=3:r&&(r.endsWith("-256color")||r.endsWith("256"))?to=2:to=1)}let Bs={enabled:sn,supportLevel:to};function Sn(e,t,n=1){const r=`\x1B[${e}m`,o=`\x1B[${t}m`,s=new RegExp(`\\x1b\\[${t}m`,"g");return a=>Bs.enabled&&Bs.supportLevel>=n?r+(""+a).replace(s,r)+o:""+a}i(Sn,"kolorist");const Os=Sn(2,22),Jo=Sn(30,39),Rs=Sn(31,39),St=Sn(32,39),Ns=Sn(33,39),Ko=Sn(46,49);var Ay=Object.freeze({__proto__:null,bgCyan:Ko,black:Jo,dim:Os,green:St,options:Bs,red:Rs,yellow:Ns});async function zc(e){try{return process.platform==="darwin"?await Je("pbcopy",{input:e}):process.platform==="win32"?await Je("clip",{input:e}):await Je("xclip",["-selection","clipboard"],{input:e}).catch(()=>Je("xsel",["--clipboard","--input"],{input:e})),!0}catch{return!1}}i(zc,"copyToClipboard");var Ps,Lc;function $y(){if(Lc)return Ps;Lc=1;const e="\x1B",t=`${e}[`,n="\x07",r={to(a,u){return u?`${t}${u+1};${a+1}H`:`${t}${a+1}G`},move(a,u){let l="";return a<0?l+=`${t}${-a}D`:a>0&&(l+=`${t}${a}C`),u<0?l+=`${t}${-u}A`:u>0&&(l+=`${t}${u}B`),l},up:i((a=1)=>`${t}${a}A`,"up"),down:i((a=1)=>`${t}${a}B`,"down"),forward:i((a=1)=>`${t}${a}C`,"forward"),backward:i((a=1)=>`${t}${a}D`,"backward"),nextLine:i((a=1)=>`${t}E`.repeat(a),"nextLine"),prevLine:i((a=1)=>`${t}F`.repeat(a),"prevLine"),left:`${t}G`,hide:`${t}?25l`,show:`${t}?25h`,save:`${e}7`,restore:`${e}8`},o={up:i((a=1)=>`${t}S`.repeat(a),"up"),down:i((a=1)=>`${t}T`.repeat(a),"down")},s={screen:`${t}2J`,up:i((a=1)=>`${t}1J`.repeat(a),"up"),down:i((a=1)=>`${t}J`.repeat(a),"down"),line:`${t}2K`,lineEnd:`${t}K`,lineStart:`${t}1K`,lines(a){let u="";for(let l=0;l<a;l++)u+=this.line+(l<a-1?r.up():"");return a&&(u+=r.left),u}};return Ps={cursor:r,scroll:o,erase:s,beep:n},Ps}i($y,"requireSrc");var Xe=$y(),Yo={exports:{}},qc;function Ty(){if(qc)return Yo.exports;qc=1;let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes("--no-color"))&&(!!n.FORCE_COLOR||t.includes("--color")||e.platform==="win32"||(e.stdout||{}).isTTY&&n.TERM!=="dumb"||!!n.CI),o=i((u,l,c=u)=>d=>{let f=""+d,h=f.indexOf(l,u.length);return~h?u+s(f,l,c,h)+l:u+f+l},"formatter"),s=i((u,l,c,d)=>{let f="",h=0;do f+=u.substring(h,d)+c,h=d+l.length,d=u.indexOf(l,h);while(~d);return f+u.substring(h)},"replaceClose"),a=i((u=r)=>{let l=u?o:()=>String;return{isColorSupported:u,reset:l("\x1B[0m","\x1B[0m"),bold:l("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:l("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:l("\x1B[3m","\x1B[23m"),underline:l("\x1B[4m","\x1B[24m"),inverse:l("\x1B[7m","\x1B[27m"),hidden:l("\x1B[8m","\x1B[28m"),strikethrough:l("\x1B[9m","\x1B[29m"),black:l("\x1B[30m","\x1B[39m"),red:l("\x1B[31m","\x1B[39m"),green:l("\x1B[32m","\x1B[39m"),yellow:l("\x1B[33m","\x1B[39m"),blue:l("\x1B[34m","\x1B[39m"),magenta:l("\x1B[35m","\x1B[39m"),cyan:l("\x1B[36m","\x1B[39m"),white:l("\x1B[37m","\x1B[39m"),gray:l("\x1B[90m","\x1B[39m"),bgBlack:l("\x1B[40m","\x1B[49m"),bgRed:l("\x1B[41m","\x1B[49m"),bgGreen:l("\x1B[42m","\x1B[49m"),bgYellow:l("\x1B[43m","\x1B[49m"),bgBlue:l("\x1B[44m","\x1B[49m"),bgMagenta:l("\x1B[45m","\x1B[49m"),bgCyan:l("\x1B[46m","\x1B[49m"),bgWhite:l("\x1B[47m","\x1B[49m"),blackBright:l("\x1B[90m","\x1B[39m"),redBright:l("\x1B[91m","\x1B[39m"),greenBright:l("\x1B[92m","\x1B[39m"),yellowBright:l("\x1B[93m","\x1B[39m"),blueBright:l("\x1B[94m","\x1B[39m"),magentaBright:l("\x1B[95m","\x1B[39m"),cyanBright:l("\x1B[96m","\x1B[39m"),whiteBright:l("\x1B[97m","\x1B[39m"),bgBlackBright:l("\x1B[100m","\x1B[49m"),bgRedBright:l("\x1B[101m","\x1B[49m"),bgGreenBright:l("\x1B[102m","\x1B[49m"),bgYellowBright:l("\x1B[103m","\x1B[49m"),bgBlueBright:l("\x1B[104m","\x1B[49m"),bgMagentaBright:l("\x1B[105m","\x1B[49m"),bgCyanBright:l("\x1B[106m","\x1B[49m"),bgWhiteBright:l("\x1B[107m","\x1B[49m")}},"createColors");return Yo.exports=a(),Yo.exports.createColors=a,Yo.exports}i(Ty,"requirePicocolors");var Sy=Ty(),L=rn(Sy);function By({onlyFirst:e=!1}={}){const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(t,e?void 0:"g")}i(By,"DD");const Oy=By();function Uc(e){if(typeof e!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(Oy,"")}i(Uc,"P$1");function Zc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}i(Zc,"L$1");var Vc={exports:{}};(function(e){var t={};e.exports=t,t.eastAsianWidth=function(r){var o=r.charCodeAt(0),s=r.length==2?r.charCodeAt(1):0,a=o;return 55296<=o&&o<=56319&&56320<=s&&s<=57343&&(o&=1023,s&=1023,a=o<<10|s,a+=65536),a==12288||65281<=a&&a<=65376||65504<=a&&a<=65510?"F":a==8361||65377<=a&&a<=65470||65474<=a&&a<=65479||65482<=a&&a<=65487||65490<=a&&a<=65495||65498<=a&&a<=65500||65512<=a&&a<=65518?"H":4352<=a&&a<=4447||4515<=a&&a<=4519||4602<=a&&a<=4607||9001<=a&&a<=9002||11904<=a&&a<=11929||11931<=a&&a<=12019||12032<=a&&a<=12245||12272<=a&&a<=12283||12289<=a&&a<=12350||12353<=a&&a<=12438||12441<=a&&a<=12543||12549<=a&&a<=12589||12593<=a&&a<=12686||12688<=a&&a<=12730||12736<=a&&a<=12771||12784<=a&&a<=12830||12832<=a&&a<=12871||12880<=a&&a<=13054||13056<=a&&a<=19903||19968<=a&&a<=42124||42128<=a&&a<=42182||43360<=a&&a<=43388||44032<=a&&a<=55203||55216<=a&&a<=55238||55243<=a&&a<=55291||63744<=a&&a<=64255||65040<=a&&a<=65049||65072<=a&&a<=65106||65108<=a&&a<=65126||65128<=a&&a<=65131||110592<=a&&a<=110593||127488<=a&&a<=127490||127504<=a&&a<=127546||127552<=a&&a<=127560||127568<=a&&a<=127569||131072<=a&&a<=194367||177984<=a&&a<=196605||196608<=a&&a<=262141?"W":32<=a&&a<=126||162<=a&&a<=163||165<=a&&a<=166||a==172||a==175||10214<=a&&a<=10221||10629<=a&&a<=10630?"Na":a==161||a==164||167<=a&&a<=168||a==170||173<=a&&a<=174||176<=a&&a<=180||182<=a&&a<=186||188<=a&&a<=191||a==198||a==208||215<=a&&a<=216||222<=a&&a<=225||a==230||232<=a&&a<=234||236<=a&&a<=237||a==240||242<=a&&a<=243||247<=a&&a<=250||a==252||a==254||a==257||a==273||a==275||a==283||294<=a&&a<=295||a==299||305<=a&&a<=307||a==312||319<=a&&a<=322||a==324||328<=a&&a<=331||a==333||338<=a&&a<=339||358<=a&&a<=359||a==363||a==462||a==464||a==466||a==468||a==470||a==472||a==474||a==476||a==593||a==609||a==708||a==711||713<=a&&a<=715||a==717||a==720||728<=a&&a<=731||a==733||a==735||768<=a&&a<=879||913<=a&&a<=929||931<=a&&a<=937||945<=a&&a<=961||963<=a&&a<=969||a==1025||1040<=a&&a<=1103||a==1105||a==8208||8211<=a&&a<=8214||8216<=a&&a<=8217||8220<=a&&a<=8221||8224<=a&&a<=8226||8228<=a&&a<=8231||a==8240||8242<=a&&a<=8243||a==8245||a==8251||a==8254||a==8308||a==8319||8321<=a&&a<=8324||a==8364||a==8451||a==8453||a==8457||a==8467||a==8470||8481<=a&&a<=8482||a==8486||a==8491||8531<=a&&a<=8532||8539<=a&&a<=8542||8544<=a&&a<=8555||8560<=a&&a<=8569||a==8585||8592<=a&&a<=8601||8632<=a&&a<=8633||a==8658||a==8660||a==8679||a==8704||8706<=a&&a<=8707||8711<=a&&a<=8712||a==8715||a==8719||a==8721||a==8725||a==8730||8733<=a&&a<=8736||a==8739||a==8741||8743<=a&&a<=8748||a==8750||8756<=a&&a<=8759||8764<=a&&a<=8765||a==8776||a==8780||a==8786||8800<=a&&a<=8801||8804<=a&&a<=8807||8810<=a&&a<=8811||8814<=a&&a<=8815||8834<=a&&a<=8835||8838<=a&&a<=8839||a==8853||a==8857||a==8869||a==8895||a==8978||9312<=a&&a<=9449||9451<=a&&a<=9547||9552<=a&&a<=9587||9600<=a&&a<=9615||9618<=a&&a<=9621||9632<=a&&a<=9633||9635<=a&&a<=9641||9650<=a&&a<=9651||9654<=a&&a<=9655||9660<=a&&a<=9661||9664<=a&&a<=9665||9670<=a&&a<=9672||a==9675||9678<=a&&a<=9681||9698<=a&&a<=9701||a==9711||9733<=a&&a<=9734||a==9737||9742<=a&&a<=9743||9748<=a&&a<=9749||a==9756||a==9758||a==9792||a==9794||9824<=a&&a<=9825||9827<=a&&a<=9829||9831<=a&&a<=9834||9836<=a&&a<=9837||a==9839||9886<=a&&a<=9887||9918<=a&&a<=9919||9924<=a&&a<=9933||9935<=a&&a<=9953||a==9955||9960<=a&&a<=9983||a==10045||a==10071||10102<=a&&a<=10111||11093<=a&&a<=11097||12872<=a&&a<=12879||57344<=a&&a<=63743||65024<=a&&a<=65039||a==65533||127232<=a&&a<=127242||127248<=a&&a<=127277||127280<=a&&a<=127337||127344<=a&&a<=127386||917760<=a&&a<=917999||983040<=a&&a<=1048573||1048576<=a&&a<=1114109?"A":"N"},t.characterLength=function(r){var o=this.eastAsianWidth(r);return o=="F"||o=="W"||o=="A"?2:1};function n(r){return r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}i(n,"t"),t.length=function(r){for(var o=n(r),s=0,a=0;a<o.length;a++)s=s+this.characterLength(o[a]);return s},t.slice=function(r,o,s){textLen=t.length(r),o=o||0,s=s||1,o<0&&(o=textLen+o),s<0&&(s=textLen+s);for(var a="",u=0,l=n(r),c=0;c<l.length;c++){var d=l[c],f=t.length(d);if(u>=o-(f==2?1:0))if(u+f<=s)a+=d;else break;u+=f}return a}})(Vc);var Ry=Vc.exports;const Ny=Zc(Ry);var Py=i(function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g},"FD");const My=Zc(Py);function no(e,t={}){if(typeof e!="string"||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=Uc(e),e.length===0))return 0;e=e.replace(My()," ");const n=t.ambiguousIsNarrow?1:2;let r=0;for(const o of e){const s=o.codePointAt(0);if(!(s<=31||s>=127&&s<=159||s>=768&&s<=879))switch(Ny.eastAsianWidth(o)){case"F":case"W":r+=2;break;case"A":r+=n;break;default:r+=1}}return r}i(no,"p");const Ms=10,Gc=i((e=0)=>t=>`\x1B[${t+e}m`,"N"),Wc=i((e=0)=>t=>`\x1B[${38+e};5;${t}m`,"I"),Hc=i((e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,"R"),Te={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(Te.modifier);const jy=Object.keys(Te.color),zy=Object.keys(Te.bgColor);[...jy,...zy];function Ly(){const e=new Map;for(const[t,n]of Object.entries(Te)){for(const[r,o]of Object.entries(n))Te[r]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[r]=Te[r],e.set(o[0],o[1]);Object.defineProperty(Te,t,{value:n,enumerable:!1})}return Object.defineProperty(Te,"codes",{value:e,enumerable:!1}),Te.color.close="\x1B[39m",Te.bgColor.close="\x1B[49m",Te.color.ansi=Gc(),Te.color.ansi256=Wc(),Te.color.ansi16m=Hc(),Te.bgColor.ansi=Gc(Ms),Te.bgColor.ansi256=Wc(Ms),Te.bgColor.ansi16m=Hc(Ms),Object.defineProperties(Te,{rgbToAnsi256:{value:i((t,n,r)=>t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5),"value"),enumerable:!1},hexToRgb:{value:i(t=>{const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));const o=Number.parseInt(r,16);return[o>>16&255,o>>8&255,o&255]},"value"),enumerable:!1},hexToAnsi256:{value:i(t=>Te.rgbToAnsi256(...Te.hexToRgb(t)),"value"),enumerable:!1},ansi256ToAnsi:{value:i(t=>{if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,o;if(t>=232)n=((t-232)*10+8)/255,r=n,o=n;else{t-=16;const u=t%36;n=Math.floor(t/36)/5,r=Math.floor(u/6)/5,o=u%6/5}const s=Math.max(n,r,o)*2;if(s===0)return 30;let a=30+(Math.round(o)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(a+=60),a},"value"),enumerable:!1},rgbToAnsi:{value:i((t,n,r)=>Te.ansi256ToAnsi(Te.rgbToAnsi256(t,n,r)),"value"),enumerable:!1},hexToAnsi:{value:i(t=>Te.ansi256ToAnsi(Te.hexToAnsi256(t)),"value"),enumerable:!1}}),Te}i(Ly,"rD");const qy=Ly(),Xo=new Set(["\x1B","\x9B"]),Uy=39,js="\x07",Jc="[",Zy="]",Kc="m",zs=`${Zy}8;;`,Yc=i(e=>`${Xo.values().next().value}${Jc}${e}${Kc}`,"z"),Xc=i(e=>`${Xo.values().next().value}${zs}${e}${js}`,"K"),Vy=i(e=>e.split(" ").map(t=>no(t)),"aD"),Ls=i((e,t,n)=>{const r=[...t];let o=!1,s=!1,a=no(Uc(e[e.length-1]));for(const[u,l]of r.entries()){const c=no(l);if(a+c<=n?e[e.length-1]+=l:(e.push(l),a=0),Xo.has(l)&&(o=!0,s=r.slice(u+1).join("").startsWith(zs)),o){s?l===js&&(o=!1,s=!1):l===Kc&&(o=!1);continue}a+=c,a===n&&u<r.length-1&&(e.push(""),a=0)}!a&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},"k$1"),Gy=i(e=>{const t=e.split(" ");let n=t.length;for(;n>0&&!(no(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},"hD"),Wy=i((e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let r="",o,s;const a=Vy(e);let u=[""];for(const[c,d]of e.split(" ").entries()){n.trim!==!1&&(u[u.length-1]=u[u.length-1].trimStart());let f=no(u[u.length-1]);if(c!==0&&(f>=t&&(n.wordWrap===!1||n.trim===!1)&&(u.push(""),f=0),(f>0||n.trim===!1)&&(u[u.length-1]+=" ",f++)),n.hard&&a[c]>t){const h=t-f,D=1+Math.floor((a[c]-h-1)/t);Math.floor((a[c]-1)/t)<D&&u.push(""),Ls(u,d,t);continue}if(f+a[c]>t&&f>0&&a[c]>0){if(n.wordWrap===!1&&f<t){Ls(u,d,t);continue}u.push("")}if(f+a[c]>t&&n.wordWrap===!1){Ls(u,d,t);continue}u[u.length-1]+=d}n.trim!==!1&&(u=u.map(c=>Gy(c)));const l=[...u.join(`
28
28
  `)];for(const[c,d]of l.entries()){if(r+=d,Xo.has(d)){const{groups:h}=new RegExp(`(?:\\${Jc}(?<code>\\d+)m|\\${zs}(?<uri>.*)${js})`).exec(l.slice(c).join(""))||{groups:{}};if(h.code!==void 0){const D=Number.parseFloat(h.code);o=D===Uy?void 0:D}else h.uri!==void 0&&(s=h.uri.length===0?void 0:h.uri)}const f=qy.codes.get(Number(o));l[c+1]===`
29
29
  `?(s&&(r+=Xc("")),o&&f&&(r+=Yc(f))):d===`
30
30
  `&&(o&&f&&(r+=Yc(o)),s&&(r+=Xc(s)))}return r},"lD");function Qc(e,t,n){return String(e).normalize().replace(/\r\n/g,`
@@ -68,12 +68,12 @@ ${L.cyan(un)}
68
68
  `)},"Ie"),Ee=i((e="")=>{process.stdout.write(`${L.gray(Fe)}
69
69
  ${L.gray(un)} ${e}
70
70
 
71
- `)},"Se");`${L.gray(Fe)}`;const Vt=i(({indicator:e="dots"}={})=>{const t=Hs?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],n=Hs?80:120,r=process.env.CI==="true";let o,s,a=!1,u="",l,c=performance.now();const d=i(x=>{const T=x>1?"Something went wrong":"Canceled";a&&C(T,x)},"p"),f=i(()=>d(2),"v"),h=i(()=>d(1),"f"),D=i(()=>{process.on("uncaughtExceptionMonitor",f),process.on("unhandledRejection",f),process.on("SIGINT",h),process.on("SIGTERM",h),process.on("exit",d)},"j"),m=i(()=>{process.removeListener("uncaughtExceptionMonitor",f),process.removeListener("unhandledRejection",f),process.removeListener("SIGINT",h),process.removeListener("SIGTERM",h),process.removeListener("exit",d)},"E"),v=i(()=>{if(l===void 0)return;r&&process.stdout.write(`
72
- `);const x=l.split(`
73
- `);process.stdout.write(Xe.cursor.move(-999,x.length-1)),process.stdout.write(Xe.erase.down(x.length))},"B"),y=i(x=>x.replace(/\.+$/,""),"R"),b=i(x=>{const T=(performance.now()-x)/1e3,O=Math.floor(T/60),$=Math.floor(T%60);return O>0?`[${O}m ${$}s]`:`[${$}s]`},"O"),w=i((x="")=>{a=!0,o=Yy(),u=y(x),c=performance.now(),process.stdout.write(`${L.gray(Fe)}
74
- `);let T=0,O=0;D(),s=setInterval(()=>{if(r&&u===l)return;v(),l=u;const $=L.magenta(t[T]);if(r)process.stdout.write(`${$} ${u}...`);else if(e==="timer")process.stdout.write(`${$} ${u} ${b(c)}`);else{const I=".".repeat(Math.floor(O)).slice(0,3);process.stdout.write(`${$} ${u}${I}`)}T=T+1<t.length?T+1:0,O=O<t.length?O+.125:0},n)},"H"),C=i((x="",T=0)=>{a=!1,clearInterval(s),v();const O=T===0?L.green(od):T===1?L.red(nd):L.red(rd);u=y(x??u),e==="timer"?process.stdout.write(`${O} ${u} ${b(c)}
71
+ `)},"Se");`${L.gray(Fe)}`;const Vt=i(({indicator:e="dots"}={})=>{const t=Hs?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],n=Hs?80:120,r=process.env.CI==="true";let o,s,a=!1,u="",l,c=performance.now();const d=i(E=>{const T=E>1?"Something went wrong":"Canceled";a&&F(T,E)},"p"),f=i(()=>d(2),"v"),h=i(()=>d(1),"f"),D=i(()=>{process.on("uncaughtExceptionMonitor",f),process.on("unhandledRejection",f),process.on("SIGINT",h),process.on("SIGTERM",h),process.on("exit",d)},"j"),m=i(()=>{process.removeListener("uncaughtExceptionMonitor",f),process.removeListener("unhandledRejection",f),process.removeListener("SIGINT",h),process.removeListener("SIGTERM",h),process.removeListener("exit",d)},"E"),v=i(()=>{if(l===void 0)return;r&&process.stdout.write(`
72
+ `);const E=l.split(`
73
+ `);process.stdout.write(Xe.cursor.move(-999,E.length-1)),process.stdout.write(Xe.erase.down(E.length))},"B"),y=i(E=>E.replace(/\.+$/,""),"R"),b=i(E=>{const T=(performance.now()-E)/1e3,O=Math.floor(T/60),$=Math.floor(T%60);return O>0?`[${O}m ${$}s]`:`[${$}s]`},"O"),C=i((E="")=>{a=!0,o=Yy(),u=y(E),c=performance.now(),process.stdout.write(`${L.gray(Fe)}
74
+ `);let T=0,O=0;D(),s=setInterval(()=>{if(r&&u===l)return;v(),l=u;const $=L.magenta(t[T]);if(r)process.stdout.write(`${$} ${u}...`);else if(e==="timer")process.stdout.write(`${$} ${u} ${b(c)}`);else{const I=".".repeat(Math.floor(O)).slice(0,3);process.stdout.write(`${$} ${u}${I}`)}T=T+1<t.length?T+1:0,O=O<t.length?O+.125:0},n)},"H"),F=i((E="",T=0)=>{a=!1,clearInterval(s),v();const O=T===0?L.green(od):T===1?L.red(nd):L.red(rd);u=y(E??u),e==="timer"?process.stdout.write(`${O} ${u} ${b(c)}
75
75
  `):process.stdout.write(`${O} ${u}
76
- `),m(),o()},"N");return{start:w,stop:C,message:i((x="")=>{u=y(x??u)},"message")}},"Y");var ro=Object.freeze({__proto__:null,confirm:c0,intro:na,isCancel:Bn,outro:Ee,password:l0,select:Ys,spinner:Vt,text:ad});const{version:d0}=hs,Cu=class Cu extends Error{};i(Cu,"KnownError");let he=Cu;const Xs=" ",sd=i(e=>{e instanceof Error&&!(e instanceof he)&&(e.stack&&console.error(Os(e.stack.split(`
76
+ `),m(),o()},"N");return{start:C,stop:F,message:i((E="")=>{u=y(E??u)},"message")}},"Y");var ro=Object.freeze({__proto__:null,confirm:c0,intro:na,isCancel:Bn,outro:Ee,password:l0,select:Ys,spinner:Vt,text:ad});const{version:d0}=hs,Cu=class Cu extends Error{};i(Cu,"KnownError");let he=Cu;const Xs=" ",sd=i(e=>{e instanceof Error&&!(e instanceof he)&&(e.stack&&console.error(Os(e.stack.split(`
77
77
  `).slice(1).join(`
78
78
  `))),console.error(`
79
79
  ${Xs}${Os(`aicommits v${d0}`)}`),console.error(`
@@ -82,45 +82,45 @@ ${Xs}Please open a Bug report with the information above:`),console.error(`${Xs}
82
82
  `).filter(Boolean).some(l=>!p0(l));let s=[];o&&(s=[...ud]),s=[...s,...e?e.map(oa):[]];const{stdout:a}=await Je("git",[...t,"--name-only",...s]);if(!a)return;const{stdout:u}=await Je("git",[...t,...s]);return{files:a.split(`
83
83
  `),diff:u}},"getStagedDiff"),f0=i(async(e,t)=>{const n=["diff","--cached","--diff-algorithm=minimal"],r=[...ud,...t?t.map(oa):[]],{stdout:o}=await Je("git",[...n,"--",...e,...r]);return{files:e,diff:o}},"getStagedDiffForFiles"),cd=i(e=>`Detected ${e.length.toLocaleString()} staged file${e.length>1?"s":""}`,"getDetectedMessage");var ei,dd;function m0(){if(dd)return ei;dd=1;const{hasOwnProperty:e}=Object.prototype,t=typeof process<"u"&&process.platform==="win32"?`\r
84
84
  `:`
85
- `,n=i((l,c)=>{const d=[];let f="";typeof c=="string"?c={section:c,whitespace:!1}:(c=c||Object.create(null),c.whitespace=c.whitespace===!0);const h=c.whitespace?" = ":"=";for(const D of Object.keys(l)){const m=l[D];if(m&&Array.isArray(m))for(const v of m)f+=a(D+"[]")+h+a(v)+t;else m&&typeof m=="object"?d.push(D):f+=a(D)+h+a(m)+t}c.section&&f.length&&(f="["+a(c.section)+"]"+t+f);for(const D of d){const m=r(D).join("\\."),v=(c.section?c.section+".":"")+m,{whitespace:y}=c,b=n(l[D],{section:v,whitespace:y});f.length&&b.length&&(f+=t),f+=b}return f},"encode"),r=i(l=>l.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(c=>c.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),"dotSplit"),o=i(l=>{const c=Object.create(null);let d=c,f=null;const h=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,D=l.split(/[\r\n]+/g);for(const v of D){if(!v||v.match(/^\s*[;#]/))continue;const y=v.match(h);if(!y)continue;if(y[1]!==void 0){if(f=u(y[1]),f==="__proto__"){d=Object.create(null);continue}d=c[f]=c[f]||Object.create(null);continue}const b=u(y[2]),w=b.length>2&&b.slice(-2)==="[]",C=w?b.slice(0,-2):b;if(C==="__proto__")continue;const x=y[3]?u(y[4]):!0,T=x==="true"||x==="false"||x==="null"?JSON.parse(x):x;w&&(e.call(d,C)?Array.isArray(d[C])||(d[C]=[d[C]]):d[C]=[]),Array.isArray(d[C])?d[C].push(T):d[C]=T}const m=[];for(const v of Object.keys(c)){if(!e.call(c,v)||typeof c[v]!="object"||Array.isArray(c[v]))continue;const y=r(v);d=c;const b=y.pop(),w=b.replace(/\\\./g,".");for(const C of y)C!=="__proto__"&&((!e.call(d,C)||typeof d[C]!="object")&&(d[C]=Object.create(null)),d=d[C]);d===c&&w===b||(d[w]=c[v],m.push(v))}for(const v of m)delete c[v];return c},"decode"),s=i(l=>l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"),"isQuoted"),a=i(l=>typeof l!="string"||l.match(/[=\r\n]/)||l.match(/^\[/)||l.length>1&&s(l)||l!==l.trim()?JSON.stringify(l):l.split(";").join("\\;").split("#").join("\\#"),"safe"),u=i((l,c)=>{if(l=(l||"").trim(),s(l)){l.charAt(0)==="'"&&(l=l.slice(1,-1));try{l=JSON.parse(l)}catch{}}else{let d=!1,f="";for(let h=0,D=l.length;h<D;h++){const m=l.charAt(h);if(d)"\\;#".indexOf(m)!==-1?f+=m:f+="\\"+m,d=!1;else{if(";#".indexOf(m)!==-1)break;m==="\\"?d=!0:f+=m}}return d&&(f+="\\"),f.trim()}return l},"unsafe");return ei={parse:o,decode:o,stringify:n,encode:n,safe:a,unsafe:u},ei}i(m0,"requireIni");var h0=m0(),pd=rn(h0);const ti=i(e=>He.lstat(e).then(()=>!0,()=>!1),"fileExists"),D0=["plain","conventional","gitmoji"],{hasOwnProperty:g0}=Object.prototype,ni=i((e,t)=>g0.call(e,t),"hasOwn"),Ot=i((e,t,n)=>{if(!t)throw new he(`Invalid config property ${e}: ${n}`)},"parseAssert"),aa={OPENAI_API_KEY(e){return e},OPENAI_BASE_URL(e){return e},OPENAI_MODEL(e){return e||""},locale(e){return e?(Ot("locale",!!e,"Cannot be empty"),Ot("locale",/^[a-z-]+$/i.test(e),"Must be a valid locale (letters and dashes/underscores)."),e):"en"},generate(e){if(!e)return 1;Ot("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Ot("generate",t>0,"Must be greater than 0"),Ot("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(Ot("type",D0.includes(e),"Invalid commit type"),e):"plain"},proxy(e){if(!(!e||e.length===0))throw new he('The "proxy" config property is deprecated and no longer supported.')},timeout(e){if(!e)return;Ot("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Ot("timeout",t>=500,"Must be greater than 500ms"),t},"max-length"(e){if(!e)return 72;Ot("max-length",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Ot("max-length",t>=20,"Must be greater than 20 characters"),t}},v0={name:"togetherai",displayName:"Together AI (recommended)",baseUrl:"https://api.together.xyz/v1",apiKeyFormat:"tgp_",modelsFilter:i(e=>e.filter(t=>(!t.type||t.type==="chat"||t.type==="language")&&!t.id.toLowerCase().includes("vision")).map(t=>t.id),"modelsFilter"),defaultModels:["moonshotai/Kimi-K2-Instruct-0905","Qwen/Qwen3-Next-80B-A3B-Instruct","zai-org/GLM-4.5-Air-FP8","meta-llama/Llama-3.2-3B-Instruct-Turbo"],requiresApiKey:!0},y0={name:"openai",displayName:"OpenAI",baseUrl:"https://api.openai.com/v1",apiKeyFormat:"sk-",modelsFilter:i(e=>e.filter(t=>t.id&&(t.id.includes("gpt")||t.id.includes("o1")||t.id.includes("o3")||t.id.includes("o4")||t.id.includes("o5")||!t.type||t.type==="chat")).map(t=>t.id),"modelsFilter"),defaultModels:["gpt-5-mini","gpt-4o-mini","gpt-4o","gpt-5-nano"],requiresApiKey:!0},_0={name:"ollama",displayName:"Ollama (local)",baseUrl:"http://localhost:11434/v1",modelsFilter:i(e=>e.filter(t=>t.name).map(t=>t.name),"modelsFilter"),defaultModels:["gpt-oss:latest","llama3.2:latest"],requiresApiKey:!1},b0={name:"custom",displayName:"Custom (OpenAI-compatible)",baseUrl:"",modelsFilter:i(e=>e.filter(t=>!t.type||t.type==="chat"||t.type==="language").map(t=>t.id),"modelsFilter"),defaultModels:[],requiresApiKey:!0},C0={name:"openrouter",displayName:"OpenRouter",baseUrl:"https://openrouter.ai/api/v1",apiKeyFormat:"sk-or-v1-",modelsFilter:i(e=>e.filter(t=>t.id&&(!t.type||t.type==="chat")).map(t=>t.id),"modelsFilter"),defaultModels:["openai/gpt-oss-20b:free","z-ai/glm-4.5-air:free"],requiresApiKey:!0},w0={name:"lmstudio",displayName:"LM Studio (local)",baseUrl:"http://localhost:1234/v1",modelsFilter:i(e=>e.filter(t=>!t.type||t.type==="chat"||t.type==="language").map(t=>t.id),"modelsFilter"),defaultModels:["qwen/qwen3-4b-2507","qwen/qwen3-8b"],requiresApiKey:!1},oo=[v0,y0,_0,w0,C0,b0],F0=i(()=>oo.find(t=>t.name==="openai")?.baseUrl||"","getDefaultBaseUrl"),E0=i((e,t)=>{if(e){const n=oo.find(r=>r.baseUrl===e||r.name==="ollama"&&e.startsWith(r.baseUrl.slice(0,-3)));return n?n.name:"custom"}else if(t)return"openai"},"detectProvider"),ri=i(()=>bt.join(El.homedir(),".aicommits"),"getConfigPath"),fd=i(async()=>{if(!await ti(ri()))return Object.create(null);const t=await He.readFile(ri(),"utf8");return pd.parse(t)},"readConfigFile"),ln=i(async(e,t,n)=>{const r=await fd();ni(r,"proxy")&&console.warn('The "proxy" config property is deprecated and no longer supported');const o={},s=t??{};for(const c of Object.keys(aa)){const d=aa[c],f=e?.[c]??s?.[c]??r[c];if(n)try{o[c]=d(f)}catch{}else o[c]=d(f)}let a,u=o.OPENAI_BASE_URL;const l=o.OPENAI_API_KEY;return!u&&l&&(u=F0(),o.OPENAI_BASE_URL=u),a=E0(u,l),{...o,model:o.OPENAI_MODEL,provider:a}},"getConfig"),oi=i(async e=>{const t=await fd();for(const[n,r]of e){if(!ni(aa,n))throw new he(`Invalid config property: ${n}`);if(r==="")delete t[n];else{const o=aa[n](r);t[n]=o}}await He.writeFile(ri(),pd.stringify(t),"utf8")},"setConfigs"),md=i(e=>`\u2705 ${e} (current)`,"CURRENT_LABEL_FORMAT"),x0=3600*1e3,hd=i(()=>{const e=process.platform,t=El.homedir();if(e==="darwin")return bt.join(t,"Library","Caches","aicommits","models");if(e==="win32")return bt.join(t,"AppData","Local","aicommits","models");{const n=process.env.XDG_CACHE_HOME,r=n||bt.join(t,".cache");return bt.join(r,"aicommits","models")}},"getCacheDir"),k0=i(e=>{const t=GD.createHash("sha256");return t.update(e),t.digest("hex")},"getCacheKey"),Dd=i(e=>bt.join(hd(),`${e}.json`),"getCachePath"),I0=i(async e=>{const t=Dd(e);try{if(!await ti(t))return null;const n=await He.readFile(t,"utf8");return JSON.parse(n)}catch{return null}},"readCache"),A0=i(async(e,t)=>{try{const n=hd();await He.mkdir(n,{recursive:!0});const r=Dd(e);await He.writeFile(r,JSON.stringify(t),"utf8")}catch{}},"writeCache"),ai=i(async(e,t)=>{const n=k0(e),r=Date.now(),o=await I0(n);if(o&&r-o.timestamp<x0)return o.data;try{const s=await fetch(`${e}/models`,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);const a=await s.json(),u=(a.data?a.data:a)||[],l={models:u};return u.length>0&&await A0(n,{data:l,timestamp:r}),l}catch(s){const a=s instanceof Error?s.message:"Request failed";return{models:[],error:a}}},"fetchModels"),$0=i(async(e,t,n)=>{const r=await ai(e,t);r.error&&console.error(`Failed to fetch models: ${r.error}`);let o=[];return n?.modelsFilter?o=n.modelsFilter(r.models):o=r.models.map(s=>s.id||s.name).filter(Boolean),o},"fetchAndFilterModels"),T0=i((e,t,n)=>{let r=e.map(o=>({label:o,value:o}));if(n?.defaultModels&&n.defaultModels.length>0){const o=n.defaultModels.filter(s=>r.some(a=>a.value===s));o.forEach(s=>{const a=r.findIndex(u=>u.value===s);a>=0&&r.splice(a,1)}),o.forEach((s,a)=>{const u=s===t,l=a===0;let c;u?c=`\u2705 ${s} (current)`:l?c=`\u{1F451} ${s} (default)`:c=`\u{1F525} ${s}`,r.unshift({label:c,value:s})})}if(t&&t!=="undefined"){const o=n?.defaultModels?.includes(t),s=r.findIndex(a=>a.value===t);if(s>=0&&!o){if(r[s].label=md(r[s].value),s>0){const[a]=r.splice(s,1),u=n?.defaultModels?.length||0;r.splice(u,0,a)}}else if(s<0&&!o){const a=n?.defaultModels?.length||0;r.splice(a,0,{label:md(t),value:t})}}return r},"prepareModelOptions"),S0=i(async(e,t,n,r)=>{const o=await n({message:"Enter search term for models:",placeholder:"e.g., gpt, llama"});if(r(o))return null;let s=e;o&&(s=e.filter(l=>l.toLowerCase().includes(o.toLowerCase())));let a=s.slice(0,20).map(l=>({label:l,value:l}));const u=await t({message:`Choose your model (filtered by "${o}"):`,options:[...a,{label:"Custom model name...",value:"custom"}]});return r(u)?null:u},"handleSearch"),B0=i(async e=>{const t=await e({message:"Enter your custom model name:",validate:i(n=>{if(!n)return"Model name is required"},"validate")});return Bn(t)?null:t},"handleCustom"),gd=i(async(e,t,n,r,o)=>{(!n||n==="undefined")&&(n=r?.defaultModels?.[0]);const s=Vt();s.start("Fetching available models...");const a=await $0(e,t,r);s.stop(`${o||"Provider"}: ${a.length} models available`);let u=null;if(a.length>0){const{select:l,text:c,isCancel:d}=await Promise.resolve().then(function(){return ro});let f=T0(a,n,r);const h=10;f.length>h&&(f=f.slice(0,h));let D=await l({message:"Choose your model:",options:[{label:"\u{1F50D} Search models...",value:"search"},...f,{label:"Custom model name...",value:"custom"}],initialValue:f.length>0?f[0].value:void 0});if(d(D))return null;if(D==="search"){const m=await S0(a,l,c,d);if(m===null)return null;D=m}if(D==="custom"){if(u=await B0(c),u===null)return null}else u=D}else{console.log("Could not fetch available models. Please specify a model name manually.");const{text:l,isCancel:c}=await Promise.resolve().then(function(){return ro});try{const d=await l({message:"Enter your model name:",validate:i(f=>{if(!f)return"Model name is required"},"validate")});if(c(d))return null;u=d}catch{return null}}return u},"selectModel");var O0=Object.freeze({__proto__:null,fetchModels:ai,selectModel:gd}),R0=Object.defineProperty,N0=i((e,t,n)=>t in e?R0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"__defNormalProp"),vd=i((e,t,n)=>N0(e,typeof t!="symbol"?t+"":t,n),"__publicField");const wu=class wu{constructor(t,n){vd(this,"config"),vd(this,"def"),this.def=t,this.config=n}get name(){return this.def.name}get displayName(){return this.def.displayName}getDefinition(){return this.def}async setup(){const{text:t,password:n,isCancel:r}=await Promise.resolve().then(function(){return ro}),o=[];if(this.def.requiresApiKey){const s=this.getApiKey(),a=await n({message:s?`Enter your API key (leave empty to keep current: ${s.substring(0,4)}****):`:"Enter your API key:",validate:i(u=>{if(!u&&!s)return"API key is required"},"validate")});if(r(a))throw new Error("Setup cancelled");a&&o.push(["OPENAI_API_KEY",a])}if(this.name==="ollama"){const s=this.getBaseUrl(),a=await t({message:"Enter Ollama endpoint (leave empty for default):",placeholder:s});if(r(a))throw new Error("Setup cancelled");a&&a!=="http://localhost:11434/v1"&&o.push(["OPENAI_BASE_URL",a])}return o}async getModels(){const t=this.getBaseUrl(),n=this.getApiKey()||"",r=await ai(t,n);if(r.error)return{models:[],error:r.error};let o;return this.def.modelsFilter?o=this.def.modelsFilter(r.models):o=r.models.map(s=>s.id||s.name).filter(Boolean),{models:o}}getApiKey(){return this.def.requiresApiKey?this.config.OPENAI_API_KEY:void 0}getBaseUrl(){return this.name==="custom"?this.config.OPENAI_BASE_URL||"":this.def.baseUrl}getDefaultModel(){return this.def.defaultModels[0]||""}getHighlightedModels(){return this.def.defaultModels}validateConfig(){const t=[];return this.def.requiresApiKey&&!this.getApiKey()&&t.push(`${this.displayName} API key is required`),this.name==="custom"&&!this.getBaseUrl()&&t.push("Custom endpoint is required"),{valid:t.length===0,errors:t}}};i(wu,"Provider");let si=wu;function Rn(e){const t=e.provider,n=oo.find(r=>r.name===t);return n?new si(n,e):null}i(Rn,"getProvider");function P0(){return oo.map(e=>({value:e.name,label:e.displayName}))}i(P0,"getAvailableProviders");function M0(e){return oo.find(n=>n.name===e)?.baseUrl||""}i(M0,"getProviderBaseUrl");var yd="vercel.ai.error",j0=Symbol.for(yd),_d,bd,Q=(Cn=class extends(bd=Error,_d=j0,bd){constructor({name:t,message:n,cause:r}){super(n),this[_d]=!0,this.name=t,this.cause=r}static isInstance(t){return Cn.hasMarker(t,yd)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}},i(Cn,"_AISDKError"),Cn),Cd="AI_APICallError",wd=`vercel.ai.error.${Cd}`,z0=Symbol.for(wd),Fd,Ed,Be=(Jn=class extends(Ed=Q,Fd=z0,Ed){constructor({message:t,url:n,requestBodyValues:r,statusCode:o,responseHeaders:s,responseBody:a,cause:u,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:Cd,message:t,cause:u}),this[Fd]=!0,this.url=n,this.requestBodyValues=r,this.statusCode=o,this.responseHeaders=s,this.responseBody=a,this.isRetryable=l,this.data=c}static isInstance(t){return Q.hasMarker(t,wd)}},i(Jn,"APICallError"),Jn),xd="AI_EmptyResponseBodyError",kd=`vercel.ai.error.${xd}`,L0=Symbol.for(kd),Id,Ad,q0=(Kn=class extends(Ad=Q,Id=L0,Ad){constructor({message:t="Empty response body"}={}){super({name:xd,message:t}),this[Id]=!0}static isInstance(t){return Q.hasMarker(t,kd)}},i(Kn,"EmptyResponseBodyError"),Kn);function ao(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}i(ao,"getErrorMessage$1");var $d="AI_InvalidArgumentError",Td=`vercel.ai.error.${$d}`,U0=Symbol.for(Td),Sd,Bd,Od=(Yn=class extends(Bd=Q,Sd=U0,Bd){constructor({message:t,cause:n,argument:r}){super({name:$d,message:t,cause:n}),this[Sd]=!0,this.argument=r}static isInstance(t){return Q.hasMarker(t,Td)}},i(Yn,"InvalidArgumentError"),Yn),Rd="AI_InvalidPromptError",Nd=`vercel.ai.error.${Rd}`,Z0=Symbol.for(Nd),Pd,Md,Gt=(Xn=class extends(Md=Q,Pd=Z0,Md){constructor({prompt:t,message:n,cause:r}){super({name:Rd,message:`Invalid prompt: ${n}`,cause:r}),this[Pd]=!0,this.prompt=t}static isInstance(t){return Q.hasMarker(t,Nd)}},i(Xn,"InvalidPromptError"),Xn),jd="AI_InvalidResponseDataError",zd=`vercel.ai.error.${jd}`,V0=Symbol.for(zd),Ld,qd,so=(Qn=class extends(qd=Q,Ld=V0,qd){constructor({data:t,message:n=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:jd,message:n}),this[Ld]=!0,this.data=t}static isInstance(t){return Q.hasMarker(t,zd)}},i(Qn,"InvalidResponseDataError"),Qn),Ud="AI_JSONParseError",Zd=`vercel.ai.error.${Ud}`,G0=Symbol.for(Zd),Vd,Gd,sa=(er=class extends(Gd=Q,Vd=G0,Gd){constructor({text:t,cause:n}){super({name:Ud,message:`JSON parsing failed: Text: ${t}.
86
- Error message: ${ao(n)}`,cause:n}),this[Vd]=!0,this.text=t}static isInstance(t){return Q.hasMarker(t,Zd)}},i(er,"JSONParseError"),er),Wd="AI_LoadAPIKeyError",Hd=`vercel.ai.error.${Wd}`,W0=Symbol.for(Hd),Jd,Kd,ia=(tr=class extends(Kd=Q,Jd=W0,Kd){constructor({message:t}){super({name:Wd,message:t}),this[Jd]=!0}static isInstance(t){return Q.hasMarker(t,Hd)}},i(tr,"LoadAPIKeyError"),tr),Yd="AI_TooManyEmbeddingValuesForCallError",Xd=`vercel.ai.error.${Yd}`,H0=Symbol.for(Xd),Qd,ep,tp=(nr=class extends(ep=Q,Qd=H0,ep){constructor(t){super({name:Yd,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[Qd]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return Q.hasMarker(t,Xd)}},i(nr,"TooManyEmbeddingValuesForCallError"),nr),np="AI_TypeValidationError",rp=`vercel.ai.error.${np}`,J0=Symbol.for(rp),op,ap,cn=(nn=class extends(ap=Q,op=J0,ap){constructor({value:t,cause:n,context:r}){let o="Type validation failed";if(r?.field&&(o+=` for ${r.field}`),r?.entityName||r?.entityId){o+=" (";const s=[];r.entityName&&s.push(r.entityName),r.entityId&&s.push(`id: "${r.entityId}"`),o+=s.join(", "),o+=")"}super({name:np,message:`${o}: Value: ${JSON.stringify(t)}.
87
- Error message: ${ao(n)}`,cause:n}),this[op]=!0,this.value=t,this.context=r}static isInstance(t){return Q.hasMarker(t,rp)}static wrap({value:t,cause:n,context:r}){var o,s,a;return nn.isInstance(n)&&n.value===t&&((o=n.context)==null?void 0:o.field)===r?.field&&((s=n.context)==null?void 0:s.entityName)===r?.entityName&&((a=n.context)==null?void 0:a.entityId)===r?.entityId?n:new nn({value:t,cause:n,context:r})}},i(nn,"_TypeValidationError"),nn),sp="AI_UnsupportedFunctionalityError",ip=`vercel.ai.error.${sp}`,K0=Symbol.for(ip),up,lp,Qe=(rr=class extends(lp=Q,up=K0,lp){constructor({functionality:t,message:n=`'${t}' functionality not supported.`}){super({name:sp,message:n}),this[up]=!0,this.functionality=t}static isInstance(t){return Q.hasMarker(t,ip)}},i(rr,"UnsupportedFunctionalityError"),rr);function A(e,t,n){function r(l,c){var d;Object.defineProperty(l,"_zod",{value:l._zod??{},enumerable:!1}),(d=l._zod).traits??(d.traits=new Set),l._zod.traits.add(e),t(l,c);for(const f in a.prototype)f in l||Object.defineProperty(l,f,{value:a.prototype[f].bind(l)});l._zod.constr=a,l._zod.def=c}i(r,"init");const o=n?.Parent??Object,u=class u extends o{};i(u,"Definition");let s=u;Object.defineProperty(s,"name",{value:e});function a(l){var c;const d=n?.Parent?new s:this;r(d,l),(c=d._zod).deferred??(c.deferred=[]);for(const f of d._zod.deferred)f();return d}return i(a,"_"),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:i(l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e),"value")}),Object.defineProperty(a,"name",{value:e}),a}i(A,"$constructor");const Fu=class Fu extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};i(Fu,"$ZodAsyncError");let dn=Fu;const cp={};function Wt(e){return cp}i(Wt,"config");function dp(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}i(dp,"getEnumValues");function Y0(e,t){return typeof t=="bigint"?t.toString():t}i(Y0,"jsonStringifyReplacer");function ii(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}i(ii,"cached");function ui(e){return e==null}i(ui,"nullish");function li(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}i(li,"cleanRegex");function X0(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}i(X0,"floatSafeRemainder$1");function De(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}i(De,"defineLazy");function ua(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}i(ua,"assignProp");function io(e){return JSON.stringify(e)}i(io,"esc");const pp=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function la(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(la,"isObject");const Q0=ii(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function ca(e){if(la(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(la(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}i(ca,"isPlainObject");const e_=new Set(["string","number","symbol"]);function uo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(uo,"escapeRegex");function pn(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}i(pn,"clone");function G(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:i(()=>t,"error")};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:i(()=>t.error,"error")}:t}i(G,"normalizeParams");function t_(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}i(t_,"optionalKeys");const n_={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]};function r_(e,t){const n={},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(n[o]=r.shape[o])}return pn(e,{...e._zod.def,shape:n,checks:[]})}i(r_,"pick");function o_(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete n[o]}return pn(e,{...e._zod.def,shape:n,checks:[]})}i(o_,"omit");function a_(e,t){if(!ca(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return ua(this,"shape",r),r},checks:[]};return pn(e,n)}i(a_,"extend");function s_(e,t){return pn(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return ua(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}i(s_,"merge");function i_(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=e?new e({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)o[s]=e?new e({type:"optional",innerType:r[s]}):r[s];return pn(t,{...t._zod.def,shape:o,checks:[]})}i(i_,"partial");function u_(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)o[s]=new e({type:"nonoptional",innerType:r[s]});return pn(t,{...t._zod.def,shape:o,checks:[]})}i(u_,"required");function lo(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}i(lo,"aborted");function fn(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}i(fn,"prefixIssues");function da(e){return typeof e=="string"?e:e?.message}i(da,"unwrapMessage");function Ht(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=da(e.inst?._zod.def?.error?.(e))??da(t?.error?.(e))??da(n.customError?.(e))??da(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}i(Ht,"finalizeIssue");function ci(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}i(ci,"getLengthableOrigin");function co(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}i(co,"issue");const fp=i((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(){return JSON.stringify(t,Y0,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:i(()=>e.message,"value"),enumerable:!1})},"initializer$1"),mp=A("$ZodError",fp),hp=A("$ZodError",fp,{Parent:Error});function l_(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}i(l_,"flattenError");function c_(e,t){const n=t||function(s){return s.message},r={_errors:[]},o=i(s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(u=>o({issues:u}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)r._errors.push(n(a));else{let u=r,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(u[c]=u[c]||{_errors:[]},u[c]._errors.push(n(a))):u[c]=u[c]||{_errors:[]},u=u[c],l++}}},"processError");return o(e),r}i(c_,"formatError");const d_=i(e=>(t,n,r,o)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new dn;if(a.issues.length){const u=new(o?.Err??e)(a.issues.map(l=>Ht(l,s,Wt())));throw pp(u,o?.callee),u}return a.value},"_parse$1"),p_=i(e=>async(t,n,r,o)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const u=new(o?.Err??e)(a.issues.map(l=>Ht(l,s,Wt())));throw pp(u,o?.callee),u}return a.value},"_parseAsync"),Dp=i(e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new dn;return s.issues.length?{success:!1,error:new(e??mp)(s.issues.map(a=>Ht(a,o,Wt())))}:{success:!0,data:s.value}},"_safeParse"),f_=Dp(hp),gp=i(e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>Ht(a,o,Wt())))}:{success:!0,data:s.value}},"_safeParseAsync"),m_=gp(hp),h_=/^[cC][^\s-]{8,}$/,D_=/^[0-9a-z]+$/,g_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,v_=/^[0-9a-vA-V]{20}$/,y_=/^[A-Za-z0-9]{27}$/,__=/^[a-zA-Z0-9_-]{21}$/,b_=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,C_=/^([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})$/,vp=i(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)$/,"uuid"),w_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,F_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function E_(){return new RegExp(F_,"u")}i(E_,"emoji");const x_=/^(?:(?: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])$/,k_=/^(([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})$/,I_=/^((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])$/,A_=/^(([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])$/,$_=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,yp=/^[A-Za-z0-9_-]*$/,T_=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,S_=/^\+(?:[0-9]){6,14}[0-9]$/,_p="(?:(?:\\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])))",B_=new RegExp(`^${_p}$`);function bp(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}i(bp,"timeSource");function O_(e){return new RegExp(`^${bp(e)}$`)}i(O_,"time$1");function R_(e){const t=bp({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${_p}T(?:${r})$`)}i(R_,"datetime$1");const N_=i(e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},"string$1"),P_=/^\d+$/,M_=/^-?\d+(?:\.\d+)?/i,j_=/true|false/i,z_=/null/i,L_=/^[^A-Z]*$/,q_=/^[^a-z]*$/,it=A("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Cp={number:"number",bigint:"bigint",object:"date"},wp=A("$ZodCheckLessThan",(e,t)=>{it.init(e,t);const n=Cp[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Fp=A("$ZodCheckGreaterThan",(e,t)=>{it.init(e,t);const n=Cp[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),U_=A("$ZodCheckMultipleOf",(e,t)=>{it.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):X0(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Z_=A("$ZodCheckNumberFormat",(e,t)=>{it.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,s]=n_[t.format];e._zod.onattach.push(a=>{const u=a._zod.bag;u.format=t.format,u.minimum=o,u.maximum=s,n&&(u.pattern=P_)}),e._zod.check=a=>{const u=a.value;if(n){if(!Number.isInteger(u)){a.issues.push({expected:r,format:t.format,code:"invalid_type",input:u,inst:e});return}if(!Number.isSafeInteger(u)){u>0?a.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):a.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}u<o&&a.issues.push({origin:"number",input:u,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),u>s&&a.issues.push({origin:"number",input:u,code:"too_big",maximum:s,inst:e})}}),V_=A("$ZodCheckMaxLength",(e,t)=>{var n;it.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ui(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const a=ci(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),G_=A("$ZodCheckMinLength",(e,t)=>{var n;it.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ui(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const a=ci(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),W_=A("$ZodCheckLengthEquals",(e,t)=>{var n;it.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ui(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,s=o.length;if(s===t.length)return;const a=ci(o),u=s>t.length;r.issues.push({origin:a,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),pa=A("$ZodCheckStringFormat",(e,t)=>{var n,r;it.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),H_=A("$ZodCheckRegex",(e,t)=>{pa.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),J_=A("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=L_),pa.init(e,t)}),K_=A("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=q_),pa.init(e,t)}),Y_=A("$ZodCheckIncludes",(e,t)=>{it.init(e,t);const n=uo(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),X_=A("$ZodCheckStartsWith",(e,t)=>{it.init(e,t);const n=new RegExp(`^${uo(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),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})}}),Q_=A("$ZodCheckEndsWith",(e,t)=>{it.init(e,t);const n=new RegExp(`.*${uo(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),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})}}),eb=A("$ZodCheckOverwrite",(e,t)=>{it.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}}),Eu=class Eu{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
85
+ `,n=i((l,c)=>{const d=[];let f="";typeof c=="string"?c={section:c,whitespace:!1}:(c=c||Object.create(null),c.whitespace=c.whitespace===!0);const h=c.whitespace?" = ":"=";for(const D of Object.keys(l)){const m=l[D];if(m&&Array.isArray(m))for(const v of m)f+=a(D+"[]")+h+a(v)+t;else m&&typeof m=="object"?d.push(D):f+=a(D)+h+a(m)+t}c.section&&f.length&&(f="["+a(c.section)+"]"+t+f);for(const D of d){const m=r(D).join("\\."),v=(c.section?c.section+".":"")+m,{whitespace:y}=c,b=n(l[D],{section:v,whitespace:y});f.length&&b.length&&(f+=t),f+=b}return f},"encode"),r=i(l=>l.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(c=>c.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,"")),"dotSplit"),o=i(l=>{const c=Object.create(null);let d=c,f=null;const h=/^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i,D=l.split(/[\r\n]+/g);for(const v of D){if(!v||v.match(/^\s*[;#]/))continue;const y=v.match(h);if(!y)continue;if(y[1]!==void 0){if(f=u(y[1]),f==="__proto__"){d=Object.create(null);continue}d=c[f]=c[f]||Object.create(null);continue}const b=u(y[2]),C=b.length>2&&b.slice(-2)==="[]",F=C?b.slice(0,-2):b;if(F==="__proto__")continue;const E=y[3]?u(y[4]):!0,T=E==="true"||E==="false"||E==="null"?JSON.parse(E):E;C&&(e.call(d,F)?Array.isArray(d[F])||(d[F]=[d[F]]):d[F]=[]),Array.isArray(d[F])?d[F].push(T):d[F]=T}const m=[];for(const v of Object.keys(c)){if(!e.call(c,v)||typeof c[v]!="object"||Array.isArray(c[v]))continue;const y=r(v);d=c;const b=y.pop(),C=b.replace(/\\\./g,".");for(const F of y)F!=="__proto__"&&((!e.call(d,F)||typeof d[F]!="object")&&(d[F]=Object.create(null)),d=d[F]);d===c&&C===b||(d[C]=c[v],m.push(v))}for(const v of m)delete c[v];return c},"decode"),s=i(l=>l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"),"isQuoted"),a=i(l=>typeof l!="string"||l.match(/[=\r\n]/)||l.match(/^\[/)||l.length>1&&s(l)||l!==l.trim()?JSON.stringify(l):l.split(";").join("\\;").split("#").join("\\#"),"safe"),u=i((l,c)=>{if(l=(l||"").trim(),s(l)){l.charAt(0)==="'"&&(l=l.slice(1,-1));try{l=JSON.parse(l)}catch{}}else{let d=!1,f="";for(let h=0,D=l.length;h<D;h++){const m=l.charAt(h);if(d)"\\;#".indexOf(m)!==-1?f+=m:f+="\\"+m,d=!1;else{if(";#".indexOf(m)!==-1)break;m==="\\"?d=!0:f+=m}}return d&&(f+="\\"),f.trim()}return l},"unsafe");return ei={parse:o,decode:o,stringify:n,encode:n,safe:a,unsafe:u},ei}i(m0,"requireIni");var h0=m0(),pd=rn(h0);const ti=i(e=>He.lstat(e).then(()=>!0,()=>!1),"fileExists"),D0=["plain","conventional","gitmoji"],{hasOwnProperty:g0}=Object.prototype,ni=i((e,t)=>g0.call(e,t),"hasOwn"),Ot=i((e,t,n)=>{if(!t)throw new he(`Invalid config property ${e}: ${n}`)},"parseAssert"),aa={OPENAI_API_KEY(e){return e},OPENAI_BASE_URL(e){return e},OPENAI_MODEL(e){return e||""},locale(e){return e?(Ot("locale",!!e,"Cannot be empty"),Ot("locale",/^[a-z-]+$/i.test(e),"Must be a valid locale (letters and dashes/underscores)."),e):"en"},generate(e){if(!e)return 1;Ot("generate",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Ot("generate",t>0,"Must be greater than 0"),Ot("generate",t<=5,"Must be less or equal to 5"),t},type(e){return e?(Ot("type",D0.includes(e),"Invalid commit type"),e):"plain"},proxy(e){if(!(!e||e.length===0))throw new he('The "proxy" config property is deprecated and no longer supported.')},timeout(e){if(!e)return;Ot("timeout",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Ot("timeout",t>=500,"Must be greater than 500ms"),t},"max-length"(e){if(!e)return 72;Ot("max-length",/^\d+$/.test(e),"Must be an integer");const t=Number(e);return Ot("max-length",t>=20,"Must be greater than 20 characters"),t}},v0={name:"togetherai",displayName:"Together AI (recommended)",baseUrl:"https://api.together.xyz/v1",apiKeyFormat:"tgp_",modelsFilter:i(e=>e.filter(t=>(!t.type||t.type==="chat"||t.type==="language")&&!t.id.toLowerCase().includes("vision")).map(t=>t.id),"modelsFilter"),defaultModels:["moonshotai/Kimi-K2-Instruct-0905","Qwen/Qwen3-Next-80B-A3B-Instruct","zai-org/GLM-4.5-Air-FP8","meta-llama/Llama-3.2-3B-Instruct-Turbo"],requiresApiKey:!0},y0={name:"openai",displayName:"OpenAI",baseUrl:"https://api.openai.com/v1",apiKeyFormat:"sk-",modelsFilter:i(e=>e.filter(t=>t.id&&(t.id.includes("gpt")||t.id.includes("o1")||t.id.includes("o3")||t.id.includes("o4")||t.id.includes("o5")||!t.type||t.type==="chat")).map(t=>t.id),"modelsFilter"),defaultModels:["gpt-5-mini","gpt-4o-mini","gpt-4o","gpt-5-nano"],requiresApiKey:!0},_0={name:"ollama",displayName:"Ollama (local)",baseUrl:"http://localhost:11434/v1",modelsFilter:i(e=>e.filter(t=>t.name).map(t=>t.name),"modelsFilter"),defaultModels:["gpt-oss:latest","llama3.2:latest"],requiresApiKey:!1},b0={name:"custom",displayName:"Custom (OpenAI-compatible)",baseUrl:"",modelsFilter:i(e=>e.filter(t=>!t.type||t.type==="chat"||t.type==="language").map(t=>t.id),"modelsFilter"),defaultModels:[],requiresApiKey:!0},C0={name:"openrouter",displayName:"OpenRouter",baseUrl:"https://openrouter.ai/api/v1",apiKeyFormat:"sk-or-v1-",modelsFilter:i(e=>e.filter(t=>t.id&&(!t.type||t.type==="chat")).map(t=>t.id),"modelsFilter"),defaultModels:["openai/gpt-oss-20b:free","z-ai/glm-4.5-air:free"],requiresApiKey:!0,headers:{"HTTP-Referer":"https://github.com/nutlope/aicommits","X-Title":"aicommits"}},w0={name:"lmstudio",displayName:"LM Studio (local)",baseUrl:"http://localhost:1234/v1",modelsFilter:i(e=>e.filter(t=>!t.type||t.type==="chat"||t.type==="language").map(t=>t.id),"modelsFilter"),defaultModels:["qwen/qwen3-4b-2507","qwen/qwen3-8b"],requiresApiKey:!1},F0={name:"groq",displayName:"Groq",baseUrl:"https://api.groq.com/openai/v1",apiKeyFormat:"gsk_",modelsFilter:i(e=>e.filter(t=>t.id&&(!t.type||t.type==="chat"||t.type==="language")).map(t=>t.id),"modelsFilter"),defaultModels:["openai/gpt-oss-120b","llama-3.1-8b-instant","openai/gpt-oss-20b"],requiresApiKey:!0},E0={name:"xai",displayName:"xAI",baseUrl:"https://api.x.ai/v1",apiKeyFormat:"xai-",modelsFilter:i(e=>e.filter(t=>t.id&&(!t.type||t.type==="chat"||t.type==="language")).map(t=>t.id),"modelsFilter"),defaultModels:["grok-4.1-fast","grok-4-fast","grok-code-fast-1"],requiresApiKey:!0},oo=[v0,y0,F0,E0,_0,w0,C0,b0],x0=i(()=>oo.find(t=>t.name==="openai")?.baseUrl||"","getDefaultBaseUrl"),k0=i((e,t)=>{if(e){const n=oo.find(r=>r.baseUrl===e||r.name==="ollama"&&e.startsWith(r.baseUrl.slice(0,-3)));return n?n.name:"custom"}else if(t)return"openai"},"detectProvider"),ri=i(()=>bt.join(El.homedir(),".aicommits"),"getConfigPath"),fd=i(async()=>{if(!await ti(ri()))return Object.create(null);const t=await He.readFile(ri(),"utf8");return pd.parse(t)},"readConfigFile"),ln=i(async(e,t,n)=>{const r=await fd();ni(r,"proxy")&&console.warn('The "proxy" config property is deprecated and no longer supported');const o={},s=t??{};for(const c of Object.keys(aa)){const d=aa[c],f=e?.[c]??s?.[c]??r[c];if(n)try{o[c]=d(f)}catch{}else o[c]=d(f)}let a,u=o.OPENAI_BASE_URL;const l=o.OPENAI_API_KEY;return!u&&l&&(u=x0(),o.OPENAI_BASE_URL=u),a=k0(u,l),{...o,model:o.OPENAI_MODEL,provider:a}},"getConfig"),oi=i(async e=>{const t=await fd();for(const[n,r]of e){if(!ni(aa,n))throw new he(`Invalid config property: ${n}`);if(r==="")delete t[n];else{const o=aa[n](r);t[n]=o}}await He.writeFile(ri(),pd.stringify(t),"utf8")},"setConfigs"),md=i(e=>`\u2705 ${e} (current)`,"CURRENT_LABEL_FORMAT"),I0=3600*1e3,hd=i(()=>{const e=process.platform,t=El.homedir();if(e==="darwin")return bt.join(t,"Library","Caches","aicommits","models");if(e==="win32")return bt.join(t,"AppData","Local","aicommits","models");{const n=process.env.XDG_CACHE_HOME,r=n||bt.join(t,".cache");return bt.join(r,"aicommits","models")}},"getCacheDir"),A0=i(e=>{const t=GD.createHash("sha256");return t.update(e),t.digest("hex")},"getCacheKey"),Dd=i(e=>bt.join(hd(),`${e}.json`),"getCachePath"),$0=i(async e=>{const t=Dd(e);try{if(!await ti(t))return null;const n=await He.readFile(t,"utf8");return JSON.parse(n)}catch{return null}},"readCache"),T0=i(async(e,t)=>{try{const n=hd();await He.mkdir(n,{recursive:!0});const r=Dd(e);await He.writeFile(r,JSON.stringify(t),"utf8")}catch{}},"writeCache"),ai=i(async(e,t)=>{const n=A0(e),r=Date.now(),o=await $0(n);if(o&&r-o.timestamp<I0)return o.data;try{const s=await fetch(`${e}/models`,{headers:{Authorization:`Bearer ${t}`}});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);const a=await s.json(),u=(a.data?a.data:a)||[],l={models:u};return u.length>0&&await T0(n,{data:l,timestamp:r}),l}catch(s){const a=s instanceof Error?s.message:"Request failed";return{models:[],error:a}}},"fetchModels"),S0=i(async(e,t,n)=>{const r=await ai(e,t);r.error&&console.error(`Failed to fetch models: ${r.error}`);let o=[];return n?.modelsFilter?o=n.modelsFilter(r.models):o=r.models.map(s=>s.id||s.name).filter(Boolean),o},"fetchAndFilterModels"),B0=i((e,t,n)=>{let r=e.map(o=>({label:o,value:o}));if(n?.defaultModels&&n.defaultModels.length>0){const o=n.defaultModels.filter(s=>r.some(a=>a.value===s));o.forEach(s=>{const a=r.findIndex(u=>u.value===s);a>=0&&r.splice(a,1)}),o.forEach((s,a)=>{const u=s===t,l=a===0;let c;u?c=`\u2705 ${s} (current)`:l?c=`\u{1F451} ${s} (default)`:c=`\u{1F525} ${s}`,r.unshift({label:c,value:s})})}if(t&&t!=="undefined"){const o=n?.defaultModels?.includes(t),s=r.findIndex(a=>a.value===t);if(s>=0&&!o){if(r[s].label=md(r[s].value),s>0){const[a]=r.splice(s,1),u=n?.defaultModels?.length||0;r.splice(u,0,a)}}else if(s<0&&!o){const a=n?.defaultModels?.length||0;r.splice(a,0,{label:md(t),value:t})}}return r},"prepareModelOptions"),O0=i(async(e,t,n,r)=>{const o=await n({message:"Enter search term for models:",placeholder:"e.g., gpt, llama"});if(r(o))return null;let s=e;o&&(s=e.filter(l=>l.toLowerCase().includes(o.toLowerCase())));let a=s.slice(0,20).map(l=>({label:l,value:l}));const u=await t({message:`Choose your model (filtered by "${o}"):`,options:[...a,{label:"Custom model name...",value:"custom"}]});return r(u)?null:u},"handleSearch"),R0=i(async e=>{const t=await e({message:"Enter your custom model name:",validate:i(n=>{if(!n)return"Model name is required"},"validate")});return Bn(t)?null:t},"handleCustom"),gd=i(async(e,t,n,r,o)=>{(!n||n==="undefined")&&(n=r?.defaultModels?.[0]);const s=Vt();s.start("Fetching available models...");const a=await S0(e,t,r);s.stop(`${o||"Provider"}: ${a.length} models available`);let u=null;if(a.length>0){const{select:l,text:c,isCancel:d}=await Promise.resolve().then(function(){return ro});let f=B0(a,n,r);const h=10;f.length>h&&(f=f.slice(0,h));let D=await l({message:"Choose your model:",options:[{label:"\u{1F50D} Search models...",value:"search"},...f,{label:"Custom model name...",value:"custom"}],initialValue:f.length>0?f[0].value:void 0});if(d(D))return null;if(D==="search"){const m=await O0(a,l,c,d);if(m===null)return null;D=m}if(D==="custom"){if(u=await R0(c),u===null)return null}else u=D}else{console.log("Could not fetch available models. Please specify a model name manually.");const{text:l,isCancel:c}=await Promise.resolve().then(function(){return ro});try{const d=await l({message:"Enter your model name:",validate:i(f=>{if(!f)return"Model name is required"},"validate")});if(c(d))return null;u=d}catch{return null}}return u},"selectModel");var N0=Object.freeze({__proto__:null,fetchModels:ai,selectModel:gd}),P0=Object.defineProperty,M0=i((e,t,n)=>t in e?P0(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,"__defNormalProp"),vd=i((e,t,n)=>M0(e,typeof t!="symbol"?t+"":t,n),"__publicField");const wu=class wu{constructor(t,n){vd(this,"config"),vd(this,"def"),this.def=t,this.config=n}get name(){return this.def.name}get displayName(){return this.def.displayName}getDefinition(){return this.def}async setup(){const{text:t,password:n,isCancel:r}=await Promise.resolve().then(function(){return ro}),o=[];if(this.def.requiresApiKey){const s=this.getApiKey(),a=await n({message:s?`Enter your API key (leave empty to keep current: ${s.substring(0,4)}****):`:"Enter your API key:",validate:i(u=>{if(!u&&!s)return"API key is required"},"validate")});if(r(a))throw new Error("Setup cancelled");a&&o.push(["OPENAI_API_KEY",a])}if(this.name==="ollama"){const s=this.getBaseUrl(),a=await t({message:"Enter Ollama endpoint (leave empty for default):",placeholder:s});if(r(a))throw new Error("Setup cancelled");a&&a!=="http://localhost:11434/v1"&&o.push(["OPENAI_BASE_URL",a])}return o}async getModels(){const t=this.getBaseUrl(),n=this.getApiKey()||"",r=await ai(t,n);if(r.error)return{models:[],error:r.error};let o;return this.def.modelsFilter?o=this.def.modelsFilter(r.models):o=r.models.map(s=>s.id||s.name).filter(Boolean),{models:o}}getApiKey(){return this.def.requiresApiKey?this.config.OPENAI_API_KEY:void 0}getBaseUrl(){return this.name==="custom"?this.config.OPENAI_BASE_URL||"":this.def.baseUrl}getDefaultModel(){return this.def.defaultModels[0]||""}getHighlightedModels(){return this.def.defaultModels}getHeaders(){return this.def.headers}validateConfig(){const t=[];return this.def.requiresApiKey&&!this.getApiKey()&&t.push(`${this.displayName} API key is required`),this.name==="custom"&&!this.getBaseUrl()&&t.push("Custom endpoint is required"),{valid:t.length===0,errors:t}}};i(wu,"Provider");let si=wu;function Rn(e){const t=e.provider,n=oo.find(r=>r.name===t);return n?new si(n,e):null}i(Rn,"getProvider");function j0(){return oo.map(e=>({value:e.name,label:e.displayName}))}i(j0,"getAvailableProviders");function z0(e){return oo.find(n=>n.name===e)?.baseUrl||""}i(z0,"getProviderBaseUrl");var yd="vercel.ai.error",L0=Symbol.for(yd),_d,bd,Q=(Cn=class extends(bd=Error,_d=L0,bd){constructor({name:t,message:n,cause:r}){super(n),this[_d]=!0,this.name=t,this.cause=r}static isInstance(t){return Cn.hasMarker(t,yd)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}},i(Cn,"_AISDKError"),Cn),Cd="AI_APICallError",wd=`vercel.ai.error.${Cd}`,q0=Symbol.for(wd),Fd,Ed,Be=(Jn=class extends(Ed=Q,Fd=q0,Ed){constructor({message:t,url:n,requestBodyValues:r,statusCode:o,responseHeaders:s,responseBody:a,cause:u,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:Cd,message:t,cause:u}),this[Fd]=!0,this.url=n,this.requestBodyValues=r,this.statusCode=o,this.responseHeaders=s,this.responseBody=a,this.isRetryable=l,this.data=c}static isInstance(t){return Q.hasMarker(t,wd)}},i(Jn,"APICallError"),Jn),xd="AI_EmptyResponseBodyError",kd=`vercel.ai.error.${xd}`,U0=Symbol.for(kd),Id,Ad,Z0=(Kn=class extends(Ad=Q,Id=U0,Ad){constructor({message:t="Empty response body"}={}){super({name:xd,message:t}),this[Id]=!0}static isInstance(t){return Q.hasMarker(t,kd)}},i(Kn,"EmptyResponseBodyError"),Kn);function ao(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}i(ao,"getErrorMessage$1");var $d="AI_InvalidArgumentError",Td=`vercel.ai.error.${$d}`,V0=Symbol.for(Td),Sd,Bd,Od=(Yn=class extends(Bd=Q,Sd=V0,Bd){constructor({message:t,cause:n,argument:r}){super({name:$d,message:t,cause:n}),this[Sd]=!0,this.argument=r}static isInstance(t){return Q.hasMarker(t,Td)}},i(Yn,"InvalidArgumentError"),Yn),Rd="AI_InvalidPromptError",Nd=`vercel.ai.error.${Rd}`,G0=Symbol.for(Nd),Pd,Md,Gt=(Xn=class extends(Md=Q,Pd=G0,Md){constructor({prompt:t,message:n,cause:r}){super({name:Rd,message:`Invalid prompt: ${n}`,cause:r}),this[Pd]=!0,this.prompt=t}static isInstance(t){return Q.hasMarker(t,Nd)}},i(Xn,"InvalidPromptError"),Xn),jd="AI_InvalidResponseDataError",zd=`vercel.ai.error.${jd}`,W0=Symbol.for(zd),Ld,qd,so=(Qn=class extends(qd=Q,Ld=W0,qd){constructor({data:t,message:n=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:jd,message:n}),this[Ld]=!0,this.data=t}static isInstance(t){return Q.hasMarker(t,zd)}},i(Qn,"InvalidResponseDataError"),Qn),Ud="AI_JSONParseError",Zd=`vercel.ai.error.${Ud}`,H0=Symbol.for(Zd),Vd,Gd,sa=(er=class extends(Gd=Q,Vd=H0,Gd){constructor({text:t,cause:n}){super({name:Ud,message:`JSON parsing failed: Text: ${t}.
86
+ Error message: ${ao(n)}`,cause:n}),this[Vd]=!0,this.text=t}static isInstance(t){return Q.hasMarker(t,Zd)}},i(er,"JSONParseError"),er),Wd="AI_LoadAPIKeyError",Hd=`vercel.ai.error.${Wd}`,J0=Symbol.for(Hd),Jd,Kd,ia=(tr=class extends(Kd=Q,Jd=J0,Kd){constructor({message:t}){super({name:Wd,message:t}),this[Jd]=!0}static isInstance(t){return Q.hasMarker(t,Hd)}},i(tr,"LoadAPIKeyError"),tr),Yd="AI_TooManyEmbeddingValuesForCallError",Xd=`vercel.ai.error.${Yd}`,K0=Symbol.for(Xd),Qd,ep,tp=(nr=class extends(ep=Q,Qd=K0,ep){constructor(t){super({name:Yd,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[Qd]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return Q.hasMarker(t,Xd)}},i(nr,"TooManyEmbeddingValuesForCallError"),nr),np="AI_TypeValidationError",rp=`vercel.ai.error.${np}`,Y0=Symbol.for(rp),op,ap,cn=(nn=class extends(ap=Q,op=Y0,ap){constructor({value:t,cause:n,context:r}){let o="Type validation failed";if(r?.field&&(o+=` for ${r.field}`),r?.entityName||r?.entityId){o+=" (";const s=[];r.entityName&&s.push(r.entityName),r.entityId&&s.push(`id: "${r.entityId}"`),o+=s.join(", "),o+=")"}super({name:np,message:`${o}: Value: ${JSON.stringify(t)}.
87
+ Error message: ${ao(n)}`,cause:n}),this[op]=!0,this.value=t,this.context=r}static isInstance(t){return Q.hasMarker(t,rp)}static wrap({value:t,cause:n,context:r}){var o,s,a;return nn.isInstance(n)&&n.value===t&&((o=n.context)==null?void 0:o.field)===r?.field&&((s=n.context)==null?void 0:s.entityName)===r?.entityName&&((a=n.context)==null?void 0:a.entityId)===r?.entityId?n:new nn({value:t,cause:n,context:r})}},i(nn,"_TypeValidationError"),nn),sp="AI_UnsupportedFunctionalityError",ip=`vercel.ai.error.${sp}`,X0=Symbol.for(ip),up,lp,Qe=(rr=class extends(lp=Q,up=X0,lp){constructor({functionality:t,message:n=`'${t}' functionality not supported.`}){super({name:sp,message:n}),this[up]=!0,this.functionality=t}static isInstance(t){return Q.hasMarker(t,ip)}},i(rr,"UnsupportedFunctionalityError"),rr);function A(e,t,n){function r(l,c){var d;Object.defineProperty(l,"_zod",{value:l._zod??{},enumerable:!1}),(d=l._zod).traits??(d.traits=new Set),l._zod.traits.add(e),t(l,c);for(const f in a.prototype)f in l||Object.defineProperty(l,f,{value:a.prototype[f].bind(l)});l._zod.constr=a,l._zod.def=c}i(r,"init");const o=n?.Parent??Object,u=class u extends o{};i(u,"Definition");let s=u;Object.defineProperty(s,"name",{value:e});function a(l){var c;const d=n?.Parent?new s:this;r(d,l),(c=d._zod).deferred??(c.deferred=[]);for(const f of d._zod.deferred)f();return d}return i(a,"_"),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:i(l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e),"value")}),Object.defineProperty(a,"name",{value:e}),a}i(A,"$constructor");const Fu=class Fu extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};i(Fu,"$ZodAsyncError");let dn=Fu;const cp={};function Wt(e){return cp}i(Wt,"config");function dp(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}i(dp,"getEnumValues");function Q0(e,t){return typeof t=="bigint"?t.toString():t}i(Q0,"jsonStringifyReplacer");function ii(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}i(ii,"cached");function ui(e){return e==null}i(ui,"nullish");function li(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}i(li,"cleanRegex");function e_(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}i(e_,"floatSafeRemainder$1");function De(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}i(De,"defineLazy");function ua(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}i(ua,"assignProp");function io(e){return JSON.stringify(e)}i(io,"esc");const pp=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function la(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(la,"isObject");const t_=ii(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function ca(e){if(la(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(la(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}i(ca,"isPlainObject");const n_=new Set(["string","number","symbol"]);function uo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(uo,"escapeRegex");function pn(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}i(pn,"clone");function G(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:i(()=>t,"error")};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:i(()=>t.error,"error")}:t}i(G,"normalizeParams");function r_(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}i(r_,"optionalKeys");const o_={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]};function a_(e,t){const n={},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(n[o]=r.shape[o])}return pn(e,{...e._zod.def,shape:n,checks:[]})}i(a_,"pick");function s_(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete n[o]}return pn(e,{...e._zod.def,shape:n,checks:[]})}i(s_,"omit");function i_(e,t){if(!ca(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return ua(this,"shape",r),r},checks:[]};return pn(e,n)}i(i_,"extend");function u_(e,t){return pn(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return ua(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}i(u_,"merge");function l_(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=e?new e({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)o[s]=e?new e({type:"optional",innerType:r[s]}):r[s];return pn(t,{...t._zod.def,shape:o,checks:[]})}i(l_,"partial");function c_(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)o[s]=new e({type:"nonoptional",innerType:r[s]});return pn(t,{...t._zod.def,shape:o,checks:[]})}i(c_,"required");function lo(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}i(lo,"aborted");function fn(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}i(fn,"prefixIssues");function da(e){return typeof e=="string"?e:e?.message}i(da,"unwrapMessage");function Ht(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=da(e.inst?._zod.def?.error?.(e))??da(t?.error?.(e))??da(n.customError?.(e))??da(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}i(Ht,"finalizeIssue");function ci(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}i(ci,"getLengthableOrigin");function co(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}i(co,"issue");const fp=i((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(){return JSON.stringify(t,Q0,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:i(()=>e.message,"value"),enumerable:!1})},"initializer$1"),mp=A("$ZodError",fp),hp=A("$ZodError",fp,{Parent:Error});function d_(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}i(d_,"flattenError");function p_(e,t){const n=t||function(s){return s.message},r={_errors:[]},o=i(s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(u=>o({issues:u}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)r._errors.push(n(a));else{let u=r,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(u[c]=u[c]||{_errors:[]},u[c]._errors.push(n(a))):u[c]=u[c]||{_errors:[]},u=u[c],l++}}},"processError");return o(e),r}i(p_,"formatError");const f_=i(e=>(t,n,r,o)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new dn;if(a.issues.length){const u=new(o?.Err??e)(a.issues.map(l=>Ht(l,s,Wt())));throw pp(u,o?.callee),u}return a.value},"_parse$1"),m_=i(e=>async(t,n,r,o)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const u=new(o?.Err??e)(a.issues.map(l=>Ht(l,s,Wt())));throw pp(u,o?.callee),u}return a.value},"_parseAsync"),Dp=i(e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new dn;return s.issues.length?{success:!1,error:new(e??mp)(s.issues.map(a=>Ht(a,o,Wt())))}:{success:!0,data:s.value}},"_safeParse"),h_=Dp(hp),gp=i(e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>Ht(a,o,Wt())))}:{success:!0,data:s.value}},"_safeParseAsync"),D_=gp(hp),g_=/^[cC][^\s-]{8,}$/,v_=/^[0-9a-z]+$/,y_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,__=/^[0-9a-vA-V]{20}$/,b_=/^[A-Za-z0-9]{27}$/,C_=/^[a-zA-Z0-9_-]{21}$/,w_=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,F_=/^([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})$/,vp=i(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)$/,"uuid"),E_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,x_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function k_(){return new RegExp(x_,"u")}i(k_,"emoji");const I_=/^(?:(?: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_=/^(([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})$/,$_=/^((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])$/,T_=/^(([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])$/,S_=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,yp=/^[A-Za-z0-9_-]*$/,B_=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,O_=/^\+(?:[0-9]){6,14}[0-9]$/,_p="(?:(?:\\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])))",R_=new RegExp(`^${_p}$`);function bp(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}i(bp,"timeSource");function N_(e){return new RegExp(`^${bp(e)}$`)}i(N_,"time$1");function P_(e){const t=bp({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${_p}T(?:${r})$`)}i(P_,"datetime$1");const M_=i(e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},"string$1"),j_=/^\d+$/,z_=/^-?\d+(?:\.\d+)?/i,L_=/true|false/i,q_=/null/i,U_=/^[^A-Z]*$/,Z_=/^[^a-z]*$/,it=A("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Cp={number:"number",bigint:"bigint",object:"date"},wp=A("$ZodCheckLessThan",(e,t)=>{it.init(e,t);const n=Cp[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Fp=A("$ZodCheckGreaterThan",(e,t)=>{it.init(e,t);const n=Cp[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),V_=A("$ZodCheckMultipleOf",(e,t)=>{it.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):e_(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),G_=A("$ZodCheckNumberFormat",(e,t)=>{it.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[o,s]=o_[t.format];e._zod.onattach.push(a=>{const u=a._zod.bag;u.format=t.format,u.minimum=o,u.maximum=s,n&&(u.pattern=j_)}),e._zod.check=a=>{const u=a.value;if(n){if(!Number.isInteger(u)){a.issues.push({expected:r,format:t.format,code:"invalid_type",input:u,inst:e});return}if(!Number.isSafeInteger(u)){u>0?a.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):a.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}u<o&&a.issues.push({origin:"number",input:u,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),u>s&&a.issues.push({origin:"number",input:u,code:"too_big",maximum:s,inst:e})}}),W_=A("$ZodCheckMaxLength",(e,t)=>{var n;it.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ui(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const a=ci(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),H_=A("$ZodCheckMinLength",(e,t)=>{var n;it.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ui(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const a=ci(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),J_=A("$ZodCheckLengthEquals",(e,t)=>{var n;it.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ui(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,s=o.length;if(s===t.length)return;const a=ci(o),u=s>t.length;r.issues.push({origin:a,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),pa=A("$ZodCheckStringFormat",(e,t)=>{var n,r;it.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),K_=A("$ZodCheckRegex",(e,t)=>{pa.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Y_=A("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=U_),pa.init(e,t)}),X_=A("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Z_),pa.init(e,t)}),Q_=A("$ZodCheckIncludes",(e,t)=>{it.init(e,t);const n=uo(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),eb=A("$ZodCheckStartsWith",(e,t)=>{it.init(e,t);const n=new RegExp(`^${uo(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),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})}}),tb=A("$ZodCheckEndsWith",(e,t)=>{it.init(e,t);const n=new RegExp(`.*${uo(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),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})}}),nb=A("$ZodCheckOverwrite",(e,t)=>{it.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}}),Eu=class Eu{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
88
88
  `).filter(a=>a),o=Math.min(...r.map(a=>a.length-a.trimStart().length)),s=r.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(const a of s)this.content.push(a)}compile(){const t=Function,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...n,o.join(`
89
- `))}};i(Eu,"Doc");let di=Eu;const tb={major:4,minor:0,patch:0},Ce=A("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=tb;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const o of r)for(const s of o._zod.onattach)s(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=i((s,a,u)=>{let l=lo(s),c;for(const d of a){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(l)continue;const f=s.issues.length,h=d._zod.check(s);if(h instanceof Promise&&u?.async===!1)throw new dn;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,s.issues.length!==f&&(l||(l=lo(s,f)))});else{if(s.issues.length===f)continue;l||(l=lo(s,f))}}return c?c.then(()=>s):s},"runChecks");e._zod.run=(s,a)=>{const u=e._zod.parse(s,a);if(u instanceof Promise){if(a.async===!1)throw new dn;return u.then(l=>o(l,r,a))}return o(u,r,a)}}e["~standard"]={validate:i(o=>{try{const s=f_(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return m_(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},"validate"),vendor:"zod",version:1}}),pi=A("$ZodString",(e,t)=>{Ce.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??N_(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Se=A("$ZodStringFormat",(e,t)=>{pa.init(e,t),pi.init(e,t)}),nb=A("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=C_),Se.init(e,t)}),rb=A("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=vp(r))}else t.pattern??(t.pattern=vp());Se.init(e,t)}),ob=A("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=w_),Se.init(e,t)}),ab=A("$ZodURL",(e,t)=>{Se.init(e,t),e._zod.check=n=>{try{const r=n.value,o=new URL(r),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:T_.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),sb=A("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=E_()),Se.init(e,t)}),ib=A("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=__),Se.init(e,t)}),ub=A("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=h_),Se.init(e,t)}),lb=A("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=D_),Se.init(e,t)}),cb=A("$ZodULID",(e,t)=>{t.pattern??(t.pattern=g_),Se.init(e,t)}),db=A("$ZodXID",(e,t)=>{t.pattern??(t.pattern=v_),Se.init(e,t)}),pb=A("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=y_),Se.init(e,t)}),fb=A("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=R_(t)),Se.init(e,t)}),mb=A("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=B_),Se.init(e,t)}),hb=A("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=O_(t)),Se.init(e,t)}),Db=A("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=b_),Se.init(e,t)}),gb=A("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=x_),Se.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),vb=A("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=k_),Se.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),yb=A("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=I_),Se.init(e,t)}),_b=A("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=A_),Se.init(e,t),e._zod.check=n=>{const[r,o]=n.value.split("/");try{if(!o)throw new Error;const s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Ep(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}i(Ep,"isValidBase64");const bb=A("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=$_),Se.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{Ep(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Cb(e){if(!yp.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Ep(n)}i(Cb,"isValidBase64URL");const wb=A("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=yp),Se.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{Cb(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Fb=A("$ZodE164",(e,t)=>{t.pattern??(t.pattern=S_),Se.init(e,t)});function Eb(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}i(Eb,"isValidJWT$1");const xb=A("$ZodJWT",(e,t)=>{Se.init(e,t),e._zod.check=n=>{Eb(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),xp=A("$ZodNumber",(e,t)=>{Ce.init(e,t),e._zod.pattern=e._zod.bag.pattern??M_,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),n}}),kb=A("$ZodNumber",(e,t)=>{Z_.init(e,t),xp.init(e,t)}),Ib=A("$ZodBoolean",(e,t)=>{Ce.init(e,t),e._zod.pattern=j_,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),Ab=A("$ZodNull",(e,t)=>{Ce.init(e,t),e._zod.pattern=z_,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),$b=A("$ZodAny",(e,t)=>{Ce.init(e,t),e._zod.parse=n=>n}),Tb=A("$ZodUnknown",(e,t)=>{Ce.init(e,t),e._zod.parse=n=>n}),Sb=A("$ZodNever",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function kp(e,t,n){e.issues.length&&t.issues.push(...fn(n,e.issues)),t.value[n]=e.value}i(kp,"handleArrayResult");const Bb=A("$ZodArray",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const s=[];for(let a=0;a<o.length;a++){const u=o[a],l=t.element._zod.run({value:u,issues:[]},r);l instanceof Promise?s.push(l.then(c=>kp(c,n,a))):kp(l,n,a)}return s.length?Promise.all(s).then(()=>n):n}});function fa(e,t,n){e.issues.length&&t.issues.push(...fn(n,e.issues)),t.value[n]=e.value}i(fa,"handleObjectResult");function Ip(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...fn(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}i(Ip,"handleOptionalObjectResult");const Ob=A("$ZodObject",(e,t)=>{Ce.init(e,t);const n=ii(()=>{const f=Object.keys(t.shape);for(const D of f)if(!(t.shape[D]instanceof Ce))throw new Error(`Invalid element at key "${D}": expected a Zod schema`);const h=t_(t.shape);return{shape:t.shape,keys:f,keySet:new Set(f),numKeys:f.length,optionalKeys:new Set(h)}});De(e._zod,"propValues",()=>{const f=t.shape,h={};for(const D in f){const m=f[D]._zod;if(m.values){h[D]??(h[D]=new Set);for(const v of m.values)h[D].add(v)}}return h});const r=i(f=>{const h=new di(["shape","payload","ctx"]),D=n.value,m=i(w=>{const C=io(w);return`shape[${C}]._zod.run({ value: input[${C}], issues: [] }, ctx)`},"parseStr");h.write("const input = payload.value;");const v=Object.create(null);let y=0;for(const w of D.keys)v[w]=`key_${y++}`;h.write("const newResult = {}");for(const w of D.keys)if(D.optionalKeys.has(w)){const C=v[w];h.write(`const ${C} = ${m(w)};`);const x=io(w);h.write(`
90
- if (${C}.issues.length) {
91
- if (input[${x}] === undefined) {
92
- if (${x} in input) {
93
- newResult[${x}] = undefined;
89
+ `))}};i(Eu,"Doc");let di=Eu;const rb={major:4,minor:0,patch:0},Ce=A("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=rb;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const o of r)for(const s of o._zod.onattach)s(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=i((s,a,u)=>{let l=lo(s),c;for(const d of a){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(l)continue;const f=s.issues.length,h=d._zod.check(s);if(h instanceof Promise&&u?.async===!1)throw new dn;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,s.issues.length!==f&&(l||(l=lo(s,f)))});else{if(s.issues.length===f)continue;l||(l=lo(s,f))}}return c?c.then(()=>s):s},"runChecks");e._zod.run=(s,a)=>{const u=e._zod.parse(s,a);if(u instanceof Promise){if(a.async===!1)throw new dn;return u.then(l=>o(l,r,a))}return o(u,r,a)}}e["~standard"]={validate:i(o=>{try{const s=h_(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return D_(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},"validate"),vendor:"zod",version:1}}),pi=A("$ZodString",(e,t)=>{Ce.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??M_(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Se=A("$ZodStringFormat",(e,t)=>{pa.init(e,t),pi.init(e,t)}),ob=A("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=F_),Se.init(e,t)}),ab=A("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=vp(r))}else t.pattern??(t.pattern=vp());Se.init(e,t)}),sb=A("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=E_),Se.init(e,t)}),ib=A("$ZodURL",(e,t)=>{Se.init(e,t),e._zod.check=n=>{try{const r=n.value,o=new URL(r),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:B_.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),ub=A("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=k_()),Se.init(e,t)}),lb=A("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=C_),Se.init(e,t)}),cb=A("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=g_),Se.init(e,t)}),db=A("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=v_),Se.init(e,t)}),pb=A("$ZodULID",(e,t)=>{t.pattern??(t.pattern=y_),Se.init(e,t)}),fb=A("$ZodXID",(e,t)=>{t.pattern??(t.pattern=__),Se.init(e,t)}),mb=A("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=b_),Se.init(e,t)}),hb=A("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=P_(t)),Se.init(e,t)}),Db=A("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=R_),Se.init(e,t)}),gb=A("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=N_(t)),Se.init(e,t)}),vb=A("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=w_),Se.init(e,t)}),yb=A("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=I_),Se.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),_b=A("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=A_),Se.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),bb=A("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=$_),Se.init(e,t)}),Cb=A("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=T_),Se.init(e,t),e._zod.check=n=>{const[r,o]=n.value.split("/");try{if(!o)throw new Error;const s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Ep(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}i(Ep,"isValidBase64");const wb=A("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=S_),Se.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{Ep(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Fb(e){if(!yp.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Ep(n)}i(Fb,"isValidBase64URL");const Eb=A("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=yp),Se.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{Fb(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),xb=A("$ZodE164",(e,t)=>{t.pattern??(t.pattern=O_),Se.init(e,t)});function kb(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}i(kb,"isValidJWT$1");const Ib=A("$ZodJWT",(e,t)=>{Se.init(e,t),e._zod.check=n=>{kb(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),xp=A("$ZodNumber",(e,t)=>{Ce.init(e,t),e._zod.pattern=e._zod.bag.pattern??z_,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),n}}),Ab=A("$ZodNumber",(e,t)=>{G_.init(e,t),xp.init(e,t)}),$b=A("$ZodBoolean",(e,t)=>{Ce.init(e,t),e._zod.pattern=L_,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),Tb=A("$ZodNull",(e,t)=>{Ce.init(e,t),e._zod.pattern=q_,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),Sb=A("$ZodAny",(e,t)=>{Ce.init(e,t),e._zod.parse=n=>n}),Bb=A("$ZodUnknown",(e,t)=>{Ce.init(e,t),e._zod.parse=n=>n}),Ob=A("$ZodNever",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function kp(e,t,n){e.issues.length&&t.issues.push(...fn(n,e.issues)),t.value[n]=e.value}i(kp,"handleArrayResult");const Rb=A("$ZodArray",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const s=[];for(let a=0;a<o.length;a++){const u=o[a],l=t.element._zod.run({value:u,issues:[]},r);l instanceof Promise?s.push(l.then(c=>kp(c,n,a))):kp(l,n,a)}return s.length?Promise.all(s).then(()=>n):n}});function fa(e,t,n){e.issues.length&&t.issues.push(...fn(n,e.issues)),t.value[n]=e.value}i(fa,"handleObjectResult");function Ip(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...fn(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}i(Ip,"handleOptionalObjectResult");const Nb=A("$ZodObject",(e,t)=>{Ce.init(e,t);const n=ii(()=>{const f=Object.keys(t.shape);for(const D of f)if(!(t.shape[D]instanceof Ce))throw new Error(`Invalid element at key "${D}": expected a Zod schema`);const h=r_(t.shape);return{shape:t.shape,keys:f,keySet:new Set(f),numKeys:f.length,optionalKeys:new Set(h)}});De(e._zod,"propValues",()=>{const f=t.shape,h={};for(const D in f){const m=f[D]._zod;if(m.values){h[D]??(h[D]=new Set);for(const v of m.values)h[D].add(v)}}return h});const r=i(f=>{const h=new di(["shape","payload","ctx"]),D=n.value,m=i(C=>{const F=io(C);return`shape[${F}]._zod.run({ value: input[${F}], issues: [] }, ctx)`},"parseStr");h.write("const input = payload.value;");const v=Object.create(null);let y=0;for(const C of D.keys)v[C]=`key_${y++}`;h.write("const newResult = {}");for(const C of D.keys)if(D.optionalKeys.has(C)){const F=v[C];h.write(`const ${F} = ${m(C)};`);const E=io(C);h.write(`
90
+ if (${F}.issues.length) {
91
+ if (input[${E}] === undefined) {
92
+ if (${E} in input) {
93
+ newResult[${E}] = undefined;
94
94
  }
95
95
  } else {
96
96
  payload.issues = payload.issues.concat(
97
- ${C}.issues.map((iss) => ({
97
+ ${F}.issues.map((iss) => ({
98
98
  ...iss,
99
- path: iss.path ? [${x}, ...iss.path] : [${x}],
99
+ path: iss.path ? [${E}, ...iss.path] : [${E}],
100
100
  }))
101
101
  );
102
102
  }
103
- } else if (${C}.value === undefined) {
104
- if (${x} in input) newResult[${x}] = undefined;
103
+ } else if (${F}.value === undefined) {
104
+ if (${E} in input) newResult[${E}] = undefined;
105
105
  } else {
106
- newResult[${x}] = ${C}.value;
106
+ newResult[${E}] = ${F}.value;
107
107
  }
108
- `)}else{const C=v[w];h.write(`const ${C} = ${m(w)};`),h.write(`
109
- if (${C}.issues.length) payload.issues = payload.issues.concat(${C}.issues.map(iss => ({
108
+ `)}else{const F=v[C];h.write(`const ${F} = ${m(C)};`),h.write(`
109
+ if (${F}.issues.length) payload.issues = payload.issues.concat(${F}.issues.map(iss => ({
110
110
  ...iss,
111
- path: iss.path ? [${io(w)}, ...iss.path] : [${io(w)}]
112
- })));`),h.write(`newResult[${io(w)}] = ${C}.value`)}h.write("payload.value = newResult;"),h.write("return payload;");const b=h.compile();return(w,C)=>b(f,w,C)},"generateFastpass");let o;const s=la,a=!cp.jitless,l=a&&Q0.value,c=t.catchall;let d;e._zod.parse=(f,h)=>{d??(d=n.value);const D=f.value;if(!s(D))return f.issues.push({expected:"object",code:"invalid_type",input:D,inst:e}),f;const m=[];if(a&&l&&h?.async===!1&&h.jitless!==!0)o||(o=r(t.shape)),f=o(f,h);else{f.value={};const C=d.shape;for(const x of d.keys){const T=C[x],O=T._zod.run({value:D[x],issues:[]},h),$=T._zod.optin==="optional"&&T._zod.optout==="optional";O instanceof Promise?m.push(O.then(I=>$?Ip(I,f,x,D):fa(I,f,x))):$?Ip(O,f,x,D):fa(O,f,x)}}if(!c)return m.length?Promise.all(m).then(()=>f):f;const v=[],y=d.keySet,b=c._zod,w=b.def.type;for(const C of Object.keys(D)){if(y.has(C))continue;if(w==="never"){v.push(C);continue}const x=b.run({value:D[C],issues:[]},h);x instanceof Promise?m.push(x.then(T=>fa(T,f,C))):fa(x,f,C)}return v.length&&f.issues.push({code:"unrecognized_keys",keys:v,input:D,inst:e}),m.length?Promise.all(m).then(()=>f):f}});function Ap(e,t,n,r){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>Ht(s,r,Wt())))}),t}i(Ap,"handleUnionResults");const $p=A("$ZodUnion",(e,t)=>{Ce.init(e,t),De(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),De(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),De(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),De(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>li(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let o=!1;const s=[];for(const a of t.options){const u=a._zod.run({value:n.value,issues:[]},r);if(u instanceof Promise)s.push(u),o=!0;else{if(u.issues.length===0)return u;s.push(u)}}return o?Promise.all(s).then(a=>Ap(a,n,e,r)):Ap(s,n,e,r)}}),Rb=A("$ZodDiscriminatedUnion",(e,t)=>{$p.init(e,t);const n=e._zod.parse;De(e._zod,"propValues",()=>{const o={};for(const s of t.options){const a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[u,l]of Object.entries(a)){o[u]||(o[u]=new Set);for(const c of l)o[u].add(c)}}return o});const r=ii(()=>{const o=t.options,s=new Map;for(const a of o){const u=a._zod.propValues[t.discriminator];if(!u||u.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const l of u){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,a)}}return s});e._zod.parse=(o,s)=>{const a=o.value;if(!la(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const u=r.value.get(a?.[t.discriminator]);return u?u._zod.run(o,s):t.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),o)}}),Nb=A("$ZodIntersection",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>{const o=n.value,s=t.left._zod.run({value:o,issues:[]},r),a=t.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([l,c])=>Tp(n,l,c)):Tp(n,s,a)}});function fi(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(ca(e)&&ca(t)){const n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};for(const s of r){const a=fi(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};o[s]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=e[r],s=t[r],a=fi(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}i(fi,"mergeValues$1");function Tp(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),lo(e))return e;const r=fi(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}i(Tp,"handleIntersectionResults");const Pb=A("$ZodRecord",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!ca(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const s=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;n.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:o[l],issues:[]},r);c instanceof Promise?s.push(c.then(d=>{d.issues.length&&n.issues.push(...fn(l,d.issues)),n.value[l]=d.value})):(c.issues.length&&n.issues.push(...fn(l,c.issues)),n.value[l]=c.value)}let u;for(const l in o)a.has(l)||(u=u??[],u.push(l));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u})}else{n.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const u=t.keyType._zod.run({value:a,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:u.issues.map(c=>Ht(c,r,Wt())),input:a,path:[a],inst:e}),n.value[u.value]=u.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},r);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&n.issues.push(...fn(a,c.issues)),n.value[u.value]=c.value})):(l.issues.length&&n.issues.push(...fn(a,l.issues)),n.value[u.value]=l.value)}}return s.length?Promise.all(s).then(()=>n):n}}),Mb=A("$ZodEnum",(e,t)=>{Ce.init(e,t);const n=dp(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>e_.has(typeof r)).map(r=>typeof r=="string"?uo(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{const s=r.value;return e._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),jb=A("$ZodLiteral",(e,t)=>{Ce.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?uo(n):n?n.toString():String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}}),zb=A("$ZodTransform",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>{const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(n.value=a,n));if(o instanceof Promise)throw new dn;return n.value=o,n}}),Lb=A("$ZodOptional",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",e._zod.optout="optional",De(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),De(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${li(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,r):n.value===void 0?n:t.innerType._zod.run(n,r)}),qb=A("$ZodNullable",(e,t)=>{Ce.init(e,t),De(e._zod,"optin",()=>t.innerType._zod.optin),De(e._zod,"optout",()=>t.innerType._zod.optout),De(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${li(n.source)}|null)$`):void 0}),De(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),Ub=A("$ZodDefault",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",De(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Sp(s,t)):Sp(o,t)}});function Sp(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}i(Sp,"handleDefaultResult");const Zb=A("$ZodPrefault",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",De(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),Vb=A("$ZodNonOptional",(e,t)=>{Ce.init(e,t),De(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Bp(s,e)):Bp(o,e)}});function Bp(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}i(Bp,"handleNonOptionalResult");const Gb=A("$ZodCatch",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",De(e._zod,"optout",()=>t.innerType._zod.optout),De(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(a=>Ht(a,r,Wt()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>Ht(s,r,Wt()))},input:n.value}),n.issues=[]),n)}}),Wb=A("$ZodPipe",(e,t)=>{Ce.init(e,t),De(e._zod,"values",()=>t.in._zod.values),De(e._zod,"optin",()=>t.in._zod.optin),De(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{const o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Op(s,t,r)):Op(o,t,r)}});function Op(e,t,n){return lo(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}i(Op,"handlePipeResult");const Hb=A("$ZodReadonly",(e,t)=>{Ce.init(e,t),De(e._zod,"propValues",()=>t.innerType._zod.propValues),De(e._zod,"values",()=>t.innerType._zod.values),De(e._zod,"optin",()=>t.innerType._zod.optin),De(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(Rp):Rp(o)}});function Rp(e){return e.value=Object.freeze(e.value),e}i(Rp,"handleReadonlyResult");const Jb=A("$ZodLazy",(e,t)=>{Ce.init(e,t),De(e._zod,"innerType",()=>t.getter()),De(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),De(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),De(e._zod,"optin",()=>e._zod.innerType._zod.optin),De(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),Kb=A("$ZodCustom",(e,t)=>{it.init(e,t),Ce.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(s=>Np(s,n,r,e));Np(o,n,r,e)}});function Np(e,t,n,r){if(!e){const o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(co(o))}}i(Np,"handleRefineResult");const xu=class xu{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const r=n[0];if(this._map.set(t,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};i(xu,"$ZodRegistry");let ma=xu;function Yb(){return new ma}i(Yb,"registry");const po=Yb();function Xb(e,t){return new e({type:"string",...G(t)})}i(Xb,"_string");function Qb(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...G(t)})}i(Qb,"_email");function Pp(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...G(t)})}i(Pp,"_guid");function eC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...G(t)})}i(eC,"_uuid");function tC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...G(t)})}i(tC,"_uuidv4");function nC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...G(t)})}i(nC,"_uuidv6");function rC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...G(t)})}i(rC,"_uuidv7");function oC(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...G(t)})}i(oC,"_url");function aC(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...G(t)})}i(aC,"_emoji");function sC(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...G(t)})}i(sC,"_nanoid");function iC(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...G(t)})}i(iC,"_cuid");function uC(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...G(t)})}i(uC,"_cuid2");function lC(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...G(t)})}i(lC,"_ulid");function cC(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...G(t)})}i(cC,"_xid");function dC(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...G(t)})}i(dC,"_ksuid");function pC(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...G(t)})}i(pC,"_ipv4");function fC(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...G(t)})}i(fC,"_ipv6");function mC(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...G(t)})}i(mC,"_cidrv4");function hC(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...G(t)})}i(hC,"_cidrv6");function DC(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...G(t)})}i(DC,"_base64");function gC(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...G(t)})}i(gC,"_base64url");function vC(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...G(t)})}i(vC,"_e164");function yC(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...G(t)})}i(yC,"_jwt");function _C(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...G(t)})}i(_C,"_isoDateTime");function bC(e,t){return new e({type:"string",format:"date",check:"string_format",...G(t)})}i(bC,"_isoDate");function CC(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...G(t)})}i(CC,"_isoTime");function wC(e,t){return new e({type:"string",format:"duration",check:"string_format",...G(t)})}i(wC,"_isoDuration");function FC(e,t){return new e({type:"number",checks:[],...G(t)})}i(FC,"_number");function EC(e,t){return new e({type:"number",coerce:!0,checks:[],...G(t)})}i(EC,"_coercedNumber");function xC(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...G(t)})}i(xC,"_int");function kC(e,t){return new e({type:"boolean",...G(t)})}i(kC,"_boolean");function IC(e,t){return new e({type:"null",...G(t)})}i(IC,"_null$1");function AC(e){return new e({type:"any"})}i(AC,"_any");function $C(e){return new e({type:"unknown"})}i($C,"_unknown");function TC(e,t){return new e({type:"never",...G(t)})}i(TC,"_never");function Mp(e,t){return new wp({check:"less_than",...G(t),value:e,inclusive:!1})}i(Mp,"_lt");function mi(e,t){return new wp({check:"less_than",...G(t),value:e,inclusive:!0})}i(mi,"_lte");function jp(e,t){return new Fp({check:"greater_than",...G(t),value:e,inclusive:!1})}i(jp,"_gt");function hi(e,t){return new Fp({check:"greater_than",...G(t),value:e,inclusive:!0})}i(hi,"_gte");function zp(e,t){return new U_({check:"multiple_of",...G(t),value:e})}i(zp,"_multipleOf");function Lp(e,t){return new V_({check:"max_length",...G(t),maximum:e})}i(Lp,"_maxLength");function ha(e,t){return new G_({check:"min_length",...G(t),minimum:e})}i(ha,"_minLength");function qp(e,t){return new W_({check:"length_equals",...G(t),length:e})}i(qp,"_length");function SC(e,t){return new H_({check:"string_format",format:"regex",...G(t),pattern:e})}i(SC,"_regex");function BC(e){return new J_({check:"string_format",format:"lowercase",...G(e)})}i(BC,"_lowercase");function OC(e){return new K_({check:"string_format",format:"uppercase",...G(e)})}i(OC,"_uppercase");function RC(e,t){return new Y_({check:"string_format",format:"includes",...G(t),includes:e})}i(RC,"_includes");function NC(e,t){return new X_({check:"string_format",format:"starts_with",...G(t),prefix:e})}i(NC,"_startsWith");function PC(e,t){return new Q_({check:"string_format",format:"ends_with",...G(t),suffix:e})}i(PC,"_endsWith");function fo(e){return new eb({check:"overwrite",tx:e})}i(fo,"_overwrite");function MC(e){return fo(t=>t.normalize(e))}i(MC,"_normalize");function jC(){return fo(e=>e.trim())}i(jC,"_trim");function zC(){return fo(e=>e.toLowerCase())}i(zC,"_toLowerCase");function LC(){return fo(e=>e.toUpperCase())}i(LC,"_toUpperCase");function qC(e,t,n){return new e({type:"array",element:t,...G(n)})}i(qC,"_array");function UC(e,t,n){const r=G(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}i(UC,"_custom");function ZC(e,t,n){return new e({type:"custom",check:"custom",fn:t,...G(n)})}i(ZC,"_refine");const ku=class ku{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??po,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var r;const o=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(t);if(a)return a.count++,n.schemaPath.includes(t)&&(a.cycle=n.path),a.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,u);const l=t._zod.toJSONSchema?.();if(l)u.schema=l;else{const f={...n,schemaPath:[...n.schemaPath,t],path:n.path},h=t._zod.parent;if(h)u.ref=h,this.process(h,f),this.seen.get(h).isParent=!0;else{const D=u.schema;switch(o.type){case"string":{const m=D;m.type="string";const{minimum:v,maximum:y,format:b,patterns:w,contentEncoding:C}=t._zod.bag;if(typeof v=="number"&&(m.minLength=v),typeof y=="number"&&(m.maxLength=y),b&&(m.format=s[b]??b,m.format===""&&delete m.format),C&&(m.contentEncoding=C),w&&w.size>0){const x=[...w];x.length===1?m.pattern=x[0].source:x.length>1&&(u.schema.allOf=[...x.map(T=>({...this.target==="draft-7"?{type:"string"}:{},pattern:T.source}))])}break}case"number":{const m=D,{minimum:v,maximum:y,format:b,multipleOf:w,exclusiveMaximum:C,exclusiveMinimum:x}=t._zod.bag;typeof b=="string"&&b.includes("int")?m.type="integer":m.type="number",typeof x=="number"&&(m.exclusiveMinimum=x),typeof v=="number"&&(m.minimum=v,typeof x=="number"&&(x>=v?delete m.minimum:delete m.exclusiveMinimum)),typeof C=="number"&&(m.exclusiveMaximum=C),typeof y=="number"&&(m.maximum=y,typeof C=="number"&&(C<=y?delete m.maximum:delete m.exclusiveMaximum)),typeof w=="number"&&(m.multipleOf=w);break}case"boolean":{const m=D;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{D.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{D.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const m=D,{minimum:v,maximum:y}=t._zod.bag;typeof v=="number"&&(m.minItems=v),typeof y=="number"&&(m.maxItems=y),m.type="array",m.items=this.process(o.element,{...f,path:[...f.path,"items"]});break}case"object":{const m=D;m.type="object",m.properties={};const v=o.shape;for(const w in v)m.properties[w]=this.process(v[w],{...f,path:[...f.path,"properties",w]});const y=new Set(Object.keys(v)),b=new Set([...y].filter(w=>{const C=o.shape[w]._zod;return this.io==="input"?C.optin===void 0:C.optout===void 0}));b.size>0&&(m.required=Array.from(b)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...f,path:[...f.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{const m=D;m.anyOf=o.options.map((v,y)=>this.process(v,{...f,path:[...f.path,"anyOf",y]}));break}case"intersection":{const m=D,v=this.process(o.left,{...f,path:[...f.path,"allOf",0]}),y=this.process(o.right,{...f,path:[...f.path,"allOf",1]}),b=i(C=>"allOf"in C&&Object.keys(C).length===1,"isSimpleIntersection"),w=[...b(v)?v.allOf:[v],...b(y)?y.allOf:[y]];m.allOf=w;break}case"tuple":{const m=D;m.type="array";const v=o.items.map((w,C)=>this.process(w,{...f,path:[...f.path,"prefixItems",C]}));if(this.target==="draft-2020-12"?m.prefixItems=v:m.items=v,o.rest){const w=this.process(o.rest,{...f,path:[...f.path,"items"]});this.target==="draft-2020-12"?m.items=w:m.additionalItems=w}o.rest&&(m.items=this.process(o.rest,{...f,path:[...f.path,"items"]}));const{minimum:y,maximum:b}=t._zod.bag;typeof y=="number"&&(m.minItems=y),typeof b=="number"&&(m.maxItems=b);break}case"record":{const m=D;m.type="object",m.propertyNames=this.process(o.keyType,{...f,path:[...f.path,"propertyNames"]}),m.additionalProperties=this.process(o.valueType,{...f,path:[...f.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const m=D,v=dp(o.entries);v.every(y=>typeof y=="number")&&(m.type="number"),v.every(y=>typeof y=="string")&&(m.type="string"),m.enum=v;break}case"literal":{const m=D,v=[];for(const y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");v.push(Number(y))}else v.push(y);if(v.length!==0)if(v.length===1){const y=v[0];m.type=y===null?"null":typeof y,m.const=y}else v.every(y=>typeof y=="number")&&(m.type="number"),v.every(y=>typeof y=="string")&&(m.type="string"),v.every(y=>typeof y=="boolean")&&(m.type="string"),v.every(y=>y===null)&&(m.type="null"),m.enum=v;break}case"file":{const m=D,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:b,mime:w}=t._zod.bag;y!==void 0&&(v.minLength=y),b!==void 0&&(v.maxLength=b),w?w.length===1?(v.contentMediaType=w[0],Object.assign(m,v)):m.anyOf=w.map(C=>({...v,contentMediaType:C})):Object.assign(m,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const m=this.process(o.innerType,f);D.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,f),u.ref=o.innerType;break}case"success":{const m=D;m.type="boolean";break}case"default":{this.process(o.innerType,f),u.ref=o.innerType,D.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,f),u.ref=o.innerType,this.io==="input"&&(D._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,f),u.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}D.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const m=D,v=t._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=v.source;break}case"pipe":{const m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,f),u.ref=m;break}case"readonly":{this.process(o.innerType,f),u.ref=o.innerType,D.readOnly=!0;break}case"promise":{this.process(o.innerType,f),u.ref=o.innerType;break}case"optional":{this.process(o.innerType,f),u.ref=o.innerType;break}case"lazy":{const m=t._zod.innerType;this.process(m,f),u.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(u.schema,c),this.io==="input"&&Ze(t)&&(delete u.schema.examples,delete u.schema.default),this.io==="input"&&u.schema._prefault&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,this.seen.get(t).schema}emit(t,n){const r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=i(d=>{const f=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const v=r.external.registry.get(d[0])?.id,y=r.external.uri??(w=>w);if(v)return{ref:y(v)};const b=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=b,{defId:b,ref:`${y("__shared")}#/${f}/${b}`}}if(d[1]===o)return{ref:"#"};const D=`#/${f}/`,m=d[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:D+m}},"makeURI"),a=i(d=>{if(d[1].schema.$ref)return;const f=d[1],{ref:h,defId:D}=s(d);f.def={...f.schema},D&&(f.defId=D);const m=f.schema;for(const v in m)delete m[v];m.$ref=h},"extractToDef");if(r.cycles==="throw")for(const d of this.seen.entries()){const f=d[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/<root>
111
+ path: iss.path ? [${io(C)}, ...iss.path] : [${io(C)}]
112
+ })));`),h.write(`newResult[${io(C)}] = ${F}.value`)}h.write("payload.value = newResult;"),h.write("return payload;");const b=h.compile();return(C,F)=>b(f,C,F)},"generateFastpass");let o;const s=la,a=!cp.jitless,l=a&&t_.value,c=t.catchall;let d;e._zod.parse=(f,h)=>{d??(d=n.value);const D=f.value;if(!s(D))return f.issues.push({expected:"object",code:"invalid_type",input:D,inst:e}),f;const m=[];if(a&&l&&h?.async===!1&&h.jitless!==!0)o||(o=r(t.shape)),f=o(f,h);else{f.value={};const F=d.shape;for(const E of d.keys){const T=F[E],O=T._zod.run({value:D[E],issues:[]},h),$=T._zod.optin==="optional"&&T._zod.optout==="optional";O instanceof Promise?m.push(O.then(I=>$?Ip(I,f,E,D):fa(I,f,E))):$?Ip(O,f,E,D):fa(O,f,E)}}if(!c)return m.length?Promise.all(m).then(()=>f):f;const v=[],y=d.keySet,b=c._zod,C=b.def.type;for(const F of Object.keys(D)){if(y.has(F))continue;if(C==="never"){v.push(F);continue}const E=b.run({value:D[F],issues:[]},h);E instanceof Promise?m.push(E.then(T=>fa(T,f,F))):fa(E,f,F)}return v.length&&f.issues.push({code:"unrecognized_keys",keys:v,input:D,inst:e}),m.length?Promise.all(m).then(()=>f):f}});function Ap(e,t,n,r){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>Ht(s,r,Wt())))}),t}i(Ap,"handleUnionResults");const $p=A("$ZodUnion",(e,t)=>{Ce.init(e,t),De(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),De(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),De(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),De(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>li(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let o=!1;const s=[];for(const a of t.options){const u=a._zod.run({value:n.value,issues:[]},r);if(u instanceof Promise)s.push(u),o=!0;else{if(u.issues.length===0)return u;s.push(u)}}return o?Promise.all(s).then(a=>Ap(a,n,e,r)):Ap(s,n,e,r)}}),Pb=A("$ZodDiscriminatedUnion",(e,t)=>{$p.init(e,t);const n=e._zod.parse;De(e._zod,"propValues",()=>{const o={};for(const s of t.options){const a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[u,l]of Object.entries(a)){o[u]||(o[u]=new Set);for(const c of l)o[u].add(c)}}return o});const r=ii(()=>{const o=t.options,s=new Map;for(const a of o){const u=a._zod.propValues[t.discriminator];if(!u||u.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const l of u){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,a)}}return s});e._zod.parse=(o,s)=>{const a=o.value;if(!la(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const u=r.value.get(a?.[t.discriminator]);return u?u._zod.run(o,s):t.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),o)}}),Mb=A("$ZodIntersection",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>{const o=n.value,s=t.left._zod.run({value:o,issues:[]},r),a=t.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([l,c])=>Tp(n,l,c)):Tp(n,s,a)}});function fi(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(ca(e)&&ca(t)){const n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};for(const s of r){const a=fi(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};o[s]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=e[r],s=t[r],a=fi(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}i(fi,"mergeValues$1");function Tp(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),lo(e))return e;const r=fi(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}i(Tp,"handleIntersectionResults");const jb=A("$ZodRecord",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!ca(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const s=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;n.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:o[l],issues:[]},r);c instanceof Promise?s.push(c.then(d=>{d.issues.length&&n.issues.push(...fn(l,d.issues)),n.value[l]=d.value})):(c.issues.length&&n.issues.push(...fn(l,c.issues)),n.value[l]=c.value)}let u;for(const l in o)a.has(l)||(u=u??[],u.push(l));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u})}else{n.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const u=t.keyType._zod.run({value:a,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(u.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:u.issues.map(c=>Ht(c,r,Wt())),input:a,path:[a],inst:e}),n.value[u.value]=u.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},r);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&n.issues.push(...fn(a,c.issues)),n.value[u.value]=c.value})):(l.issues.length&&n.issues.push(...fn(a,l.issues)),n.value[u.value]=l.value)}}return s.length?Promise.all(s).then(()=>n):n}}),zb=A("$ZodEnum",(e,t)=>{Ce.init(e,t);const n=dp(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>n_.has(typeof r)).map(r=>typeof r=="string"?uo(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{const s=r.value;return e._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:e}),r}}),Lb=A("$ZodLiteral",(e,t)=>{Ce.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?uo(n):n?n.toString():String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}}),qb=A("$ZodTransform",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>{const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(n.value=a,n));if(o instanceof Promise)throw new dn;return n.value=o,n}}),Ub=A("$ZodOptional",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",e._zod.optout="optional",De(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),De(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${li(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,r):n.value===void 0?n:t.innerType._zod.run(n,r)}),Zb=A("$ZodNullable",(e,t)=>{Ce.init(e,t),De(e._zod,"optin",()=>t.innerType._zod.optin),De(e._zod,"optout",()=>t.innerType._zod.optout),De(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${li(n.source)}|null)$`):void 0}),De(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),Vb=A("$ZodDefault",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",De(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Sp(s,t)):Sp(o,t)}});function Sp(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}i(Sp,"handleDefaultResult");const Gb=A("$ZodPrefault",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",De(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),Wb=A("$ZodNonOptional",(e,t)=>{Ce.init(e,t),De(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Bp(s,e)):Bp(o,e)}});function Bp(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}i(Bp,"handleNonOptionalResult");const Hb=A("$ZodCatch",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",De(e._zod,"optout",()=>t.innerType._zod.optout),De(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(a=>Ht(a,r,Wt()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>Ht(s,r,Wt()))},input:n.value}),n.issues=[]),n)}}),Jb=A("$ZodPipe",(e,t)=>{Ce.init(e,t),De(e._zod,"values",()=>t.in._zod.values),De(e._zod,"optin",()=>t.in._zod.optin),De(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{const o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Op(s,t,r)):Op(o,t,r)}});function Op(e,t,n){return lo(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}i(Op,"handlePipeResult");const Kb=A("$ZodReadonly",(e,t)=>{Ce.init(e,t),De(e._zod,"propValues",()=>t.innerType._zod.propValues),De(e._zod,"values",()=>t.innerType._zod.values),De(e._zod,"optin",()=>t.innerType._zod.optin),De(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(Rp):Rp(o)}});function Rp(e){return e.value=Object.freeze(e.value),e}i(Rp,"handleReadonlyResult");const Yb=A("$ZodLazy",(e,t)=>{Ce.init(e,t),De(e._zod,"innerType",()=>t.getter()),De(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),De(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),De(e._zod,"optin",()=>e._zod.innerType._zod.optin),De(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),Xb=A("$ZodCustom",(e,t)=>{it.init(e,t),Ce.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(s=>Np(s,n,r,e));Np(o,n,r,e)}});function Np(e,t,n,r){if(!e){const o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(co(o))}}i(Np,"handleRefineResult");const xu=class xu{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const r=n[0];if(this._map.set(t,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};i(xu,"$ZodRegistry");let ma=xu;function Qb(){return new ma}i(Qb,"registry");const po=Qb();function eC(e,t){return new e({type:"string",...G(t)})}i(eC,"_string");function tC(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...G(t)})}i(tC,"_email");function Pp(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...G(t)})}i(Pp,"_guid");function nC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...G(t)})}i(nC,"_uuid");function rC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...G(t)})}i(rC,"_uuidv4");function oC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...G(t)})}i(oC,"_uuidv6");function aC(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...G(t)})}i(aC,"_uuidv7");function sC(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...G(t)})}i(sC,"_url");function iC(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...G(t)})}i(iC,"_emoji");function uC(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...G(t)})}i(uC,"_nanoid");function lC(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...G(t)})}i(lC,"_cuid");function cC(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...G(t)})}i(cC,"_cuid2");function dC(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...G(t)})}i(dC,"_ulid");function pC(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...G(t)})}i(pC,"_xid");function fC(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...G(t)})}i(fC,"_ksuid");function mC(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...G(t)})}i(mC,"_ipv4");function hC(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...G(t)})}i(hC,"_ipv6");function DC(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...G(t)})}i(DC,"_cidrv4");function gC(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...G(t)})}i(gC,"_cidrv6");function vC(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...G(t)})}i(vC,"_base64");function yC(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...G(t)})}i(yC,"_base64url");function _C(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...G(t)})}i(_C,"_e164");function bC(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...G(t)})}i(bC,"_jwt");function CC(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...G(t)})}i(CC,"_isoDateTime");function wC(e,t){return new e({type:"string",format:"date",check:"string_format",...G(t)})}i(wC,"_isoDate");function FC(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...G(t)})}i(FC,"_isoTime");function EC(e,t){return new e({type:"string",format:"duration",check:"string_format",...G(t)})}i(EC,"_isoDuration");function xC(e,t){return new e({type:"number",checks:[],...G(t)})}i(xC,"_number");function kC(e,t){return new e({type:"number",coerce:!0,checks:[],...G(t)})}i(kC,"_coercedNumber");function IC(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...G(t)})}i(IC,"_int");function AC(e,t){return new e({type:"boolean",...G(t)})}i(AC,"_boolean");function $C(e,t){return new e({type:"null",...G(t)})}i($C,"_null$1");function TC(e){return new e({type:"any"})}i(TC,"_any");function SC(e){return new e({type:"unknown"})}i(SC,"_unknown");function BC(e,t){return new e({type:"never",...G(t)})}i(BC,"_never");function Mp(e,t){return new wp({check:"less_than",...G(t),value:e,inclusive:!1})}i(Mp,"_lt");function mi(e,t){return new wp({check:"less_than",...G(t),value:e,inclusive:!0})}i(mi,"_lte");function jp(e,t){return new Fp({check:"greater_than",...G(t),value:e,inclusive:!1})}i(jp,"_gt");function hi(e,t){return new Fp({check:"greater_than",...G(t),value:e,inclusive:!0})}i(hi,"_gte");function zp(e,t){return new V_({check:"multiple_of",...G(t),value:e})}i(zp,"_multipleOf");function Lp(e,t){return new W_({check:"max_length",...G(t),maximum:e})}i(Lp,"_maxLength");function ha(e,t){return new H_({check:"min_length",...G(t),minimum:e})}i(ha,"_minLength");function qp(e,t){return new J_({check:"length_equals",...G(t),length:e})}i(qp,"_length");function OC(e,t){return new K_({check:"string_format",format:"regex",...G(t),pattern:e})}i(OC,"_regex");function RC(e){return new Y_({check:"string_format",format:"lowercase",...G(e)})}i(RC,"_lowercase");function NC(e){return new X_({check:"string_format",format:"uppercase",...G(e)})}i(NC,"_uppercase");function PC(e,t){return new Q_({check:"string_format",format:"includes",...G(t),includes:e})}i(PC,"_includes");function MC(e,t){return new eb({check:"string_format",format:"starts_with",...G(t),prefix:e})}i(MC,"_startsWith");function jC(e,t){return new tb({check:"string_format",format:"ends_with",...G(t),suffix:e})}i(jC,"_endsWith");function fo(e){return new nb({check:"overwrite",tx:e})}i(fo,"_overwrite");function zC(e){return fo(t=>t.normalize(e))}i(zC,"_normalize");function LC(){return fo(e=>e.trim())}i(LC,"_trim");function qC(){return fo(e=>e.toLowerCase())}i(qC,"_toLowerCase");function UC(){return fo(e=>e.toUpperCase())}i(UC,"_toUpperCase");function ZC(e,t,n){return new e({type:"array",element:t,...G(n)})}i(ZC,"_array");function VC(e,t,n){const r=G(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}i(VC,"_custom");function GC(e,t,n){return new e({type:"custom",check:"custom",fn:t,...G(n)})}i(GC,"_refine");const ku=class ku{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??po,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var r;const o=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(t);if(a)return a.count++,n.schemaPath.includes(t)&&(a.cycle=n.path),a.schema;const u={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,u);const l=t._zod.toJSONSchema?.();if(l)u.schema=l;else{const f={...n,schemaPath:[...n.schemaPath,t],path:n.path},h=t._zod.parent;if(h)u.ref=h,this.process(h,f),this.seen.get(h).isParent=!0;else{const D=u.schema;switch(o.type){case"string":{const m=D;m.type="string";const{minimum:v,maximum:y,format:b,patterns:C,contentEncoding:F}=t._zod.bag;if(typeof v=="number"&&(m.minLength=v),typeof y=="number"&&(m.maxLength=y),b&&(m.format=s[b]??b,m.format===""&&delete m.format),F&&(m.contentEncoding=F),C&&C.size>0){const E=[...C];E.length===1?m.pattern=E[0].source:E.length>1&&(u.schema.allOf=[...E.map(T=>({...this.target==="draft-7"?{type:"string"}:{},pattern:T.source}))])}break}case"number":{const m=D,{minimum:v,maximum:y,format:b,multipleOf:C,exclusiveMaximum:F,exclusiveMinimum:E}=t._zod.bag;typeof b=="string"&&b.includes("int")?m.type="integer":m.type="number",typeof E=="number"&&(m.exclusiveMinimum=E),typeof v=="number"&&(m.minimum=v,typeof E=="number"&&(E>=v?delete m.minimum:delete m.exclusiveMinimum)),typeof F=="number"&&(m.exclusiveMaximum=F),typeof y=="number"&&(m.maximum=y,typeof F=="number"&&(F<=y?delete m.maximum:delete m.exclusiveMaximum)),typeof C=="number"&&(m.multipleOf=C);break}case"boolean":{const m=D;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{D.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{D.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const m=D,{minimum:v,maximum:y}=t._zod.bag;typeof v=="number"&&(m.minItems=v),typeof y=="number"&&(m.maxItems=y),m.type="array",m.items=this.process(o.element,{...f,path:[...f.path,"items"]});break}case"object":{const m=D;m.type="object",m.properties={};const v=o.shape;for(const C in v)m.properties[C]=this.process(v[C],{...f,path:[...f.path,"properties",C]});const y=new Set(Object.keys(v)),b=new Set([...y].filter(C=>{const F=o.shape[C]._zod;return this.io==="input"?F.optin===void 0:F.optout===void 0}));b.size>0&&(m.required=Array.from(b)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...f,path:[...f.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{const m=D;m.anyOf=o.options.map((v,y)=>this.process(v,{...f,path:[...f.path,"anyOf",y]}));break}case"intersection":{const m=D,v=this.process(o.left,{...f,path:[...f.path,"allOf",0]}),y=this.process(o.right,{...f,path:[...f.path,"allOf",1]}),b=i(F=>"allOf"in F&&Object.keys(F).length===1,"isSimpleIntersection"),C=[...b(v)?v.allOf:[v],...b(y)?y.allOf:[y]];m.allOf=C;break}case"tuple":{const m=D;m.type="array";const v=o.items.map((C,F)=>this.process(C,{...f,path:[...f.path,"prefixItems",F]}));if(this.target==="draft-2020-12"?m.prefixItems=v:m.items=v,o.rest){const C=this.process(o.rest,{...f,path:[...f.path,"items"]});this.target==="draft-2020-12"?m.items=C:m.additionalItems=C}o.rest&&(m.items=this.process(o.rest,{...f,path:[...f.path,"items"]}));const{minimum:y,maximum:b}=t._zod.bag;typeof y=="number"&&(m.minItems=y),typeof b=="number"&&(m.maxItems=b);break}case"record":{const m=D;m.type="object",m.propertyNames=this.process(o.keyType,{...f,path:[...f.path,"propertyNames"]}),m.additionalProperties=this.process(o.valueType,{...f,path:[...f.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const m=D,v=dp(o.entries);v.every(y=>typeof y=="number")&&(m.type="number"),v.every(y=>typeof y=="string")&&(m.type="string"),m.enum=v;break}case"literal":{const m=D,v=[];for(const y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");v.push(Number(y))}else v.push(y);if(v.length!==0)if(v.length===1){const y=v[0];m.type=y===null?"null":typeof y,m.const=y}else v.every(y=>typeof y=="number")&&(m.type="number"),v.every(y=>typeof y=="string")&&(m.type="string"),v.every(y=>typeof y=="boolean")&&(m.type="string"),v.every(y=>y===null)&&(m.type="null"),m.enum=v;break}case"file":{const m=D,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:b,mime:C}=t._zod.bag;y!==void 0&&(v.minLength=y),b!==void 0&&(v.maxLength=b),C?C.length===1?(v.contentMediaType=C[0],Object.assign(m,v)):m.anyOf=C.map(F=>({...v,contentMediaType:F})):Object.assign(m,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const m=this.process(o.innerType,f);D.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,f),u.ref=o.innerType;break}case"success":{const m=D;m.type="boolean";break}case"default":{this.process(o.innerType,f),u.ref=o.innerType,D.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,f),u.ref=o.innerType,this.io==="input"&&(D._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,f),u.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}D.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const m=D,v=t._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=v.source;break}case"pipe":{const m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,f),u.ref=m;break}case"readonly":{this.process(o.innerType,f),u.ref=o.innerType,D.readOnly=!0;break}case"promise":{this.process(o.innerType,f),u.ref=o.innerType;break}case"optional":{this.process(o.innerType,f),u.ref=o.innerType;break}case"lazy":{const m=t._zod.innerType;this.process(m,f),u.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(u.schema,c),this.io==="input"&&Ze(t)&&(delete u.schema.examples,delete u.schema.default),this.io==="input"&&u.schema._prefault&&((r=u.schema).default??(r.default=u.schema._prefault)),delete u.schema._prefault,this.seen.get(t).schema}emit(t,n){const r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=i(d=>{const f=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const v=r.external.registry.get(d[0])?.id,y=r.external.uri??(C=>C);if(v)return{ref:y(v)};const b=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=b,{defId:b,ref:`${y("__shared")}#/${f}/${b}`}}if(d[1]===o)return{ref:"#"};const D=`#/${f}/`,m=d[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:D+m}},"makeURI"),a=i(d=>{if(d[1].schema.$ref)return;const f=d[1],{ref:h,defId:D}=s(d);f.def={...f.schema},D&&(f.defId=D);const m=f.schema;for(const v in m)delete m[v];m.$ref=h},"extractToDef");if(r.cycles==="throw")for(const d of this.seen.entries()){const f=d[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/<root>
113
113
 
114
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const d of this.seen.entries()){const f=d[1];if(t===d[0]){a(d);continue}if(r.external){const D=r.external.registry.get(d[0])?.id;if(t!==d[0]&&D){a(d);continue}}if(this.metadataRegistry.get(d[0])?.id){a(d);continue}if(f.cycle){a(d);continue}if(f.count>1&&r.reused==="ref"){a(d);continue}}const u=i((d,f)=>{const h=this.seen.get(d),D=h.def??h.schema,m={...D};if(h.ref===null)return;const v=h.ref;if(h.ref=null,v){u(v,f);const y=this.seen.get(v).schema;y.$ref&&f.target==="draft-7"?(D.allOf=D.allOf??[],D.allOf.push(y)):(Object.assign(D,y),Object.assign(D,m))}h.isParent||this.override({zodSchema:d,jsonSchema:D,path:h.path??[]})},"flattenRef");for(const d of[...this.seen.entries()].reverse())u(d[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){const d=r.external.registry.get(t)?.id;if(!d)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(d)}Object.assign(l,o.def);const c=r.external?.defs??{};for(const d of this.seen.entries()){const f=d[1];f.def&&f.defId&&(c[f.defId]=f.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}};i(ku,"JSONSchemaGenerator");let Da=ku;function VC(e,t){if(e instanceof ma){const r=new Da(t),o={};for(const u of e._idmap.entries()){const[l,c]=u;r.process(c)}const s={},a={registry:e,uri:t?.uri,defs:o};for(const u of e._idmap.entries()){const[l,c]=u;s[l]=r.emit(c,{...t,external:a})}if(Object.keys(o).length>0){const u=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[u]:o}}return{schemas:s}}const n=new Da(t);return n.process(e),n.emit(e,t)}i(VC,"toJSONSchema");function Ze(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const o=e._zod.def;switch(o.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":return!1;case"array":return Ze(o.element,n);case"object":{for(const s in o.shape)if(Ze(o.shape[s],n))return!0;return!1}case"union":{for(const s of o.options)if(Ze(s,n))return!0;return!1}case"intersection":return Ze(o.left,n)||Ze(o.right,n);case"tuple":{for(const s of o.items)if(Ze(s,n))return!0;return!!(o.rest&&Ze(o.rest,n))}case"record":return Ze(o.keyType,n)||Ze(o.valueType,n);case"map":return Ze(o.keyType,n)||Ze(o.valueType,n);case"set":return Ze(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ze(o.innerType,n);case"lazy":return Ze(o.getter(),n);case"default":return Ze(o.innerType,n);case"prefault":return Ze(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Ze(o.in,n)||Ze(o.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}i(Ze,"isTransforming");const GC=A("ZodISODateTime",(e,t)=>{fb.init(e,t),Oe.init(e,t)});function WC(e){return _C(GC,e)}i(WC,"datetime");const HC=A("ZodISODate",(e,t)=>{mb.init(e,t),Oe.init(e,t)});function JC(e){return bC(HC,e)}i(JC,"date");const KC=A("ZodISOTime",(e,t)=>{hb.init(e,t),Oe.init(e,t)});function YC(e){return CC(KC,e)}i(YC,"time");const XC=A("ZodISODuration",(e,t)=>{Db.init(e,t),Oe.init(e,t)});function QC(e){return wC(XC,e)}i(QC,"duration");const ew=i((e,t)=>{mp.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:i(n=>c_(e,n),"value")},flatten:{value:i(n=>l_(e,n),"value")},addIssue:{value:i(n=>e.issues.push(n),"value")},addIssues:{value:i(n=>e.issues.push(...n),"value")},isEmpty:{get(){return e.issues.length===0}}})},"initializer"),ga=A("ZodError",ew,{Parent:Error}),tw=d_(ga),nw=p_(ga),rw=Dp(ga),Up=gp(ga),Ie=A("ZodType",(e,t)=>(Ce.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>pn(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>tw(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>rw(e,n,r),e.parseAsync=async(n,r)=>nw(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Up(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(Yw(n,r)),e.superRefine=n=>e.check(Xw(n)),e.overwrite=n=>e.check(fo(n)),e.optional=()=>Yp(e),e.nullable=()=>Xp(e),e.nullish=()=>Yp(Xp(e)),e.nonoptional=n=>qw(e,n),e.array=()=>B(e),e.or=n=>ee([e,n]),e.and=n=>Sw(e,n),e.transform=n=>ef(e,Nw(n)),e.default=n=>jw(e,n),e.prefault=n=>Lw(e,n),e.catch=n=>Zw(e,n),e.pipe=n=>ef(e,n),e.readonly=()=>Ww(e),e.describe=n=>{const r=e.clone();return po.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return po.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return po.get(e);const r=e.clone();return po.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Zp=A("_ZodString",(e,t)=>{pi.init(e,t),Ie.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(SC(...r)),e.includes=(...r)=>e.check(RC(...r)),e.startsWith=(...r)=>e.check(NC(...r)),e.endsWith=(...r)=>e.check(PC(...r)),e.min=(...r)=>e.check(ha(...r)),e.max=(...r)=>e.check(Lp(...r)),e.length=(...r)=>e.check(qp(...r)),e.nonempty=(...r)=>e.check(ha(1,...r)),e.lowercase=r=>e.check(BC(r)),e.uppercase=r=>e.check(OC(r)),e.trim=()=>e.check(jC()),e.normalize=(...r)=>e.check(MC(...r)),e.toLowerCase=()=>e.check(zC()),e.toUpperCase=()=>e.check(LC())}),ow=A("ZodString",(e,t)=>{pi.init(e,t),Zp.init(e,t),e.email=n=>e.check(Qb(aw,n)),e.url=n=>e.check(oC(sw,n)),e.jwt=n=>e.check(yC(bw,n)),e.emoji=n=>e.check(aC(iw,n)),e.guid=n=>e.check(Pp(Vp,n)),e.uuid=n=>e.check(eC(va,n)),e.uuidv4=n=>e.check(tC(va,n)),e.uuidv6=n=>e.check(nC(va,n)),e.uuidv7=n=>e.check(rC(va,n)),e.nanoid=n=>e.check(sC(uw,n)),e.guid=n=>e.check(Pp(Vp,n)),e.cuid=n=>e.check(iC(lw,n)),e.cuid2=n=>e.check(uC(cw,n)),e.ulid=n=>e.check(lC(dw,n)),e.base64=n=>e.check(DC(vw,n)),e.base64url=n=>e.check(gC(yw,n)),e.xid=n=>e.check(cC(pw,n)),e.ksuid=n=>e.check(dC(fw,n)),e.ipv4=n=>e.check(pC(mw,n)),e.ipv6=n=>e.check(fC(hw,n)),e.cidrv4=n=>e.check(mC(Dw,n)),e.cidrv6=n=>e.check(hC(gw,n)),e.e164=n=>e.check(vC(_w,n)),e.datetime=n=>e.check(WC(n)),e.date=n=>e.check(JC(n)),e.time=n=>e.check(YC(n)),e.duration=n=>e.check(QC(n))});function p(e){return Xb(ow,e)}i(p,"string");const Oe=A("ZodStringFormat",(e,t)=>{Se.init(e,t),Zp.init(e,t)}),aw=A("ZodEmail",(e,t)=>{ob.init(e,t),Oe.init(e,t)}),Vp=A("ZodGUID",(e,t)=>{nb.init(e,t),Oe.init(e,t)}),va=A("ZodUUID",(e,t)=>{rb.init(e,t),Oe.init(e,t)}),sw=A("ZodURL",(e,t)=>{ab.init(e,t),Oe.init(e,t)}),iw=A("ZodEmoji",(e,t)=>{sb.init(e,t),Oe.init(e,t)}),uw=A("ZodNanoID",(e,t)=>{ib.init(e,t),Oe.init(e,t)}),lw=A("ZodCUID",(e,t)=>{ub.init(e,t),Oe.init(e,t)}),cw=A("ZodCUID2",(e,t)=>{lb.init(e,t),Oe.init(e,t)}),dw=A("ZodULID",(e,t)=>{cb.init(e,t),Oe.init(e,t)}),pw=A("ZodXID",(e,t)=>{db.init(e,t),Oe.init(e,t)}),fw=A("ZodKSUID",(e,t)=>{pb.init(e,t),Oe.init(e,t)}),mw=A("ZodIPv4",(e,t)=>{gb.init(e,t),Oe.init(e,t)}),hw=A("ZodIPv6",(e,t)=>{vb.init(e,t),Oe.init(e,t)}),Dw=A("ZodCIDRv4",(e,t)=>{yb.init(e,t),Oe.init(e,t)}),gw=A("ZodCIDRv6",(e,t)=>{_b.init(e,t),Oe.init(e,t)}),vw=A("ZodBase64",(e,t)=>{bb.init(e,t),Oe.init(e,t)}),yw=A("ZodBase64URL",(e,t)=>{wb.init(e,t),Oe.init(e,t)}),_w=A("ZodE164",(e,t)=>{Fb.init(e,t),Oe.init(e,t)}),bw=A("ZodJWT",(e,t)=>{xb.init(e,t),Oe.init(e,t)}),Di=A("ZodNumber",(e,t)=>{xp.init(e,t),Ie.init(e,t),e.gt=(r,o)=>e.check(jp(r,o)),e.gte=(r,o)=>e.check(hi(r,o)),e.min=(r,o)=>e.check(hi(r,o)),e.lt=(r,o)=>e.check(Mp(r,o)),e.lte=(r,o)=>e.check(mi(r,o)),e.max=(r,o)=>e.check(mi(r,o)),e.int=r=>e.check(Gp(r)),e.safe=r=>e.check(Gp(r)),e.positive=r=>e.check(jp(0,r)),e.nonnegative=r=>e.check(hi(0,r)),e.negative=r=>e.check(Mp(0,r)),e.nonpositive=r=>e.check(mi(0,r)),e.multipleOf=(r,o)=>e.check(zp(r,o)),e.step=(r,o)=>e.check(zp(r,o)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function E(e){return FC(Di,e)}i(E,"number$1");const Cw=A("ZodNumberFormat",(e,t)=>{kb.init(e,t),Di.init(e,t)});function Gp(e){return xC(Cw,e)}i(Gp,"int");const ww=A("ZodBoolean",(e,t)=>{Ib.init(e,t),Ie.init(e,t)});function Re(e){return kC(ww,e)}i(Re,"boolean");const Fw=A("ZodNull",(e,t)=>{Ab.init(e,t),Ie.init(e,t)});function Wp(e){return IC(Fw,e)}i(Wp,"_null");const Ew=A("ZodAny",(e,t)=>{$b.init(e,t),Ie.init(e,t)});function et(){return AC(Ew)}i(et,"any");const xw=A("ZodUnknown",(e,t)=>{Tb.init(e,t),Ie.init(e,t)});function ut(){return $C(xw)}i(ut,"unknown");const kw=A("ZodNever",(e,t)=>{Sb.init(e,t),Ie.init(e,t)});function Iw(e){return TC(kw,e)}i(Iw,"never");const Aw=A("ZodArray",(e,t)=>{Bb.init(e,t),Ie.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(ha(n,r)),e.nonempty=n=>e.check(ha(1,n)),e.max=(n,r)=>e.check(Lp(n,r)),e.length=(n,r)=>e.check(qp(n,r)),e.unwrap=()=>e.element});function B(e,t){return qC(Aw,e,t)}i(B,"array$1");const Hp=A("ZodObject",(e,t)=>{Ob.init(e,t),Ie.init(e,t),De(e,"shape",()=>t.shape),e.keyof=()=>se(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ut()}),e.loose=()=>e.clone({...e._zod.def,catchall:ut()}),e.strict=()=>e.clone({...e._zod.def,catchall:Iw()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>a_(e,n),e.merge=n=>s_(e,n),e.pick=n=>r_(e,n),e.omit=n=>o_(e,n),e.partial=(...n)=>i_(Kp,e,n[0]),e.required=(...n)=>u_(Qp,e,n[0])});function g(e,t){const n={type:"object",get shape(){return ua(this,"shape",{...e}),this.shape},...G(t)};return new Hp(n)}i(g,"object$1");function gi(e,t){return new Hp({type:"object",get shape(){return ua(this,"shape",{...e}),this.shape},catchall:ut(),...G(t)})}i(gi,"looseObject");const Jp=A("ZodUnion",(e,t)=>{$p.init(e,t),Ie.init(e,t),e.options=t.options});function ee(e,t){return new Jp({type:"union",options:e,...G(t)})}i(ee,"union");const $w=A("ZodDiscriminatedUnion",(e,t)=>{Jp.init(e,t),Rb.init(e,t)});function ge(e,t,n){return new $w({type:"union",options:t,discriminator:e,...G(n)})}i(ge,"discriminatedUnion");const Tw=A("ZodIntersection",(e,t)=>{Nb.init(e,t),Ie.init(e,t)});function Sw(e,t){return new Tw({type:"intersection",left:e,right:t})}i(Sw,"intersection");const Bw=A("ZodRecord",(e,t)=>{Pb.init(e,t),Ie.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function be(e,t,n){return new Bw({type:"record",keyType:e,valueType:t,...G(n)})}i(be,"record");const vi=A("ZodEnum",(e,t)=>{Mb.init(e,t),Ie.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{const s={};for(const a of r)if(n.has(a))s[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new vi({...t,checks:[],...G(o),entries:s})},e.exclude=(r,o)=>{const s={...t.entries};for(const a of r)if(n.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new vi({...t,checks:[],...G(o),entries:s})}});function se(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new vi({type:"enum",entries:n,...G(t)})}i(se,"_enum");const Ow=A("ZodLiteral",(e,t)=>{jb.init(e,t),Ie.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function F(e,t){return new Ow({type:"literal",values:Array.isArray(e)?e:[e],...G(t)})}i(F,"literal");const Rw=A("ZodTransform",(e,t)=>{zb.init(e,t),Ie.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(co(s,n.value,t));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),n.issues.push(co(a))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function Nw(e){return new Rw({type:"transform",transform:e})}i(Nw,"transform");const Kp=A("ZodOptional",(e,t)=>{Lb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Yp(e){return new Kp({type:"optional",innerType:e})}i(Yp,"optional");const Pw=A("ZodNullable",(e,t)=>{qb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Xp(e){return new Pw({type:"nullable",innerType:e})}i(Xp,"nullable");const Mw=A("ZodDefault",(e,t)=>{Ub.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function jw(e,t){return new Mw({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}i(jw,"_default");const zw=A("ZodPrefault",(e,t)=>{Zb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Lw(e,t){return new zw({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}i(Lw,"prefault");const Qp=A("ZodNonOptional",(e,t)=>{Vb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function qw(e,t){return new Qp({type:"nonoptional",innerType:e,...G(t)})}i(qw,"nonoptional");const Uw=A("ZodCatch",(e,t)=>{Gb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Zw(e,t){return new Uw({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}i(Zw,"_catch");const Vw=A("ZodPipe",(e,t)=>{Wb.init(e,t),Ie.init(e,t),e.in=t.in,e.out=t.out});function ef(e,t){return new Vw({type:"pipe",in:e,out:t})}i(ef,"pipe");const Gw=A("ZodReadonly",(e,t)=>{Hb.init(e,t),Ie.init(e,t)});function Ww(e){return new Gw({type:"readonly",innerType:e})}i(Ww,"readonly");const Hw=A("ZodLazy",(e,t)=>{Jb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.getter()});function yi(e){return new Hw({type:"lazy",getter:e})}i(yi,"lazy");const _i=A("ZodCustom",(e,t)=>{Kb.init(e,t),Ie.init(e,t)});function Jw(e){const t=new it({check:"custom"});return t._zod.check=e,t}i(Jw,"check");function Kw(e,t){return UC(_i,e??(()=>!0),t)}i(Kw,"custom");function Yw(e,t={}){return ZC(_i,e,t)}i(Yw,"refine");function Xw(e){const t=Jw(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(co(r,n.value,t._zod.def));else{const o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),n.issues.push(co(o))}},e(n.value,n)));return t}i(Xw,"superRefine");function ya(e,t={error:`Input not instance of ${e.name}`}){const n=new _i({type:"custom",check:"custom",fn:i(r=>r instanceof e,"fn"),abort:!0,...G(t)});return n._zod.bag.Class=e,n}i(ya,"_instanceof");function Qw(e){return EC(Di,e)}i(Qw,"number");var me;(function(e){e.assertEqual=o=>{};function t(o){}i(t,"assertIs"),e.assertIs=t;function n(o){throw new Error}i(n,"assertNever"),e.assertNever=n,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(u=>typeof o[o[u]]!="number"),a={};for(const u of s)a[u]=o[u];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}i(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(me||(me={}));var tf;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(tf||(tf={}));const V=me.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Jt=i(e=>{switch(typeof e){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(e)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(e)?V.array:e===null?V.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?V.promise:typeof Map<"u"&&e instanceof Map?V.map:typeof Set<"u"&&e instanceof Set?V.set:typeof Date<"u"&&e instanceof Date?V.date:V.object;default:return V.unknown}},"getParsedType"),R=me.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"]),Ja=class Ja extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(s){return s.message},r={_errors:[]},o=i(s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let u=r,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(u[c]=u[c]||{_errors:[]},u[c]._errors.push(n(a))):u[c]=u[c]||{_errors:[]},u=u[c],l++}}},"processError");return o(this),r}static assert(t){if(!(t instanceof Ja))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,me.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};i(Ja,"ZodError");let jt=Ja;jt.create=e=>new jt(e);const bi=i((e,t)=>{let n;switch(e.code){case R.invalid_type:e.received===V.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case R.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,me.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:n=`Unrecognized key(s) in object: ${me.joinValues(e.keys,", ")}`;break;case R.invalid_union:n="Invalid input";break;case R.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${me.joinValues(e.options)}`;break;case R.invalid_enum_value:n=`Invalid enum value. Expected ${me.joinValues(e.options)}, received '${e.received}'`;break;case R.invalid_arguments:n="Invalid function arguments";break;case R.invalid_return_type:n="Invalid function return type";break;case R.invalid_date:n="Invalid date";break;case R.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:me.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case R.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case R.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case R.custom:n="Invalid input";break;case R.invalid_intersection_types:n="Intersection results could not be merged";break;case R.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case R.not_finite:n="Number must be finite";break;default:n=t.defaultError,me.assertNever(e)}return{message:n}},"errorMap");let eF=bi;function tF(){return eF}i(tF,"getErrorMap");const nF=i(e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let u="";const l=r.filter(c=>!!c).slice().reverse();for(const c of l)u=c(a,{data:t,defaultError:u}).message;return{...o,path:s,message:u}},"makeIssue");function U(e,t){const n=tF(),r=nF({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===bi?void 0:bi].filter(o=>!!o)});e.common.issues.push(r)}i(U,"addIssueToContext");const Ka=class Ka{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return ne;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n){const s=await o.key,a=await o.value;r.push({key:s,value:a})}return Ka.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return ne;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}};i(Ka,"ParseStatus");let mt=Ka;const ne=Object.freeze({status:"aborted"}),mo=i(e=>({status:"dirty",value:e}),"DIRTY"),yt=i(e=>({status:"valid",value:e}),"OK"),nf=i(e=>e.status==="aborted","isAborted"),rf=i(e=>e.status==="dirty","isDirty"),Nn=i(e=>e.status==="valid","isValid"),_a=i(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync");var W;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(W||(W={}));const Iu=class Iu{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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}};i(Iu,"ParseInputLazyPath");let Rt=Iu;const of=i((e,t)=>{if(Nn(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new jt(e.common.issues);return this._error=n,this._error}}},"handleResult");function ie(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:i((a,u)=>{const{message:l}=e;return a.code==="invalid_enum_value"?{message:l??u.defaultError}:typeof u.data>"u"?{message:l??r??u.defaultError}:a.code!=="invalid_type"?{message:u.defaultError}:{message:l??n??u.defaultError}},"customMap"),description:o}}i(ie,"processCreateParams");const Au=class Au{get description(){return this._def.description}_getType(t){return Jt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Jt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new mt,ctx:{common:t.parent.common,data:t.data,parsedType:Jt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(_a(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){const r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Jt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return of(r,o)}"~validate"(t){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Jt(t)};if(!this["~standard"].async)try{const r=this._parseSync({data:t,path:[],parent:n});return Nn(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>Nn(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Jt(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(_a(o)?o:Promise.resolve(o));return of(r,s)}refine(t,n){const r=i(o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n,"getIssueProperties");return this._refinement((o,s)=>{const a=t(o),u=i(()=>s.addIssue({code:R.custom,...r(o)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(u(),!1)):a?!0:(u(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Yt({schema:this,typeName:P.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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:i(n=>this["~validate"](n),"validate")}}optional(){return Pt.create(this,this._def)}nullable(){return Xt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Kt.create(this)}promise(){return zn.create(this,this._def)}or(t){return Mn.create([this,t],this._def)}and(t){return jn.create(this,t,this._def)}transform(t){return new Yt({...ie(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new vo({...ie(this._def),innerType:this,defaultValue:n,typeName:P.ZodDefault})}brand(){return new Fi({typeName:P.ZodBranded,type:this,...ie(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new yo({...ie(this._def),innerType:this,catchValue:n,typeName:P.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Ei.create(this,t)}readonly(){return _o.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};i(Au,"ZodType");let ce=Au;const rF=/^c[^\s-]{8,}$/i,oF=/^[0-9a-z]+$/,aF=/^[0-9A-HJKMNP-TV-Z]{26}$/i,sF=/^[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,iF=/^[a-z0-9_-]{21}$/i,uF=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,lF=/^[-+]?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)?)??$/,cF=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,dF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ci;const pF=/^(?:(?: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])$/,fF=/^(?:(?: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])$/,mF=/^(([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]))$/,hF=/^(([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])$/,DF=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,gF=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,af="((\\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])))",vF=new RegExp(`^${af}$`);function sf(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}i(sf,"timeRegexSource");function yF(e){return new RegExp(`^${sf(e)}$`)}i(yF,"timeRegex");function _F(e){let t=`${af}T${sf(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}i(_F,"datetimeRegex");function bF(e,t){return!!((t==="v4"||!t)&&pF.test(e)||(t==="v6"||!t)&&mF.test(e))}i(bF,"isValidIP");function CF(e,t){if(!uF.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}i(CF,"isValidJWT");function wF(e,t){return!!((t==="v4"||!t)&&fF.test(e)||(t==="v6"||!t)&&hF.test(e))}i(wF,"isValidCidr");const bn=class bn extends ce{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==V.string){const s=this._getOrReturnCtx(t);return U(s,{code:R.invalid_type,expected:V.string,received:s.parsedType}),ne}const r=new mt;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:R.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:R.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,u=t.data.length<s.value;(a||u)&&(o=this._getOrReturnCtx(t,o),a?U(o,{code:R.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):u&&U(o,{code:R.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")cF.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"email",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Ci||(Ci=new RegExp(dF,"u")),Ci.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"emoji",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")sF.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"uuid",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")iF.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"nanoid",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")rF.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")oF.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid2",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")aF.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ulid",code:R.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),U(o,{validation:"url",code:R.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"regex",code:R.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),U(o,{code:R.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:R.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:R.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?_F(s).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:R.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?vF.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:R.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?yF(s).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:R.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?lF.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"duration",code:R.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?bF(t.data,s.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ip",code:R.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?CF(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"jwt",code:R.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?wF(t.data,s.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cidr",code:R.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?DF.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64",code:R.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?gF.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64url",code:R.invalid_string,message:s.message}),r.dirty()):me.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:R.invalid_string,...W.errToObj(r)})}_addCheck(t){return new bn({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...W.errToObj(t)})}url(t){return this._addCheck({kind:"url",...W.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...W.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...W.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...W.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...W.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...W.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...W.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...W.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...W.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...W.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...W.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...W.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...W.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...W.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...W.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...W.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...W.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...W.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...W.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...W.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...W.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...W.errToObj(n)})}nonempty(t){return this.min(1,W.errToObj(t))}trim(){return new bn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new bn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new bn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};i(bn,"ZodString");let ho=bn;ho.create=e=>new ho({checks:[],typeName:P.ZodString,coerce:e?.coerce??!1,...ie(e)});function FF(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}i(FF,"floatSafeRemainder");const So=class So extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==V.number){const s=this._getOrReturnCtx(t);return U(s,{code:R.invalid_type,expected:V.number,received:s.parsedType}),ne}let r;const o=new mt;for(const s of this._def.checks)s.kind==="int"?me.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:R.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:R.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:R.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?FF(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),U(r,{code:R.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:R.not_finite,message:s.message}),o.dirty()):me.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,W.toString(n))}gt(t,n){return this.setLimit("min",t,!1,W.toString(n))}lte(t,n){return this.setLimit("max",t,!0,W.toString(n))}lt(t,n){return this.setLimit("max",t,!1,W.toString(n))}setLimit(t,n,r,o){return new So({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:W.toString(o)}]})}_addCheck(t){return new So({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:W.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:W.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:W.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&me.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};i(So,"ZodNumber");let Do=So;Do.create=e=>new Do({checks:[],typeName:P.ZodNumber,coerce:e?.coerce||!1,...ie(e)});const Bo=class Bo extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==V.bigint)return this._getInvalidInput(t);let r;const o=new mt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:R.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:R.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),U(r,{code:R.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):me.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return U(n,{code:R.invalid_type,expected:V.bigint,received:n.parsedType}),ne}gte(t,n){return this.setLimit("min",t,!0,W.toString(n))}gt(t,n){return this.setLimit("min",t,!1,W.toString(n))}lte(t,n){return this.setLimit("max",t,!0,W.toString(n))}lt(t,n){return this.setLimit("max",t,!1,W.toString(n))}setLimit(t,n,r,o){return new Bo({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:W.toString(o)}]})}_addCheck(t){return new Bo({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:W.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:W.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};i(Bo,"ZodBigInt");let ba=Bo;ba.create=e=>new ba({checks:[],typeName:P.ZodBigInt,coerce:e?.coerce??!1,...ie(e)});const $u=class $u extends ce{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==V.boolean){const r=this._getOrReturnCtx(t);return U(r,{code:R.invalid_type,expected:V.boolean,received:r.parsedType}),ne}return yt(t.data)}};i($u,"ZodBoolean");let Ca=$u;Ca.create=e=>new Ca({typeName:P.ZodBoolean,coerce:e?.coerce||!1,...ie(e)});const Ya=class Ya extends ce{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==V.date){const s=this._getOrReturnCtx(t);return U(s,{code:R.invalid_type,expected:V.date,received:s.parsedType}),ne}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return U(s,{code:R.invalid_date}),ne}const r=new mt;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:R.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:R.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):me.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Ya({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:W.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:W.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};i(Ya,"ZodDate");let wa=Ya;wa.create=e=>new wa({checks:[],coerce:e?.coerce||!1,typeName:P.ZodDate,...ie(e)});const Tu=class Tu extends ce{_parse(t){if(this._getType(t)!==V.symbol){const r=this._getOrReturnCtx(t);return U(r,{code:R.invalid_type,expected:V.symbol,received:r.parsedType}),ne}return yt(t.data)}};i(Tu,"ZodSymbol");let Fa=Tu;Fa.create=e=>new Fa({typeName:P.ZodSymbol,...ie(e)});const Su=class Su extends ce{_parse(t){if(this._getType(t)!==V.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:R.invalid_type,expected:V.undefined,received:r.parsedType}),ne}return yt(t.data)}};i(Su,"ZodUndefined");let Ea=Su;Ea.create=e=>new Ea({typeName:P.ZodUndefined,...ie(e)});const Bu=class Bu extends ce{_parse(t){if(this._getType(t)!==V.null){const r=this._getOrReturnCtx(t);return U(r,{code:R.invalid_type,expected:V.null,received:r.parsedType}),ne}return yt(t.data)}};i(Bu,"ZodNull");let xa=Bu;xa.create=e=>new xa({typeName:P.ZodNull,...ie(e)});const Ou=class Ou extends ce{constructor(){super(...arguments),this._any=!0}_parse(t){return yt(t.data)}};i(Ou,"ZodAny");let ka=Ou;ka.create=e=>new ka({typeName:P.ZodAny,...ie(e)});const Ru=class Ru extends ce{constructor(){super(...arguments),this._unknown=!0}_parse(t){return yt(t.data)}};i(Ru,"ZodUnknown");let Ia=Ru;Ia.create=e=>new Ia({typeName:P.ZodUnknown,...ie(e)});const Nu=class Nu extends ce{_parse(t){const n=this._getOrReturnCtx(t);return U(n,{code:R.invalid_type,expected:V.never,received:n.parsedType}),ne}};i(Nu,"ZodNever");let Nt=Nu;Nt.create=e=>new Nt({typeName:P.ZodNever,...ie(e)});const Pu=class Pu extends ce{_parse(t){if(this._getType(t)!==V.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:R.invalid_type,expected:V.void,received:r.parsedType}),ne}return yt(t.data)}};i(Pu,"ZodVoid");let Aa=Pu;Aa.create=e=>new Aa({typeName:P.ZodVoid,...ie(e)});const Wn=class Wn extends ce{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==V.array)return U(n,{code:R.invalid_type,expected:V.array,received:n.parsedType}),ne;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,u=n.data.length<o.exactLength.value;(a||u)&&(U(n,{code:a?R.too_big:R.too_small,minimum:u?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(U(n,{code:R.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(U(n,{code:R.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,u)=>o.type._parseAsync(new Rt(n,a,n.path,u)))).then(a=>mt.mergeArray(r,a));const s=[...n.data].map((a,u)=>o.type._parseSync(new Rt(n,a,n.path,u)));return mt.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new Wn({...this._def,minLength:{value:t,message:W.toString(n)}})}max(t,n){return new Wn({...this._def,maxLength:{value:t,message:W.toString(n)}})}length(t,n){return new Wn({...this._def,exactLength:{value:t,message:W.toString(n)}})}nonempty(t){return this.min(1,t)}};i(Wn,"ZodArray");let Kt=Wn;Kt.create=(e,t)=>new Kt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...ie(t)});function Pn(e){if(e instanceof Ct){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Pt.create(Pn(r))}return new Ct({...e._def,shape:i(()=>t,"shape")})}else return e instanceof Kt?new Kt({...e._def,type:Pn(e.element)}):e instanceof Pt?Pt.create(Pn(e.unwrap())):e instanceof Xt?Xt.create(Pn(e.unwrap())):e instanceof mn?mn.create(e.items.map(t=>Pn(t))):e}i(Pn,"deepPartialify");const vt=class vt extends ce{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=me.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==V.object){const c=this._getOrReturnCtx(t);return U(c,{code:R.invalid_type,expected:V.object,received:c.parsedType}),ne}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),u=[];if(!(this._def.catchall instanceof Nt&&this._def.unknownKeys==="strip"))for(const c in o.data)a.includes(c)||u.push(c);const l=[];for(const c of a){const d=s[c],f=o.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new Rt(o,f,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Nt){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of u)l.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(c==="strict")u.length>0&&(U(o,{code:R.unrecognized_keys,keys:u}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const d of u){const f=o.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new Rt(o,f,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const f=await d.key,h=await d.value;c.push({key:f,value:h,alwaysSet:d.alwaysSet})}return c}).then(c=>mt.mergeObjectSync(r,c)):mt.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return W.errToObj,new vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:i((n,r)=>{const o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:W.errToObj(t).message??o}:{message:o}},"errorMap")}:{}})}strip(){return new vt({...this._def,unknownKeys:"strip"})}passthrough(){return new vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new vt({...this._def,shape:i(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:i(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:P.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new vt({...this._def,catchall:t})}pick(t){const n={};for(const r of me.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new vt({...this._def,shape:i(()=>n,"shape")})}omit(t){const n={};for(const r of me.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new vt({...this._def,shape:i(()=>n,"shape")})}deepPartial(){return Pn(this)}partial(t){const n={};for(const r of me.objectKeys(this.shape)){const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new vt({...this._def,shape:i(()=>n,"shape")})}required(t){const n={};for(const r of me.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Pt;)s=s._def.innerType;n[r]=s}return new vt({...this._def,shape:i(()=>n,"shape")})}keyof(){return uf(me.objectKeys(this.shape))}};i(vt,"ZodObject");let Ct=vt;Ct.create=(e,t)=>new Ct({shape:i(()=>e,"shape"),unknownKeys:"strip",catchall:Nt.create(),typeName:P.ZodObject,...ie(t)}),Ct.strictCreate=(e,t)=>new Ct({shape:i(()=>e,"shape"),unknownKeys:"strict",catchall:Nt.create(),typeName:P.ZodObject,...ie(t)}),Ct.lazycreate=(e,t)=>new Ct({shape:e,unknownKeys:"strip",catchall:Nt.create(),typeName:P.ZodObject,...ie(t)});const Mu=class Mu extends ce{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(const u of s)if(u.result.status==="valid")return u.result;for(const u of s)if(u.result.status==="dirty")return n.common.issues.push(...u.ctx.common.issues),u.result;const a=s.map(u=>new jt(u.ctx.common.issues));return U(n,{code:R.invalid_union,unionErrors:a}),ne}if(i(o,"handleResults"),n.common.async)return Promise.all(r.map(async s=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of r){const c={...n,common:{...n.common,issues:[]},parent:null},d=l._parseSync({data:n.data,path:n.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const u=a.map(l=>new jt(l));return U(n,{code:R.invalid_union,unionErrors:u}),ne}}get options(){return this._def.options}};i(Mu,"ZodUnion");let Mn=Mu;Mn.create=(e,t)=>new Mn({options:e,typeName:P.ZodUnion,...ie(t)});function wi(e,t){const n=Jt(e),r=Jt(t);if(e===t)return{valid:!0,data:e};if(n===V.object&&r===V.object){const o=me.objectKeys(t),s=me.objectKeys(e).filter(u=>o.indexOf(u)!==-1),a={...e,...t};for(const u of s){const l=wi(e[u],t[u]);if(!l.valid)return{valid:!1};a[u]=l.data}return{valid:!0,data:a}}else if(n===V.array&&r===V.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],u=t[s],l=wi(a,u);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===V.date&&r===V.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}i(wi,"mergeValues");const ju=class ju extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=i((s,a)=>{if(nf(s)||nf(a))return ne;const u=wi(s.value,a.value);return u.valid?((rf(s)||rf(a))&&n.dirty(),{status:n.value,value:u.data}):(U(r,{code:R.invalid_intersection_types}),ne)},"handleParsed");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(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};i(ju,"ZodIntersection");let jn=ju;jn.create=(e,t,n)=>new jn({left:e,right:t,typeName:P.ZodIntersection,...ie(n)});const Xa=class Xa extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==V.array)return U(r,{code:R.invalid_type,expected:V.array,received:r.parsedType}),ne;if(r.data.length<this._def.items.length)return U(r,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ne;!this._def.rest&&r.data.length>this._def.items.length&&(U(r,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,u)=>{const l=this._def.items[u]||this._def.rest;return l?l._parse(new Rt(r,a,r.path,u)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>mt.mergeArray(n,a)):mt.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new Xa({...this._def,rest:t})}};i(Xa,"ZodTuple");let mn=Xa;mn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mn({items:e,typeName:P.ZodTuple,rest:null,...ie(t)})};const zu=class zu extends ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==V.map)return U(r,{code:R.invalid_type,expected:V.map,received:r.parsedType}),ne;const o=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([u,l],c)=>({key:o._parse(new Rt(r,u,r.path,[c,"key"])),value:s._parse(new Rt(r,l,r.path,[c,"value"]))}));if(r.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return ne;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),u.set(c.value,d.value)}return{status:n.value,value:u}})}else{const u=new Map;for(const l of a){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return ne;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),u.set(c.value,d.value)}return{status:n.value,value:u}}}};i(zu,"ZodMap");let $a=zu;$a.create=(e,t,n)=>new $a({valueType:t,keyType:e,typeName:P.ZodMap,...ie(n)});const Oo=class Oo extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==V.set)return U(r,{code:R.invalid_type,expected:V.set,received:r.parsedType}),ne;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(U(r,{code:R.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(U(r,{code:R.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function a(l){const c=new Set;for(const d of l){if(d.status==="aborted")return ne;d.status==="dirty"&&n.dirty(),c.add(d.value)}return{status:n.value,value:c}}i(a,"finalizeSet");const u=[...r.data.values()].map((l,c)=>s._parse(new Rt(r,l,r.path,c)));return r.common.async?Promise.all(u).then(l=>a(l)):a(u)}min(t,n){return new Oo({...this._def,minSize:{value:t,message:W.toString(n)}})}max(t,n){return new Oo({...this._def,maxSize:{value:t,message:W.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};i(Oo,"ZodSet");let Ta=Oo;Ta.create=(e,t)=>new Ta({valueType:e,minSize:null,maxSize:null,typeName:P.ZodSet,...ie(t)});const Lu=class Lu extends ce{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};i(Lu,"ZodLazy");let Sa=Lu;Sa.create=(e,t)=>new Sa({getter:e,typeName:P.ZodLazy,...ie(t)});const qu=class qu extends ce{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return U(n,{received:n.data,code:R.invalid_literal,expected:this._def.value}),ne}return{status:"valid",value:t.data}}get value(){return this._def.value}};i(qu,"ZodLiteral");let Ba=qu;Ba.create=(e,t)=>new Ba({value:e,typeName:P.ZodLiteral,...ie(t)});function uf(e,t){return new go({values:e,typeName:P.ZodEnum,...ie(t)})}i(uf,"createZodEnum");const Ro=class Ro extends ce{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{expected:me.joinValues(r),received:n.parsedType,code:R.invalid_type}),ne}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{received:n.data,code:R.invalid_enum_value,options:r}),ne}return yt(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Ro.create(t,{...this._def,...n})}exclude(t,n=this._def){return Ro.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};i(Ro,"ZodEnum");let go=Ro;go.create=uf;const Uu=class Uu extends ce{_parse(t){const n=me.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==V.string&&r.parsedType!==V.number){const o=me.objectValues(n);return U(r,{expected:me.joinValues(o),received:r.parsedType,code:R.invalid_type}),ne}if(this._cache||(this._cache=new Set(me.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=me.objectValues(n);return U(r,{received:r.data,code:R.invalid_enum_value,options:o}),ne}return yt(t.data)}get enum(){return this._def.values}};i(Uu,"ZodNativeEnum");let Oa=Uu;Oa.create=(e,t)=>new Oa({values:e,typeName:P.ZodNativeEnum,...ie(t)});const Zu=class Zu extends ce{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==V.promise&&n.common.async===!1)return U(n,{code:R.invalid_type,expected:V.promise,received:n.parsedType}),ne;const r=n.parsedType===V.promise?n.data:Promise.resolve(n.data);return yt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};i(Zu,"ZodPromise");let zn=Zu;zn.create=(e,t)=>new zn({type:e,typeName:P.ZodPromise,...ie(t)});const Vu=class Vu extends ce{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===P.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i(a=>{U(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async u=>{if(n.value==="aborted")return ne;const l=await this._def.schema._parseAsync({data:u,path:r.path,parent:r});return l.status==="aborted"?ne:l.status==="dirty"||n.value==="dirty"?mo(l.value):l});{if(n.value==="aborted")return ne;const u=this._def.schema._parseSync({data:a,path:r.path,parent:r});return u.status==="aborted"?ne:u.status==="dirty"||n.value==="dirty"?mo(u.value):u}}if(o.type==="refinement"){const a=i(u=>{const l=o.refinement(u,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u},"executeRefinement");if(r.common.async===!1){const u=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return u.status==="aborted"?ne:(u.status==="dirty"&&n.dirty(),a(u.value),{status:n.value,value:u.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(u=>u.status==="aborted"?ne:(u.status==="dirty"&&n.dirty(),a(u.value).then(()=>({status:n.value,value:u.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Nn(a))return ne;const u=o.transform(a.value,s);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:u}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Nn(a)?Promise.resolve(o.transform(a.value,s)).then(u=>({status:n.value,value:u})):ne);me.assertNever(o)}};i(Vu,"ZodEffects");let Yt=Vu;Yt.create=(e,t,n)=>new Yt({schema:e,typeName:P.ZodEffects,effect:t,...ie(n)}),Yt.createWithPreprocess=(e,t,n)=>new Yt({schema:t,effect:{type:"preprocess",transform:e},typeName:P.ZodEffects,...ie(n)});const Gu=class Gu extends ce{_parse(t){return this._getType(t)===V.undefined?yt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};i(Gu,"ZodOptional");let Pt=Gu;Pt.create=(e,t)=>new Pt({innerType:e,typeName:P.ZodOptional,...ie(t)});const Wu=class Wu extends ce{_parse(t){return this._getType(t)===V.null?yt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};i(Wu,"ZodNullable");let Xt=Wu;Xt.create=(e,t)=>new Xt({innerType:e,typeName:P.ZodNullable,...ie(t)});const Hu=class Hu extends ce{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===V.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};i(Hu,"ZodDefault");let vo=Hu;vo.create=(e,t)=>new vo({innerType:e,typeName:P.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ie(t)});const Ju=class Ju extends ce{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return _a(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new jt(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new jt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};i(Ju,"ZodCatch");let yo=Ju;yo.create=(e,t)=>new yo({innerType:e,typeName:P.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ie(t)});const Ku=class Ku extends ce{_parse(t){if(this._getType(t)!==V.nan){const r=this._getOrReturnCtx(t);return U(r,{code:R.invalid_type,expected:V.nan,received:r.parsedType}),ne}return{status:"valid",value:t.data}}};i(Ku,"ZodNaN");let Ra=Ku;Ra.create=e=>new Ra({typeName:P.ZodNaN,...ie(e)});const Yu=class Yu extends ce{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}};i(Yu,"ZodBranded");let Fi=Yu;const Qa=class Qa extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return i(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?ne:s.status==="dirty"?(n.dirty(),mo(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})},"handleAsync")();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?ne:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new Qa({in:t,out:n,typeName:P.ZodPipeline})}};i(Qa,"ZodPipeline");let Ei=Qa;const Xu=class Xu extends ce{_parse(t){const n=this._def.innerType._parse(t),r=i(o=>(Nn(o)&&(o.value=Object.freeze(o.value)),o),"freeze");return _a(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};i(Xu,"ZodReadonly");let _o=Xu;_o.create=(e,t)=>new _o({innerType:e,typeName:P.ZodReadonly,...ie(t)});var P;(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"})(P||(P={}));const we=ho.create,Mt=Do.create;Nt.create;const Qt=Kt.create,wt=Ct.create,xi=Mn.create;jn.create,mn.create;const Na=go.create;zn.create,Pt.create,Xt.create;const Qu=class Qu extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}};i(Qu,"ParseError");let Pa=Qu;function ki(e){}i(ki,"noop");function EF(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=ki,onError:n=ki,onRetry:r=ki,onComment:o}=e;let s="",a=!0,u,l="",c="";function d(v){const y=a?v.replace(/^\xEF\xBB\xBF/,""):v,[b,w]=xF(`${s}${y}`);for(const C of b)f(C);s=w,a=!1}i(d,"feed");function f(v){if(v===""){D();return}if(v.startsWith(":")){o&&o(v.slice(v.startsWith(": ")?2:1));return}const y=v.indexOf(":");if(y!==-1){const b=v.slice(0,y),w=v[y+1]===" "?2:1,C=v.slice(y+w);h(b,C,v);return}h(v,"",v)}i(f,"parseLine");function h(v,y,b){switch(v){case"event":c=y;break;case"data":l=`${l}${y}
114
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const d of this.seen.entries()){const f=d[1];if(t===d[0]){a(d);continue}if(r.external){const D=r.external.registry.get(d[0])?.id;if(t!==d[0]&&D){a(d);continue}}if(this.metadataRegistry.get(d[0])?.id){a(d);continue}if(f.cycle){a(d);continue}if(f.count>1&&r.reused==="ref"){a(d);continue}}const u=i((d,f)=>{const h=this.seen.get(d),D=h.def??h.schema,m={...D};if(h.ref===null)return;const v=h.ref;if(h.ref=null,v){u(v,f);const y=this.seen.get(v).schema;y.$ref&&f.target==="draft-7"?(D.allOf=D.allOf??[],D.allOf.push(y)):(Object.assign(D,y),Object.assign(D,m))}h.isParent||this.override({zodSchema:d,jsonSchema:D,path:h.path??[]})},"flattenRef");for(const d of[...this.seen.entries()].reverse())u(d[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){const d=r.external.registry.get(t)?.id;if(!d)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(d)}Object.assign(l,o.def);const c=r.external?.defs??{};for(const d of this.seen.entries()){const f=d[1];f.def&&f.defId&&(c[f.defId]=f.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}};i(ku,"JSONSchemaGenerator");let Da=ku;function WC(e,t){if(e instanceof ma){const r=new Da(t),o={};for(const u of e._idmap.entries()){const[l,c]=u;r.process(c)}const s={},a={registry:e,uri:t?.uri,defs:o};for(const u of e._idmap.entries()){const[l,c]=u;s[l]=r.emit(c,{...t,external:a})}if(Object.keys(o).length>0){const u=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[u]:o}}return{schemas:s}}const n=new Da(t);return n.process(e),n.emit(e,t)}i(WC,"toJSONSchema");function Ze(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const o=e._zod.def;switch(o.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":return!1;case"array":return Ze(o.element,n);case"object":{for(const s in o.shape)if(Ze(o.shape[s],n))return!0;return!1}case"union":{for(const s of o.options)if(Ze(s,n))return!0;return!1}case"intersection":return Ze(o.left,n)||Ze(o.right,n);case"tuple":{for(const s of o.items)if(Ze(s,n))return!0;return!!(o.rest&&Ze(o.rest,n))}case"record":return Ze(o.keyType,n)||Ze(o.valueType,n);case"map":return Ze(o.keyType,n)||Ze(o.valueType,n);case"set":return Ze(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ze(o.innerType,n);case"lazy":return Ze(o.getter(),n);case"default":return Ze(o.innerType,n);case"prefault":return Ze(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Ze(o.in,n)||Ze(o.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}i(Ze,"isTransforming");const HC=A("ZodISODateTime",(e,t)=>{hb.init(e,t),Oe.init(e,t)});function JC(e){return CC(HC,e)}i(JC,"datetime");const KC=A("ZodISODate",(e,t)=>{Db.init(e,t),Oe.init(e,t)});function YC(e){return wC(KC,e)}i(YC,"date");const XC=A("ZodISOTime",(e,t)=>{gb.init(e,t),Oe.init(e,t)});function QC(e){return FC(XC,e)}i(QC,"time");const ew=A("ZodISODuration",(e,t)=>{vb.init(e,t),Oe.init(e,t)});function tw(e){return EC(ew,e)}i(tw,"duration");const nw=i((e,t)=>{mp.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:i(n=>p_(e,n),"value")},flatten:{value:i(n=>d_(e,n),"value")},addIssue:{value:i(n=>e.issues.push(n),"value")},addIssues:{value:i(n=>e.issues.push(...n),"value")},isEmpty:{get(){return e.issues.length===0}}})},"initializer"),ga=A("ZodError",nw,{Parent:Error}),rw=f_(ga),ow=m_(ga),aw=Dp(ga),Up=gp(ga),Ie=A("ZodType",(e,t)=>(Ce.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>pn(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>rw(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>aw(e,n,r),e.parseAsync=async(n,r)=>ow(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Up(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(Qw(n,r)),e.superRefine=n=>e.check(eF(n)),e.overwrite=n=>e.check(fo(n)),e.optional=()=>Yp(e),e.nullable=()=>Xp(e),e.nullish=()=>Yp(Xp(e)),e.nonoptional=n=>Zw(e,n),e.array=()=>S(e),e.or=n=>ee([e,n]),e.and=n=>Ow(e,n),e.transform=n=>ef(e,Mw(n)),e.default=n=>Lw(e,n),e.prefault=n=>Uw(e,n),e.catch=n=>Gw(e,n),e.pipe=n=>ef(e,n),e.readonly=()=>Jw(e),e.describe=n=>{const r=e.clone();return po.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return po.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return po.get(e);const r=e.clone();return po.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Zp=A("_ZodString",(e,t)=>{pi.init(e,t),Ie.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(OC(...r)),e.includes=(...r)=>e.check(PC(...r)),e.startsWith=(...r)=>e.check(MC(...r)),e.endsWith=(...r)=>e.check(jC(...r)),e.min=(...r)=>e.check(ha(...r)),e.max=(...r)=>e.check(Lp(...r)),e.length=(...r)=>e.check(qp(...r)),e.nonempty=(...r)=>e.check(ha(1,...r)),e.lowercase=r=>e.check(RC(r)),e.uppercase=r=>e.check(NC(r)),e.trim=()=>e.check(LC()),e.normalize=(...r)=>e.check(zC(...r)),e.toLowerCase=()=>e.check(qC()),e.toUpperCase=()=>e.check(UC())}),sw=A("ZodString",(e,t)=>{pi.init(e,t),Zp.init(e,t),e.email=n=>e.check(tC(iw,n)),e.url=n=>e.check(sC(uw,n)),e.jwt=n=>e.check(bC(ww,n)),e.emoji=n=>e.check(iC(lw,n)),e.guid=n=>e.check(Pp(Vp,n)),e.uuid=n=>e.check(nC(va,n)),e.uuidv4=n=>e.check(rC(va,n)),e.uuidv6=n=>e.check(oC(va,n)),e.uuidv7=n=>e.check(aC(va,n)),e.nanoid=n=>e.check(uC(cw,n)),e.guid=n=>e.check(Pp(Vp,n)),e.cuid=n=>e.check(lC(dw,n)),e.cuid2=n=>e.check(cC(pw,n)),e.ulid=n=>e.check(dC(fw,n)),e.base64=n=>e.check(vC(_w,n)),e.base64url=n=>e.check(yC(bw,n)),e.xid=n=>e.check(pC(mw,n)),e.ksuid=n=>e.check(fC(hw,n)),e.ipv4=n=>e.check(mC(Dw,n)),e.ipv6=n=>e.check(hC(gw,n)),e.cidrv4=n=>e.check(DC(vw,n)),e.cidrv6=n=>e.check(gC(yw,n)),e.e164=n=>e.check(_C(Cw,n)),e.datetime=n=>e.check(JC(n)),e.date=n=>e.check(YC(n)),e.time=n=>e.check(QC(n)),e.duration=n=>e.check(tw(n))});function p(e){return eC(sw,e)}i(p,"string");const Oe=A("ZodStringFormat",(e,t)=>{Se.init(e,t),Zp.init(e,t)}),iw=A("ZodEmail",(e,t)=>{sb.init(e,t),Oe.init(e,t)}),Vp=A("ZodGUID",(e,t)=>{ob.init(e,t),Oe.init(e,t)}),va=A("ZodUUID",(e,t)=>{ab.init(e,t),Oe.init(e,t)}),uw=A("ZodURL",(e,t)=>{ib.init(e,t),Oe.init(e,t)}),lw=A("ZodEmoji",(e,t)=>{ub.init(e,t),Oe.init(e,t)}),cw=A("ZodNanoID",(e,t)=>{lb.init(e,t),Oe.init(e,t)}),dw=A("ZodCUID",(e,t)=>{cb.init(e,t),Oe.init(e,t)}),pw=A("ZodCUID2",(e,t)=>{db.init(e,t),Oe.init(e,t)}),fw=A("ZodULID",(e,t)=>{pb.init(e,t),Oe.init(e,t)}),mw=A("ZodXID",(e,t)=>{fb.init(e,t),Oe.init(e,t)}),hw=A("ZodKSUID",(e,t)=>{mb.init(e,t),Oe.init(e,t)}),Dw=A("ZodIPv4",(e,t)=>{yb.init(e,t),Oe.init(e,t)}),gw=A("ZodIPv6",(e,t)=>{_b.init(e,t),Oe.init(e,t)}),vw=A("ZodCIDRv4",(e,t)=>{bb.init(e,t),Oe.init(e,t)}),yw=A("ZodCIDRv6",(e,t)=>{Cb.init(e,t),Oe.init(e,t)}),_w=A("ZodBase64",(e,t)=>{wb.init(e,t),Oe.init(e,t)}),bw=A("ZodBase64URL",(e,t)=>{Eb.init(e,t),Oe.init(e,t)}),Cw=A("ZodE164",(e,t)=>{xb.init(e,t),Oe.init(e,t)}),ww=A("ZodJWT",(e,t)=>{Ib.init(e,t),Oe.init(e,t)}),Di=A("ZodNumber",(e,t)=>{xp.init(e,t),Ie.init(e,t),e.gt=(r,o)=>e.check(jp(r,o)),e.gte=(r,o)=>e.check(hi(r,o)),e.min=(r,o)=>e.check(hi(r,o)),e.lt=(r,o)=>e.check(Mp(r,o)),e.lte=(r,o)=>e.check(mi(r,o)),e.max=(r,o)=>e.check(mi(r,o)),e.int=r=>e.check(Gp(r)),e.safe=r=>e.check(Gp(r)),e.positive=r=>e.check(jp(0,r)),e.nonnegative=r=>e.check(hi(0,r)),e.negative=r=>e.check(Mp(0,r)),e.nonpositive=r=>e.check(mi(0,r)),e.multipleOf=(r,o)=>e.check(zp(r,o)),e.step=(r,o)=>e.check(zp(r,o)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function x(e){return xC(Di,e)}i(x,"number$1");const Fw=A("ZodNumberFormat",(e,t)=>{Ab.init(e,t),Di.init(e,t)});function Gp(e){return IC(Fw,e)}i(Gp,"int");const Ew=A("ZodBoolean",(e,t)=>{$b.init(e,t),Ie.init(e,t)});function Re(e){return AC(Ew,e)}i(Re,"boolean");const xw=A("ZodNull",(e,t)=>{Tb.init(e,t),Ie.init(e,t)});function Wp(e){return $C(xw,e)}i(Wp,"_null");const kw=A("ZodAny",(e,t)=>{Sb.init(e,t),Ie.init(e,t)});function et(){return TC(kw)}i(et,"any");const Iw=A("ZodUnknown",(e,t)=>{Bb.init(e,t),Ie.init(e,t)});function ut(){return SC(Iw)}i(ut,"unknown");const Aw=A("ZodNever",(e,t)=>{Ob.init(e,t),Ie.init(e,t)});function $w(e){return BC(Aw,e)}i($w,"never");const Tw=A("ZodArray",(e,t)=>{Rb.init(e,t),Ie.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(ha(n,r)),e.nonempty=n=>e.check(ha(1,n)),e.max=(n,r)=>e.check(Lp(n,r)),e.length=(n,r)=>e.check(qp(n,r)),e.unwrap=()=>e.element});function S(e,t){return ZC(Tw,e,t)}i(S,"array$1");const Hp=A("ZodObject",(e,t)=>{Nb.init(e,t),Ie.init(e,t),De(e,"shape",()=>t.shape),e.keyof=()=>se(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ut()}),e.loose=()=>e.clone({...e._zod.def,catchall:ut()}),e.strict=()=>e.clone({...e._zod.def,catchall:$w()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>i_(e,n),e.merge=n=>u_(e,n),e.pick=n=>a_(e,n),e.omit=n=>s_(e,n),e.partial=(...n)=>l_(Kp,e,n[0]),e.required=(...n)=>c_(Qp,e,n[0])});function g(e,t){const n={type:"object",get shape(){return ua(this,"shape",{...e}),this.shape},...G(t)};return new Hp(n)}i(g,"object$1");function gi(e,t){return new Hp({type:"object",get shape(){return ua(this,"shape",{...e}),this.shape},catchall:ut(),...G(t)})}i(gi,"looseObject");const Jp=A("ZodUnion",(e,t)=>{$p.init(e,t),Ie.init(e,t),e.options=t.options});function ee(e,t){return new Jp({type:"union",options:e,...G(t)})}i(ee,"union");const Sw=A("ZodDiscriminatedUnion",(e,t)=>{Jp.init(e,t),Pb.init(e,t)});function ge(e,t,n){return new Sw({type:"union",options:t,discriminator:e,...G(n)})}i(ge,"discriminatedUnion");const Bw=A("ZodIntersection",(e,t)=>{Mb.init(e,t),Ie.init(e,t)});function Ow(e,t){return new Bw({type:"intersection",left:e,right:t})}i(Ow,"intersection");const Rw=A("ZodRecord",(e,t)=>{jb.init(e,t),Ie.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function be(e,t,n){return new Rw({type:"record",keyType:e,valueType:t,...G(n)})}i(be,"record");const vi=A("ZodEnum",(e,t)=>{zb.init(e,t),Ie.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{const s={};for(const a of r)if(n.has(a))s[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new vi({...t,checks:[],...G(o),entries:s})},e.exclude=(r,o)=>{const s={...t.entries};for(const a of r)if(n.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new vi({...t,checks:[],...G(o),entries:s})}});function se(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new vi({type:"enum",entries:n,...G(t)})}i(se,"_enum");const Nw=A("ZodLiteral",(e,t)=>{Lb.init(e,t),Ie.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function w(e,t){return new Nw({type:"literal",values:Array.isArray(e)?e:[e],...G(t)})}i(w,"literal");const Pw=A("ZodTransform",(e,t)=>{qb.init(e,t),Ie.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(co(s,n.value,t));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),n.issues.push(co(a))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function Mw(e){return new Pw({type:"transform",transform:e})}i(Mw,"transform");const Kp=A("ZodOptional",(e,t)=>{Ub.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Yp(e){return new Kp({type:"optional",innerType:e})}i(Yp,"optional");const jw=A("ZodNullable",(e,t)=>{Zb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Xp(e){return new jw({type:"nullable",innerType:e})}i(Xp,"nullable");const zw=A("ZodDefault",(e,t)=>{Vb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Lw(e,t){return new zw({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}i(Lw,"_default");const qw=A("ZodPrefault",(e,t)=>{Gb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Uw(e,t){return new qw({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}i(Uw,"prefault");const Qp=A("ZodNonOptional",(e,t)=>{Wb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Zw(e,t){return new Qp({type:"nonoptional",innerType:e,...G(t)})}i(Zw,"nonoptional");const Vw=A("ZodCatch",(e,t)=>{Hb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Gw(e,t){return new Vw({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}i(Gw,"_catch");const Ww=A("ZodPipe",(e,t)=>{Jb.init(e,t),Ie.init(e,t),e.in=t.in,e.out=t.out});function ef(e,t){return new Ww({type:"pipe",in:e,out:t})}i(ef,"pipe");const Hw=A("ZodReadonly",(e,t)=>{Kb.init(e,t),Ie.init(e,t)});function Jw(e){return new Hw({type:"readonly",innerType:e})}i(Jw,"readonly");const Kw=A("ZodLazy",(e,t)=>{Yb.init(e,t),Ie.init(e,t),e.unwrap=()=>e._zod.def.getter()});function yi(e){return new Kw({type:"lazy",getter:e})}i(yi,"lazy");const _i=A("ZodCustom",(e,t)=>{Xb.init(e,t),Ie.init(e,t)});function Yw(e){const t=new it({check:"custom"});return t._zod.check=e,t}i(Yw,"check");function Xw(e,t){return VC(_i,e??(()=>!0),t)}i(Xw,"custom");function Qw(e,t={}){return GC(_i,e,t)}i(Qw,"refine");function eF(e){const t=Yw(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(co(r,n.value,t._zod.def));else{const o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),n.issues.push(co(o))}},e(n.value,n)));return t}i(eF,"superRefine");function ya(e,t={error:`Input not instance of ${e.name}`}){const n=new _i({type:"custom",check:"custom",fn:i(r=>r instanceof e,"fn"),abort:!0,...G(t)});return n._zod.bag.Class=e,n}i(ya,"_instanceof");function tF(e){return kC(Di,e)}i(tF,"number");var fe;(function(e){e.assertEqual=o=>{};function t(o){}i(t,"assertIs"),e.assertIs=t;function n(o){throw new Error}i(n,"assertNever"),e.assertNever=n,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(u=>typeof o[o[u]]!="number"),a={};for(const u of s)a[u]=o[u];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}i(r,"joinValues"),e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(fe||(fe={}));var tf;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(tf||(tf={}));const V=fe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Jt=i(e=>{switch(typeof e){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(e)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(e)?V.array:e===null?V.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?V.promise:typeof Map<"u"&&e instanceof Map?V.map:typeof Set<"u"&&e instanceof Set?V.set:typeof Date<"u"&&e instanceof Date?V.date:V.object;default:return V.unknown}},"getParsedType"),N=fe.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"]),Ja=class Ja extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(s){return s.message},r={_errors:[]},o=i(s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let u=r,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(u[c]=u[c]||{_errors:[]},u[c]._errors.push(n(a))):u[c]=u[c]||{_errors:[]},u=u[c],l++}}},"processError");return o(this),r}static assert(t){if(!(t instanceof Ja))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,fe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};i(Ja,"ZodError");let jt=Ja;jt.create=e=>new jt(e);const bi=i((e,t)=>{let n;switch(e.code){case N.invalid_type:e.received===V.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,fe.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${fe.joinValues(e.keys,", ")}`;break;case N.invalid_union:n="Invalid input";break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${fe.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${fe.joinValues(e.options)}, received '${e.received}'`;break;case N.invalid_arguments:n="Invalid function arguments";break;case N.invalid_return_type:n="Invalid function return type";break;case N.invalid_date:n="Invalid date";break;case N.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:fe.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case N.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case N.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case N.custom:n="Invalid input";break;case N.invalid_intersection_types:n="Intersection results could not be merged";break;case N.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case N.not_finite:n="Number must be finite";break;default:n=t.defaultError,fe.assertNever(e)}return{message:n}},"errorMap");let nF=bi;function rF(){return nF}i(rF,"getErrorMap");const oF=i(e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let u="";const l=r.filter(c=>!!c).slice().reverse();for(const c of l)u=c(a,{data:t,defaultError:u}).message;return{...o,path:s,message:u}},"makeIssue");function Z(e,t){const n=rF(),r=oF({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===bi?void 0:bi].filter(o=>!!o)});e.common.issues.push(r)}i(Z,"addIssueToContext");const Ka=class Ka{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return ne;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n){const s=await o.key,a=await o.value;r.push({key:s,value:a})}return Ka.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return ne;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[s.value]=a.value)}return{status:t.value,value:r}}};i(Ka,"ParseStatus");let mt=Ka;const ne=Object.freeze({status:"aborted"}),mo=i(e=>({status:"dirty",value:e}),"DIRTY"),yt=i(e=>({status:"valid",value:e}),"OK"),nf=i(e=>e.status==="aborted","isAborted"),rf=i(e=>e.status==="dirty","isDirty"),Nn=i(e=>e.status==="valid","isValid"),_a=i(e=>typeof Promise<"u"&&e instanceof Promise,"isAsync");var W;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(W||(W={}));const Iu=class Iu{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}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}};i(Iu,"ParseInputLazyPath");let Rt=Iu;const of=i((e,t)=>{if(Nn(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new jt(e.common.issues);return this._error=n,this._error}}},"handleResult");function ie(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:i((a,u)=>{const{message:l}=e;return a.code==="invalid_enum_value"?{message:l??u.defaultError}:typeof u.data>"u"?{message:l??r??u.defaultError}:a.code!=="invalid_type"?{message:u.defaultError}:{message:l??n??u.defaultError}},"customMap"),description:o}}i(ie,"processCreateParams");const Au=class Au{get description(){return this._def.description}_getType(t){return Jt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Jt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new mt,ctx:{common:t.parent.common,data:t.data,parsedType:Jt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(_a(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){const r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Jt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return of(r,o)}"~validate"(t){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Jt(t)};if(!this["~standard"].async)try{const r=this._parseSync({data:t,path:[],parent:n});return Nn(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>Nn(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Jt(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(_a(o)?o:Promise.resolve(o));return of(r,s)}refine(t,n){const r=i(o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n,"getIssueProperties");return this._refinement((o,s)=>{const a=t(o),u=i(()=>s.addIssue({code:N.custom,...r(o)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(u(),!1)):a?!0:(u(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Yt({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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:i(n=>this["~validate"](n),"validate")}}optional(){return Pt.create(this,this._def)}nullable(){return Xt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Kt.create(this)}promise(){return zn.create(this,this._def)}or(t){return Mn.create([this,t],this._def)}and(t){return jn.create(this,t,this._def)}transform(t){return new Yt({...ie(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new vo({...ie(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new Fi({typeName:M.ZodBranded,type:this,...ie(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new yo({...ie(this._def),innerType:this,catchValue:n,typeName:M.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Ei.create(this,t)}readonly(){return _o.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};i(Au,"ZodType");let ce=Au;const aF=/^c[^\s-]{8,}$/i,sF=/^[0-9a-z]+$/,iF=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uF=/^[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,lF=/^[a-z0-9_-]{21}$/i,cF=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,dF=/^[-+]?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)?)??$/,pF=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,fF="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ci;const mF=/^(?:(?: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])$/,hF=/^(?:(?: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])$/,DF=/^(([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]))$/,gF=/^(([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])$/,vF=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,yF=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,af="((\\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])))",_F=new RegExp(`^${af}$`);function sf(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}i(sf,"timeRegexSource");function bF(e){return new RegExp(`^${sf(e)}$`)}i(bF,"timeRegex");function CF(e){let t=`${af}T${sf(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}i(CF,"datetimeRegex");function wF(e,t){return!!((t==="v4"||!t)&&mF.test(e)||(t==="v6"||!t)&&DF.test(e))}i(wF,"isValidIP");function FF(e,t){if(!cF.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}i(FF,"isValidJWT");function EF(e,t){return!!((t==="v4"||!t)&&hF.test(e)||(t==="v6"||!t)&&gF.test(e))}i(EF,"isValidCidr");const bn=class bn extends ce{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==V.string){const s=this._getOrReturnCtx(t);return Z(s,{code:N.invalid_type,expected:V.string,received:s.parsedType}),ne}const r=new mt;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),Z(o,{code:N.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),Z(o,{code:N.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,u=t.data.length<s.value;(a||u)&&(o=this._getOrReturnCtx(t,o),a?Z(o,{code:N.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):u&&Z(o,{code:N.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")pF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"email",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Ci||(Ci=new RegExp(fF,"u")),Ci.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"emoji",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")uF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"uuid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")lF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"nanoid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")aF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"cuid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")sF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"cuid2",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")iF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"ulid",code:N.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),Z(o,{validation:"url",code:N.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"regex",code:N.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?CF(s).test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?_F.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?bF(s).test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{code:N.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?dF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"duration",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?wF(t.data,s.version)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"ip",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?FF(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"jwt",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?EF(t.data,s.version)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"cidr",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?vF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"base64",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?yF.test(t.data)||(o=this._getOrReturnCtx(t,o),Z(o,{validation:"base64url",code:N.invalid_string,message:s.message}),r.dirty()):fe.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:N.invalid_string,...W.errToObj(r)})}_addCheck(t){return new bn({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...W.errToObj(t)})}url(t){return this._addCheck({kind:"url",...W.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...W.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...W.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...W.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...W.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...W.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...W.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...W.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...W.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...W.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...W.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...W.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...W.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...W.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...W.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...W.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...W.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...W.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...W.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...W.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...W.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...W.errToObj(n)})}nonempty(t){return this.min(1,W.errToObj(t))}trim(){return new bn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new bn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new bn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};i(bn,"ZodString");let ho=bn;ho.create=e=>new ho({checks:[],typeName:M.ZodString,coerce:e?.coerce??!1,...ie(e)});function xF(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}i(xF,"floatSafeRemainder");const So=class So extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==V.number){const s=this._getOrReturnCtx(t);return Z(s,{code:N.invalid_type,expected:V.number,received:s.parsedType}),ne}let r;const o=new mt;for(const s of this._def.checks)s.kind==="int"?fe.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Z(r,{code:N.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?xF(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Z(r,{code:N.not_finite,message:s.message}),o.dirty()):fe.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,W.toString(n))}gt(t,n){return this.setLimit("min",t,!1,W.toString(n))}lte(t,n){return this.setLimit("max",t,!0,W.toString(n))}lt(t,n){return this.setLimit("max",t,!1,W.toString(n))}setLimit(t,n,r,o){return new So({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:W.toString(o)}]})}_addCheck(t){return new So({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:W.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:W.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:W.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&fe.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};i(So,"ZodNumber");let Do=So;Do.create=e=>new Do({checks:[],typeName:M.ZodNumber,coerce:e?.coerce||!1,...ie(e)});const Bo=class Bo extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==V.bigint)return this._getInvalidInput(t);let r;const o=new mt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Z(r,{code:N.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):fe.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return Z(n,{code:N.invalid_type,expected:V.bigint,received:n.parsedType}),ne}gte(t,n){return this.setLimit("min",t,!0,W.toString(n))}gt(t,n){return this.setLimit("min",t,!1,W.toString(n))}lte(t,n){return this.setLimit("max",t,!0,W.toString(n))}lt(t,n){return this.setLimit("max",t,!1,W.toString(n))}setLimit(t,n,r,o){return new Bo({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:W.toString(o)}]})}_addCheck(t){return new Bo({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:W.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:W.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};i(Bo,"ZodBigInt");let ba=Bo;ba.create=e=>new ba({checks:[],typeName:M.ZodBigInt,coerce:e?.coerce??!1,...ie(e)});const $u=class $u extends ce{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==V.boolean){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.boolean,received:r.parsedType}),ne}return yt(t.data)}};i($u,"ZodBoolean");let Ca=$u;Ca.create=e=>new Ca({typeName:M.ZodBoolean,coerce:e?.coerce||!1,...ie(e)});const Ya=class Ya extends ce{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==V.date){const s=this._getOrReturnCtx(t);return Z(s,{code:N.invalid_type,expected:V.date,received:s.parsedType}),ne}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return Z(s,{code:N.invalid_date}),ne}const r=new mt;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),Z(o,{code:N.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),Z(o,{code:N.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):fe.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Ya({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:W.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:W.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};i(Ya,"ZodDate");let wa=Ya;wa.create=e=>new wa({checks:[],coerce:e?.coerce||!1,typeName:M.ZodDate,...ie(e)});const Tu=class Tu extends ce{_parse(t){if(this._getType(t)!==V.symbol){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.symbol,received:r.parsedType}),ne}return yt(t.data)}};i(Tu,"ZodSymbol");let Fa=Tu;Fa.create=e=>new Fa({typeName:M.ZodSymbol,...ie(e)});const Su=class Su extends ce{_parse(t){if(this._getType(t)!==V.undefined){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.undefined,received:r.parsedType}),ne}return yt(t.data)}};i(Su,"ZodUndefined");let Ea=Su;Ea.create=e=>new Ea({typeName:M.ZodUndefined,...ie(e)});const Bu=class Bu extends ce{_parse(t){if(this._getType(t)!==V.null){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.null,received:r.parsedType}),ne}return yt(t.data)}};i(Bu,"ZodNull");let xa=Bu;xa.create=e=>new xa({typeName:M.ZodNull,...ie(e)});const Ou=class Ou extends ce{constructor(){super(...arguments),this._any=!0}_parse(t){return yt(t.data)}};i(Ou,"ZodAny");let ka=Ou;ka.create=e=>new ka({typeName:M.ZodAny,...ie(e)});const Ru=class Ru extends ce{constructor(){super(...arguments),this._unknown=!0}_parse(t){return yt(t.data)}};i(Ru,"ZodUnknown");let Ia=Ru;Ia.create=e=>new Ia({typeName:M.ZodUnknown,...ie(e)});const Nu=class Nu extends ce{_parse(t){const n=this._getOrReturnCtx(t);return Z(n,{code:N.invalid_type,expected:V.never,received:n.parsedType}),ne}};i(Nu,"ZodNever");let Nt=Nu;Nt.create=e=>new Nt({typeName:M.ZodNever,...ie(e)});const Pu=class Pu extends ce{_parse(t){if(this._getType(t)!==V.undefined){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.void,received:r.parsedType}),ne}return yt(t.data)}};i(Pu,"ZodVoid");let Aa=Pu;Aa.create=e=>new Aa({typeName:M.ZodVoid,...ie(e)});const Wn=class Wn extends ce{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==V.array)return Z(n,{code:N.invalid_type,expected:V.array,received:n.parsedType}),ne;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,u=n.data.length<o.exactLength.value;(a||u)&&(Z(n,{code:a?N.too_big:N.too_small,minimum:u?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(Z(n,{code:N.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(Z(n,{code:N.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,u)=>o.type._parseAsync(new Rt(n,a,n.path,u)))).then(a=>mt.mergeArray(r,a));const s=[...n.data].map((a,u)=>o.type._parseSync(new Rt(n,a,n.path,u)));return mt.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new Wn({...this._def,minLength:{value:t,message:W.toString(n)}})}max(t,n){return new Wn({...this._def,maxLength:{value:t,message:W.toString(n)}})}length(t,n){return new Wn({...this._def,exactLength:{value:t,message:W.toString(n)}})}nonempty(t){return this.min(1,t)}};i(Wn,"ZodArray");let Kt=Wn;Kt.create=(e,t)=>new Kt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...ie(t)});function Pn(e){if(e instanceof Ct){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Pt.create(Pn(r))}return new Ct({...e._def,shape:i(()=>t,"shape")})}else return e instanceof Kt?new Kt({...e._def,type:Pn(e.element)}):e instanceof Pt?Pt.create(Pn(e.unwrap())):e instanceof Xt?Xt.create(Pn(e.unwrap())):e instanceof mn?mn.create(e.items.map(t=>Pn(t))):e}i(Pn,"deepPartialify");const vt=class vt extends ce{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=fe.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==V.object){const c=this._getOrReturnCtx(t);return Z(c,{code:N.invalid_type,expected:V.object,received:c.parsedType}),ne}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),u=[];if(!(this._def.catchall instanceof Nt&&this._def.unknownKeys==="strip"))for(const c in o.data)a.includes(c)||u.push(c);const l=[];for(const c of a){const d=s[c],f=o.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new Rt(o,f,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Nt){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of u)l.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(c==="strict")u.length>0&&(Z(o,{code:N.unrecognized_keys,keys:u}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const d of u){const f=o.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new Rt(o,f,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const f=await d.key,h=await d.value;c.push({key:f,value:h,alwaysSet:d.alwaysSet})}return c}).then(c=>mt.mergeObjectSync(r,c)):mt.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return W.errToObj,new vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:i((n,r)=>{const o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:W.errToObj(t).message??o}:{message:o}},"errorMap")}:{}})}strip(){return new vt({...this._def,unknownKeys:"strip"})}passthrough(){return new vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new vt({...this._def,shape:i(()=>({...this._def.shape(),...t}),"shape")})}merge(t){return new vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:i(()=>({...this._def.shape(),...t._def.shape()}),"shape"),typeName:M.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new vt({...this._def,catchall:t})}pick(t){const n={};for(const r of fe.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new vt({...this._def,shape:i(()=>n,"shape")})}omit(t){const n={};for(const r of fe.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new vt({...this._def,shape:i(()=>n,"shape")})}deepPartial(){return Pn(this)}partial(t){const n={};for(const r of fe.objectKeys(this.shape)){const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new vt({...this._def,shape:i(()=>n,"shape")})}required(t){const n={};for(const r of fe.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Pt;)s=s._def.innerType;n[r]=s}return new vt({...this._def,shape:i(()=>n,"shape")})}keyof(){return uf(fe.objectKeys(this.shape))}};i(vt,"ZodObject");let Ct=vt;Ct.create=(e,t)=>new Ct({shape:i(()=>e,"shape"),unknownKeys:"strip",catchall:Nt.create(),typeName:M.ZodObject,...ie(t)}),Ct.strictCreate=(e,t)=>new Ct({shape:i(()=>e,"shape"),unknownKeys:"strict",catchall:Nt.create(),typeName:M.ZodObject,...ie(t)}),Ct.lazycreate=(e,t)=>new Ct({shape:e,unknownKeys:"strip",catchall:Nt.create(),typeName:M.ZodObject,...ie(t)});const Mu=class Mu extends ce{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(const u of s)if(u.result.status==="valid")return u.result;for(const u of s)if(u.result.status==="dirty")return n.common.issues.push(...u.ctx.common.issues),u.result;const a=s.map(u=>new jt(u.ctx.common.issues));return Z(n,{code:N.invalid_union,unionErrors:a}),ne}if(i(o,"handleResults"),n.common.async)return Promise.all(r.map(async s=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of r){const c={...n,common:{...n.common,issues:[]},parent:null},d=l._parseSync({data:n.data,path:n.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const u=a.map(l=>new jt(l));return Z(n,{code:N.invalid_union,unionErrors:u}),ne}}get options(){return this._def.options}};i(Mu,"ZodUnion");let Mn=Mu;Mn.create=(e,t)=>new Mn({options:e,typeName:M.ZodUnion,...ie(t)});function wi(e,t){const n=Jt(e),r=Jt(t);if(e===t)return{valid:!0,data:e};if(n===V.object&&r===V.object){const o=fe.objectKeys(t),s=fe.objectKeys(e).filter(u=>o.indexOf(u)!==-1),a={...e,...t};for(const u of s){const l=wi(e[u],t[u]);if(!l.valid)return{valid:!1};a[u]=l.data}return{valid:!0,data:a}}else if(n===V.array&&r===V.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],u=t[s],l=wi(a,u);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===V.date&&r===V.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}i(wi,"mergeValues");const ju=class ju extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=i((s,a)=>{if(nf(s)||nf(a))return ne;const u=wi(s.value,a.value);return u.valid?((rf(s)||rf(a))&&n.dirty(),{status:n.value,value:u.data}):(Z(r,{code:N.invalid_intersection_types}),ne)},"handleParsed");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(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};i(ju,"ZodIntersection");let jn=ju;jn.create=(e,t,n)=>new jn({left:e,right:t,typeName:M.ZodIntersection,...ie(n)});const Xa=class Xa extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==V.array)return Z(r,{code:N.invalid_type,expected:V.array,received:r.parsedType}),ne;if(r.data.length<this._def.items.length)return Z(r,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ne;!this._def.rest&&r.data.length>this._def.items.length&&(Z(r,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,u)=>{const l=this._def.items[u]||this._def.rest;return l?l._parse(new Rt(r,a,r.path,u)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>mt.mergeArray(n,a)):mt.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new Xa({...this._def,rest:t})}};i(Xa,"ZodTuple");let mn=Xa;mn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mn({items:e,typeName:M.ZodTuple,rest:null,...ie(t)})};const zu=class zu extends ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==V.map)return Z(r,{code:N.invalid_type,expected:V.map,received:r.parsedType}),ne;const o=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([u,l],c)=>({key:o._parse(new Rt(r,u,r.path,[c,"key"])),value:s._parse(new Rt(r,l,r.path,[c,"value"]))}));if(r.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return ne;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),u.set(c.value,d.value)}return{status:n.value,value:u}})}else{const u=new Map;for(const l of a){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return ne;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),u.set(c.value,d.value)}return{status:n.value,value:u}}}};i(zu,"ZodMap");let $a=zu;$a.create=(e,t,n)=>new $a({valueType:t,keyType:e,typeName:M.ZodMap,...ie(n)});const Oo=class Oo extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==V.set)return Z(r,{code:N.invalid_type,expected:V.set,received:r.parsedType}),ne;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(Z(r,{code:N.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(Z(r,{code:N.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const s=this._def.valueType;function a(l){const c=new Set;for(const d of l){if(d.status==="aborted")return ne;d.status==="dirty"&&n.dirty(),c.add(d.value)}return{status:n.value,value:c}}i(a,"finalizeSet");const u=[...r.data.values()].map((l,c)=>s._parse(new Rt(r,l,r.path,c)));return r.common.async?Promise.all(u).then(l=>a(l)):a(u)}min(t,n){return new Oo({...this._def,minSize:{value:t,message:W.toString(n)}})}max(t,n){return new Oo({...this._def,maxSize:{value:t,message:W.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};i(Oo,"ZodSet");let Ta=Oo;Ta.create=(e,t)=>new Ta({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...ie(t)});const Lu=class Lu extends ce{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};i(Lu,"ZodLazy");let Sa=Lu;Sa.create=(e,t)=>new Sa({getter:e,typeName:M.ZodLazy,...ie(t)});const qu=class qu extends ce{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Z(n,{received:n.data,code:N.invalid_literal,expected:this._def.value}),ne}return{status:"valid",value:t.data}}get value(){return this._def.value}};i(qu,"ZodLiteral");let Ba=qu;Ba.create=(e,t)=>new Ba({value:e,typeName:M.ZodLiteral,...ie(t)});function uf(e,t){return new go({values:e,typeName:M.ZodEnum,...ie(t)})}i(uf,"createZodEnum");const Ro=class Ro extends ce{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Z(n,{expected:fe.joinValues(r),received:n.parsedType,code:N.invalid_type}),ne}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return Z(n,{received:n.data,code:N.invalid_enum_value,options:r}),ne}return yt(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Ro.create(t,{...this._def,...n})}exclude(t,n=this._def){return Ro.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};i(Ro,"ZodEnum");let go=Ro;go.create=uf;const Uu=class Uu extends ce{_parse(t){const n=fe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==V.string&&r.parsedType!==V.number){const o=fe.objectValues(n);return Z(r,{expected:fe.joinValues(o),received:r.parsedType,code:N.invalid_type}),ne}if(this._cache||(this._cache=new Set(fe.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=fe.objectValues(n);return Z(r,{received:r.data,code:N.invalid_enum_value,options:o}),ne}return yt(t.data)}get enum(){return this._def.values}};i(Uu,"ZodNativeEnum");let Oa=Uu;Oa.create=(e,t)=>new Oa({values:e,typeName:M.ZodNativeEnum,...ie(t)});const Zu=class Zu extends ce{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==V.promise&&n.common.async===!1)return Z(n,{code:N.invalid_type,expected:V.promise,received:n.parsedType}),ne;const r=n.parsedType===V.promise?n.data:Promise.resolve(n.data);return yt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};i(Zu,"ZodPromise");let zn=Zu;zn.create=(e,t)=>new zn({type:e,typeName:M.ZodPromise,...ie(t)});const Vu=class Vu extends ce{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i(a=>{Z(r,a),a.fatal?n.abort():n.dirty()},"addIssue"),get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async u=>{if(n.value==="aborted")return ne;const l=await this._def.schema._parseAsync({data:u,path:r.path,parent:r});return l.status==="aborted"?ne:l.status==="dirty"||n.value==="dirty"?mo(l.value):l});{if(n.value==="aborted")return ne;const u=this._def.schema._parseSync({data:a,path:r.path,parent:r});return u.status==="aborted"?ne:u.status==="dirty"||n.value==="dirty"?mo(u.value):u}}if(o.type==="refinement"){const a=i(u=>{const l=o.refinement(u,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u},"executeRefinement");if(r.common.async===!1){const u=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return u.status==="aborted"?ne:(u.status==="dirty"&&n.dirty(),a(u.value),{status:n.value,value:u.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(u=>u.status==="aborted"?ne:(u.status==="dirty"&&n.dirty(),a(u.value).then(()=>({status:n.value,value:u.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Nn(a))return ne;const u=o.transform(a.value,s);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:u}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Nn(a)?Promise.resolve(o.transform(a.value,s)).then(u=>({status:n.value,value:u})):ne);fe.assertNever(o)}};i(Vu,"ZodEffects");let Yt=Vu;Yt.create=(e,t,n)=>new Yt({schema:e,typeName:M.ZodEffects,effect:t,...ie(n)}),Yt.createWithPreprocess=(e,t,n)=>new Yt({schema:t,effect:{type:"preprocess",transform:e},typeName:M.ZodEffects,...ie(n)});const Gu=class Gu extends ce{_parse(t){return this._getType(t)===V.undefined?yt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};i(Gu,"ZodOptional");let Pt=Gu;Pt.create=(e,t)=>new Pt({innerType:e,typeName:M.ZodOptional,...ie(t)});const Wu=class Wu extends ce{_parse(t){return this._getType(t)===V.null?yt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};i(Wu,"ZodNullable");let Xt=Wu;Xt.create=(e,t)=>new Xt({innerType:e,typeName:M.ZodNullable,...ie(t)});const Hu=class Hu extends ce{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===V.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};i(Hu,"ZodDefault");let vo=Hu;vo.create=(e,t)=>new vo({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ie(t)});const Ju=class Ju extends ce{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return _a(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new jt(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new jt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};i(Ju,"ZodCatch");let yo=Ju;yo.create=(e,t)=>new yo({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ie(t)});const Ku=class Ku extends ce{_parse(t){if(this._getType(t)!==V.nan){const r=this._getOrReturnCtx(t);return Z(r,{code:N.invalid_type,expected:V.nan,received:r.parsedType}),ne}return{status:"valid",value:t.data}}};i(Ku,"ZodNaN");let Ra=Ku;Ra.create=e=>new Ra({typeName:M.ZodNaN,...ie(e)});const Yu=class Yu extends ce{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}};i(Yu,"ZodBranded");let Fi=Yu;const Qa=class Qa extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return i(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?ne:s.status==="dirty"?(n.dirty(),mo(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})},"handleAsync")();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?ne:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new Qa({in:t,out:n,typeName:M.ZodPipeline})}};i(Qa,"ZodPipeline");let Ei=Qa;const Xu=class Xu extends ce{_parse(t){const n=this._def.innerType._parse(t),r=i(o=>(Nn(o)&&(o.value=Object.freeze(o.value)),o),"freeze");return _a(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};i(Xu,"ZodReadonly");let _o=Xu;_o.create=(e,t)=>new _o({innerType:e,typeName:M.ZodReadonly,...ie(t)});var M;(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"})(M||(M={}));const we=ho.create,Mt=Do.create;Nt.create;const Qt=Kt.create,wt=Ct.create,xi=Mn.create;jn.create,mn.create;const Na=go.create;zn.create,Pt.create,Xt.create;const Qu=class Qu extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}};i(Qu,"ParseError");let Pa=Qu;function ki(e){}i(ki,"noop");function kF(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=ki,onError:n=ki,onRetry:r=ki,onComment:o}=e;let s="",a=!0,u,l="",c="";function d(v){const y=a?v.replace(/^\xEF\xBB\xBF/,""):v,[b,C]=IF(`${s}${y}`);for(const F of b)f(F);s=C,a=!1}i(d,"feed");function f(v){if(v===""){D();return}if(v.startsWith(":")){o&&o(v.slice(v.startsWith(": ")?2:1));return}const y=v.indexOf(":");if(y!==-1){const b=v.slice(0,y),C=v[y+1]===" "?2:1,F=v.slice(y+C);h(b,F,v);return}h(v,"",v)}i(f,"parseLine");function h(v,y,b){switch(v){case"event":c=y;break;case"data":l=`${l}${y}
115
115
  `;break;case"id":u=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?r(parseInt(y,10)):n(new Pa(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:b}));break;default:n(new Pa(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:y,line:b}));break}}i(h,"processField");function D(){l.length>0&&t({id:u,event:c||void 0,data:l.endsWith(`
116
- `)?l.slice(0,-1):l}),u=void 0,l="",c=""}i(D,"dispatchEvent");function m(v={}){s&&v.consume&&f(s),a=!0,u=void 0,l="",c="",s=""}return i(m,"reset"),{feed:d,reset:m}}i(EF,"createParser");function xF(e){const t=[];let n="",r=0;for(;r<e.length;){const o=e.indexOf("\r",r),s=e.indexOf(`
116
+ `)?l.slice(0,-1):l}),u=void 0,l="",c=""}i(D,"dispatchEvent");function m(v={}){s&&v.consume&&f(s),a=!0,u=void 0,l="",c="",s=""}return i(m,"reset"),{feed:d,reset:m}}i(kF,"createParser");function IF(e){const t=[];let n="",r=0;for(;r<e.length;){const o=e.indexOf("\r",r),s=e.indexOf(`
117
117
  `,r);let a=-1;if(o!==-1&&s!==-1?a=Math.min(o,s):o!==-1?o===e.length-1?a=-1:a=o:s!==-1&&(a=s),a===-1){n=e.slice(r);break}else{const u=e.slice(r,a);t.push(u),r=a+1,e[r-1]==="\r"&&e[r]===`
118
- `&&r++}}return[t,n]}i(xF,"splitLines");const el=class el extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let o;super({start(s){o=EF({onEvent:i(a=>{s.enqueue(a)},"onEvent"),onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:n,onComment:r})},transform(s){o.feed(s)}})}};i(el,"EventSourceParserStream");let Ii=el;function Ne(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}i(Ne,"combineHeaders");function kF({tools:e=[],providerToolNames:t}){const n={},r={};for(const o of e)if(o.type==="provider"&&o.id in t){const s=t[o.id];n[o.name]=s,r[s]=o.name}return{toProviderToolName:i(o=>{var s;return(s=n[o])!=null?s:o},"toProviderToolName"),toCustomToolName:i(o=>{var s;return(s=r[o])!=null?s:o},"toCustomToolName")}}i(kF,"createToolNameMapping");async function IF(e,t){if(e==null)return Promise.resolve();const n=t?.abortSignal;return new Promise((r,o)=>{if(n?.aborted){o(lf());return}const s=setTimeout(()=>{a(),r()},e),a=i(()=>{clearTimeout(s),n?.removeEventListener("abort",u)},"cleanup"),u=i(()=>{a(),o(lf())},"onAbort");n?.addEventListener("abort",u)})}i(IF,"delay");function lf(){return new DOMException("Delay was aborted","AbortError")}i(lf,"createAbortError");function Ln(e){return Object.fromEntries([...e.headers])}i(Ln,"extractResponseHeaders");var{btoa:AF,atob:$F}=globalThis;function hn(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=$F(t);return Uint8Array.from(n,r=>r.codePointAt(0))}i(hn,"convertBase64ToUint8Array");function qn(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return AF(t)}i(qn,"convertUint8ArrayToBase64");function zt(e){return e instanceof Uint8Array?qn(e):e}i(zt,"convertToBase64");function cf(e,t={}){const{useArrayBrackets:n=!0}=t,r=new FormData;for(const[o,s]of Object.entries(e))if(s!=null){if(Array.isArray(s)){if(s.length===1){r.append(o,s[0]);continue}const a=n?`${o}[]`:o;for(const u of s)r.append(a,u);continue}r.append(o,s)}return r}i(cf,"convertToFormData");var df="AI_DownloadError",pf=`vercel.ai.error.${df}`,TF=Symbol.for(pf),ff,mf,en=(or=class extends(mf=Q,ff=TF,mf){constructor({url:t,statusCode:n,statusText:r,cause:o,message:s=o==null?`Failed to download ${t}: ${n} ${r}`:`Failed to download ${t}: ${o}`}){super({name:df,message:s,cause:o}),this[ff]=!0,this.url=t,this.statusCode=n,this.statusText=r}static isInstance(t){return Q.hasMarker(t,pf)}},i(or,"DownloadError"),or),Ai=2*1024*1024*1024;async function hf({response:e,url:t,maxBytes:n=Ai}){const r=e.headers.get("content-length");if(r!=null){const d=parseInt(r,10);if(!isNaN(d)&&d>n)throw new en({url:t,message:`Download of ${t} exceeded maximum size of ${n} bytes (Content-Length: ${d}).`})}const o=e.body;if(o==null)return new Uint8Array(0);const s=o.getReader(),a=[];let u=0;try{for(;;){const{done:d,value:f}=await s.read();if(d)break;if(u+=f.length,u>n)throw new en({url:t,message:`Download of ${t} exceeded maximum size of ${n} bytes.`});a.push(f)}}finally{try{await s.cancel()}finally{s.releaseLock()}}const l=new Uint8Array(u);let c=0;for(const d of a)l.set(d,c),c+=d.length;return l}i(hf,"readResponseWithSizeLimit");async function $i(e,t){var n,r;try{const o=await fetch(e,{signal:t?.abortSignal});if(!o.ok)throw new en({url:e,statusCode:o.status,statusText:o.statusText});const s=await hf({response:o,url:e,maxBytes:(n=t?.maxBytes)!=null?n:Ai}),a=(r=o.headers.get("content-type"))!=null?r:void 0;return new Blob([s],a?{type:a}:void 0)}catch(o){throw en.isInstance(o)?o:new en({url:e,cause:o})}}i($i,"downloadBlob");var bo=i(({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=i(()=>{const s=n.length,a=new Array(t);for(let u=0;u<t;u++)a[u]=n[Math.random()*s|0];return a.join("")},"generator");if(e==null)return o;if(n.includes(r))throw new Od({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},"createIdGenerator"),Ve=bo();function Df(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}i(Df,"getErrorMessage");function Un(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}i(Un,"isAbortError");var SF=["fetch failed","failed to fetch"],BF=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function OF(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&BF.includes(t))}i(OF,"isBunNetworkError");function gf({error:e,url:t,requestBodyValues:n}){if(Un(e))return e;if(e instanceof TypeError&&SF.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new Be({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return OF(e)?new Be({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:n,isRetryable:!0}):e}i(gf,"handleFetchError");function Ti(e=globalThis){var t,n,r;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(r=(n=e.process)==null?void 0:n.versions)!=null&&r.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}i(Ti,"getRuntimeEnvironmentUserAgent");function RF(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,r)=>{t[r.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,r]of e)r!=null&&(t[n.toLowerCase()]=r)}return t}i(RF,"normalizeHeaders");function Dn(e,...t){const n=new Headers(RF(e)),r=n.get("user-agent")||"";return n.set("user-agent",[r,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}i(Dn,"withUserAgentSuffix");var vf="4.0.15",NF=i(()=>globalThis.fetch,"getOriginalFetch"),yf=i(async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:o,fetch:s=NF()})=>{try{const a=await s(e,{method:"GET",headers:Dn(t,`ai-sdk/provider-utils/${vf}`,Ti()),signal:o}),u=Ln(a);if(!a.ok){let l;try{l=await r({response:a,url:e,requestBodyValues:{}})}catch(c){throw Un(c)||Be.isInstance(c)?c:new Be({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:u,requestBodyValues:{}})}throw l.value}try{return await n({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Un(l)||Be.isInstance(l))?l:new Be({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:u,requestBodyValues:{}})}}catch(a){throw gf({error:a,url:e,requestBodyValues:{}})}},"getFromApi");function PF(e){return e!=null}i(PF,"isNonNullable");function MF({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,o])=>{const s=r.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:s.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}i(MF,"isUrlSupported");function jF({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if(typeof e=="string")return e;if(e!=null)throw new ia({message:`${r} API key must be a string.`});if(typeof process>"u")throw new ia({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new ia({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ia({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}i(jF,"loadApiKey");function Co({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}i(Co,"loadOptionalSetting");function zF(e){var t;const[n,r=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[r])!=null?t:r}i(zF,"mediaTypeToExtension");var LF=/"__proto__"\s*:/,qF=/"constructor"\s*:/;function _f(e){const t=JSON.parse(e);return t===null||typeof t!="object"||LF.test(e)===!1&&qF.test(e)===!1?t:UF(t)}i(_f,"_parse");function UF(e){let t=[e];for(;t.length;){const n=t;t=[];for(const r of n){if(Object.prototype.hasOwnProperty.call(r,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(r,"constructor")&&Object.prototype.hasOwnProperty.call(r.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in r){const s=r[o];s&&typeof s=="object"&&t.push(s)}}}return e}i(UF,"filter");function Si(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return _f(e)}try{return _f(e)}finally{Error.stackTraceLimit=t}}i(Si,"secureJsonParse");function Bi(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;const{properties:n}=e;if(n!=null)for(const r of Object.keys(n))n[r]=gn(n[r])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(gn):gn(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(gn)),e.allOf!=null&&(e.allOf=e.allOf.map(gn)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(gn));const{definitions:t}=e;if(t!=null)for(const n of Object.keys(t))t[n]=gn(t[n]);return e}i(Bi,"addAdditionalPropertiesToJsonSchema");function gn(e){return typeof e=="boolean"?e:Bi(e)}i(gn,"visit");var ZF=Symbol("Let zodToJsonSchema decide on which parser to use"),bf={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},VF=i(e=>typeof e=="string"?{...bf,name:e}:{...bf,...e},"getDefaultOptions");function ht(){return{}}i(ht,"parseAnyDef");function GF(e,t){var n,r,o;const s={type:"array"};return(n=e.type)!=null&&n._def&&((o=(r=e.type)==null?void 0:r._def)==null?void 0:o.typeName)!==P.ZodAny&&(s.items=_e(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}i(GF,"parseArrayDef");function WF(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}i(WF,"parseBigintDef");function HF(){return{type:"boolean"}}i(HF,"parseBooleanDef");function Cf(e,t){return _e(e.type._def,t)}i(Cf,"parseBrandedDef");var JF=i((e,t)=>_e(e.innerType._def,t),"parseCatchDef");function wf(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>wf(e,t,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return KF(e)}}i(wf,"parseDateDef");var KF=i(e=>{const t={type:"integer",format:"unix-time"};for(const n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t},"integerDateParser");function YF(e,t){return{..._e(e.innerType._def,t),default:e.defaultValue()}}i(YF,"parseDefaultDef");function XF(e,t){return t.effectStrategy==="input"?_e(e.schema._def,t):ht()}i(XF,"parseEffectsDef");function QF(e){return{type:"string",enum:Array.from(e.values)}}i(QF,"parseEnumDef");var e2=i(e=>"type"in e&&e.type==="string"?!1:"allOf"in e,"isJsonSchema7AllOfType");function t2(e,t){const n=[_e(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),_e(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),r=[];return n.forEach(o=>{if(e2(o))r.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...u}=o;s=u}r.push(s)}}),r.length?{allOf:r}:void 0}i(t2,"parseIntersectionDef");function n2(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}i(n2,"parseLiteralDef");var Oi=void 0,Ft={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:i(()=>(Oi===void 0&&(Oi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Oi),"emoji"),uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Ff(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"email":switch(t.emailStrategy){case"format:email":Et(n,"email",r.message,t);break;case"format:idn-email":Et(n,"idn-email",r.message,t);break;case"pattern:zod":nt(n,Ft.email,r.message,t);break}break;case"url":Et(n,"uri",r.message,t);break;case"uuid":Et(n,"uuid",r.message,t);break;case"regex":nt(n,r.regex,r.message,t);break;case"cuid":nt(n,Ft.cuid,r.message,t);break;case"cuid2":nt(n,Ft.cuid2,r.message,t);break;case"startsWith":nt(n,RegExp(`^${Ri(r.value,t)}`),r.message,t);break;case"endsWith":nt(n,RegExp(`${Ri(r.value,t)}$`),r.message,t);break;case"datetime":Et(n,"date-time",r.message,t);break;case"date":Et(n,"date",r.message,t);break;case"time":Et(n,"time",r.message,t);break;case"duration":Et(n,"duration",r.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"includes":{nt(n,RegExp(Ri(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&Et(n,"ipv4",r.message,t),r.version!=="v4"&&Et(n,"ipv6",r.message,t);break}case"base64url":nt(n,Ft.base64url,r.message,t);break;case"jwt":nt(n,Ft.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&nt(n,Ft.ipv4Cidr,r.message,t),r.version!=="v4"&&nt(n,Ft.ipv6Cidr,r.message,t);break}case"emoji":nt(n,Ft.emoji(),r.message,t);break;case"ulid":{nt(n,Ft.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Et(n,"binary",r.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{nt(n,Ft.base64,r.message,t);break}}break}case"nanoid":nt(n,Ft.nanoid,r.message,t)}return n}i(Ff,"parseStringDef");function Ri(e,t){return t.patternStrategy==="escape"?o2(e):e}i(Ri,"escapeLiteralCheckValue");var r2=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function o2(e){let t="";for(let n=0;n<e.length;n++)r2.has(e[n])||(t+="\\"),t+=e[n];return t}i(o2,"escapeNonAlphaNumeric");function Et(e,t,n,r){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}i(Et,"addFormat");function nt(e,t,n,r){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Ef(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=Ef(t,r)}i(nt,"addPattern");function Ef(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=r.i?e.source.toLowerCase():e.source;let s="",a=!1,u=!1,l=!1;for(let c=0;c<o.length;c++){if(a){s+=o[c],a=!1;continue}if(r.i){if(u){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((n=o[c+2])!=null&&n.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){s+=`(^|(?<=[\r
118
+ `&&r++}}return[t,n]}i(IF,"splitLines");const el=class el extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let o;super({start(s){o=kF({onEvent:i(a=>{s.enqueue(a)},"onEvent"),onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:n,onComment:r})},transform(s){o.feed(s)}})}};i(el,"EventSourceParserStream");let Ii=el;function Ne(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}i(Ne,"combineHeaders");function AF({tools:e=[],providerToolNames:t}){const n={},r={};for(const o of e)if(o.type==="provider"&&o.id in t){const s=t[o.id];n[o.name]=s,r[s]=o.name}return{toProviderToolName:i(o=>{var s;return(s=n[o])!=null?s:o},"toProviderToolName"),toCustomToolName:i(o=>{var s;return(s=r[o])!=null?s:o},"toCustomToolName")}}i(AF,"createToolNameMapping");async function $F(e,t){if(e==null)return Promise.resolve();const n=t?.abortSignal;return new Promise((r,o)=>{if(n?.aborted){o(lf());return}const s=setTimeout(()=>{a(),r()},e),a=i(()=>{clearTimeout(s),n?.removeEventListener("abort",u)},"cleanup"),u=i(()=>{a(),o(lf())},"onAbort");n?.addEventListener("abort",u)})}i($F,"delay");function lf(){return new DOMException("Delay was aborted","AbortError")}i(lf,"createAbortError");function Ln(e){return Object.fromEntries([...e.headers])}i(Ln,"extractResponseHeaders");var{btoa:TF,atob:SF}=globalThis;function hn(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=SF(t);return Uint8Array.from(n,r=>r.codePointAt(0))}i(hn,"convertBase64ToUint8Array");function qn(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return TF(t)}i(qn,"convertUint8ArrayToBase64");function zt(e){return e instanceof Uint8Array?qn(e):e}i(zt,"convertToBase64");function cf(e,t={}){const{useArrayBrackets:n=!0}=t,r=new FormData;for(const[o,s]of Object.entries(e))if(s!=null){if(Array.isArray(s)){if(s.length===1){r.append(o,s[0]);continue}const a=n?`${o}[]`:o;for(const u of s)r.append(a,u);continue}r.append(o,s)}return r}i(cf,"convertToFormData");var df="AI_DownloadError",pf=`vercel.ai.error.${df}`,BF=Symbol.for(pf),ff,mf,en=(or=class extends(mf=Q,ff=BF,mf){constructor({url:t,statusCode:n,statusText:r,cause:o,message:s=o==null?`Failed to download ${t}: ${n} ${r}`:`Failed to download ${t}: ${o}`}){super({name:df,message:s,cause:o}),this[ff]=!0,this.url=t,this.statusCode=n,this.statusText=r}static isInstance(t){return Q.hasMarker(t,pf)}},i(or,"DownloadError"),or),Ai=2*1024*1024*1024;async function hf({response:e,url:t,maxBytes:n=Ai}){const r=e.headers.get("content-length");if(r!=null){const d=parseInt(r,10);if(!isNaN(d)&&d>n)throw new en({url:t,message:`Download of ${t} exceeded maximum size of ${n} bytes (Content-Length: ${d}).`})}const o=e.body;if(o==null)return new Uint8Array(0);const s=o.getReader(),a=[];let u=0;try{for(;;){const{done:d,value:f}=await s.read();if(d)break;if(u+=f.length,u>n)throw new en({url:t,message:`Download of ${t} exceeded maximum size of ${n} bytes.`});a.push(f)}}finally{try{await s.cancel()}finally{s.releaseLock()}}const l=new Uint8Array(u);let c=0;for(const d of a)l.set(d,c),c+=d.length;return l}i(hf,"readResponseWithSizeLimit");async function $i(e,t){var n,r;try{const o=await fetch(e,{signal:t?.abortSignal});if(!o.ok)throw new en({url:e,statusCode:o.status,statusText:o.statusText});const s=await hf({response:o,url:e,maxBytes:(n=t?.maxBytes)!=null?n:Ai}),a=(r=o.headers.get("content-type"))!=null?r:void 0;return new Blob([s],a?{type:a}:void 0)}catch(o){throw en.isInstance(o)?o:new en({url:e,cause:o})}}i($i,"downloadBlob");var bo=i(({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=i(()=>{const s=n.length,a=new Array(t);for(let u=0;u<t;u++)a[u]=n[Math.random()*s|0];return a.join("")},"generator");if(e==null)return o;if(n.includes(r))throw new Od({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},"createIdGenerator"),Ve=bo();function Df(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}i(Df,"getErrorMessage");function Un(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}i(Un,"isAbortError");var OF=["fetch failed","failed to fetch"],RF=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function NF(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&RF.includes(t))}i(NF,"isBunNetworkError");function gf({error:e,url:t,requestBodyValues:n}){if(Un(e))return e;if(e instanceof TypeError&&OF.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new Be({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return NF(e)?new Be({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:n,isRetryable:!0}):e}i(gf,"handleFetchError");function Ti(e=globalThis){var t,n,r;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(r=(n=e.process)==null?void 0:n.versions)!=null&&r.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}i(Ti,"getRuntimeEnvironmentUserAgent");function PF(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,r)=>{t[r.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,r]of e)r!=null&&(t[n.toLowerCase()]=r)}return t}i(PF,"normalizeHeaders");function Dn(e,...t){const n=new Headers(PF(e)),r=n.get("user-agent")||"";return n.set("user-agent",[r,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}i(Dn,"withUserAgentSuffix");var vf="4.0.15",MF=i(()=>globalThis.fetch,"getOriginalFetch"),yf=i(async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:o,fetch:s=MF()})=>{try{const a=await s(e,{method:"GET",headers:Dn(t,`ai-sdk/provider-utils/${vf}`,Ti()),signal:o}),u=Ln(a);if(!a.ok){let l;try{l=await r({response:a,url:e,requestBodyValues:{}})}catch(c){throw Un(c)||Be.isInstance(c)?c:new Be({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:u,requestBodyValues:{}})}throw l.value}try{return await n({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Un(l)||Be.isInstance(l))?l:new Be({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:u,requestBodyValues:{}})}}catch(a){throw gf({error:a,url:e,requestBodyValues:{}})}},"getFromApi");function jF(e){return e!=null}i(jF,"isNonNullable");function zF({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,o])=>{const s=r.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:s.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}i(zF,"isUrlSupported");function LF({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if(typeof e=="string")return e;if(e!=null)throw new ia({message:`${r} API key must be a string.`});if(typeof process>"u")throw new ia({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new ia({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new ia({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}i(LF,"loadApiKey");function Co({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}i(Co,"loadOptionalSetting");function qF(e){var t;const[n,r=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[r])!=null?t:r}i(qF,"mediaTypeToExtension");var UF=/"__proto__"\s*:/,ZF=/"constructor"\s*:/;function _f(e){const t=JSON.parse(e);return t===null||typeof t!="object"||UF.test(e)===!1&&ZF.test(e)===!1?t:VF(t)}i(_f,"_parse");function VF(e){let t=[e];for(;t.length;){const n=t;t=[];for(const r of n){if(Object.prototype.hasOwnProperty.call(r,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(r,"constructor")&&Object.prototype.hasOwnProperty.call(r.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in r){const s=r[o];s&&typeof s=="object"&&t.push(s)}}}return e}i(VF,"filter");function Si(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return _f(e)}try{return _f(e)}finally{Error.stackTraceLimit=t}}i(Si,"secureJsonParse");function Bi(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;const{properties:n}=e;if(n!=null)for(const r of Object.keys(n))n[r]=gn(n[r])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(gn):gn(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(gn)),e.allOf!=null&&(e.allOf=e.allOf.map(gn)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(gn));const{definitions:t}=e;if(t!=null)for(const n of Object.keys(t))t[n]=gn(t[n]);return e}i(Bi,"addAdditionalPropertiesToJsonSchema");function gn(e){return typeof e=="boolean"?e:Bi(e)}i(gn,"visit");var GF=Symbol("Let zodToJsonSchema decide on which parser to use"),bf={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},WF=i(e=>typeof e=="string"?{...bf,name:e}:{...bf,...e},"getDefaultOptions");function ht(){return{}}i(ht,"parseAnyDef");function HF(e,t){var n,r,o;const s={type:"array"};return(n=e.type)!=null&&n._def&&((o=(r=e.type)==null?void 0:r._def)==null?void 0:o.typeName)!==M.ZodAny&&(s.items=_e(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}i(HF,"parseArrayDef");function JF(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}i(JF,"parseBigintDef");function KF(){return{type:"boolean"}}i(KF,"parseBooleanDef");function Cf(e,t){return _e(e.type._def,t)}i(Cf,"parseBrandedDef");var YF=i((e,t)=>_e(e.innerType._def,t),"parseCatchDef");function wf(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>wf(e,t,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return XF(e)}}i(wf,"parseDateDef");var XF=i(e=>{const t={type:"integer",format:"unix-time"};for(const n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t},"integerDateParser");function QF(e,t){return{..._e(e.innerType._def,t),default:e.defaultValue()}}i(QF,"parseDefaultDef");function e2(e,t){return t.effectStrategy==="input"?_e(e.schema._def,t):ht()}i(e2,"parseEffectsDef");function t2(e){return{type:"string",enum:Array.from(e.values)}}i(t2,"parseEnumDef");var n2=i(e=>"type"in e&&e.type==="string"?!1:"allOf"in e,"isJsonSchema7AllOfType");function r2(e,t){const n=[_e(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),_e(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),r=[];return n.forEach(o=>{if(n2(o))r.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...u}=o;s=u}r.push(s)}}),r.length?{allOf:r}:void 0}i(r2,"parseIntersectionDef");function o2(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}i(o2,"parseLiteralDef");var Oi=void 0,Ft={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:i(()=>(Oi===void 0&&(Oi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Oi),"emoji"),uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Ff(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"email":switch(t.emailStrategy){case"format:email":Et(n,"email",r.message,t);break;case"format:idn-email":Et(n,"idn-email",r.message,t);break;case"pattern:zod":nt(n,Ft.email,r.message,t);break}break;case"url":Et(n,"uri",r.message,t);break;case"uuid":Et(n,"uuid",r.message,t);break;case"regex":nt(n,r.regex,r.message,t);break;case"cuid":nt(n,Ft.cuid,r.message,t);break;case"cuid2":nt(n,Ft.cuid2,r.message,t);break;case"startsWith":nt(n,RegExp(`^${Ri(r.value,t)}`),r.message,t);break;case"endsWith":nt(n,RegExp(`${Ri(r.value,t)}$`),r.message,t);break;case"datetime":Et(n,"date-time",r.message,t);break;case"date":Et(n,"date",r.message,t);break;case"time":Et(n,"time",r.message,t);break;case"duration":Et(n,"duration",r.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"includes":{nt(n,RegExp(Ri(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&Et(n,"ipv4",r.message,t),r.version!=="v4"&&Et(n,"ipv6",r.message,t);break}case"base64url":nt(n,Ft.base64url,r.message,t);break;case"jwt":nt(n,Ft.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&nt(n,Ft.ipv4Cidr,r.message,t),r.version!=="v4"&&nt(n,Ft.ipv6Cidr,r.message,t);break}case"emoji":nt(n,Ft.emoji(),r.message,t);break;case"ulid":{nt(n,Ft.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Et(n,"binary",r.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{nt(n,Ft.base64,r.message,t);break}}break}case"nanoid":nt(n,Ft.nanoid,r.message,t)}return n}i(Ff,"parseStringDef");function Ri(e,t){return t.patternStrategy==="escape"?s2(e):e}i(Ri,"escapeLiteralCheckValue");var a2=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function s2(e){let t="";for(let n=0;n<e.length;n++)a2.has(e[n])||(t+="\\"),t+=e[n];return t}i(s2,"escapeNonAlphaNumeric");function Et(e,t,n,r){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}i(Et,"addFormat");function nt(e,t,n,r){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Ef(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=Ef(t,r)}i(nt,"addPattern");function Ef(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=r.i?e.source.toLowerCase():e.source;let s="",a=!1,u=!1,l=!1;for(let c=0;c<o.length;c++){if(a){s+=o[c],a=!1;continue}if(r.i){if(u){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((n=o[c+2])!=null&&n.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){s+=`(^|(?<=[\r
119
119
  ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
120
120
  ]))`;continue}}if(r.s&&o[c]==="."){s+=u?`${o[c]}\r
121
121
  `:`[${o[c]}\r
122
- ]`;continue}s+=o[c],o[c]==="\\"?a=!0:u&&o[c]==="]"?u=!1:!u&&o[c]==="["&&(u=!0)}try{new RegExp(s)}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 s}i(Ef,"stringifyRegExpWithFlags");function xf(e,t){var n,r,o,s,a,u;const l={type:"object",additionalProperties:(n=_e(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((r=e.keyType)==null?void 0:r._def.typeName)===P.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...d}=Ff(e.keyType._def,t);return{...l,propertyNames:d}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===P.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===P.ZodBranded&&e.keyType._def.type._def.typeName===P.ZodString&&((u=e.keyType._def.type._def.checks)!=null&&u.length)){const{type:c,...d}=Cf(e.keyType._def,t);return{...l,propertyNames:d}}}return l}i(xf,"parseRecordDef");function a2(e,t){if(t.mapStrategy==="record")return xf(e,t);const n=_e(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||ht(),r=_e(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||ht();return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}i(a2,"parseMapDef");function s2(e){const t=e.values,r=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}i(s2,"parseNativeEnumDef");function i2(){return{not:ht()}}i(i2,"parseNeverDef");function u2(){return{type:"null"}}i(u2,"parseNullDef");var Ni={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function l2(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Ni&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,s)=>{const a=Ni[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){const o=r.filter((s,a,u)=>u.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:n.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return c2(e,t)}i(l2,"parseUnionDef");var c2=i((e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,o)=>_e(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0},"asAnyOf");function d2(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Ni[e.innerType._def.typeName],"null"]};const n=_e(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}i(d2,"parseNullableDef");function p2(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}i(p2,"parseNumberDef");function f2(e,t){const n={type:"object",properties:{}},r=[],o=e.shape();for(const a in o){let u=o[a];if(u===void 0||u._def===void 0)continue;const l=h2(u),c=_e(u._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(n.properties[a]=c,l||r.push(a))}r.length&&(n.required=r);const s=m2(e,t);return s!==void 0&&(n.additionalProperties=s),n}i(f2,"parseObjectDef");function m2(e,t){if(e.catchall._def.typeName!=="ZodNever")return _e(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}i(m2,"decideAdditionalProperties");function h2(e){try{return e.isOptional()}catch{return!0}}i(h2,"safeIsOptional");var D2=i((e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return _e(e.innerType._def,t);const r=_e(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ht()},r]}:ht()},"parseOptionalDef"),g2=i((e,t)=>{if(t.pipeStrategy==="input")return _e(e.in._def,t);if(t.pipeStrategy==="output")return _e(e.out._def,t);const n=_e(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=_e(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}},"parsePipelineDef");function v2(e,t){return _e(e.type._def,t)}i(v2,"parsePromiseDef");function y2(e,t){const r={type:"array",uniqueItems:!0,items:_e(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}i(y2,"parseSetDef");function _2(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>_e(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:_e(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>_e(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}i(_2,"parseTupleDef");function b2(){return{not:ht()}}i(b2,"parseUndefinedDef");function C2(){return ht()}i(C2,"parseUnknownDef");var w2=i((e,t)=>_e(e.innerType._def,t),"parseReadonlyDef"),F2=i((e,t,n)=>{switch(t){case P.ZodString:return Ff(e,n);case P.ZodNumber:return p2(e);case P.ZodObject:return f2(e,n);case P.ZodBigInt:return WF(e);case P.ZodBoolean:return HF();case P.ZodDate:return wf(e,n);case P.ZodUndefined:return b2();case P.ZodNull:return u2();case P.ZodArray:return GF(e,n);case P.ZodUnion:case P.ZodDiscriminatedUnion:return l2(e,n);case P.ZodIntersection:return t2(e,n);case P.ZodTuple:return _2(e,n);case P.ZodRecord:return xf(e,n);case P.ZodLiteral:return n2(e);case P.ZodEnum:return QF(e);case P.ZodNativeEnum:return s2(e);case P.ZodNullable:return d2(e,n);case P.ZodOptional:return D2(e,n);case P.ZodMap:return a2(e,n);case P.ZodSet:return y2(e,n);case P.ZodLazy:return()=>e.getter()._def;case P.ZodPromise:return v2(e,n);case P.ZodNaN:case P.ZodNever:return i2();case P.ZodEffects:return XF(e,n);case P.ZodAny:return ht();case P.ZodUnknown:return C2();case P.ZodDefault:return YF(e,n);case P.ZodBranded:return Cf(e,n);case P.ZodReadonly:return w2(e,n);case P.ZodCatch:return JF(e,n);case P.ZodPipeline:return g2(e,n);case P.ZodFunction:case P.ZodVoid:case P.ZodSymbol:return;default:return(r=>{})()}},"selectParser"),E2=i((e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},"getRelativePath");function _e(e,t,n=!1){var r;const o=t.seen.get(e);if(t.override){const l=(r=t.override)==null?void 0:r.call(t,e,t,o,n);if(l!==ZF)return l}if(o&&!n){const l=x2(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=F2(e,e.typeName,t),u=typeof a=="function"?_e(a(),t):a;if(u&&k2(e,t,u),t.postProcess){const l=t.postProcess(u,e,t);return s.jsonSchema=u,l}return s.jsonSchema=u,u}i(_e,"parseDef");var x2=i((e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:E2(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),ht()):t.$refStrategy==="seen"?ht():void 0}},"get$ref"),k2=i((e,t,n)=>(e.description&&(n.description=e.description),n),"addMeta"),I2=i(e=>{const t=VF(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},"getRefs"),A2=i((e,t)=>{var n;const r=I2(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[d,f])=>{var h;return{...c,[d]:(h=_e(f._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0))!=null?h:ht()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(n=_e(e._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1))!=null?n:ht(),u=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;u!==void 0&&(a.title=u);const l=s===void 0?o?{...a,[r.definitionPath]:o}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...o,[s]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},"zod3ToJsonSchema"),Pi=Symbol.for("vercel.ai.schema");function Y(e){let t;return()=>(t==null&&(t=e()),t)}i(Y,"lazySchema");function Ma(e,{validate:t}={}){return{[Pi]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}i(Ma,"jsonSchema");function $2(e){return typeof e=="object"&&e!==null&&Pi in e&&e[Pi]===!0&&"jsonSchema"in e&&"validate"in e}i($2,"isSchema");function Zn(e){return e==null?Ma({properties:{},additionalProperties:!1}):$2(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?K(e):T2(e):e()}i(Zn,"asSchema");function T2(e){return Ma(()=>Bi(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:i(async t=>{const n=await e["~standard"].validate(t);return"value"in n?{success:!0,value:n.value}:{success:!1,error:new cn({value:t,cause:n.issues})}},"validate")})}i(T2,"standardSchema");function S2(e,t){var n;const r=(n=void 0)!=null?n:!1;return Ma(()=>A2(e,{$refStrategy:r?"root":"none"}),{validate:i(async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}},"validate")})}i(S2,"zod3Schema");function B2(e,t){var n;const r=(n=void 0)!=null?n:!1;return Ma(()=>Bi(VC(e,{target:"draft-7",io:"input",reused:r?"ref":"inline"})),{validate:i(async o=>{const s=await Up(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}},"validate")})}i(B2,"zod4Schema");function O2(e){return"_zod"in e}i(O2,"isZod4Schema");function K(e,t){return O2(e)?B2(e):S2(e)}i(K,"zodSchema");async function rt({value:e,schema:t,context:n}){const r=await xt({value:e,schema:t,context:n});if(!r.success)throw cn.wrap({value:e,cause:r.error,context:n});return r.value}i(rt,"validateTypes");async function xt({value:e,schema:t,context:n}){const r=Zn(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const o=await r.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:cn.wrap({value:e,cause:o.error,context:n}),rawValue:e}}catch(o){return{success:!1,error:cn.wrap({value:e,cause:o,context:n}),rawValue:e}}}i(xt,"safeValidateTypes");async function R2({text:e,schema:t}){try{const n=Si(e);return t==null?n:rt({value:n,schema:t})}catch(n){throw sa.isInstance(n)||cn.isInstance(n)?n:new sa({text:e,cause:n})}}i(R2,"parseJSON");async function kt({text:e,schema:t}){try{const n=Si(e);return t==null?{success:!0,value:n,rawValue:n}:await xt({value:n,schema:t})}catch(n){return{success:!1,error:sa.isInstance(n)?n:new sa({text:e,cause:n}),rawValue:void 0}}}i(kt,"safeParseJSON");function ja(e){try{return Si(e),!0}catch{return!1}}i(ja,"isParsableJson");function kf({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Ii).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await kt({text:n,schema:t}))}}))}i(kf,"parseJsonEventStream");async function tt({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;const r=await xt({value:t[e],schema:n});if(!r.success)throw new Od({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}i(tt,"parseProviderOptions");var N2=i(()=>globalThis.fetch,"getOriginalFetch2"),qe=i(async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>If({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),"postJsonToApi"),Mi=i(async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>If({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),"postFormDataToApi"),If=i(async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:s,fetch:a=N2()})=>{try{const u=await a(e,{method:"POST",headers:Dn(t,`ai-sdk/provider-utils/${vf}`,Ti()),body:n.content,signal:s}),l=Ln(u);if(!u.ok){let c;try{c=await o({response:u,url:e,requestBodyValues:n.values})}catch(d){throw Un(d)||Be.isInstance(d)?d:new Be({message:"Failed to process error response",cause:d,statusCode:u.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw c.value}try{return await r({response:u,url:e,requestBodyValues:n.values})}catch(c){throw c instanceof Error&&(Un(c)||Be.isInstance(c))?c:new Be({message:"Failed to process successful response",cause:c,statusCode:u.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(u){throw gf({error:u,url:e,requestBodyValues:n.values})}},"postToApi");function x8(e){return e}i(x8,"tool");function It({id:e,inputSchema:t,outputSchema:n,supportsDeferredResults:r}){return({execute:o,needsApproval:s,toModelOutput:a,onInputStart:u,onInputDelta:l,onInputAvailable:c,...d})=>({type:"provider",id:e,args:d,inputSchema:t,outputSchema:n,execute:o,needsApproval:s,toModelOutput:a,onInputStart:u,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:r})}i(It,"createProviderToolFactoryWithOutputSchema");async function lt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}i(lt,"resolve");var Dt=i(({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:s})=>{const a=await r.text(),u=Ln(r);if(a.trim()==="")return{responseHeaders:u,value:new Be({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:a,isRetryable:n?.(r)})};try{const l=await R2({text:a,schema:e});return{responseHeaders:u,value:new Be({message:t(l),url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:a,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:u,value:new Be({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:a,isRetryable:n?.(r)})}}},"createJsonErrorResponseHandler"),Vn=i(e=>async({response:t})=>{const n=Ln(t);if(t.body==null)throw new q0({});return{responseHeaders:n,value:kf({stream:t.body,schema:e})}},"createEventSourceResponseHandler"),Ke=i(e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),s=await kt({text:o,schema:e}),a=Ln(t);if(!s.success)throw new Be({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:n,requestBodyValues:r});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}},"createJsonResponseHandler"),P2=i(()=>async({response:e,url:t,requestBodyValues:n})=>{const r=Ln(e);if(!e.body)throw new Be({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(o)}}catch(o){throw new Be({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:o})}},"createBinaryResponseHandler");function ji(e){return e?.replace(/\/$/,"")}i(ji,"withoutTrailingSlash");function M2(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}i(M2,"isAsyncIterable");async function*j2({execute:e,input:t,options:n}){const r=e(t,n);if(M2(r)){let o;for await(const s of r)o=s,yield{type:"preliminary",output:s};yield{type:"final",output:o}}else yield{type:"final",output:await r}}i(j2,"executeTool");var zi,Af;function $f(){if(Af)return zi;Af=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((d,f)=>{for(var h in f)e(d,h,{get:f[h],enumerable:!0})},"__export"),s=i((d,f,h,D)=>{if(f&&typeof f=="object"||typeof f=="function")for(let m of n(f))!r.call(d,m)&&m!==h&&e(d,m,{get:i(()=>f[m],"get"),enumerable:!(D=t(f,m))||D.enumerable});return d},"__copyProps"),a=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};o(u,{SYMBOL_FOR_REQ_CONTEXT:i(()=>l,"SYMBOL_FOR_REQ_CONTEXT"),getContext:i(()=>c,"getContext")}),zi=a(u);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return i(c,"getContext"),zi}i($f,"requireGetContext");var Li,Tf;function Sf(){if(Tf)return Li;Tf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((d,f)=>{for(var h in f)e(d,h,{get:f[h],enumerable:!0})},"__export"),s=i((d,f,h,D)=>{if(f&&typeof f=="object"||typeof f=="function")for(let m of n(f))!r.call(d,m)&&m!==h&&e(d,m,{get:i(()=>f[m],"get"),enumerable:!(D=t(f,m))||D.enumerable});return d},"__copyProps"),a=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};o(u,{VercelOidcTokenError:i(()=>l,"VercelOidcTokenError")}),Li=a(u);const c=class c extends Error{constructor(f,h){super(f),this.name="VercelOidcTokenError",this.cause=h}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}};i(c,"VercelOidcTokenError");let l=c;return Li}i(Sf,"requireTokenError");var qi,Bf;function z2(){if(Bf)return qi;Bf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((h,D)=>{for(var m in D)e(h,m,{get:D[m],enumerable:!0})},"__export"),s=i((h,D,m,v)=>{if(D&&typeof D=="object"||typeof D=="function")for(let y of n(D))!r.call(h,y)&&y!==m&&e(h,y,{get:i(()=>D[y],"get"),enumerable:!(v=t(D,y))||v.enumerable});return h},"__copyProps"),a=i(h=>s(e({},"__esModule",{value:!0}),h),"__toCommonJS"),u={};o(u,{getVercelOidcToken:i(()=>d,"getVercelOidcToken"),getVercelOidcTokenSync:i(()=>f,"getVercelOidcTokenSync")}),qi=a(u);var l=$f(),c=Sf();async function d(){let h="",D;try{h=f()}catch(m){D=m}try{const[{getTokenPayload:m,isExpired:v},{refreshToken:y}]=await Promise.all([await import("./token-util-DbfFzcBE.mjs").then(function(b){return b.t}),await import("./token-DOYMhGwX.mjs").then(function(b){return b.t})]);(!h||v(m(h)))&&(await y(),h=f())}catch(m){let v=D instanceof Error?D.message:"";throw m instanceof Error&&(v=`${v}
123
- ${m.message}`),v?new c.VercelOidcTokenError(v):m}return h}i(d,"getVercelOidcToken");function f(){const h=(0,l.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!h)throw new Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return h}return i(f,"getVercelOidcTokenSync"),qi}i(z2,"requireGetVercelOidcToken");var Ui,Of;function L2(){if(Of)return Ui;Of=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((d,f)=>{for(var h in f)e(d,h,{get:f[h],enumerable:!0})},"__export"),s=i((d,f,h,D)=>{if(f&&typeof f=="object"||typeof f=="function")for(let m of n(f))!r.call(d,m)&&m!==h&&e(d,m,{get:i(()=>f[m],"get"),enumerable:!(D=t(f,m))||D.enumerable});return d},"__copyProps"),a=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};o(u,{getContext:i(()=>c.getContext,"getContext"),getVercelOidcToken:i(()=>l.getVercelOidcToken,"getVercelOidcToken"),getVercelOidcTokenSync:i(()=>l.getVercelOidcTokenSync,"getVercelOidcTokenSync")}),Ui=a(u);var l=z2(),c=$f();return Ui}i(L2,"requireDist");var Rf=L2(),q2="vercel.ai.gateway.error",Zi=Symbol.for(q2),Nf,Pf,ot=(wn=class extends(Pf=Error,Nf=Zi,Pf){constructor({message:t,statusCode:n=500,cause:r,generationId:o}){super(o?`${t} [${o}]`:t),this[Nf]=!0,this.statusCode=n,this.cause=r,this.generationId=o}static isInstance(t){return wn.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Zi in t&&t[Zi]===!0}},i(wn,"_GatewayError"),wn),Mf="GatewayAuthenticationError",U2=`vercel.ai.gateway.error.${Mf}`,jf=Symbol.for(U2),zf,Lf,Vi=(Fn=class extends(Lf=ot,zf=jf,Lf){constructor({message:t="Authentication failed",statusCode:n=401,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[zf]=!0,this.name=Mf,this.type="authentication_error"}static isInstance(t){return ot.hasMarker(t)&&jf in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r="Authentication failed",statusCode:o=401,cause:s,generationId:a}){let u;return t?u=`AI Gateway authentication failed: Invalid API key.
122
+ ]`;continue}s+=o[c],o[c]==="\\"?a=!0:u&&o[c]==="]"?u=!1:!u&&o[c]==="["&&(u=!0)}try{new RegExp(s)}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 s}i(Ef,"stringifyRegExpWithFlags");function xf(e,t){var n,r,o,s,a,u;const l={type:"object",additionalProperties:(n=_e(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((r=e.keyType)==null?void 0:r._def.typeName)===M.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...d}=Ff(e.keyType._def,t);return{...l,propertyNames:d}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===M.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===M.ZodBranded&&e.keyType._def.type._def.typeName===M.ZodString&&((u=e.keyType._def.type._def.checks)!=null&&u.length)){const{type:c,...d}=Cf(e.keyType._def,t);return{...l,propertyNames:d}}}return l}i(xf,"parseRecordDef");function i2(e,t){if(t.mapStrategy==="record")return xf(e,t);const n=_e(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||ht(),r=_e(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||ht();return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}i(i2,"parseMapDef");function u2(e){const t=e.values,r=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}i(u2,"parseNativeEnumDef");function l2(){return{not:ht()}}i(l2,"parseNeverDef");function c2(){return{type:"null"}}i(c2,"parseNullDef");var Ni={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function d2(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Ni&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,s)=>{const a=Ni[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){const o=r.filter((s,a,u)=>u.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:n.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return p2(e,t)}i(d2,"parseUnionDef");var p2=i((e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,o)=>_e(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0},"asAnyOf");function f2(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Ni[e.innerType._def.typeName],"null"]};const n=_e(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}i(f2,"parseNullableDef");function m2(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}i(m2,"parseNumberDef");function h2(e,t){const n={type:"object",properties:{}},r=[],o=e.shape();for(const a in o){let u=o[a];if(u===void 0||u._def===void 0)continue;const l=g2(u),c=_e(u._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(n.properties[a]=c,l||r.push(a))}r.length&&(n.required=r);const s=D2(e,t);return s!==void 0&&(n.additionalProperties=s),n}i(h2,"parseObjectDef");function D2(e,t){if(e.catchall._def.typeName!=="ZodNever")return _e(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}i(D2,"decideAdditionalProperties");function g2(e){try{return e.isOptional()}catch{return!0}}i(g2,"safeIsOptional");var v2=i((e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return _e(e.innerType._def,t);const r=_e(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ht()},r]}:ht()},"parseOptionalDef"),y2=i((e,t)=>{if(t.pipeStrategy==="input")return _e(e.in._def,t);if(t.pipeStrategy==="output")return _e(e.out._def,t);const n=_e(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=_e(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}},"parsePipelineDef");function _2(e,t){return _e(e.type._def,t)}i(_2,"parsePromiseDef");function b2(e,t){const r={type:"array",uniqueItems:!0,items:_e(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}i(b2,"parseSetDef");function C2(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>_e(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:_e(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>_e(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}i(C2,"parseTupleDef");function w2(){return{not:ht()}}i(w2,"parseUndefinedDef");function F2(){return ht()}i(F2,"parseUnknownDef");var E2=i((e,t)=>_e(e.innerType._def,t),"parseReadonlyDef"),x2=i((e,t,n)=>{switch(t){case M.ZodString:return Ff(e,n);case M.ZodNumber:return m2(e);case M.ZodObject:return h2(e,n);case M.ZodBigInt:return JF(e);case M.ZodBoolean:return KF();case M.ZodDate:return wf(e,n);case M.ZodUndefined:return w2();case M.ZodNull:return c2();case M.ZodArray:return HF(e,n);case M.ZodUnion:case M.ZodDiscriminatedUnion:return d2(e,n);case M.ZodIntersection:return r2(e,n);case M.ZodTuple:return C2(e,n);case M.ZodRecord:return xf(e,n);case M.ZodLiteral:return o2(e);case M.ZodEnum:return t2(e);case M.ZodNativeEnum:return u2(e);case M.ZodNullable:return f2(e,n);case M.ZodOptional:return v2(e,n);case M.ZodMap:return i2(e,n);case M.ZodSet:return b2(e,n);case M.ZodLazy:return()=>e.getter()._def;case M.ZodPromise:return _2(e,n);case M.ZodNaN:case M.ZodNever:return l2();case M.ZodEffects:return e2(e,n);case M.ZodAny:return ht();case M.ZodUnknown:return F2();case M.ZodDefault:return QF(e,n);case M.ZodBranded:return Cf(e,n);case M.ZodReadonly:return E2(e,n);case M.ZodCatch:return YF(e,n);case M.ZodPipeline:return y2(e,n);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(r=>{})()}},"selectParser"),k2=i((e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")},"getRelativePath");function _e(e,t,n=!1){var r;const o=t.seen.get(e);if(t.override){const l=(r=t.override)==null?void 0:r.call(t,e,t,o,n);if(l!==GF)return l}if(o&&!n){const l=I2(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=x2(e,e.typeName,t),u=typeof a=="function"?_e(a(),t):a;if(u&&A2(e,t,u),t.postProcess){const l=t.postProcess(u,e,t);return s.jsonSchema=u,l}return s.jsonSchema=u,u}i(_e,"parseDef");var I2=i((e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:k2(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),ht()):t.$refStrategy==="seen"?ht():void 0}},"get$ref"),A2=i((e,t,n)=>(e.description&&(n.description=e.description),n),"addMeta"),$2=i(e=>{const t=WF(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},"getRefs"),T2=i((e,t)=>{var n;const r=$2(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[d,f])=>{var h;return{...c,[d]:(h=_e(f._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0))!=null?h:ht()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(n=_e(e._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1))!=null?n:ht(),u=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;u!==void 0&&(a.title=u);const l=s===void 0?o?{...a,[r.definitionPath]:o}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...o,[s]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},"zod3ToJsonSchema"),Pi=Symbol.for("vercel.ai.schema");function K(e){let t;return()=>(t==null&&(t=e()),t)}i(K,"lazySchema");function Ma(e,{validate:t}={}){return{[Pi]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}i(Ma,"jsonSchema");function S2(e){return typeof e=="object"&&e!==null&&Pi in e&&e[Pi]===!0&&"jsonSchema"in e&&"validate"in e}i(S2,"isSchema");function Zn(e){return e==null?Ma({properties:{},additionalProperties:!1}):S2(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?J(e):B2(e):e()}i(Zn,"asSchema");function B2(e){return Ma(()=>Bi(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:i(async t=>{const n=await e["~standard"].validate(t);return"value"in n?{success:!0,value:n.value}:{success:!1,error:new cn({value:t,cause:n.issues})}},"validate")})}i(B2,"standardSchema");function O2(e,t){var n;const r=(n=void 0)!=null?n:!1;return Ma(()=>T2(e,{$refStrategy:r?"root":"none"}),{validate:i(async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}},"validate")})}i(O2,"zod3Schema");function R2(e,t){var n;const r=(n=void 0)!=null?n:!1;return Ma(()=>Bi(WC(e,{target:"draft-7",io:"input",reused:r?"ref":"inline"})),{validate:i(async o=>{const s=await Up(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}},"validate")})}i(R2,"zod4Schema");function N2(e){return"_zod"in e}i(N2,"isZod4Schema");function J(e,t){return N2(e)?R2(e):O2(e)}i(J,"zodSchema");async function rt({value:e,schema:t,context:n}){const r=await xt({value:e,schema:t,context:n});if(!r.success)throw cn.wrap({value:e,cause:r.error,context:n});return r.value}i(rt,"validateTypes");async function xt({value:e,schema:t,context:n}){const r=Zn(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const o=await r.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:cn.wrap({value:e,cause:o.error,context:n}),rawValue:e}}catch(o){return{success:!1,error:cn.wrap({value:e,cause:o,context:n}),rawValue:e}}}i(xt,"safeValidateTypes");async function P2({text:e,schema:t}){try{const n=Si(e);return t==null?n:rt({value:n,schema:t})}catch(n){throw sa.isInstance(n)||cn.isInstance(n)?n:new sa({text:e,cause:n})}}i(P2,"parseJSON");async function kt({text:e,schema:t}){try{const n=Si(e);return t==null?{success:!0,value:n,rawValue:n}:await xt({value:n,schema:t})}catch(n){return{success:!1,error:sa.isInstance(n)?n:new sa({text:e,cause:n}),rawValue:void 0}}}i(kt,"safeParseJSON");function ja(e){try{return Si(e),!0}catch{return!1}}i(ja,"isParsableJson");function kf({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Ii).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await kt({text:n,schema:t}))}}))}i(kf,"parseJsonEventStream");async function tt({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;const r=await xt({value:t[e],schema:n});if(!r.success)throw new Od({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}i(tt,"parseProviderOptions");var M2=i(()=>globalThis.fetch,"getOriginalFetch2"),qe=i(async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>If({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),"postJsonToApi"),Mi=i(async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>If({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),"postFormDataToApi"),If=i(async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:s,fetch:a=M2()})=>{try{const u=await a(e,{method:"POST",headers:Dn(t,`ai-sdk/provider-utils/${vf}`,Ti()),body:n.content,signal:s}),l=Ln(u);if(!u.ok){let c;try{c=await o({response:u,url:e,requestBodyValues:n.values})}catch(d){throw Un(d)||Be.isInstance(d)?d:new Be({message:"Failed to process error response",cause:d,statusCode:u.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw c.value}try{return await r({response:u,url:e,requestBodyValues:n.values})}catch(c){throw c instanceof Error&&(Un(c)||Be.isInstance(c))?c:new Be({message:"Failed to process successful response",cause:c,statusCode:u.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(u){throw gf({error:u,url:e,requestBodyValues:n.values})}},"postToApi");function I8(e){return e}i(I8,"tool");function It({id:e,inputSchema:t,outputSchema:n,supportsDeferredResults:r}){return({execute:o,needsApproval:s,toModelOutput:a,onInputStart:u,onInputDelta:l,onInputAvailable:c,...d})=>({type:"provider",id:e,args:d,inputSchema:t,outputSchema:n,execute:o,needsApproval:s,toModelOutput:a,onInputStart:u,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:r})}i(It,"createProviderToolFactoryWithOutputSchema");async function lt(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}i(lt,"resolve");var Dt=i(({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:s})=>{const a=await r.text(),u=Ln(r);if(a.trim()==="")return{responseHeaders:u,value:new Be({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:a,isRetryable:n?.(r)})};try{const l=await P2({text:a,schema:e});return{responseHeaders:u,value:new Be({message:t(l),url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:a,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:u,value:new Be({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:u,responseBody:a,isRetryable:n?.(r)})}}},"createJsonErrorResponseHandler"),Vn=i(e=>async({response:t})=>{const n=Ln(t);if(t.body==null)throw new Z0({});return{responseHeaders:n,value:kf({stream:t.body,schema:e})}},"createEventSourceResponseHandler"),Ke=i(e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),s=await kt({text:o,schema:e}),a=Ln(t);if(!s.success)throw new Be({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:n,requestBodyValues:r});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}},"createJsonResponseHandler"),j2=i(()=>async({response:e,url:t,requestBodyValues:n})=>{const r=Ln(e);if(!e.body)throw new Be({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(o)}}catch(o){throw new Be({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:o})}},"createBinaryResponseHandler");function ji(e){return e?.replace(/\/$/,"")}i(ji,"withoutTrailingSlash");function z2(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}i(z2,"isAsyncIterable");async function*L2({execute:e,input:t,options:n}){const r=e(t,n);if(z2(r)){let o;for await(const s of r)o=s,yield{type:"preliminary",output:s};yield{type:"final",output:o}}else yield{type:"final",output:await r}}i(L2,"executeTool");var zi,Af;function $f(){if(Af)return zi;Af=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((d,f)=>{for(var h in f)e(d,h,{get:f[h],enumerable:!0})},"__export"),s=i((d,f,h,D)=>{if(f&&typeof f=="object"||typeof f=="function")for(let m of n(f))!r.call(d,m)&&m!==h&&e(d,m,{get:i(()=>f[m],"get"),enumerable:!(D=t(f,m))||D.enumerable});return d},"__copyProps"),a=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};o(u,{SYMBOL_FOR_REQ_CONTEXT:i(()=>l,"SYMBOL_FOR_REQ_CONTEXT"),getContext:i(()=>c,"getContext")}),zi=a(u);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return i(c,"getContext"),zi}i($f,"requireGetContext");var Li,Tf;function Sf(){if(Tf)return Li;Tf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((d,f)=>{for(var h in f)e(d,h,{get:f[h],enumerable:!0})},"__export"),s=i((d,f,h,D)=>{if(f&&typeof f=="object"||typeof f=="function")for(let m of n(f))!r.call(d,m)&&m!==h&&e(d,m,{get:i(()=>f[m],"get"),enumerable:!(D=t(f,m))||D.enumerable});return d},"__copyProps"),a=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};o(u,{VercelOidcTokenError:i(()=>l,"VercelOidcTokenError")}),Li=a(u);const c=class c extends Error{constructor(f,h){super(f),this.name="VercelOidcTokenError",this.cause=h}toString(){return this.cause?`${this.name}: ${this.message}: ${this.cause}`:`${this.name}: ${this.message}`}};i(c,"VercelOidcTokenError");let l=c;return Li}i(Sf,"requireTokenError");var qi,Bf;function q2(){if(Bf)return qi;Bf=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((h,D)=>{for(var m in D)e(h,m,{get:D[m],enumerable:!0})},"__export"),s=i((h,D,m,v)=>{if(D&&typeof D=="object"||typeof D=="function")for(let y of n(D))!r.call(h,y)&&y!==m&&e(h,y,{get:i(()=>D[y],"get"),enumerable:!(v=t(D,y))||v.enumerable});return h},"__copyProps"),a=i(h=>s(e({},"__esModule",{value:!0}),h),"__toCommonJS"),u={};o(u,{getVercelOidcToken:i(()=>d,"getVercelOidcToken"),getVercelOidcTokenSync:i(()=>f,"getVercelOidcTokenSync")}),qi=a(u);var l=$f(),c=Sf();async function d(){let h="",D;try{h=f()}catch(m){D=m}try{const[{getTokenPayload:m,isExpired:v},{refreshToken:y}]=await Promise.all([await import("./token-util-Cx-QFbQa.mjs").then(function(b){return b.t}),await import("./token-D1j68gCO.mjs").then(function(b){return b.t})]);(!h||v(m(h)))&&(await y(),h=f())}catch(m){let v=D instanceof Error?D.message:"";throw m instanceof Error&&(v=`${v}
123
+ ${m.message}`),v?new c.VercelOidcTokenError(v):m}return h}i(d,"getVercelOidcToken");function f(){const h=(0,l.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!h)throw new Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return h}return i(f,"getVercelOidcTokenSync"),qi}i(q2,"requireGetVercelOidcToken");var Ui,Of;function U2(){if(Of)return Ui;Of=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=i((d,f)=>{for(var h in f)e(d,h,{get:f[h],enumerable:!0})},"__export"),s=i((d,f,h,D)=>{if(f&&typeof f=="object"||typeof f=="function")for(let m of n(f))!r.call(d,m)&&m!==h&&e(d,m,{get:i(()=>f[m],"get"),enumerable:!(D=t(f,m))||D.enumerable});return d},"__copyProps"),a=i(d=>s(e({},"__esModule",{value:!0}),d),"__toCommonJS"),u={};o(u,{getContext:i(()=>c.getContext,"getContext"),getVercelOidcToken:i(()=>l.getVercelOidcToken,"getVercelOidcToken"),getVercelOidcTokenSync:i(()=>l.getVercelOidcTokenSync,"getVercelOidcTokenSync")}),Ui=a(u);var l=q2(),c=$f();return Ui}i(U2,"requireDist");var Rf=U2(),Z2="vercel.ai.gateway.error",Zi=Symbol.for(Z2),Nf,Pf,ot=(wn=class extends(Pf=Error,Nf=Zi,Pf){constructor({message:t,statusCode:n=500,cause:r,generationId:o}){super(o?`${t} [${o}]`:t),this[Nf]=!0,this.statusCode=n,this.cause=r,this.generationId=o}static isInstance(t){return wn.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Zi in t&&t[Zi]===!0}},i(wn,"_GatewayError"),wn),Mf="GatewayAuthenticationError",V2=`vercel.ai.gateway.error.${Mf}`,jf=Symbol.for(V2),zf,Lf,Vi=(Fn=class extends(Lf=ot,zf=jf,Lf){constructor({message:t="Authentication failed",statusCode:n=401,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[zf]=!0,this.name=Mf,this.type="authentication_error"}static isInstance(t){return ot.hasMarker(t)&&jf in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r="Authentication failed",statusCode:o=401,cause:s,generationId:a}){let u;return t?u=`AI Gateway authentication failed: Invalid API key.
124
124
 
125
125
  Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
126
126
 
@@ -135,9 +135,9 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
135
135
  Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
136
136
 
137
137
  Option 2 - OIDC token:
138
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new Fn({message:u,statusCode:o,cause:s,generationId:a})}},i(Fn,"_GatewayAuthenticationError"),Fn),qf="GatewayInvalidRequestError",Z2=`vercel.ai.gateway.error.${qf}`,Uf=Symbol.for(Z2),Zf,Vf,V2=(ar=class extends(Vf=ot,Zf=Uf,Vf){constructor({message:t="Invalid request",statusCode:n=400,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[Zf]=!0,this.name=qf,this.type="invalid_request_error"}static isInstance(t){return ot.hasMarker(t)&&Uf in t}},i(ar,"GatewayInvalidRequestError"),ar),Gf="GatewayRateLimitError",G2=`vercel.ai.gateway.error.${Gf}`,Wf=Symbol.for(G2),Hf,Jf,W2=(sr=class extends(Jf=ot,Hf=Wf,Jf){constructor({message:t="Rate limit exceeded",statusCode:n=429,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[Hf]=!0,this.name=Gf,this.type="rate_limit_exceeded"}static isInstance(t){return ot.hasMarker(t)&&Wf in t}},i(sr,"GatewayRateLimitError"),sr),Kf="GatewayModelNotFoundError",H2=`vercel.ai.gateway.error.${Kf}`,Yf=Symbol.for(H2),J2=Y(()=>K(g({modelId:p()}))),Xf,Qf,K2=(ir=class extends(Qf=ot,Xf=Yf,Qf){constructor({message:t="Model not found",statusCode:n=404,modelId:r,cause:o,generationId:s}={}){super({message:t,statusCode:n,cause:o,generationId:s}),this[Xf]=!0,this.name=Kf,this.type="model_not_found",this.modelId=r}static isInstance(t){return ot.hasMarker(t)&&Yf in t}},i(ir,"GatewayModelNotFoundError"),ir),em="GatewayInternalServerError",Y2=`vercel.ai.gateway.error.${em}`,tm=Symbol.for(Y2),nm,rm,om=(ur=class extends(rm=ot,nm=tm,rm){constructor({message:t="Internal server error",statusCode:n=500,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[nm]=!0,this.name=em,this.type="internal_server_error"}static isInstance(t){return ot.hasMarker(t)&&tm in t}},i(ur,"GatewayInternalServerError"),ur),am="GatewayResponseError",X2=`vercel.ai.gateway.error.${am}`,sm=Symbol.for(X2),im,um,Q2=(lr=class extends(um=ot,im=sm,um){constructor({message:t="Invalid response from Gateway",statusCode:n=502,response:r,validationError:o,cause:s,generationId:a}={}){super({message:t,statusCode:n,cause:s,generationId:a}),this[im]=!0,this.name=am,this.type="response_error",this.response=r,this.validationError=o}static isInstance(t){return ot.hasMarker(t)&&sm in t}},i(lr,"GatewayResponseError"),lr);async function lm({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:r,authMethod:o}){var s;const a=await xt({value:e,schema:eE});if(!a.success){const f=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new Q2({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:a.error,cause:r,generationId:f})}const u=a.value,l=u.error.type,c=u.error.message,d=(s=u.generationId)!=null?s:void 0;switch(l){case"authentication_error":return Vi.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:r,generationId:d});case"invalid_request_error":return new V2({message:c,statusCode:t,cause:r,generationId:d});case"rate_limit_exceeded":return new W2({message:c,statusCode:t,cause:r,generationId:d});case"model_not_found":{const f=await xt({value:u.error.param,schema:J2});return new K2({message:c,statusCode:t,modelId:f.success?f.value.modelId:void 0,cause:r,generationId:d})}case"internal_server_error":return new om({message:c,statusCode:t,cause:r,generationId:d});default:return new om({message:c,statusCode:t,cause:r,generationId:d})}}i(lm,"createGatewayErrorFromResponse");var eE=Y(()=>K(g({error:g({message:p(),type:p().nullish(),param:ut().nullish(),code:ee([p(),E()]).nullish()}),generationId:p().nullish()}))),cm="GatewayTimeoutError",tE=`vercel.ai.gateway.error.${cm}`,dm=Symbol.for(tE),pm,fm,mm=(En=class extends(fm=ot,pm=dm,fm){constructor({message:t="Request timed out",statusCode:n=408,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[pm]=!0,this.name=cm,this.type="timeout_error"}static isInstance(t){return ot.hasMarker(t)&&dm in t}static createTimeoutError({originalMessage:t,statusCode:n=408,cause:r,generationId:o}){const s=`Gateway request timed out: ${t}
138
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new Fn({message:u,statusCode:o,cause:s,generationId:a})}},i(Fn,"_GatewayAuthenticationError"),Fn),qf="GatewayInvalidRequestError",G2=`vercel.ai.gateway.error.${qf}`,Uf=Symbol.for(G2),Zf,Vf,W2=(ar=class extends(Vf=ot,Zf=Uf,Vf){constructor({message:t="Invalid request",statusCode:n=400,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[Zf]=!0,this.name=qf,this.type="invalid_request_error"}static isInstance(t){return ot.hasMarker(t)&&Uf in t}},i(ar,"GatewayInvalidRequestError"),ar),Gf="GatewayRateLimitError",H2=`vercel.ai.gateway.error.${Gf}`,Wf=Symbol.for(H2),Hf,Jf,J2=(sr=class extends(Jf=ot,Hf=Wf,Jf){constructor({message:t="Rate limit exceeded",statusCode:n=429,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[Hf]=!0,this.name=Gf,this.type="rate_limit_exceeded"}static isInstance(t){return ot.hasMarker(t)&&Wf in t}},i(sr,"GatewayRateLimitError"),sr),Kf="GatewayModelNotFoundError",K2=`vercel.ai.gateway.error.${Kf}`,Yf=Symbol.for(K2),Y2=K(()=>J(g({modelId:p()}))),Xf,Qf,X2=(ir=class extends(Qf=ot,Xf=Yf,Qf){constructor({message:t="Model not found",statusCode:n=404,modelId:r,cause:o,generationId:s}={}){super({message:t,statusCode:n,cause:o,generationId:s}),this[Xf]=!0,this.name=Kf,this.type="model_not_found",this.modelId=r}static isInstance(t){return ot.hasMarker(t)&&Yf in t}},i(ir,"GatewayModelNotFoundError"),ir),em="GatewayInternalServerError",Q2=`vercel.ai.gateway.error.${em}`,tm=Symbol.for(Q2),nm,rm,om=(ur=class extends(rm=ot,nm=tm,rm){constructor({message:t="Internal server error",statusCode:n=500,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[nm]=!0,this.name=em,this.type="internal_server_error"}static isInstance(t){return ot.hasMarker(t)&&tm in t}},i(ur,"GatewayInternalServerError"),ur),am="GatewayResponseError",eE=`vercel.ai.gateway.error.${am}`,sm=Symbol.for(eE),im,um,tE=(lr=class extends(um=ot,im=sm,um){constructor({message:t="Invalid response from Gateway",statusCode:n=502,response:r,validationError:o,cause:s,generationId:a}={}){super({message:t,statusCode:n,cause:s,generationId:a}),this[im]=!0,this.name=am,this.type="response_error",this.response=r,this.validationError=o}static isInstance(t){return ot.hasMarker(t)&&sm in t}},i(lr,"GatewayResponseError"),lr);async function lm({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:r,authMethod:o}){var s;const a=await xt({value:e,schema:nE});if(!a.success){const f=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new tE({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:a.error,cause:r,generationId:f})}const u=a.value,l=u.error.type,c=u.error.message,d=(s=u.generationId)!=null?s:void 0;switch(l){case"authentication_error":return Vi.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:r,generationId:d});case"invalid_request_error":return new W2({message:c,statusCode:t,cause:r,generationId:d});case"rate_limit_exceeded":return new J2({message:c,statusCode:t,cause:r,generationId:d});case"model_not_found":{const f=await xt({value:u.error.param,schema:Y2});return new X2({message:c,statusCode:t,modelId:f.success?f.value.modelId:void 0,cause:r,generationId:d})}case"internal_server_error":return new om({message:c,statusCode:t,cause:r,generationId:d});default:return new om({message:c,statusCode:t,cause:r,generationId:d})}}i(lm,"createGatewayErrorFromResponse");var nE=K(()=>J(g({error:g({message:p(),type:p().nullish(),param:ut().nullish(),code:ee([p(),x()]).nullish()}),generationId:p().nullish()}))),cm="GatewayTimeoutError",rE=`vercel.ai.gateway.error.${cm}`,dm=Symbol.for(rE),pm,fm,mm=(En=class extends(fm=ot,pm=dm,fm){constructor({message:t="Request timed out",statusCode:n=408,cause:r,generationId:o}={}){super({message:t,statusCode:n,cause:r,generationId:o}),this[pm]=!0,this.name=cm,this.type="timeout_error"}static isInstance(t){return ot.hasMarker(t)&&dm in t}static createTimeoutError({originalMessage:t,statusCode:n=408,cause:r,generationId:o}){const s=`Gateway request timed out: ${t}
139
139
 
140
- This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new En({message:s,statusCode:n,cause:r,generationId:o})}},i(En,"_GatewayTimeoutError"),En);function hm(e){if(!(e instanceof Error))return!1;const t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}i(hm,"isTimeoutError");async function Lt(e,t){var n;return ot.isInstance(e)?e:hm(e)?mm.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):Be.isInstance(e)?e.cause&&hm(e.cause)?mm.createTimeoutError({originalMessage:e.message,cause:e}):await lm({response:nE(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await lm({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}i(Lt,"asGatewayError");function nE(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}i(nE,"extractApiCallResponse");var Dm="ai-gateway-auth-method";async function vn(e){const t=await xt({value:e[Dm],schema:rE});return t.success?t.value:void 0}i(vn,"parseAuthMethod");var rE=Y(()=>K(ee([F("api-key"),F("oidc")]))),gm=(cr=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await yf({url:`${this.config.baseURL}/config`,headers:await lt(this.config.headers()),successfulResponseHandler:Ke(oE),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(n=>n,"errorToMessage")}),fetch:this.config.fetch});return t}catch(t){throw await Lt(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:n}=await yf({url:`${t.origin}/v1/credits`,headers:await lt(this.config.headers()),successfulResponseHandler:Ke(aE),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(r=>r,"errorToMessage")}),fetch:this.config.fetch});return n}catch(t){throw await Lt(t)}}},i(cr,"GatewayFetchMetadata"),cr),oE=Y(()=>K(g({models:B(g({id:p(),name:p(),description:p().nullish(),pricing:g({input:p(),output:p(),input_cache_read:p().nullish(),input_cache_write:p().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:r})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...r?{cacheCreationInputTokens:r}:{}})).nullish(),specification:g({specificationVersion:F("v3"),provider:p(),modelId:p()}),modelType:se(["embedding","image","language","video"]).nullish()}))}))),aE=Y(()=>K(g({balance:p(),total_used:p()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),sE=(dr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:n,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:n,warnings:r}=await this.getArgs(t),{abortSignal:o}=t,s=await lt(this.config.headers());try{const{responseHeaders:a,value:u,rawValue:l}=await qe({url:this.getUrl(),headers:Ne(s,t.headers,this.getModelConfigHeaders(this.modelId,!1),await lt(this.config.o11yHeaders)),body:n,successfulResponseHandler:Ke(et()),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(c=>c,"errorToMessage")}),...o&&{abortSignal:o},fetch:this.config.fetch});return{...u,request:{body:n},response:{headers:a,body:l},warnings:r}}catch(a){throw await Lt(a,await vn(s))}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),{abortSignal:o}=t,s=await lt(this.config.headers());try{const{value:a,responseHeaders:u}=await qe({url:this.getUrl(),headers:Ne(s,t.headers,this.getModelConfigHeaders(this.modelId,!0),await lt(this.config.o11yHeaders)),body:n,successfulResponseHandler:Vn(et()),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(l=>l,"errorToMessage")}),...o&&{abortSignal:o},fetch:this.config.fetch});return{stream:a.pipeThrough(new TransformStream({start(l){r.length>0&&l.enqueue({type:"stream-start",warnings:r})},transform(l,c){if(l.success){const d=l.value;if(d.type==="raw"&&!t.includeRawChunks)return;d.type==="response-metadata"&&d.timestamp&&typeof d.timestamp=="string"&&(d.timestamp=new Date(d.timestamp)),c.enqueue(d)}else c.error(l.error)}})),request:{body:n},response:{headers:u}}}catch(a){throw await Lt(a,await vn(s))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const n of t.prompt)for(const r of n.content)if(this.isFilePart(r)){const o=r;if(o.data instanceof Uint8Array){const s=Uint8Array.from(o.data),a=Buffer.from(s).toString("base64");o.data=new URL(`data:${o.mediaType||"application/octet-stream"};base64,${a}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,n){return{"ai-language-model-specification-version":"3","ai-language-model-id":t,"ai-language-model-streaming":String(n)}}},i(dr,"GatewayLanguageModel"),dr),iE=(pr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:o}){var s;const a=await lt(this.config.headers());try{const{responseHeaders:u,value:l,rawValue:c}=await qe({url:this.getUrl(),headers:Ne(a,n??{},this.getModelConfigHeaders(),await lt(this.config.o11yHeaders)),body:{values:t,...o?{providerOptions:o}:{}},successfulResponseHandler:Ke(uE),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(d=>d,"errorToMessage")}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:l.embeddings,usage:(s=l.usage)!=null?s:void 0,providerMetadata:l.providerMetadata,response:{headers:u,body:c},warnings:[]}}catch(u){throw await Lt(u,await vn(a))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},i(pr,"GatewayEmbeddingModel"),pr),uE=Y(()=>K(g({embeddings:B(B(E())),usage:g({tokens:E()}).nullish(),providerMetadata:be(p(),be(p(),ut())).optional()}))),lE=(fr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n,size:r,aspectRatio:o,seed:s,files:a,mask:u,providerOptions:l,headers:c,abortSignal:d}){var f,h,D,m;const v=await lt(this.config.headers());try{const{responseHeaders:y,value:b,rawValue:w}=await qe({url:this.getUrl(),headers:Ne(v,c??{},this.getModelConfigHeaders(),await lt(this.config.o11yHeaders)),body:{prompt:t,n,...r&&{size:r},...o&&{aspectRatio:o},...s&&{seed:s},...l&&{providerOptions:l},...a&&{files:a.map(C=>vm(C))},...u&&{mask:vm(u)}},successfulResponseHandler:Ke(fE),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(C=>C,"errorToMessage")}),...d&&{abortSignal:d},fetch:this.config.fetch});return{images:b.images,warnings:(f=b.warnings)!=null?f:[],providerMetadata:b.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:y},...b.usage!=null&&{usage:{inputTokens:(h=b.usage.inputTokens)!=null?h:void 0,outputTokens:(D=b.usage.outputTokens)!=null?D:void 0,totalTokens:(m=b.usage.totalTokens)!=null?m:void 0}}}}catch(y){throw await Lt(y,await vn(v))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}},i(fr,"GatewayImageModel"),fr);function vm(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:qn(e.data)}:e}i(vm,"maybeEncodeImageFile");var cE=g({images:B(ut()).optional()}).catchall(ut()),dE=ge("type",[g({type:F("unsupported"),feature:p(),details:p().optional()}),g({type:F("compatibility"),feature:p(),details:p().optional()}),g({type:F("other"),message:p()})]),pE=g({inputTokens:E().nullish(),outputTokens:E().nullish(),totalTokens:E().nullish()}),fE=g({images:B(p()),warnings:B(dE).optional(),providerMetadata:be(p(),cE).optional(),usage:pE.optional()}),mE=(mr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n,aspectRatio:r,resolution:o,duration:s,fps:a,seed:u,image:l,providerOptions:c,headers:d,abortSignal:f}){var h;const D=await lt(this.config.headers());try{const{responseHeaders:m,value:v}=await qe({url:this.getUrl(),headers:Ne(D,d??{},this.getModelConfigHeaders(),await lt(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:t,n,...r&&{aspectRatio:r},...o&&{resolution:o},...s&&{duration:s},...a&&{fps:a},...u&&{seed:u},...c&&{providerOptions:c},...l&&{image:hE(l)}},successfulResponseHandler:i(async({response:y,url:b,requestBodyValues:w})=>{if(y.body==null)throw new Be({message:"SSE response body is empty",url:b,requestBodyValues:w,statusCode:y.status});const x=kf({stream:y.body,schema:yE}).getReader(),{done:T,value:O}=await x.read();if(x.releaseLock(),T||!O)throw new Be({message:"SSE stream ended without a data event",url:b,requestBodyValues:w,statusCode:y.status});if(!O.success)throw new Be({message:"Failed to parse video SSE event",cause:O.error,url:b,requestBodyValues:w,statusCode:y.status});const $=O.value;if($.type==="error")throw new Be({message:$.message,statusCode:$.statusCode,url:b,requestBodyValues:w,responseHeaders:Object.fromEntries([...y.headers]),responseBody:JSON.stringify($),data:{error:{message:$.message,type:$.errorType,param:$.param}}});return{value:{videos:$.videos,warnings:$.warnings,providerMetadata:$.providerMetadata},responseHeaders:Object.fromEntries([...y.headers])}},"successfulResponseHandler"),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(y=>y,"errorToMessage")}),...f&&{abortSignal:f},fetch:this.config.fetch});return{videos:v.videos,warnings:(h=v.warnings)!=null?h:[],providerMetadata:v.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:m}}}catch(m){throw await Lt(m,await vn(D))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}},i(mr,"GatewayVideoModel"),mr);function hE(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:qn(e.data)}:e}i(hE,"maybeEncodeVideoFile");var DE=g({videos:B(ut()).optional()}).catchall(ut()),gE=ee([g({type:F("url"),url:p(),mediaType:p()}),g({type:F("base64"),data:p(),mediaType:p()})]),vE=ge("type",[g({type:F("unsupported"),feature:p(),details:p().optional()}),g({type:F("compatibility"),feature:p(),details:p().optional()}),g({type:F("other"),message:p()})]),yE=ge("type",[g({type:F("result"),videos:B(gE),warnings:B(vE).optional(),providerMetadata:be(p(),DE).optional()}),g({type:F("error"),message:p(),errorType:p(),statusCode:E(),param:ut().nullable()})]),_E=Y(()=>K(wt({objective:we().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:Qt(we()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Na(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:Mt().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:wt({include_domains:Qt(we()).optional().describe("List of domains to include in search results."),exclude_domains:Qt(we()).optional().describe("List of domains to exclude from search results."),after_date:we().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:wt({max_chars_per_result:Mt().optional().describe("Maximum characters per result."),max_chars_total:Mt().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:wt({max_age_seconds:Mt().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),bE=Y(()=>K(xi([wt({searchId:we(),results:Qt(wt({url:we(),title:we(),excerpt:we(),publishDate:we().nullable().optional(),relevanceScore:Mt().optional()}))}),wt({error:Na(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:Mt().optional(),message:we()})]))),CE=It({id:"gateway.parallel_search",inputSchema:_E,outputSchema:bE}),wE=i((e={})=>CE(e),"parallelSearch"),FE=Y(()=>K(wt({query:xi([we(),Qt(we())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:Mt().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:Mt().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:Mt().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:we().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:Qt(we()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:Qt(we()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:we().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:we().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:we().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:we().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:Na(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),EE=Y(()=>K(xi([wt({results:Qt(wt({title:we(),url:we(),snippet:we(),date:we().optional(),lastUpdated:we().optional()})),id:we()}),wt({error:Na(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:Mt().optional(),message:we()})]))),xE=It({id:"gateway.perplexity_search",inputSchema:FE,outputSchema:EE}),kE=i((e={})=>xE(e),"perplexitySearch"),IE={parallelSearch:wE,perplexitySearch:kE};async function AE(){var e;return(e=Rf.getContext().headers)==null?void 0:e["x-vercel-id"]}i(AE,"getVercelRequestId");var $E="3.0.53",TE="0.0.1";function SE(e={}){var t,n;let r=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const u=(n=ji(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v3/ai",l=i(async()=>{try{const v=await OE(e);return Dn({Authorization:`Bearer ${v.token}`,"ai-gateway-protocol-version":TE,[Dm]:v.authMethod,...e.headers},`ai-sdk/gateway/${$E}`)}catch(v){throw Vi.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:v})}},"getHeaders"),c=i(()=>{const v=Co({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=Co({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),b=Co({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const w=await AE();return{...v&&{"ai-o11y-deployment-id":v},...y&&{"ai-o11y-environment":y},...b&&{"ai-o11y-region":b},...w&&{"ai-o11y-request-id":w}}}},"createO11yHeaders"),d=i(v=>new sE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),"createLanguageModel"),f=i(async()=>{var v,y,b;const w=(b=(y=(v=e._internal)==null?void 0:v.currentDate)==null?void 0:y.call(v).getTime())!=null?b:Date.now();return(!r||w-a>s)&&(a=w,r=new gm({baseURL:u,headers:l,fetch:e.fetch}).getAvailableModels().then(C=>(o=C,C)).catch(async C=>{throw await Lt(C,await vn(await l()))})),o?Promise.resolve(o):r},"getAvailableModels"),h=i(async()=>new gm({baseURL:u,headers:l,fetch:e.fetch}).getCredits().catch(async v=>{throw await Lt(v,await vn(await l()))}),"getCredits"),D=i(function(v){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return d(v)},"provider");D.specificationVersion="v3",D.getAvailableModels=f,D.getCredits=h,D.imageModel=v=>new lE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),D.languageModel=d;const m=i(v=>new iE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),"createEmbeddingModel");return D.embeddingModel=m,D.textEmbeddingModel=m,D.videoModel=v=>new mE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),D.chat=D.languageModel,D.embedding=D.embeddingModel,D.image=D.imageModel,D.video=D.videoModel,D.tools=IE,D}i(SE,"createGatewayProvider");var BE=SE();async function OE(e){const t=Co({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await Rf.getVercelOidcToken(),authMethod:"oidc"}}i(OE,"getGatewayAuthToken");var RE=typeof globalThis=="object"?globalThis:global,yn="1.9.0",ym=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function NE(e){var t=new Set([e]),n=new Set,r=e.match(ym);if(!r)return function(){return!1};var o={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(o.prerelease!=null)return i(function(l){return l===e},"isExactmatch");function s(u){return n.add(u),!1}i(s,"_reject");function a(u){return t.add(u),!0}return i(a,"_accept"),i(function(l){if(t.has(l))return!0;if(n.has(l))return!1;var c=l.match(ym);if(!c)return s(l);var d={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return d.prerelease!=null||o.major!==d.major?s(l):o.major===0?o.minor===d.minor&&o.patch<=d.patch?a(l):s(l):o.minor<=d.minor?a(l):s(l)},"isCompatible2")}i(NE,"_makeCompatibilityCheck");var PE=NE(yn),ME=yn.split(".")[0],wo=Symbol.for("opentelemetry.js.api."+ME),Fo=RE;function Gi(e,t,n,r){var o;r===void 0&&(r=!1);var s=Fo[wo]=(o=Fo[wo])!==null&&o!==void 0?o:{version:yn};if(!r&&s[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(a.stack||a.message),!1}if(s.version!==yn){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+yn);return n.error(a.stack||a.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+yn+"."),!0}i(Gi,"registerGlobal");function Eo(e){var t,n,r=(t=Fo[wo])===null||t===void 0?void 0:t.version;if(!(!r||!PE(r)))return(n=Fo[wo])===null||n===void 0?void 0:n[e]}i(Eo,"getGlobal");function Wi(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+yn+".");var n=Fo[wo];n&&delete n[e]}i(Wi,"unregisterGlobal");var jE=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read$3"),zE=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$3"),LE=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return i(e,"DiagComponentLogger2"),e.prototype.debug=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return xo("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return xo("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return xo("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return xo("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return xo("verbose",this._namespace,t)},e})();function xo(e,t,n){var r=Eo("diag");if(r)return n.unshift(t),r[e].apply(r,zE([],jE(n),!1))}i(xo,"logProxy");var gt;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(gt||(gt={}));function qE(e,t){e<gt.NONE?e=gt.NONE:e>gt.ALL&&(e=gt.ALL),t=t||{};function n(r,o){var s=t[r];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return i(n,"_filterFunc"),{error:n("error",gt.ERROR),warn:n("warn",gt.WARN),info:n("info",gt.INFO),debug:n("debug",gt.DEBUG),verbose:n("verbose",gt.VERBOSE)}}i(qE,"createLogLevelDiagLogger");var UE=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read$2"),ZE=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$2"),VE="diag",za=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var u=Eo("diag");if(u)return u[o].apply(u,ZE([],UE(s),!1))}}i(t,"_logProxy");var n=this,r=i(function(o,s){var a,u,l;if(s===void 0&&(s={logLevel:gt.INFO}),o===n){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof s=="number"&&(s={logLevel:s});var d=Eo("diag"),f=qE((u=s.logLevel)!==null&&u!==void 0?u:gt.INFO,o);if(d&&!s.suppressOverrideMessage){var h=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+h),f.warn("Current logger will overwrite one already registered from "+h)}return Gi("diag",f,n,!0)},"setLogger");n.setLogger=r,n.disable=function(){Wi(VE,n)},n.createComponentLogger=function(o){return new LE(o)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return i(e,"DiagAPI2"),e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})();function GE(e){return Symbol.for(e)}i(GE,"createContextKey");var WE=(function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(r){return n._currentContext.get(r)},n.setValue=function(r,o){var s=new e(n._currentContext);return s._currentContext.set(r,o),s},n.deleteValue=function(r){var o=new e(n._currentContext);return o._currentContext.delete(r),o}}return i(e,"BaseContext2"),e})(),HE=new WE,JE=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read$1"),KE=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$1"),YE=(function(){function e(){}return i(e,"NoopContextManager2"),e.prototype.active=function(){return HE},e.prototype.with=function(t,n,r){for(var o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return n.call.apply(n,KE([r],JE(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),XE=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read"),QE=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray"),Hi="context",e1=new YE,Ji=(function(){function e(){}return i(e,"ContextAPI2"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Gi(Hi,t,za.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,r){for(var o,s=[],a=3;a<arguments.length;a++)s[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,QE([t,n,r],XE(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return Eo(Hi)||e1},e.prototype.disable=function(){this._getContextManager().disable(),Wi(Hi,za.instance())},e})(),Ki;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Ki||(Ki={}));var _m="0000000000000000",bm="00000000000000000000000000000000",t1={traceId:bm,spanId:_m,traceFlags:Ki.NONE},ko=(function(){function e(t){t===void 0&&(t=t1),this._spanContext=t}return i(e,"NonRecordingSpan2"),e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,n){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,n){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,n){},e})(),Yi=GE("OpenTelemetry Context Key SPAN");function Xi(e){return e.getValue(Yi)||void 0}i(Xi,"getSpan");function n1(){return Xi(Ji.getInstance().active())}i(n1,"getActiveSpan");function Qi(e,t){return e.setValue(Yi,t)}i(Qi,"setSpan");function r1(e){return e.deleteValue(Yi)}i(r1,"deleteSpan");function o1(e,t){return Qi(e,new ko(t))}i(o1,"setSpanContext");function Cm(e){var t;return(t=Xi(e))===null||t===void 0?void 0:t.spanContext()}i(Cm,"getSpanContext");var a1=/^([0-9a-f]{32})$/i,s1=/^[0-9a-f]{16}$/i;function i1(e){return a1.test(e)&&e!==bm}i(i1,"isValidTraceId");function u1(e){return s1.test(e)&&e!==_m}i(u1,"isValidSpanId");function wm(e){return i1(e.traceId)&&u1(e.spanId)}i(wm,"isSpanContextValid");function l1(e){return new ko(e)}i(l1,"wrapSpanContext");var eu=Ji.getInstance(),Fm=(function(){function e(){}return i(e,"NoopTracer2"),e.prototype.startSpan=function(t,n,r){r===void 0&&(r=eu.active());var o=!!n?.root;if(o)return new ko;var s=r&&Cm(r);return c1(s)&&wm(s)?new ko(s):new ko},e.prototype.startActiveSpan=function(t,n,r,o){var s,a,u;if(!(arguments.length<2)){arguments.length===2?u=n:arguments.length===3?(s=n,u=r):(s=n,a=r,u=o);var l=a??eu.active(),c=this.startSpan(t,s,l),d=Qi(l,c);return eu.with(d,u,void 0,c)}},e})();function c1(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}i(c1,"isSpanContext");var d1=new Fm,p1=(function(){function e(t,n,r,o){this._provider=t,this.name=n,this.version=r,this.options=o}return i(e,"ProxyTracer2"),e.prototype.startSpan=function(t,n,r){return this._getTracer().startSpan(t,n,r)},e.prototype.startActiveSpan=function(t,n,r,o){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):d1},e})(),f1=(function(){function e(){}return i(e,"NoopTracerProvider2"),e.prototype.getTracer=function(t,n,r){return new Fm},e})(),m1=new f1,Em=(function(){function e(){}return i(e,"ProxyTracerProvider2"),e.prototype.getTracer=function(t,n,r){var o;return(o=this.getDelegateTracer(t,n,r))!==null&&o!==void 0?o:new p1(this,t,n,r)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:m1},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,n,r){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,n,r)},e})(),La;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(La||(La={}));var xm=Ji.getInstance(),tu="trace",h1=(function(){function e(){this._proxyTracerProvider=new Em,this.wrapSpanContext=l1,this.isSpanContextValid=wm,this.deleteSpan=r1,this.getSpan=Xi,this.getActiveSpan=n1,this.getSpanContext=Cm,this.setSpan=Qi,this.setSpanContext=o1}return i(e,"TraceAPI2"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=Gi(tu,this._proxyTracerProvider,za.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return Eo(tu)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){Wi(tu,za.instance()),this._proxyTracerProvider=new Em},e})(),D1=h1.getInstance(),g1=Object.defineProperty,v1=i((e,t)=>{for(var n in t)g1(e,n,{get:t[n],enumerable:!0})},"__export"),km="AI_InvalidArgumentError",Im=`vercel.ai.error.${km}`,y1=Symbol.for(Im),Am,qt=(hr=class extends Q{constructor({parameter:t,value:n,message:r}){super({name:km,message:`Invalid argument for parameter ${t}: ${r}`}),this[Am]=!0,this.parameter=t,this.value=n}static isInstance(t){return Q.hasMarker(t,Im)}},i(hr,"InvalidArgumentError"),hr);Am=y1;var $m="AI_InvalidToolApprovalError",Tm=`vercel.ai.error.${$m}`,_1=Symbol.for(Tm),Sm,b1=(Dr=class extends Q{constructor({approvalId:t}){super({name:$m,message:`Tool approval response references unknown approvalId: "${t}". No matching tool-approval-request found in message history.`}),this[Sm]=!0,this.approvalId=t}static isInstance(t){return Q.hasMarker(t,Tm)}},i(Dr,"InvalidToolApprovalError"),Dr);Sm=_1;var Bm="AI_InvalidToolInputError",Om=`vercel.ai.error.${Bm}`,C1=Symbol.for(Om),Rm,nu=(gr=class extends Q{constructor({toolInput:t,toolName:n,cause:r,message:o=`Invalid input for tool ${n}: ${ao(r)}`}){super({name:Bm,message:o,cause:r}),this[Rm]=!0,this.toolInput=t,this.toolName=n}static isInstance(t){return Q.hasMarker(t,Om)}},i(gr,"InvalidToolInputError"),gr);Rm=C1;var Nm="AI_ToolCallNotFoundForApprovalError",Pm=`vercel.ai.error.${Nm}`,w1=Symbol.for(Pm),Mm,jm=(vr=class extends Q{constructor({toolCallId:t,approvalId:n}){super({name:Nm,message:`Tool call "${t}" not found for approval request "${n}".`}),this[Mm]=!0,this.toolCallId=t,this.approvalId=n}static isInstance(t){return Q.hasMarker(t,Pm)}},i(vr,"ToolCallNotFoundForApprovalError"),vr);Mm=w1;var zm="AI_MissingToolResultsError",Lm=`vercel.ai.error.${zm}`,F1=Symbol.for(Lm),qm,Um=(yr=class extends Q{constructor({toolCallIds:t}){super({name:zm,message:`Tool result${t.length>1?"s are":" is"} missing for tool call${t.length>1?"s":""} ${t.join(", ")}.`}),this[qm]=!0,this.toolCallIds=t}static isInstance(t){return Q.hasMarker(t,Lm)}},i(yr,"MissingToolResultsError"),yr);qm=F1;var Zm="AI_NoObjectGeneratedError",Vm=`vercel.ai.error.${Zm}`,E1=Symbol.for(Vm),Gm,tn=(_r=class extends Q{constructor({message:t="No object generated.",cause:n,text:r,response:o,usage:s,finishReason:a}){super({name:Zm,message:t,cause:n}),this[Gm]=!0,this.text=r,this.response=o,this.usage=s,this.finishReason=a}static isInstance(t){return Q.hasMarker(t,Vm)}},i(_r,"NoObjectGeneratedError"),_r);Gm=E1;var Wm="AI_NoOutputGeneratedError",Hm=`vercel.ai.error.${Wm}`,x1=Symbol.for(Hm),Jm,k1=(br=class extends Q{constructor({message:t="No output generated.",cause:n}={}){super({name:Wm,message:t,cause:n}),this[Jm]=!0}static isInstance(t){return Q.hasMarker(t,Hm)}},i(br,"NoOutputGeneratedError"),br);Jm=x1;var Km="AI_NoSuchToolError",Ym=`vercel.ai.error.${Km}`,I1=Symbol.for(Ym),Xm,ru=(Cr=class extends Q{constructor({toolName:t,availableTools:n=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${n===void 0?"No tools are available.":`Available tools: ${n.join(", ")}.`}`}){super({name:Km,message:r}),this[Xm]=!0,this.toolName=t,this.availableTools=n}static isInstance(t){return Q.hasMarker(t,Ym)}},i(Cr,"NoSuchToolError"),Cr);Xm=I1;var Qm="AI_ToolCallRepairError",eh=`vercel.ai.error.${Qm}`,A1=Symbol.for(eh),th,$1=(wr=class extends Q{constructor({cause:t,originalError:n,message:r=`Error repairing tool call: ${ao(t)}`}){super({name:Qm,message:r,cause:t}),this[th]=!0,this.originalError=n}static isInstance(t){return Q.hasMarker(t,eh)}},i(wr,"ToolCallRepairError"),wr);th=A1;var T1=(Fr=class extends Q{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},i(Fr,"UnsupportedModelVersionError"),Fr),nh="AI_InvalidMessageRoleError",rh=`vercel.ai.error.${nh}`,S1=Symbol.for(rh),oh,B1=(Er=class extends Q{constructor({role:t,message:n=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:nh,message:n}),this[oh]=!0,this.role=t}static isInstance(t){return Q.hasMarker(t,rh)}},i(Er,"InvalidMessageRoleError"),Er);oh=S1;var ah="AI_RetryError",sh=`vercel.ai.error.${ah}`,O1=Symbol.for(sh),ih,uh=(xr=class extends Q{constructor({message:t,reason:n,errors:r}){super({name:ah,message:t}),this[ih]=!0,this.reason=n,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return Q.hasMarker(t,sh)}},i(xr,"RetryError"),xr);ih=O1;function R1({warning:e,provider:t,model:n}){const r=`AI SDK Warning (${t} / ${n}):`;switch(e.type){case"unsupported":{let o=`${r} The feature "${e.feature}" is not supported.`;return e.details&&(o+=` ${e.details}`),o}case"compatibility":{let o=`${r} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(o+=` ${e.details}`),o}case"other":return`${r} ${e.message}`;default:return`${r} ${JSON.stringify(e,null,2)}`}}i(R1,"formatWarning");var N1="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",lh=!1,ch=i(e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}lh||(lh=!0,console.info(N1));for(const n of e.warnings)console.warn(R1({warning:n,provider:e.provider,model:e.model}))}},"logWarnings");function P1({provider:e,modelId:t}){ch({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}i(P1,"logV2CompatibilityWarning");function M1(e){return e.specificationVersion==="v3"?e:(P1({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){switch(n){case"specificationVersion":return"v3";case"doGenerate":return async(...r)=>{const o=await t.doGenerate(...r);return{...o,finishReason:dh(o.finishReason),usage:ph(o.usage)}};case"doStream":return async(...r)=>{const o=await t.doStream(...r);return{...o,stream:j1(o.stream)}};default:return t[n]}}}))}i(M1,"asLanguageModelV3");function j1(e){return e.pipeThrough(new TransformStream({transform(t,n){switch(t.type){case"finish":n.enqueue({...t,finishReason:dh(t.finishReason),usage:ph(t.usage)});break;default:n.enqueue(t);break}}}))}i(j1,"convertV2StreamToV3");function dh(e){return{unified:e==="unknown"?"other":e,raw:void 0}}i(dh,"convertV2FinishReasonToV3");function ph(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}i(ph,"convertV2UsageToV3");function fh(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new T1({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return M1(e)}return z1().languageModel(e)}i(fh,"resolveLanguageModel");function z1(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:BE}i(z1,"getGlobalProvider");function mh(e){if(e!=null)return typeof e=="number"?e:e.totalMs}i(mh,"getTotalTimeoutMs");function L1(e){if(!(e==null||typeof e=="number"))return e.stepMs}i(L1,"getStepTimeoutMs");var q1=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],U1=i(e=>{const t=typeof e=="string"?hn(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)},"stripID3");function Z1(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?U1(e):e}i(Z1,"stripID3TagsIfPresent");function V1({data:e,signatures:t}){const n=Z1(e),r=typeof n=="string"?hn(n.substring(0,Math.min(n.length,24))):n;for(const o of t)if(r.length>=o.bytesPrefix.length&&o.bytesPrefix.every((s,a)=>s===null||r[a]===s))return o.mediaType}i(V1,"detectMediaType");var hh="6.0.97",G1=i(async({url:e,maxBytes:t,abortSignal:n})=>{var r;const o=e.toString();try{const s=await fetch(o,{headers:Dn({},`ai-sdk/${hh}`,Ti()),signal:n});if(!s.ok)throw new en({url:o,statusCode:s.status,statusText:s.statusText});return{data:await hf({response:s,url:o,maxBytes:t??Ai}),mediaType:(r=s.headers.get("content-type"))!=null?r:void 0}}catch(s){throw en.isInstance(s)?s:new en({url:o,cause:s})}},"download"),W1=i((e=G1)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n))),"createDefaultDownloadFunction");function H1(e){try{const[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}i(H1,"splitDataUrl");var Dh=ee([p(),ya(Uint8Array),ya(ArrayBuffer),Kw(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function gh(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:n}=H1(e.toString());if(t==null||n==null)throw new Q({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}i(gh,"convertToLanguageModelV3DataContent");function J1(e){return typeof e=="string"?e:e instanceof ArrayBuffer?qn(new Uint8Array(e)):qn(e)}i(J1,"convertDataContentToBase64String");function ou(e){return e===void 0?[]:Array.isArray(e)?e:[e]}i(ou,"asArray");async function K1({prompt:e,supportedUrls:t,download:n=W1()}){const r=await X1(e.messages,n,t),o=new Map;for(const c of e.messages)if(c.role==="assistant"&&Array.isArray(c.content))for(const d of c.content)d.type==="tool-approval-request"&&"approvalId"in d&&"toolCallId"in d&&o.set(d.approvalId,d.toolCallId);const s=new Set;for(const c of e.messages)if(c.role==="tool"){for(const d of c.content)if(d.type==="tool-approval-response"){const f=o.get(d.approvalId);f&&s.add(f)}}const a=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:ou(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>Y1({message:c,downloadedAssets:r}))],u=[];for(const c of a){if(c.role!=="tool"){u.push(c);continue}const d=u.at(-1);d?.role==="tool"?d.content.push(...c.content):u.push(c)}const l=new Set;for(const c of u)switch(c.role){case"assistant":{for(const d of c.content)d.type==="tool-call"&&!d.providerExecuted&&l.add(d.toolCallId);break}case"tool":{for(const d of c.content)d.type==="tool-result"&&l.delete(d.toolCallId);break}case"user":case"system":for(const d of s)l.delete(d);if(l.size>0)throw new Um({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new Um({toolCallIds:Array.from(l)});return u.filter(c=>c.role!=="tool"||c.content.length>0)}i(K1,"convertToLanguageModelPrompt");function Y1({message:e,downloadedAssets:t}){const n=e.role;switch(n){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(r=>Q1(r,t)).filter(r=>r.type!=="text"||r.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(r=>r.type!=="text"||r.text!==""||r.providerOptions!=null).filter(r=>r.type!=="tool-approval-request").map(r=>{const o=r.providerOptions;switch(r.type){case"file":{const{data:s,mediaType:a}=gh(r.data);return{type:"file",data:s,filename:r.filename,mediaType:a??r.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:r.text,providerOptions:o};case"text":return{type:"text",text:r.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:r.input,providerExecuted:r.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:vh(r.output),providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(r=>r.type!=="tool-approval-response"||r.providerExecuted).map(r=>{switch(r.type){case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:vh(r.output),providerOptions:r.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:r.approvalId,approved:r.approved,reason:r.reason}}}),providerOptions:e.providerOptions};default:{const r=n;throw new B1({role:r})}}}i(Y1,"convertToLanguageModelMessage");async function X1(e,t,n){const r=e.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var a;const u=(a=s.mediaType)!=null?a:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:u,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&MF({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:n})})),o=await t(r);return Object.fromEntries(o.map((s,a)=>s==null?null:[r[a].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}i(X1,"downloadAssets");function Q1(e,t){var n;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let r;const o=e.type;switch(o){case"image":r=e.image;break;case"file":r=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:s,mediaType:a}=gh(r);let u=a??e.mediaType,l=s;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,u??(u=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(u=(n=V1({data:l,signatures:q1}))!=null?n:u),{type:"file",mediaType:u??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(u==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:u,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}i(Q1,"convertPartToLanguageModelPart");function vh(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}i(vh,"mapToolResultOutput");async function qa({toolCallId:e,input:t,output:n,tool:r,errorMode:o}){return o==="text"?{type:"error-text",value:ao(n)}:o==="json"?{type:"error-json",value:yh(n)}:r?.toModelOutput?await r.toModelOutput({toolCallId:e,input:t,output:n}):typeof n=="string"?{type:"text",value:n}:{type:"json",value:yh(n)}}i(qa,"createToolModelOutput");function yh(e){return e===void 0?null:e}i(yh,"toJSONValue");function _h({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,seed:a,stopSequences:u}){if(e!=null){if(!Number.isInteger(e))throw new qt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new qt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new qt({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new qt({parameter:"topP",value:n,message:"topP must be a number"});if(r!=null&&typeof r!="number")throw new qt({parameter:"topK",value:r,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new qt({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new qt({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new qt({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,stopSequences:u,seed:a}}i(_h,"prepareCallSettings");function e3(e){return e!=null&&Object.keys(e).length>0}i(e3,"isNonEmptyObject");async function t3({tools:e,toolChoice:t,activeTools:n}){if(!e3(e))return{tools:void 0,toolChoice:void 0};const r=n!=null?Object.entries(e).filter(([s])=>n.includes(s)):Object.entries(e),o=[];for(const[s,a]of r){const u=a.type;switch(u){case void 0:case"dynamic":case"function":o.push({type:"function",name:s,description:a.description,inputSchema:await Zn(a.inputSchema).jsonSchema,...a.inputExamples!=null?{inputExamples:a.inputExamples}:{},providerOptions:a.providerOptions,...a.strict!=null?{strict:a.strict}:{}});break;case"provider":o.push({type:"provider",name:s,id:a.id,args:a.args});break;default:{const l=u;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:o,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}i(t3,"prepareToolsAndToolChoice");var Io=yi(()=>ee([Wp(),p(),E(),Re(),be(p(),Io.optional()),B(Io)])),Pe=be(p(),be(p(),Io.optional())),bh=g({type:F("text"),text:p(),providerOptions:Pe.optional()}),n3=g({type:F("image"),image:ee([Dh,ya(URL)]),mediaType:p().optional(),providerOptions:Pe.optional()}),Ch=g({type:F("file"),data:ee([Dh,ya(URL)]),filename:p().optional(),mediaType:p(),providerOptions:Pe.optional()}),r3=g({type:F("reasoning"),text:p(),providerOptions:Pe.optional()}),o3=g({type:F("tool-call"),toolCallId:p(),toolName:p(),input:ut(),providerOptions:Pe.optional(),providerExecuted:Re().optional()}),a3=ge("type",[g({type:F("text"),value:p(),providerOptions:Pe.optional()}),g({type:F("json"),value:Io,providerOptions:Pe.optional()}),g({type:F("execution-denied"),reason:p().optional(),providerOptions:Pe.optional()}),g({type:F("error-text"),value:p(),providerOptions:Pe.optional()}),g({type:F("error-json"),value:Io,providerOptions:Pe.optional()}),g({type:F("content"),value:B(ee([g({type:F("text"),text:p(),providerOptions:Pe.optional()}),g({type:F("media"),data:p(),mediaType:p()}),g({type:F("file-data"),data:p(),mediaType:p(),filename:p().optional(),providerOptions:Pe.optional()}),g({type:F("file-url"),url:p(),providerOptions:Pe.optional()}),g({type:F("file-id"),fileId:ee([p(),be(p(),p())]),providerOptions:Pe.optional()}),g({type:F("image-data"),data:p(),mediaType:p(),providerOptions:Pe.optional()}),g({type:F("image-url"),url:p(),providerOptions:Pe.optional()}),g({type:F("image-file-id"),fileId:ee([p(),be(p(),p())]),providerOptions:Pe.optional()}),g({type:F("custom"),providerOptions:Pe.optional()})]))})]),wh=g({type:F("tool-result"),toolCallId:p(),toolName:p(),output:a3,providerOptions:Pe.optional()}),s3=g({type:F("tool-approval-request"),approvalId:p(),toolCallId:p()}),i3=g({type:F("tool-approval-response"),approvalId:p(),approved:Re(),reason:p().optional()}),u3=g({role:F("system"),content:p(),providerOptions:Pe.optional()}),l3=g({role:F("user"),content:ee([p(),B(ee([bh,n3,Ch]))]),providerOptions:Pe.optional()}),c3=g({role:F("assistant"),content:ee([p(),B(ee([bh,Ch,r3,o3,wh,s3]))]),providerOptions:Pe.optional()}),d3=g({role:F("tool"),content:B(ee([wh,i3])),providerOptions:Pe.optional()}),p3=ee([u3,l3,c3,d3]);async function f3(e){if(e.prompt==null&&e.messages==null)throw new Gt({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Gt({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!ou(e.system).every(r=>typeof r=="object"&&r!==null&&"role"in r&&r.role==="system"))throw new Gt({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new Gt({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Gt({prompt:e,message:"messages must not be empty"});const n=await xt({value:t,schema:B(p3)});if(!n.success)throw new Gt({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:n.error});return{messages:t,system:e.system}}i(f3,"standardizePrompt");function m3(e){if(!Vi.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",n="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new Q({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${n}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
140
+ This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new En({message:s,statusCode:n,cause:r,generationId:o})}},i(En,"_GatewayTimeoutError"),En);function hm(e){if(!(e instanceof Error))return!1;const t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}i(hm,"isTimeoutError");async function Lt(e,t){var n;return ot.isInstance(e)?e:hm(e)?mm.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):Be.isInstance(e)?e.cause&&hm(e.cause)?mm.createTimeoutError({originalMessage:e.message,cause:e}):await lm({response:oE(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await lm({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}i(Lt,"asGatewayError");function oE(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}i(oE,"extractApiCallResponse");var Dm="ai-gateway-auth-method";async function vn(e){const t=await xt({value:e[Dm],schema:aE});return t.success?t.value:void 0}i(vn,"parseAuthMethod");var aE=K(()=>J(ee([w("api-key"),w("oidc")]))),gm=(cr=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await yf({url:`${this.config.baseURL}/config`,headers:await lt(this.config.headers()),successfulResponseHandler:Ke(sE),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(n=>n,"errorToMessage")}),fetch:this.config.fetch});return t}catch(t){throw await Lt(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:n}=await yf({url:`${t.origin}/v1/credits`,headers:await lt(this.config.headers()),successfulResponseHandler:Ke(iE),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(r=>r,"errorToMessage")}),fetch:this.config.fetch});return n}catch(t){throw await Lt(t)}}},i(cr,"GatewayFetchMetadata"),cr),sE=K(()=>J(g({models:S(g({id:p(),name:p(),description:p().nullish(),pricing:g({input:p(),output:p(),input_cache_read:p().nullish(),input_cache_write:p().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:r})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...r?{cacheCreationInputTokens:r}:{}})).nullish(),specification:g({specificationVersion:w("v3"),provider:p(),modelId:p()}),modelType:se(["embedding","image","language","video"]).nullish()}))}))),iE=K(()=>J(g({balance:p(),total_used:p()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),uE=(dr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:n,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:n,warnings:r}=await this.getArgs(t),{abortSignal:o}=t,s=await lt(this.config.headers());try{const{responseHeaders:a,value:u,rawValue:l}=await qe({url:this.getUrl(),headers:Ne(s,t.headers,this.getModelConfigHeaders(this.modelId,!1),await lt(this.config.o11yHeaders)),body:n,successfulResponseHandler:Ke(et()),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(c=>c,"errorToMessage")}),...o&&{abortSignal:o},fetch:this.config.fetch});return{...u,request:{body:n},response:{headers:a,body:l},warnings:r}}catch(a){throw await Lt(a,await vn(s))}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),{abortSignal:o}=t,s=await lt(this.config.headers());try{const{value:a,responseHeaders:u}=await qe({url:this.getUrl(),headers:Ne(s,t.headers,this.getModelConfigHeaders(this.modelId,!0),await lt(this.config.o11yHeaders)),body:n,successfulResponseHandler:Vn(et()),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(l=>l,"errorToMessage")}),...o&&{abortSignal:o},fetch:this.config.fetch});return{stream:a.pipeThrough(new TransformStream({start(l){r.length>0&&l.enqueue({type:"stream-start",warnings:r})},transform(l,c){if(l.success){const d=l.value;if(d.type==="raw"&&!t.includeRawChunks)return;d.type==="response-metadata"&&d.timestamp&&typeof d.timestamp=="string"&&(d.timestamp=new Date(d.timestamp)),c.enqueue(d)}else c.error(l.error)}})),request:{body:n},response:{headers:u}}}catch(a){throw await Lt(a,await vn(s))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const n of t.prompt)for(const r of n.content)if(this.isFilePart(r)){const o=r;if(o.data instanceof Uint8Array){const s=Uint8Array.from(o.data),a=Buffer.from(s).toString("base64");o.data=new URL(`data:${o.mediaType||"application/octet-stream"};base64,${a}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,n){return{"ai-language-model-specification-version":"3","ai-language-model-id":t,"ai-language-model-streaming":String(n)}}},i(dr,"GatewayLanguageModel"),dr),lE=(pr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:o}){var s;const a=await lt(this.config.headers());try{const{responseHeaders:u,value:l,rawValue:c}=await qe({url:this.getUrl(),headers:Ne(a,n??{},this.getModelConfigHeaders(),await lt(this.config.o11yHeaders)),body:{values:t,...o?{providerOptions:o}:{}},successfulResponseHandler:Ke(cE),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(d=>d,"errorToMessage")}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:l.embeddings,usage:(s=l.usage)!=null?s:void 0,providerMetadata:l.providerMetadata,response:{headers:u,body:c},warnings:[]}}catch(u){throw await Lt(u,await vn(a))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},i(pr,"GatewayEmbeddingModel"),pr),cE=K(()=>J(g({embeddings:S(S(x())),usage:g({tokens:x()}).nullish(),providerMetadata:be(p(),be(p(),ut())).optional()}))),dE=(fr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n,size:r,aspectRatio:o,seed:s,files:a,mask:u,providerOptions:l,headers:c,abortSignal:d}){var f,h,D,m;const v=await lt(this.config.headers());try{const{responseHeaders:y,value:b,rawValue:C}=await qe({url:this.getUrl(),headers:Ne(v,c??{},this.getModelConfigHeaders(),await lt(this.config.o11yHeaders)),body:{prompt:t,n,...r&&{size:r},...o&&{aspectRatio:o},...s&&{seed:s},...l&&{providerOptions:l},...a&&{files:a.map(F=>vm(F))},...u&&{mask:vm(u)}},successfulResponseHandler:Ke(hE),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(F=>F,"errorToMessage")}),...d&&{abortSignal:d},fetch:this.config.fetch});return{images:b.images,warnings:(f=b.warnings)!=null?f:[],providerMetadata:b.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:y},...b.usage!=null&&{usage:{inputTokens:(h=b.usage.inputTokens)!=null?h:void 0,outputTokens:(D=b.usage.outputTokens)!=null?D:void 0,totalTokens:(m=b.usage.totalTokens)!=null?m:void 0}}}}catch(y){throw await Lt(y,await vn(v))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}},i(fr,"GatewayImageModel"),fr);function vm(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:qn(e.data)}:e}i(vm,"maybeEncodeImageFile");var pE=g({images:S(ut()).optional()}).catchall(ut()),fE=ge("type",[g({type:w("unsupported"),feature:p(),details:p().optional()}),g({type:w("compatibility"),feature:p(),details:p().optional()}),g({type:w("other"),message:p()})]),mE=g({inputTokens:x().nullish(),outputTokens:x().nullish(),totalTokens:x().nullish()}),hE=g({images:S(p()),warnings:S(fE).optional(),providerMetadata:be(p(),pE).optional(),usage:mE.optional()}),DE=(mr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n,aspectRatio:r,resolution:o,duration:s,fps:a,seed:u,image:l,providerOptions:c,headers:d,abortSignal:f}){var h;const D=await lt(this.config.headers());try{const{responseHeaders:m,value:v}=await qe({url:this.getUrl(),headers:Ne(D,d??{},this.getModelConfigHeaders(),await lt(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:t,n,...r&&{aspectRatio:r},...o&&{resolution:o},...s&&{duration:s},...a&&{fps:a},...u&&{seed:u},...c&&{providerOptions:c},...l&&{image:gE(l)}},successfulResponseHandler:i(async({response:y,url:b,requestBodyValues:C})=>{if(y.body==null)throw new Be({message:"SSE response body is empty",url:b,requestBodyValues:C,statusCode:y.status});const E=kf({stream:y.body,schema:bE}).getReader(),{done:T,value:O}=await E.read();if(E.releaseLock(),T||!O)throw new Be({message:"SSE stream ended without a data event",url:b,requestBodyValues:C,statusCode:y.status});if(!O.success)throw new Be({message:"Failed to parse video SSE event",cause:O.error,url:b,requestBodyValues:C,statusCode:y.status});const $=O.value;if($.type==="error")throw new Be({message:$.message,statusCode:$.statusCode,url:b,requestBodyValues:C,responseHeaders:Object.fromEntries([...y.headers]),responseBody:JSON.stringify($),data:{error:{message:$.message,type:$.errorType,param:$.param}}});return{value:{videos:$.videos,warnings:$.warnings,providerMetadata:$.providerMetadata},responseHeaders:Object.fromEntries([...y.headers])}},"successfulResponseHandler"),failedResponseHandler:Dt({errorSchema:et(),errorToMessage:i(y=>y,"errorToMessage")}),...f&&{abortSignal:f},fetch:this.config.fetch});return{videos:v.videos,warnings:(h=v.warnings)!=null?h:[],providerMetadata:v.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:m}}}catch(m){throw await Lt(m,await vn(D))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}},i(mr,"GatewayVideoModel"),mr);function gE(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:qn(e.data)}:e}i(gE,"maybeEncodeVideoFile");var vE=g({videos:S(ut()).optional()}).catchall(ut()),yE=ee([g({type:w("url"),url:p(),mediaType:p()}),g({type:w("base64"),data:p(),mediaType:p()})]),_E=ge("type",[g({type:w("unsupported"),feature:p(),details:p().optional()}),g({type:w("compatibility"),feature:p(),details:p().optional()}),g({type:w("other"),message:p()})]),bE=ge("type",[g({type:w("result"),videos:S(yE),warnings:S(_E).optional(),providerMetadata:be(p(),vE).optional()}),g({type:w("error"),message:p(),errorType:p(),statusCode:x(),param:ut().nullable()})]),CE=K(()=>J(wt({objective:we().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:Qt(we()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Na(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:Mt().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:wt({include_domains:Qt(we()).optional().describe("List of domains to include in search results."),exclude_domains:Qt(we()).optional().describe("List of domains to exclude from search results."),after_date:we().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:wt({max_chars_per_result:Mt().optional().describe("Maximum characters per result."),max_chars_total:Mt().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:wt({max_age_seconds:Mt().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),wE=K(()=>J(xi([wt({searchId:we(),results:Qt(wt({url:we(),title:we(),excerpt:we(),publishDate:we().nullable().optional(),relevanceScore:Mt().optional()}))}),wt({error:Na(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:Mt().optional(),message:we()})]))),FE=It({id:"gateway.parallel_search",inputSchema:CE,outputSchema:wE}),EE=i((e={})=>FE(e),"parallelSearch"),xE=K(()=>J(wt({query:xi([we(),Qt(we())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:Mt().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:Mt().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:Mt().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:we().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:Qt(we()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:Qt(we()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:we().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:we().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:we().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:we().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:Na(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),kE=K(()=>J(xi([wt({results:Qt(wt({title:we(),url:we(),snippet:we(),date:we().optional(),lastUpdated:we().optional()})),id:we()}),wt({error:Na(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:Mt().optional(),message:we()})]))),IE=It({id:"gateway.perplexity_search",inputSchema:xE,outputSchema:kE}),AE=i((e={})=>IE(e),"perplexitySearch"),$E={parallelSearch:EE,perplexitySearch:AE};async function TE(){var e;return(e=Rf.getContext().headers)==null?void 0:e["x-vercel-id"]}i(TE,"getVercelRequestId");var SE="3.0.53",BE="0.0.1";function OE(e={}){var t,n;let r=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const u=(n=ji(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v3/ai",l=i(async()=>{try{const v=await NE(e);return Dn({Authorization:`Bearer ${v.token}`,"ai-gateway-protocol-version":BE,[Dm]:v.authMethod,...e.headers},`ai-sdk/gateway/${SE}`)}catch(v){throw Vi.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:v})}},"getHeaders"),c=i(()=>{const v=Co({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),y=Co({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),b=Co({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const C=await TE();return{...v&&{"ai-o11y-deployment-id":v},...y&&{"ai-o11y-environment":y},...b&&{"ai-o11y-region":b},...C&&{"ai-o11y-request-id":C}}}},"createO11yHeaders"),d=i(v=>new uE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),"createLanguageModel"),f=i(async()=>{var v,y,b;const C=(b=(y=(v=e._internal)==null?void 0:v.currentDate)==null?void 0:y.call(v).getTime())!=null?b:Date.now();return(!r||C-a>s)&&(a=C,r=new gm({baseURL:u,headers:l,fetch:e.fetch}).getAvailableModels().then(F=>(o=F,F)).catch(async F=>{throw await Lt(F,await vn(await l()))})),o?Promise.resolve(o):r},"getAvailableModels"),h=i(async()=>new gm({baseURL:u,headers:l,fetch:e.fetch}).getCredits().catch(async v=>{throw await Lt(v,await vn(await l()))}),"getCredits"),D=i(function(v){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return d(v)},"provider");D.specificationVersion="v3",D.getAvailableModels=f,D.getCredits=h,D.imageModel=v=>new dE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),D.languageModel=d;const m=i(v=>new lE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),"createEmbeddingModel");return D.embeddingModel=m,D.textEmbeddingModel=m,D.videoModel=v=>new DE(v,{provider:"gateway",baseURL:u,headers:l,fetch:e.fetch,o11yHeaders:c()}),D.chat=D.languageModel,D.embedding=D.embeddingModel,D.image=D.imageModel,D.video=D.videoModel,D.tools=$E,D}i(OE,"createGatewayProvider");var RE=OE();async function NE(e){const t=Co({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await Rf.getVercelOidcToken(),authMethod:"oidc"}}i(NE,"getGatewayAuthToken");var PE=typeof globalThis=="object"?globalThis:global,yn="1.9.0",ym=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function ME(e){var t=new Set([e]),n=new Set,r=e.match(ym);if(!r)return function(){return!1};var o={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(o.prerelease!=null)return i(function(l){return l===e},"isExactmatch");function s(u){return n.add(u),!1}i(s,"_reject");function a(u){return t.add(u),!0}return i(a,"_accept"),i(function(l){if(t.has(l))return!0;if(n.has(l))return!1;var c=l.match(ym);if(!c)return s(l);var d={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return d.prerelease!=null||o.major!==d.major?s(l):o.major===0?o.minor===d.minor&&o.patch<=d.patch?a(l):s(l):o.minor<=d.minor?a(l):s(l)},"isCompatible2")}i(ME,"_makeCompatibilityCheck");var jE=ME(yn),zE=yn.split(".")[0],wo=Symbol.for("opentelemetry.js.api."+zE),Fo=PE;function Gi(e,t,n,r){var o;r===void 0&&(r=!1);var s=Fo[wo]=(o=Fo[wo])!==null&&o!==void 0?o:{version:yn};if(!r&&s[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(a.stack||a.message),!1}if(s.version!==yn){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+yn);return n.error(a.stack||a.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+yn+"."),!0}i(Gi,"registerGlobal");function Eo(e){var t,n,r=(t=Fo[wo])===null||t===void 0?void 0:t.version;if(!(!r||!jE(r)))return(n=Fo[wo])===null||n===void 0?void 0:n[e]}i(Eo,"getGlobal");function Wi(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+yn+".");var n=Fo[wo];n&&delete n[e]}i(Wi,"unregisterGlobal");var LE=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read$3"),qE=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$3"),UE=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return i(e,"DiagComponentLogger2"),e.prototype.debug=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return xo("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return xo("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return xo("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return xo("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return xo("verbose",this._namespace,t)},e})();function xo(e,t,n){var r=Eo("diag");if(r)return n.unshift(t),r[e].apply(r,qE([],LE(n),!1))}i(xo,"logProxy");var gt;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(gt||(gt={}));function ZE(e,t){e<gt.NONE?e=gt.NONE:e>gt.ALL&&(e=gt.ALL),t=t||{};function n(r,o){var s=t[r];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return i(n,"_filterFunc"),{error:n("error",gt.ERROR),warn:n("warn",gt.WARN),info:n("info",gt.INFO),debug:n("debug",gt.DEBUG),verbose:n("verbose",gt.VERBOSE)}}i(ZE,"createLogLevelDiagLogger");var VE=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read$2"),GE=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$2"),WE="diag",za=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var u=Eo("diag");if(u)return u[o].apply(u,GE([],VE(s),!1))}}i(t,"_logProxy");var n=this,r=i(function(o,s){var a,u,l;if(s===void 0&&(s={logLevel:gt.INFO}),o===n){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof s=="number"&&(s={logLevel:s});var d=Eo("diag"),f=ZE((u=s.logLevel)!==null&&u!==void 0?u:gt.INFO,o);if(d&&!s.suppressOverrideMessage){var h=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+h),f.warn("Current logger will overwrite one already registered from "+h)}return Gi("diag",f,n,!0)},"setLogger");n.setLogger=r,n.disable=function(){Wi(WE,n)},n.createComponentLogger=function(o){return new UE(o)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return i(e,"DiagAPI2"),e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})();function HE(e){return Symbol.for(e)}i(HE,"createContextKey");var JE=(function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(r){return n._currentContext.get(r)},n.setValue=function(r,o){var s=new e(n._currentContext);return s._currentContext.set(r,o),s},n.deleteValue=function(r){var o=new e(n._currentContext);return o._currentContext.delete(r),o}}return i(e,"BaseContext2"),e})(),KE=new JE,YE=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read$1"),XE=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray$1"),QE=(function(){function e(){}return i(e,"NoopContextManager2"),e.prototype.active=function(){return KE},e.prototype.with=function(t,n,r){for(var o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return n.call.apply(n,XE([r],YE(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),e1=i(function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(u){a={error:u}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},"__read"),t1=i(function(e,t,n){if(arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},"__spreadArray"),Hi="context",n1=new QE,Ji=(function(){function e(){}return i(e,"ContextAPI2"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Gi(Hi,t,za.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,r){for(var o,s=[],a=3;a<arguments.length;a++)s[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,t1([t,n,r],e1(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return Eo(Hi)||n1},e.prototype.disable=function(){this._getContextManager().disable(),Wi(Hi,za.instance())},e})(),Ki;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Ki||(Ki={}));var _m="0000000000000000",bm="00000000000000000000000000000000",r1={traceId:bm,spanId:_m,traceFlags:Ki.NONE},ko=(function(){function e(t){t===void 0&&(t=r1),this._spanContext=t}return i(e,"NonRecordingSpan2"),e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,n){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,n){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,n){},e})(),Yi=HE("OpenTelemetry Context Key SPAN");function Xi(e){return e.getValue(Yi)||void 0}i(Xi,"getSpan");function o1(){return Xi(Ji.getInstance().active())}i(o1,"getActiveSpan");function Qi(e,t){return e.setValue(Yi,t)}i(Qi,"setSpan");function a1(e){return e.deleteValue(Yi)}i(a1,"deleteSpan");function s1(e,t){return Qi(e,new ko(t))}i(s1,"setSpanContext");function Cm(e){var t;return(t=Xi(e))===null||t===void 0?void 0:t.spanContext()}i(Cm,"getSpanContext");var i1=/^([0-9a-f]{32})$/i,u1=/^[0-9a-f]{16}$/i;function l1(e){return i1.test(e)&&e!==bm}i(l1,"isValidTraceId");function c1(e){return u1.test(e)&&e!==_m}i(c1,"isValidSpanId");function wm(e){return l1(e.traceId)&&c1(e.spanId)}i(wm,"isSpanContextValid");function d1(e){return new ko(e)}i(d1,"wrapSpanContext");var eu=Ji.getInstance(),Fm=(function(){function e(){}return i(e,"NoopTracer2"),e.prototype.startSpan=function(t,n,r){r===void 0&&(r=eu.active());var o=!!n?.root;if(o)return new ko;var s=r&&Cm(r);return p1(s)&&wm(s)?new ko(s):new ko},e.prototype.startActiveSpan=function(t,n,r,o){var s,a,u;if(!(arguments.length<2)){arguments.length===2?u=n:arguments.length===3?(s=n,u=r):(s=n,a=r,u=o);var l=a??eu.active(),c=this.startSpan(t,s,l),d=Qi(l,c);return eu.with(d,u,void 0,c)}},e})();function p1(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}i(p1,"isSpanContext");var f1=new Fm,m1=(function(){function e(t,n,r,o){this._provider=t,this.name=n,this.version=r,this.options=o}return i(e,"ProxyTracer2"),e.prototype.startSpan=function(t,n,r){return this._getTracer().startSpan(t,n,r)},e.prototype.startActiveSpan=function(t,n,r,o){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):f1},e})(),h1=(function(){function e(){}return i(e,"NoopTracerProvider2"),e.prototype.getTracer=function(t,n,r){return new Fm},e})(),D1=new h1,Em=(function(){function e(){}return i(e,"ProxyTracerProvider2"),e.prototype.getTracer=function(t,n,r){var o;return(o=this.getDelegateTracer(t,n,r))!==null&&o!==void 0?o:new m1(this,t,n,r)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:D1},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,n,r){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,n,r)},e})(),La;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(La||(La={}));var xm=Ji.getInstance(),tu="trace",g1=(function(){function e(){this._proxyTracerProvider=new Em,this.wrapSpanContext=d1,this.isSpanContextValid=wm,this.deleteSpan=a1,this.getSpan=Xi,this.getActiveSpan=o1,this.getSpanContext=Cm,this.setSpan=Qi,this.setSpanContext=s1}return i(e,"TraceAPI2"),e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=Gi(tu,this._proxyTracerProvider,za.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return Eo(tu)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){Wi(tu,za.instance()),this._proxyTracerProvider=new Em},e})(),v1=g1.getInstance(),y1=Object.defineProperty,_1=i((e,t)=>{for(var n in t)y1(e,n,{get:t[n],enumerable:!0})},"__export"),km="AI_InvalidArgumentError",Im=`vercel.ai.error.${km}`,b1=Symbol.for(Im),Am,qt=(hr=class extends Q{constructor({parameter:t,value:n,message:r}){super({name:km,message:`Invalid argument for parameter ${t}: ${r}`}),this[Am]=!0,this.parameter=t,this.value=n}static isInstance(t){return Q.hasMarker(t,Im)}},i(hr,"InvalidArgumentError"),hr);Am=b1;var $m="AI_InvalidToolApprovalError",Tm=`vercel.ai.error.${$m}`,C1=Symbol.for(Tm),Sm,w1=(Dr=class extends Q{constructor({approvalId:t}){super({name:$m,message:`Tool approval response references unknown approvalId: "${t}". No matching tool-approval-request found in message history.`}),this[Sm]=!0,this.approvalId=t}static isInstance(t){return Q.hasMarker(t,Tm)}},i(Dr,"InvalidToolApprovalError"),Dr);Sm=C1;var Bm="AI_InvalidToolInputError",Om=`vercel.ai.error.${Bm}`,F1=Symbol.for(Om),Rm,nu=(gr=class extends Q{constructor({toolInput:t,toolName:n,cause:r,message:o=`Invalid input for tool ${n}: ${ao(r)}`}){super({name:Bm,message:o,cause:r}),this[Rm]=!0,this.toolInput=t,this.toolName=n}static isInstance(t){return Q.hasMarker(t,Om)}},i(gr,"InvalidToolInputError"),gr);Rm=F1;var Nm="AI_ToolCallNotFoundForApprovalError",Pm=`vercel.ai.error.${Nm}`,E1=Symbol.for(Pm),Mm,jm=(vr=class extends Q{constructor({toolCallId:t,approvalId:n}){super({name:Nm,message:`Tool call "${t}" not found for approval request "${n}".`}),this[Mm]=!0,this.toolCallId=t,this.approvalId=n}static isInstance(t){return Q.hasMarker(t,Pm)}},i(vr,"ToolCallNotFoundForApprovalError"),vr);Mm=E1;var zm="AI_MissingToolResultsError",Lm=`vercel.ai.error.${zm}`,x1=Symbol.for(Lm),qm,Um=(yr=class extends Q{constructor({toolCallIds:t}){super({name:zm,message:`Tool result${t.length>1?"s are":" is"} missing for tool call${t.length>1?"s":""} ${t.join(", ")}.`}),this[qm]=!0,this.toolCallIds=t}static isInstance(t){return Q.hasMarker(t,Lm)}},i(yr,"MissingToolResultsError"),yr);qm=x1;var Zm="AI_NoObjectGeneratedError",Vm=`vercel.ai.error.${Zm}`,k1=Symbol.for(Vm),Gm,tn=(_r=class extends Q{constructor({message:t="No object generated.",cause:n,text:r,response:o,usage:s,finishReason:a}){super({name:Zm,message:t,cause:n}),this[Gm]=!0,this.text=r,this.response=o,this.usage=s,this.finishReason=a}static isInstance(t){return Q.hasMarker(t,Vm)}},i(_r,"NoObjectGeneratedError"),_r);Gm=k1;var Wm="AI_NoOutputGeneratedError",Hm=`vercel.ai.error.${Wm}`,I1=Symbol.for(Hm),Jm,A1=(br=class extends Q{constructor({message:t="No output generated.",cause:n}={}){super({name:Wm,message:t,cause:n}),this[Jm]=!0}static isInstance(t){return Q.hasMarker(t,Hm)}},i(br,"NoOutputGeneratedError"),br);Jm=I1;var Km="AI_NoSuchToolError",Ym=`vercel.ai.error.${Km}`,$1=Symbol.for(Ym),Xm,ru=(Cr=class extends Q{constructor({toolName:t,availableTools:n=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${n===void 0?"No tools are available.":`Available tools: ${n.join(", ")}.`}`}){super({name:Km,message:r}),this[Xm]=!0,this.toolName=t,this.availableTools=n}static isInstance(t){return Q.hasMarker(t,Ym)}},i(Cr,"NoSuchToolError"),Cr);Xm=$1;var Qm="AI_ToolCallRepairError",eh=`vercel.ai.error.${Qm}`,T1=Symbol.for(eh),th,S1=(wr=class extends Q{constructor({cause:t,originalError:n,message:r=`Error repairing tool call: ${ao(t)}`}){super({name:Qm,message:r,cause:t}),this[th]=!0,this.originalError=n}static isInstance(t){return Q.hasMarker(t,eh)}},i(wr,"ToolCallRepairError"),wr);th=T1;var B1=(Fr=class extends Q{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},i(Fr,"UnsupportedModelVersionError"),Fr),nh="AI_InvalidMessageRoleError",rh=`vercel.ai.error.${nh}`,O1=Symbol.for(rh),oh,R1=(Er=class extends Q{constructor({role:t,message:n=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:nh,message:n}),this[oh]=!0,this.role=t}static isInstance(t){return Q.hasMarker(t,rh)}},i(Er,"InvalidMessageRoleError"),Er);oh=O1;var ah="AI_RetryError",sh=`vercel.ai.error.${ah}`,N1=Symbol.for(sh),ih,uh=(xr=class extends Q{constructor({message:t,reason:n,errors:r}){super({name:ah,message:t}),this[ih]=!0,this.reason=n,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return Q.hasMarker(t,sh)}},i(xr,"RetryError"),xr);ih=N1;function P1({warning:e,provider:t,model:n}){const r=`AI SDK Warning (${t} / ${n}):`;switch(e.type){case"unsupported":{let o=`${r} The feature "${e.feature}" is not supported.`;return e.details&&(o+=` ${e.details}`),o}case"compatibility":{let o=`${r} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(o+=` ${e.details}`),o}case"other":return`${r} ${e.message}`;default:return`${r} ${JSON.stringify(e,null,2)}`}}i(P1,"formatWarning");var M1="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",lh=!1,ch=i(e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}lh||(lh=!0,console.info(M1));for(const n of e.warnings)console.warn(P1({warning:n,provider:e.provider,model:e.model}))}},"logWarnings");function j1({provider:e,modelId:t}){ch({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}i(j1,"logV2CompatibilityWarning");function z1(e){return e.specificationVersion==="v3"?e:(j1({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,n){switch(n){case"specificationVersion":return"v3";case"doGenerate":return async(...r)=>{const o=await t.doGenerate(...r);return{...o,finishReason:dh(o.finishReason),usage:ph(o.usage)}};case"doStream":return async(...r)=>{const o=await t.doStream(...r);return{...o,stream:L1(o.stream)}};default:return t[n]}}}))}i(z1,"asLanguageModelV3");function L1(e){return e.pipeThrough(new TransformStream({transform(t,n){switch(t.type){case"finish":n.enqueue({...t,finishReason:dh(t.finishReason),usage:ph(t.usage)});break;default:n.enqueue(t);break}}}))}i(L1,"convertV2StreamToV3");function dh(e){return{unified:e==="unknown"?"other":e,raw:void 0}}i(dh,"convertV2FinishReasonToV3");function ph(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}i(ph,"convertV2UsageToV3");function fh(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new B1({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return z1(e)}return q1().languageModel(e)}i(fh,"resolveLanguageModel");function q1(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:RE}i(q1,"getGlobalProvider");function mh(e){if(e!=null)return typeof e=="number"?e:e.totalMs}i(mh,"getTotalTimeoutMs");function U1(e){if(!(e==null||typeof e=="number"))return e.stepMs}i(U1,"getStepTimeoutMs");var Z1=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],V1=i(e=>{const t=typeof e=="string"?hn(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)},"stripID3");function G1(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?V1(e):e}i(G1,"stripID3TagsIfPresent");function W1({data:e,signatures:t}){const n=G1(e),r=typeof n=="string"?hn(n.substring(0,Math.min(n.length,24))):n;for(const o of t)if(r.length>=o.bytesPrefix.length&&o.bytesPrefix.every((s,a)=>s===null||r[a]===s))return o.mediaType}i(W1,"detectMediaType");var hh="6.0.97",H1=i(async({url:e,maxBytes:t,abortSignal:n})=>{var r;const o=e.toString();try{const s=await fetch(o,{headers:Dn({},`ai-sdk/${hh}`,Ti()),signal:n});if(!s.ok)throw new en({url:o,statusCode:s.status,statusText:s.statusText});return{data:await hf({response:s,url:o,maxBytes:t??Ai}),mediaType:(r=s.headers.get("content-type"))!=null?r:void 0}}catch(s){throw en.isInstance(s)?s:new en({url:o,cause:s})}},"download"),J1=i((e=H1)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n))),"createDefaultDownloadFunction");function K1(e){try{const[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}i(K1,"splitDataUrl");var Dh=ee([p(),ya(Uint8Array),ya(ArrayBuffer),Xw(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function gh(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:n}=K1(e.toString());if(t==null||n==null)throw new Q({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}i(gh,"convertToLanguageModelV3DataContent");function Y1(e){return typeof e=="string"?e:e instanceof ArrayBuffer?qn(new Uint8Array(e)):qn(e)}i(Y1,"convertDataContentToBase64String");function ou(e){return e===void 0?[]:Array.isArray(e)?e:[e]}i(ou,"asArray");async function X1({prompt:e,supportedUrls:t,download:n=J1()}){const r=await e3(e.messages,n,t),o=new Map;for(const c of e.messages)if(c.role==="assistant"&&Array.isArray(c.content))for(const d of c.content)d.type==="tool-approval-request"&&"approvalId"in d&&"toolCallId"in d&&o.set(d.approvalId,d.toolCallId);const s=new Set;for(const c of e.messages)if(c.role==="tool"){for(const d of c.content)if(d.type==="tool-approval-response"){const f=o.get(d.approvalId);f&&s.add(f)}}const a=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:ou(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>Q1({message:c,downloadedAssets:r}))],u=[];for(const c of a){if(c.role!=="tool"){u.push(c);continue}const d=u.at(-1);d?.role==="tool"?d.content.push(...c.content):u.push(c)}const l=new Set;for(const c of u)switch(c.role){case"assistant":{for(const d of c.content)d.type==="tool-call"&&!d.providerExecuted&&l.add(d.toolCallId);break}case"tool":{for(const d of c.content)d.type==="tool-result"&&l.delete(d.toolCallId);break}case"user":case"system":for(const d of s)l.delete(d);if(l.size>0)throw new Um({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new Um({toolCallIds:Array.from(l)});return u.filter(c=>c.role!=="tool"||c.content.length>0)}i(X1,"convertToLanguageModelPrompt");function Q1({message:e,downloadedAssets:t}){const n=e.role;switch(n){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(r=>t3(r,t)).filter(r=>r.type!=="text"||r.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(r=>r.type!=="text"||r.text!==""||r.providerOptions!=null).filter(r=>r.type!=="tool-approval-request").map(r=>{const o=r.providerOptions;switch(r.type){case"file":{const{data:s,mediaType:a}=gh(r.data);return{type:"file",data:s,filename:r.filename,mediaType:a??r.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:r.text,providerOptions:o};case"text":return{type:"text",text:r.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:r.input,providerExecuted:r.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:vh(r.output),providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(r=>r.type!=="tool-approval-response"||r.providerExecuted).map(r=>{switch(r.type){case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:vh(r.output),providerOptions:r.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:r.approvalId,approved:r.approved,reason:r.reason}}}),providerOptions:e.providerOptions};default:{const r=n;throw new R1({role:r})}}}i(Q1,"convertToLanguageModelMessage");async function e3(e,t,n){const r=e.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var a;const u=(a=s.mediaType)!=null?a:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:u,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&zF({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:n})})),o=await t(r);return Object.fromEntries(o.map((s,a)=>s==null?null:[r[a].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}i(e3,"downloadAssets");function t3(e,t){var n;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let r;const o=e.type;switch(o){case"image":r=e.image;break;case"file":r=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:s,mediaType:a}=gh(r);let u=a??e.mediaType,l=s;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,u??(u=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(u=(n=W1({data:l,signatures:Z1}))!=null?n:u),{type:"file",mediaType:u??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(u==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:u,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}i(t3,"convertPartToLanguageModelPart");function vh(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}i(vh,"mapToolResultOutput");async function qa({toolCallId:e,input:t,output:n,tool:r,errorMode:o}){return o==="text"?{type:"error-text",value:ao(n)}:o==="json"?{type:"error-json",value:yh(n)}:r?.toModelOutput?await r.toModelOutput({toolCallId:e,input:t,output:n}):typeof n=="string"?{type:"text",value:n}:{type:"json",value:yh(n)}}i(qa,"createToolModelOutput");function yh(e){return e===void 0?null:e}i(yh,"toJSONValue");function _h({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,seed:a,stopSequences:u}){if(e!=null){if(!Number.isInteger(e))throw new qt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new qt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new qt({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new qt({parameter:"topP",value:n,message:"topP must be a number"});if(r!=null&&typeof r!="number")throw new qt({parameter:"topK",value:r,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new qt({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new qt({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new qt({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,stopSequences:u,seed:a}}i(_h,"prepareCallSettings");function n3(e){return e!=null&&Object.keys(e).length>0}i(n3,"isNonEmptyObject");async function r3({tools:e,toolChoice:t,activeTools:n}){if(!n3(e))return{tools:void 0,toolChoice:void 0};const r=n!=null?Object.entries(e).filter(([s])=>n.includes(s)):Object.entries(e),o=[];for(const[s,a]of r){const u=a.type;switch(u){case void 0:case"dynamic":case"function":o.push({type:"function",name:s,description:a.description,inputSchema:await Zn(a.inputSchema).jsonSchema,...a.inputExamples!=null?{inputExamples:a.inputExamples}:{},providerOptions:a.providerOptions,...a.strict!=null?{strict:a.strict}:{}});break;case"provider":o.push({type:"provider",name:s,id:a.id,args:a.args});break;default:{const l=u;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:o,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}i(r3,"prepareToolsAndToolChoice");var Io=yi(()=>ee([Wp(),p(),x(),Re(),be(p(),Io.optional()),S(Io)])),Pe=be(p(),be(p(),Io.optional())),bh=g({type:w("text"),text:p(),providerOptions:Pe.optional()}),o3=g({type:w("image"),image:ee([Dh,ya(URL)]),mediaType:p().optional(),providerOptions:Pe.optional()}),Ch=g({type:w("file"),data:ee([Dh,ya(URL)]),filename:p().optional(),mediaType:p(),providerOptions:Pe.optional()}),a3=g({type:w("reasoning"),text:p(),providerOptions:Pe.optional()}),s3=g({type:w("tool-call"),toolCallId:p(),toolName:p(),input:ut(),providerOptions:Pe.optional(),providerExecuted:Re().optional()}),i3=ge("type",[g({type:w("text"),value:p(),providerOptions:Pe.optional()}),g({type:w("json"),value:Io,providerOptions:Pe.optional()}),g({type:w("execution-denied"),reason:p().optional(),providerOptions:Pe.optional()}),g({type:w("error-text"),value:p(),providerOptions:Pe.optional()}),g({type:w("error-json"),value:Io,providerOptions:Pe.optional()}),g({type:w("content"),value:S(ee([g({type:w("text"),text:p(),providerOptions:Pe.optional()}),g({type:w("media"),data:p(),mediaType:p()}),g({type:w("file-data"),data:p(),mediaType:p(),filename:p().optional(),providerOptions:Pe.optional()}),g({type:w("file-url"),url:p(),providerOptions:Pe.optional()}),g({type:w("file-id"),fileId:ee([p(),be(p(),p())]),providerOptions:Pe.optional()}),g({type:w("image-data"),data:p(),mediaType:p(),providerOptions:Pe.optional()}),g({type:w("image-url"),url:p(),providerOptions:Pe.optional()}),g({type:w("image-file-id"),fileId:ee([p(),be(p(),p())]),providerOptions:Pe.optional()}),g({type:w("custom"),providerOptions:Pe.optional()})]))})]),wh=g({type:w("tool-result"),toolCallId:p(),toolName:p(),output:i3,providerOptions:Pe.optional()}),u3=g({type:w("tool-approval-request"),approvalId:p(),toolCallId:p()}),l3=g({type:w("tool-approval-response"),approvalId:p(),approved:Re(),reason:p().optional()}),c3=g({role:w("system"),content:p(),providerOptions:Pe.optional()}),d3=g({role:w("user"),content:ee([p(),S(ee([bh,o3,Ch]))]),providerOptions:Pe.optional()}),p3=g({role:w("assistant"),content:ee([p(),S(ee([bh,Ch,a3,s3,wh,u3]))]),providerOptions:Pe.optional()}),f3=g({role:w("tool"),content:S(ee([wh,l3])),providerOptions:Pe.optional()}),m3=ee([c3,d3,p3,f3]);async function h3(e){if(e.prompt==null&&e.messages==null)throw new Gt({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Gt({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!ou(e.system).every(r=>typeof r=="object"&&r!==null&&"role"in r&&r.role==="system"))throw new Gt({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new Gt({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Gt({prompt:e,message:"messages must not be empty"});const n=await xt({value:t,schema:S(m3)});if(!n.success)throw new Gt({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:n.error});return{messages:t,system:e.system}}i(h3,"standardizePrompt");function D3(e){if(!Vi.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",n="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new Q({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${n}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
141
141
 
142
142
  To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
143
143
 
@@ -145,12 +145,12 @@ Alternatively, you can use a provider module instead of the AI Gateway.
145
145
 
146
146
  Learn more: \x1B[34m${n}\x1B[0m
147
147
 
148
- `),{name:"GatewayAuthenticationError"})}i(m3,"wrapGatewayError");function au({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}i(au,"assembleOperationName");function h3({model:e,settings:t,telemetry:n,headers:r}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[a,u])=>{if(a==="timeout"){const l=mh(u);l!=null&&(s[`ai.settings.${a}`]=l)}else s[`ai.settings.${a}`]=u;return s},{}),...Object.entries((o=n?.metadata)!=null?o:{}).reduce((s,[a,u])=>(s[`ai.telemetry.metadata.${a}`]=u,s),{}),...Object.entries(r??{}).reduce((s,[a,u])=>(u!==void 0&&(s[`ai.request.headers.${a}`]=u),s),{})}}i(h3,"getBaseTelemetryAttributes");var D3={startSpan(){return Ua},startActiveSpan(e,t,n,r){if(typeof t=="function")return t(Ua);if(typeof n=="function")return n(Ua);if(typeof r=="function")return r(Ua)}},Ua={spanContext(){return g3},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},g3={traceId:"",spanId:"",traceFlags:0};function v3({isEnabled:e=!1,tracer:t}={}){return e?t||D1.getTracer("ai"):D3}i(v3,"getTracer");async function su({name:e,tracer:t,attributes:n,fn:r,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await n},async s=>{const a=xm.active();try{const u=await xm.with(a,()=>r(s));return o&&s.end(),u}catch(u){try{Fh(s,u)}finally{s.end()}throw u}})}i(su,"recordSpan");function Fh(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:La.ERROR,message:t.message})):e.setStatus({code:La.ERROR})}i(Fh,"recordErrorOnSpan");async function Gn({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const n={};for(const[r,o]of Object.entries(t))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;const s=await o.input();s!=null&&(n[r]=s);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const s=await o.output();s!=null&&(n[r]=s);continue}n[r]=o}return n}i(Gn,"selectTelemetryAttributes");function y3(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(n=>n.type==="file"?{...n,data:n.data instanceof Uint8Array?J1(n.data):n.data}:n)})))}i(y3,"stringifyForTelemetry");function _3(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:At(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}i(_3,"asLanguageModelUsage");function b3(e,t){var n,r,o,s,a,u,l,c,d,f;return{inputTokens:At(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:At((n=e.inputTokenDetails)==null?void 0:n.noCacheTokens,(r=t.inputTokenDetails)==null?void 0:r.noCacheTokens),cacheReadTokens:At((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:At((a=e.inputTokenDetails)==null?void 0:a.cacheWriteTokens,(u=t.inputTokenDetails)==null?void 0:u.cacheWriteTokens)},outputTokens:At(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:At((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:At((d=e.outputTokenDetails)==null?void 0:d.reasoningTokens,(f=t.outputTokenDetails)==null?void 0:f.reasoningTokens)},totalTokens:At(e.totalTokens,t.totalTokens),reasoningTokens:At(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:At(e.cachedInputTokens,t.cachedInputTokens)}}i(b3,"addLanguageModelUsage");function At(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}i(At,"addTokenCounts");function Eh(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=t[r];if(o===void 0)continue;const s=r in e?e[r]:void 0,a=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),u=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);a&&u?n[r]=Eh(s,o):n[r]=o}return n}i(Eh,"mergeObjects");function C3({error:e,exponentialBackoffDelay:t}){const n=e.responseHeaders;if(!n)return t;let r;const o=n["retry-after-ms"];if(o){const a=parseFloat(o);Number.isNaN(a)||(r=a)}const s=n["retry-after"];if(s&&r===void 0){const a=parseFloat(s);Number.isNaN(a)?r=Date.parse(s)-Date.now():r=a*1e3}return r!=null&&!Number.isNaN(r)&&0<=r&&(r<60*1e3||r<t)?r:t}i(C3,"getRetryDelayInMs");var w3=i(({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async o=>xh(o,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r}),"retryWithExponentialBackoffRespectingRetryHeaders");async function xh(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:o},s=[]){try{return await e()}catch(a){if(Un(a)||t===0)throw a;const u=Df(a),l=[...s,a],c=l.length;if(c>t)throw new uh({message:`Failed after ${c} attempts. Last error: ${u}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&Be.isInstance(a)&&a.isRetryable===!0&&c<=t)return await IF(C3({error:a,exponentialBackoffDelay:n}),{abortSignal:o}),xh(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:o},l);throw c===1?a:new uh({message:`Failed after ${c} attempts with non-retryable error: '${u}'`,reason:"errorNotRetryable",errors:l})}}i(xh,"_retryWithExponentialBackoff");function F3({maxRetries:e,abortSignal:t}){if(!Number.isInteger(e))throw new qt({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});const n=e;return{maxRetries:n,retry:w3({maxRetries:n,abortSignal:t})}}i(F3,"prepareRetries");function E3({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const d of c)d.type==="tool-call"&&(n[d.toolCallId]=d)}const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const d of c)d.type==="tool-approval-request"&&(r[d.approvalId]=d)}const o={};for(const l of t.content)l.type==="tool-result"&&(o[l.toolCallId]=l);const s=[],a=[],u=t.content.filter(l=>l.type==="tool-approval-response");for(const l of u){const c=r[l.approvalId];if(c==null)throw new b1({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const d=n[c.toolCallId];if(d==null)throw new jm({toolCallId:c.toolCallId,approvalId:c.approvalId});const f={approvalRequest:c,approvalResponse:l,toolCall:d};l.approved?s.push(f):a.push(f)}return{approvedToolApprovals:s,deniedToolApprovals:a}}i(E3,"collectToolApprovals");function iu(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}i(iu,"now");async function x3({toolCall:e,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a,stepNumber:u,model:l,onPreliminaryToolResult:c,onToolCallStart:d,onToolCallFinish:f}){const{toolName:h,toolCallId:D,input:m}=e,v=t?.[h];if(v?.execute==null)return;const y={stepNumber:u,model:l,toolCall:e,messages:o,abortSignal:s,functionId:r?.functionId,metadata:r?.metadata,experimental_context:a};return su({name:"ai.toolCall",attributes:Gn({telemetry:r,attributes:{...au({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":h,"ai.toolCall.id":D,"ai.toolCall.args":{output:i(()=>JSON.stringify(m),"output")}}}),tracer:n,fn:i(async b=>{let w;try{await d?.(y)}catch{}const C=iu();try{const T=j2({execute:v.execute.bind(v),input:m,options:{toolCallId:D,messages:o,abortSignal:s,experimental_context:a}});for await(const O of T)O.type==="preliminary"?c?.({...e,type:"tool-result",output:O.output,preliminary:!0}):w=O.output}catch(T){const O=iu()-C;try{await f?.({...y,success:!1,error:T,durationMs:O})}catch{}return Fh(b,T),{type:"tool-error",toolCallId:D,toolName:h,input:m,error:T,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}const x=iu()-C;try{await f?.({...y,success:!0,output:w,durationMs:x})}catch{}try{b.setAttributes(await Gn({telemetry:r,attributes:{"ai.toolCall.result":{output:i(()=>JSON.stringify(w),"output")}}}))}catch{}return{type:"tool-result",toolCallId:D,toolName:h,input:m,output:w,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}},"fn")})}i(x3,"executeToolCall");function kh(e){const t=e.filter(n=>n.type==="reasoning");return t.length===0?void 0:t.map(n=>n.text).join(`
149
- `)}i(kh,"extractReasoningContent");function Ih(e){const t=e.filter(n=>n.type==="text");if(t.length!==0)return t.map(n=>n.text).join("")}i(Ih,"extractTextContent");var k3=(kr=class{constructor({data:t,mediaType:n}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=n}get base64(){return this.base64Data==null&&(this.base64Data=qn(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=hn(this.base64Data)),this.uint8ArrayData}},i(kr,"DefaultGeneratedFile"),kr);async function I3({tool:e,toolCall:t,messages:n,experimental_context:r}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:n,experimental_context:r})}i(I3,"isApprovalNeeded");var A3={};v1(A3,{array:i(()=>S3,"array"),choice:i(()=>B3,"choice"),json:i(()=>O3,"json"),object:i(()=>T3,"object"),text:i(()=>Ah,"text")});function $3(e){const t=["ROOT"];let n=-1,r=null;function o(l,c,d){switch(l){case'"':{n=c,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=c,r=c,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=c,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=c,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}i(o,"processValueStart");function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=c,t.pop();break}}}i(s,"processAfterObjectValue");function a(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}}}i(a,"processAfterArrayValue");for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{n=l,t.pop();break}default:{n=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):n=l;break}}}let u=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{u+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{u+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{u+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?u+="true".slice(d.length):"false".startsWith(d)?u+="false".slice(d.length):"null".startsWith(d)&&(u+="null".slice(d.length))}}return u}i($3,"fixJson");async function Za(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await kt({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await kt({text:$3(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}i(Za,"parsePartialJson");var Ah=i(()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),"text"),T3=i(({schema:e,name:t,description:n})=>{const r=Zn(e);return{name:"object",responseFormat:lt(r.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:o},s){const a=await kt({text:o});if(!a.success)throw new tn({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const u=await xt({value:a.value,schema:r});if(!u.success)throw new tn({message:"No object generated: response did not match schema.",cause:u.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});return u.value},async parsePartialOutput({text:o}){const s=await Za(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},"object"),S3=i(({element:e,name:t,description:n})=>{const r=Zn(e);return{name:"array",responseFormat:lt(r.jsonSchema).then(o=>{const{$schema:s,...a}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:a}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}}),async parseCompleteOutput({text:o},s){const a=await kt({text:o});if(!a.success)throw new tn({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const u=a.value;if(u==null||typeof u!="object"||!("elements"in u)||!Array.isArray(u.elements))throw new tn({message:"No object generated: response did not match schema.",cause:new cn({value:u,cause:"response must be an object with an elements array"}),text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});for(const l of u.elements){const c=await xt({value:l,schema:r});if(!c.success)throw new tn({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason})}return u.elements},async parsePartialOutput({text:o}){const s=await Za(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const a=s.value;if(a==null||typeof a!="object"||!("elements"in a)||!Array.isArray(a.elements))return;const u=s.state==="repaired-parse"&&a.elements.length>0?a.elements.slice(0,-1):a.elements,l=[];for(const c of u){const d=await xt({value:c,schema:r});d.success&&l.push(d.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:s},a){if(s!=null)for(;o<s.length;o++)a.enqueue(s[o])}})}}},"array"),B3=i(({options:e,name:t,description:n})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:r},o){const s=await kt({text:r});if(!s.success)throw new tn({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:o.response,usage:o.usage,finishReason:o.finishReason});const a=s.value;if(a==null||typeof a!="object"||!("result"in a)||typeof a.result!="string"||!e.includes(a.result))throw new tn({message:"No object generated: response did not match schema.",cause:new cn({value:a,cause:"response must be an object that contains a choice value."}),text:r,response:o.response,usage:o.usage,finishReason:o.finishReason});return a.result},async parsePartialOutput({text:r}){const o=await Za(r);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const s=o.value;if(s==null||typeof s!="object"||!("result"in s)||typeof s.result!="string")return;const a=e.filter(u=>u.startsWith(s.result));return o.state==="successful-parse"?a.includes(s.result)?{partial:s.result}:void 0:a.length===1?{partial:a[0]}:void 0}}},createElementStreamTransform(){}}),"choice"),O3=i(({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:n},r){const o=await kt({text:n});if(!o.success)throw new tn({message:"No object generated: could not parse the response.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value},async parsePartialOutput({text:n}){const r=await Za(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return r.value===void 0?void 0:{partial:r.value}}},createElementStreamTransform(){}}),"json");async function R3({toolCall:e,tools:t,repairToolCall:n,system:r,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await $h(e);throw new ru({toolName:e.toolName})}try{return await Th({toolCall:e,tools:t})}catch(a){if(n==null||!(ru.isInstance(a)||nu.isInstance(a)))throw a;let u=null;try{u=await n({toolCall:e,tools:t,inputSchema:i(async({toolName:l})=>{const{inputSchema:c}=t[l];return await Zn(c).jsonSchema},"inputSchema"),system:r,messages:o,error:a})}catch(l){throw new $1({cause:l,originalError:a})}if(u==null)throw a;return await Th({toolCall:u,tools:t})}}catch(a){const u=await kt({text:e.input}),l=u.success?u.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:a,title:(s=t?.[e.toolName])==null?void 0:s.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}i(R3,"parseToolCall");async function $h(e){const t=e.input.trim()===""?{success:!0,value:{}}:await kt({text:e.input});if(t.success===!1)throw new nu({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}i($h,"parseProviderExecutedDynamicToolCall");async function Th({toolCall:e,tools:t}){const n=e.toolName,r=t[n];if(r==null){if(e.providerExecuted&&e.dynamic)return await $h(e);throw new ru({toolName:e.toolName,availableTools:Object.keys(t)})}const o=Zn(r.inputSchema),s=e.input.trim()===""?await xt({value:{},schema:o}):await kt({text:e.input,schema:o});if(s.success===!1)throw new nu({toolName:n,toolInput:e.input,cause:s.error});return r.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:r.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:r.title}}i(Th,"doParseToolCall");var N3=(Ir=class{constructor({stepNumber:t,model:n,functionId:r,metadata:o,experimental_context:s,content:a,finishReason:u,rawFinishReason:l,usage:c,warnings:d,request:f,response:h,providerMetadata:D}){this.stepNumber=t,this.model=n,this.functionId=r,this.metadata=o,this.experimental_context=s,this.content=a,this.finishReason=u,this.rawFinishReason=l,this.usage=c,this.warnings=d,this.request=f,this.response=h,this.providerMetadata=D}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}},i(Ir,"DefaultStepResult"),Ir);function P3(e){return({steps:t})=>t.length===e}i(P3,"stepCountIs");async function M3({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}i(M3,"isStopConditionMet");async function j3({content:e,tools:t}){const n=[],r=[];for(const s of e)if(s.type!=="source"&&!((s.type==="tool-result"||s.type==="tool-error")&&!s.providerExecuted)&&!(s.type==="text"&&s.text.length===0))switch(s.type){case"text":r.push({type:"text",text:s.text,providerOptions:s.providerMetadata});break;case"reasoning":r.push({type:"reasoning",text:s.text,providerOptions:s.providerMetadata});break;case"file":r.push({type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata});break;case"tool-call":r.push({type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata});break;case"tool-result":{const a=await qa({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.output,errorMode:"none"});r.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-error":{const a=await qa({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.error,errorMode:"json"});r.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-approval-request":r.push({type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId});break}r.length>0&&n.push({role:"assistant",content:r});const o=[];for(const s of e){if(!(s.type==="tool-result"||s.type==="tool-error")||s.providerExecuted)continue;const a=await qa({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return o.length>0&&n.push({role:"tool",content:o}),n}i(j3,"toResponseMessages");function z3(...e){const t=e.filter(r=>r!=null);if(t.length===0)return;if(t.length===1)return t[0];const n=new AbortController;for(const r of t){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>{n.abort(r.reason)},{once:!0})}return n.signal}i(z3,"mergeAbortSignals");var L3=bo({prefix:"aitxt",size:24});async function Ao({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:s,maxRetries:a,abortSignal:u,timeout:l,headers:c,stopWhen:d=P3(1),experimental_output:f,output:h=f,experimental_telemetry:D,providerOptions:m,experimental_activeTools:v,activeTools:y=v,experimental_prepareStep:b,prepareStep:w=b,experimental_repairToolCall:C,experimental_download:x,experimental_context:T,experimental_include:O,_internal:{generateId:$=L3}={},experimental_onStart:I,experimental_onStepStart:re,experimental_onToolCallStart:k,experimental_onToolCallFinish:X,onStepFinish:S,onFinish:j,...z}){const Z=fh(e),N=ou(d),J=mh(l),pe=L1(l),oe=pe!=null?new AbortController:void 0,de=z3(u,J!=null?AbortSignal.timeout(J):void 0,oe?.signal),{maxRetries:fe,retry:H}=F3({maxRetries:a,abortSignal:de}),je=_h(z),xe=Dn(c??{},`ai/${hh}`),at=h3({model:Z,telemetry:D,headers:xe,settings:{...je,maxRetries:fe}}),Ae={provider:Z.provider,modelId:Z.modelId},M=await f3({system:r,prompt:o,messages:s});try{await I?.({model:Ae,system:r,prompt:o,messages:s,tools:t,toolChoice:n,activeTools:y,maxOutputTokens:je.maxOutputTokens,temperature:je.temperature,topP:je.topP,topK:je.topK,presencePenalty:je.presencePenalty,frequencyPenalty:je.frequencyPenalty,stopSequences:je.stopSequences,seed:je.seed,maxRetries:fe,timeout:l,headers:c,providerOptions:m,stopWhen:d,output:h,abortSignal:u,include:O,functionId:D?.functionId,metadata:D?.metadata,experimental_context:T})}catch{}const te=v3(D);try{return await su({name:"ai.generateText",attributes:Gn({telemetry:D,attributes:{...au({operationId:"ai.generateText",telemetry:D}),...at,"ai.model.provider":Z.provider,"ai.model.id":Z.modelId,"ai.prompt":{input:i(()=>JSON.stringify({system:r,prompt:o,messages:s}),"input")}}}),tracer:te,fn:i(async Ge=>{var ve,Lr,qr,Ur,Zr,Vr,Gr,Wr,Hr,_,q,ze,st;const xn=M.messages,Jr=[],{approvedToolApprovals:tl,deniedToolApprovals:es}=E3({messages:xn}),nl=tl.filter(We=>!We.toolCall.providerExecuted);if(es.length>0||nl.length>0){const We=await Sh({toolCalls:nl.map(le=>le.toolCall),tools:t,tracer:te,telemetry:D,messages:xn,abortSignal:de,experimental_context:T,stepNumber:0,model:Ae,onToolCallStart:k,onToolCallFinish:X}),dt=[];for(const le of We){const _t=await qa({toolCallId:le.toolCallId,input:le.input,tool:t?.[le.toolName],output:le.type==="tool-result"?le.output:le.error,errorMode:le.type==="tool-error"?"json":"none"});dt.push({type:"tool-result",toolCallId:le.toolCallId,toolName:le.toolName,output:_t})}for(const le of es)dt.push({type:"tool-result",toolCallId:le.toolCall.toolCallId,toolName:le.toolCall.toolName,output:{type:"execution-denied",reason:le.approvalResponse.reason,...le.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:le.approvalResponse.approvalId}}}}});Jr.push({role:"tool",content:dt})}const rl=[...tl,...es].filter(We=>We.toolCall.providerExecuted);rl.length>0&&Jr.push({role:"tool",content:rl.map(We=>({type:"tool-approval-response",approvalId:We.approvalResponse.approvalId,approved:We.approvalResponse.approved,reason:We.approvalResponse.reason,providerExecuted:!0}))});const FD=_h(z);let Me,No=[],Kr=[];const ct=[],ts=new Map;do{const We=pe!=null?setTimeout(()=>oe.abort(),pe):void 0;try{const dt=[...xn,...Jr],le=await w?.({model:Z,steps:ct,stepNumber:ct.length,messages:dt,experimental_context:T}),_t=fh((ve=le?.model)!=null?ve:Z),Yr={provider:_t.provider,modelId:_t.modelId},sl=await K1({prompt:{system:(Lr=le?.system)!=null?Lr:M.system,messages:(qr=le?.messages)!=null?qr:dt},supportedUrls:await _t.supportedUrls,download:x});T=(Ur=le?.experimental_context)!=null?Ur:T;const il=(Zr=le?.activeTools)!=null?Zr:y,{toolChoice:Po,tools:ns}=await t3({tools:t,toolChoice:(Vr=le?.toolChoice)!=null?Vr:n,activeTools:il}),ED=(Gr=le?.messages)!=null?Gr:dt,xD=(Wr=le?.system)!=null?Wr:M.system,ul=Eh(m,le?.providerOptions);try{await re?.({stepNumber:ct.length,model:Yr,system:xD,messages:ED,tools:t,toolChoice:Po,activeTools:il,steps:[...ct],providerOptions:ul,timeout:l,headers:c,stopWhen:d,output:h,abortSignal:u,include:O,functionId:D?.functionId,metadata:D?.metadata,experimental_context:T})}catch{}Me=await H(()=>{var ue;return su({name:"ai.generateText.doGenerate",attributes:Gn({telemetry:D,attributes:{...au({operationId:"ai.generateText.doGenerate",telemetry:D}),...at,"ai.model.provider":_t.provider,"ai.model.id":_t.modelId,"ai.prompt.messages":{input:i(()=>y3(sl),"input")},"ai.prompt.tools":{input:i(()=>ns?.map(pt=>JSON.stringify(pt)),"input")},"ai.prompt.toolChoice":{input:i(()=>Po!=null?JSON.stringify(Po):void 0,"input")},"gen_ai.system":_t.provider,"gen_ai.request.model":_t.modelId,"gen_ai.request.frequency_penalty":z.frequencyPenalty,"gen_ai.request.max_tokens":z.maxOutputTokens,"gen_ai.request.presence_penalty":z.presencePenalty,"gen_ai.request.stop_sequences":z.stopSequences,"gen_ai.request.temperature":(ue=z.temperature)!=null?ue:void 0,"gen_ai.request.top_k":z.topK,"gen_ai.request.top_p":z.topP}}),tracer:te,fn:i(async pt=>{var os,Qr,dl,pl,fl,ml,hl,Dl;const Ye=await _t.doGenerate({...FD,tools:ns,toolChoice:Po,responseFormat:await h?.responseFormat,prompt:sl,providerOptions:ul,abortSignal:de,headers:xe}),kn={id:(Qr=(os=Ye.response)==null?void 0:os.id)!=null?Qr:$(),timestamp:(pl=(dl=Ye.response)==null?void 0:dl.timestamp)!=null?pl:new Date,modelId:(ml=(fl=Ye.response)==null?void 0:fl.modelId)!=null?ml:_t.modelId,headers:(hl=Ye.response)==null?void 0:hl.headers,body:(Dl=Ye.response)==null?void 0:Dl.body};return pt.setAttributes(await Gn({telemetry:D,attributes:{"ai.response.finishReason":Ye.finishReason.unified,"ai.response.text":{output:i(()=>Ih(Ye.content),"output")},"ai.response.reasoning":{output:i(()=>kh(Ye.content),"output")},"ai.response.toolCalls":{output:i(()=>{const gl=Bh(Ye.content);return gl==null?void 0:JSON.stringify(gl)},"output")},"ai.response.id":kn.id,"ai.response.model":kn.modelId,"ai.response.timestamp":kn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Ye.providerMetadata),"ai.usage.promptTokens":Ye.usage.inputTokens.total,"ai.usage.completionTokens":Ye.usage.outputTokens.total,"gen_ai.response.finish_reasons":[Ye.finishReason.unified],"gen_ai.response.id":kn.id,"gen_ai.response.model":kn.modelId,"gen_ai.usage.input_tokens":Ye.usage.inputTokens.total,"gen_ai.usage.output_tokens":Ye.usage.outputTokens.total}})),{...Ye,response:kn}},"fn")})});const Xr=await Promise.all(Me.content.filter(ue=>ue.type==="tool-call").map(ue=>R3({toolCall:ue,tools:t,repairToolCall:C,system:r,messages:dt}))),rs={};for(const ue of Xr){if(ue.invalid)continue;const pt=t?.[ue.toolName];pt!=null&&(pt?.onInputAvailable!=null&&await pt.onInputAvailable({input:ue.input,toolCallId:ue.toolCallId,messages:dt,abortSignal:de,experimental_context:T}),await I3({tool:pt,toolCall:ue,messages:dt,experimental_context:T})&&(rs[ue.toolCallId]={type:"tool-approval-request",approvalId:$(),toolCall:ue}))}const kD=Xr.filter(ue=>ue.invalid&&ue.dynamic);Kr=[];for(const ue of kD)Kr.push({type:"tool-error",toolCallId:ue.toolCallId,toolName:ue.toolName,input:ue.input,error:Df(ue.error),dynamic:!0});No=Xr.filter(ue=>!ue.providerExecuted),t!=null&&Kr.push(...await Sh({toolCalls:No.filter(ue=>!ue.invalid&&rs[ue.toolCallId]==null),tools:t,tracer:te,telemetry:D,messages:dt,abortSignal:de,experimental_context:T,stepNumber:ct.length,model:Yr,onToolCallStart:k,onToolCallFinish:X}));for(const ue of Xr){if(!ue.providerExecuted)continue;const pt=t?.[ue.toolName];pt?.type==="provider"&&pt.supportsDeferredResults&&(Me.content.some(Qr=>Qr.type==="tool-result"&&Qr.toolCallId===ue.toolCallId)||ts.set(ue.toolCallId,{toolName:ue.toolName}))}for(const ue of Me.content)ue.type==="tool-result"&&ts.delete(ue.toolCallId);const ll=U3({content:Me.content,toolCalls:Xr,toolOutputs:Kr,toolApprovalRequests:Object.values(rs),tools:t});Jr.push(...await j3({content:ll,tools:t}));const ID=(Hr=O?.requestBody)==null||Hr?(_=Me.request)!=null?_:{}:{...Me.request,body:void 0},AD={...Me.response,messages:structuredClone(Jr),body:(q=O?.responseBody)==null||q?(ze=Me.response)==null?void 0:ze.body:void 0},$D=ct.length,cl=new N3({stepNumber:$D,model:Yr,functionId:D?.functionId,metadata:D?.metadata,experimental_context:T,content:ll,finishReason:Me.finishReason.unified,rawFinishReason:Me.finishReason.raw,usage:_3(Me.usage),warnings:Me.warnings,providerMetadata:Me.providerMetadata,request:ID,response:AD});ch({warnings:(st=Me.warnings)!=null?st:[],provider:Yr.provider,model:Yr.modelId}),ct.push(cl),await S?.(cl)}finally{We!=null&&clearTimeout(We)}}while((No.length>0&&Kr.length===No.length||ts.size>0)&&!await M3({stopConditions:N,steps:ct}));Ge.setAttributes(await Gn({telemetry:D,attributes:{"ai.response.finishReason":Me.finishReason.unified,"ai.response.text":{output:i(()=>Ih(Me.content),"output")},"ai.response.reasoning":{output:i(()=>kh(Me.content),"output")},"ai.response.toolCalls":{output:i(()=>{const We=Bh(Me.content);return We==null?void 0:JSON.stringify(We)},"output")},"ai.response.providerMetadata":JSON.stringify(Me.providerMetadata),"ai.usage.promptTokens":Me.usage.inputTokens.total,"ai.usage.completionTokens":Me.usage.outputTokens.total}}));const ye=ct[ct.length-1],ol=ct.reduce((We,dt)=>b3(We,dt.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await j?.({stepNumber:ye.stepNumber,model:ye.model,functionId:ye.functionId,metadata:ye.metadata,experimental_context:ye.experimental_context,finishReason:ye.finishReason,rawFinishReason:ye.rawFinishReason,usage:ye.usage,content:ye.content,text:ye.text,reasoningText:ye.reasoningText,reasoning:ye.reasoning,files:ye.files,sources:ye.sources,toolCalls:ye.toolCalls,staticToolCalls:ye.staticToolCalls,dynamicToolCalls:ye.dynamicToolCalls,toolResults:ye.toolResults,staticToolResults:ye.staticToolResults,dynamicToolResults:ye.dynamicToolResults,request:ye.request,response:ye.response,warnings:ye.warnings,providerMetadata:ye.providerMetadata,steps:ct,totalUsage:ol});let al;return ye.finishReason==="stop"&&(al=await(h??Ah()).parseCompleteOutput({text:ye.text},{response:ye.response,usage:ye.usage,finishReason:ye.finishReason})),new q3({steps:ct,totalUsage:ol,output:al})},"fn")})}catch(Ge){throw m3(Ge)}}i(Ao,"generateText");async function Sh({toolCalls:e,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a,stepNumber:u,model:l,onToolCallStart:c,onToolCallFinish:d}){return(await Promise.all(e.map(async h=>x3({toolCall:h,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a,stepNumber:u,model:l,onToolCallStart:c,onToolCallFinish:d})))).filter(h=>h!=null)}i(Sh,"executeTools");var q3=(Ar=class{constructor(t){this.steps=t.steps,this._output=t.output,this.totalUsage=t.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new k1;return this._output}},i(Ar,"DefaultGenerateTextResult"),Ar);function Bh(e){const t=e.filter(n=>n.type==="tool-call");if(t.length!==0)return t.map(n=>({toolCallId:n.toolCallId,toolName:n.toolName,input:n.input}))}i(Bh,"asToolCalls");function U3({content:e,toolCalls:t,toolOutputs:n,toolApprovalRequests:r,tools:o}){const s=[];for(const a of e)switch(a.type){case"text":case"reasoning":case"source":s.push(a);break;case"file":{s.push({type:"file",file:new k3(a),...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}});break}case"tool-call":{s.push(t.find(u=>u.toolCallId===a.toolCallId));break}case"tool-result":{const u=t.find(l=>l.toolCallId===a.toolCallId);if(u==null){const l=o?.[a.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${a.toolCallId} not found.`);a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,error:a.result,providerExecuted:!0,dynamic:a.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,output:a.result,providerExecuted:!0,dynamic:a.dynamic});break}a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:u.input,error:a.result,providerExecuted:!0,dynamic:u.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:u.input,output:a.result,providerExecuted:!0,dynamic:u.dynamic});break}case"tool-approval-request":{const u=t.find(l=>l.toolCallId===a.toolCallId);if(u==null)throw new jm({toolCallId:a.toolCallId,approvalId:a.approvalId});s.push({type:"tool-approval-request",approvalId:a.approvalId,toolCall:u});break}}return[...s,...n,...r]}i(U3,"asContent"),class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
148
+ `),{name:"GatewayAuthenticationError"})}i(D3,"wrapGatewayError");function au({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}i(au,"assembleOperationName");function g3({model:e,settings:t,telemetry:n,headers:r}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[a,u])=>{if(a==="timeout"){const l=mh(u);l!=null&&(s[`ai.settings.${a}`]=l)}else s[`ai.settings.${a}`]=u;return s},{}),...Object.entries((o=n?.metadata)!=null?o:{}).reduce((s,[a,u])=>(s[`ai.telemetry.metadata.${a}`]=u,s),{}),...Object.entries(r??{}).reduce((s,[a,u])=>(u!==void 0&&(s[`ai.request.headers.${a}`]=u),s),{})}}i(g3,"getBaseTelemetryAttributes");var v3={startSpan(){return Ua},startActiveSpan(e,t,n,r){if(typeof t=="function")return t(Ua);if(typeof n=="function")return n(Ua);if(typeof r=="function")return r(Ua)}},Ua={spanContext(){return y3},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},y3={traceId:"",spanId:"",traceFlags:0};function _3({isEnabled:e=!1,tracer:t}={}){return e?t||v1.getTracer("ai"):v3}i(_3,"getTracer");async function su({name:e,tracer:t,attributes:n,fn:r,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await n},async s=>{const a=xm.active();try{const u=await xm.with(a,()=>r(s));return o&&s.end(),u}catch(u){try{Fh(s,u)}finally{s.end()}throw u}})}i(su,"recordSpan");function Fh(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:La.ERROR,message:t.message})):e.setStatus({code:La.ERROR})}i(Fh,"recordErrorOnSpan");async function Gn({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const n={};for(const[r,o]of Object.entries(t))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;const s=await o.input();s!=null&&(n[r]=s);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const s=await o.output();s!=null&&(n[r]=s);continue}n[r]=o}return n}i(Gn,"selectTelemetryAttributes");function b3(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(n=>n.type==="file"?{...n,data:n.data instanceof Uint8Array?Y1(n.data):n.data}:n)})))}i(b3,"stringifyForTelemetry");function C3(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:At(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}i(C3,"asLanguageModelUsage");function w3(e,t){var n,r,o,s,a,u,l,c,d,f;return{inputTokens:At(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:At((n=e.inputTokenDetails)==null?void 0:n.noCacheTokens,(r=t.inputTokenDetails)==null?void 0:r.noCacheTokens),cacheReadTokens:At((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:At((a=e.inputTokenDetails)==null?void 0:a.cacheWriteTokens,(u=t.inputTokenDetails)==null?void 0:u.cacheWriteTokens)},outputTokens:At(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:At((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:At((d=e.outputTokenDetails)==null?void 0:d.reasoningTokens,(f=t.outputTokenDetails)==null?void 0:f.reasoningTokens)},totalTokens:At(e.totalTokens,t.totalTokens),reasoningTokens:At(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:At(e.cachedInputTokens,t.cachedInputTokens)}}i(w3,"addLanguageModelUsage");function At(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}i(At,"addTokenCounts");function Eh(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const o=t[r];if(o===void 0)continue;const s=r in e?e[r]:void 0,a=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),u=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);a&&u?n[r]=Eh(s,o):n[r]=o}return n}i(Eh,"mergeObjects");function F3({error:e,exponentialBackoffDelay:t}){const n=e.responseHeaders;if(!n)return t;let r;const o=n["retry-after-ms"];if(o){const a=parseFloat(o);Number.isNaN(a)||(r=a)}const s=n["retry-after"];if(s&&r===void 0){const a=parseFloat(s);Number.isNaN(a)?r=Date.parse(s)-Date.now():r=a*1e3}return r!=null&&!Number.isNaN(r)&&0<=r&&(r<60*1e3||r<t)?r:t}i(F3,"getRetryDelayInMs");var E3=i(({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async o=>xh(o,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r}),"retryWithExponentialBackoffRespectingRetryHeaders");async function xh(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:o},s=[]){try{return await e()}catch(a){if(Un(a)||t===0)throw a;const u=Df(a),l=[...s,a],c=l.length;if(c>t)throw new uh({message:`Failed after ${c} attempts. Last error: ${u}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&Be.isInstance(a)&&a.isRetryable===!0&&c<=t)return await $F(F3({error:a,exponentialBackoffDelay:n}),{abortSignal:o}),xh(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:o},l);throw c===1?a:new uh({message:`Failed after ${c} attempts with non-retryable error: '${u}'`,reason:"errorNotRetryable",errors:l})}}i(xh,"_retryWithExponentialBackoff");function x3({maxRetries:e,abortSignal:t}){if(!Number.isInteger(e))throw new qt({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});const n=e;return{maxRetries:n,retry:E3({maxRetries:n,abortSignal:t})}}i(x3,"prepareRetries");function k3({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const d of c)d.type==="tool-call"&&(n[d.toolCallId]=d)}const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const d of c)d.type==="tool-approval-request"&&(r[d.approvalId]=d)}const o={};for(const l of t.content)l.type==="tool-result"&&(o[l.toolCallId]=l);const s=[],a=[],u=t.content.filter(l=>l.type==="tool-approval-response");for(const l of u){const c=r[l.approvalId];if(c==null)throw new w1({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const d=n[c.toolCallId];if(d==null)throw new jm({toolCallId:c.toolCallId,approvalId:c.approvalId});const f={approvalRequest:c,approvalResponse:l,toolCall:d};l.approved?s.push(f):a.push(f)}return{approvedToolApprovals:s,deniedToolApprovals:a}}i(k3,"collectToolApprovals");function iu(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}i(iu,"now");async function I3({toolCall:e,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a,stepNumber:u,model:l,onPreliminaryToolResult:c,onToolCallStart:d,onToolCallFinish:f}){const{toolName:h,toolCallId:D,input:m}=e,v=t?.[h];if(v?.execute==null)return;const y={stepNumber:u,model:l,toolCall:e,messages:o,abortSignal:s,functionId:r?.functionId,metadata:r?.metadata,experimental_context:a};return su({name:"ai.toolCall",attributes:Gn({telemetry:r,attributes:{...au({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":h,"ai.toolCall.id":D,"ai.toolCall.args":{output:i(()=>JSON.stringify(m),"output")}}}),tracer:n,fn:i(async b=>{let C;try{await d?.(y)}catch{}const F=iu();try{const T=L2({execute:v.execute.bind(v),input:m,options:{toolCallId:D,messages:o,abortSignal:s,experimental_context:a}});for await(const O of T)O.type==="preliminary"?c?.({...e,type:"tool-result",output:O.output,preliminary:!0}):C=O.output}catch(T){const O=iu()-F;try{await f?.({...y,success:!1,error:T,durationMs:O})}catch{}return Fh(b,T),{type:"tool-error",toolCallId:D,toolName:h,input:m,error:T,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}const E=iu()-F;try{await f?.({...y,success:!0,output:C,durationMs:E})}catch{}try{b.setAttributes(await Gn({telemetry:r,attributes:{"ai.toolCall.result":{output:i(()=>JSON.stringify(C),"output")}}}))}catch{}return{type:"tool-result",toolCallId:D,toolName:h,input:m,output:C,dynamic:v.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}},"fn")})}i(I3,"executeToolCall");function kh(e){const t=e.filter(n=>n.type==="reasoning");return t.length===0?void 0:t.map(n=>n.text).join(`
149
+ `)}i(kh,"extractReasoningContent");function Ih(e){const t=e.filter(n=>n.type==="text");if(t.length!==0)return t.map(n=>n.text).join("")}i(Ih,"extractTextContent");var A3=(kr=class{constructor({data:t,mediaType:n}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=n}get base64(){return this.base64Data==null&&(this.base64Data=qn(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=hn(this.base64Data)),this.uint8ArrayData}},i(kr,"DefaultGeneratedFile"),kr);async function $3({tool:e,toolCall:t,messages:n,experimental_context:r}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:n,experimental_context:r})}i($3,"isApprovalNeeded");var T3={};_1(T3,{array:i(()=>O3,"array"),choice:i(()=>R3,"choice"),json:i(()=>N3,"json"),object:i(()=>B3,"object"),text:i(()=>Ah,"text")});function S3(e){const t=["ROOT"];let n=-1,r=null;function o(l,c,d){switch(l){case'"':{n=c,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=c,r=c,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=c,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=c,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}i(o,"processValueStart");function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=c,t.pop();break}}}i(s,"processAfterObjectValue");function a(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}}}i(a,"processAfterArrayValue");for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{n=l,t.pop();break}default:{n=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):n=l;break}}}let u=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{u+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{u+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{u+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?u+="true".slice(d.length):"false".startsWith(d)?u+="false".slice(d.length):"null".startsWith(d)&&(u+="null".slice(d.length))}}return u}i(S3,"fixJson");async function Za(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await kt({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await kt({text:S3(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}i(Za,"parsePartialJson");var Ah=i(()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),"text"),B3=i(({schema:e,name:t,description:n})=>{const r=Zn(e);return{name:"object",responseFormat:lt(r.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:o},s){const a=await kt({text:o});if(!a.success)throw new tn({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const u=await xt({value:a.value,schema:r});if(!u.success)throw new tn({message:"No object generated: response did not match schema.",cause:u.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});return u.value},async parsePartialOutput({text:o}){const s=await Za(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},"object"),O3=i(({element:e,name:t,description:n})=>{const r=Zn(e);return{name:"array",responseFormat:lt(r.jsonSchema).then(o=>{const{$schema:s,...a}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:a}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}}),async parseCompleteOutput({text:o},s){const a=await kt({text:o});if(!a.success)throw new tn({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const u=a.value;if(u==null||typeof u!="object"||!("elements"in u)||!Array.isArray(u.elements))throw new tn({message:"No object generated: response did not match schema.",cause:new cn({value:u,cause:"response must be an object with an elements array"}),text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});for(const l of u.elements){const c=await xt({value:l,schema:r});if(!c.success)throw new tn({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason})}return u.elements},async parsePartialOutput({text:o}){const s=await Za(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const a=s.value;if(a==null||typeof a!="object"||!("elements"in a)||!Array.isArray(a.elements))return;const u=s.state==="repaired-parse"&&a.elements.length>0?a.elements.slice(0,-1):a.elements,l=[];for(const c of u){const d=await xt({value:c,schema:r});d.success&&l.push(d.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:s},a){if(s!=null)for(;o<s.length;o++)a.enqueue(s[o])}})}}},"array"),R3=i(({options:e,name:t,description:n})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:r},o){const s=await kt({text:r});if(!s.success)throw new tn({message:"No object generated: could not parse the response.",cause:s.error,text:r,response:o.response,usage:o.usage,finishReason:o.finishReason});const a=s.value;if(a==null||typeof a!="object"||!("result"in a)||typeof a.result!="string"||!e.includes(a.result))throw new tn({message:"No object generated: response did not match schema.",cause:new cn({value:a,cause:"response must be an object that contains a choice value."}),text:r,response:o.response,usage:o.usage,finishReason:o.finishReason});return a.result},async parsePartialOutput({text:r}){const o=await Za(r);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const s=o.value;if(s==null||typeof s!="object"||!("result"in s)||typeof s.result!="string")return;const a=e.filter(u=>u.startsWith(s.result));return o.state==="successful-parse"?a.includes(s.result)?{partial:s.result}:void 0:a.length===1?{partial:a[0]}:void 0}}},createElementStreamTransform(){}}),"choice"),N3=i(({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:n},r){const o=await kt({text:n});if(!o.success)throw new tn({message:"No object generated: could not parse the response.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value},async parsePartialOutput({text:n}){const r=await Za(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return r.value===void 0?void 0:{partial:r.value}}},createElementStreamTransform(){}}),"json");async function P3({toolCall:e,tools:t,repairToolCall:n,system:r,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await $h(e);throw new ru({toolName:e.toolName})}try{return await Th({toolCall:e,tools:t})}catch(a){if(n==null||!(ru.isInstance(a)||nu.isInstance(a)))throw a;let u=null;try{u=await n({toolCall:e,tools:t,inputSchema:i(async({toolName:l})=>{const{inputSchema:c}=t[l];return await Zn(c).jsonSchema},"inputSchema"),system:r,messages:o,error:a})}catch(l){throw new S1({cause:l,originalError:a})}if(u==null)throw a;return await Th({toolCall:u,tools:t})}}catch(a){const u=await kt({text:e.input}),l=u.success?u.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:a,title:(s=t?.[e.toolName])==null?void 0:s.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}i(P3,"parseToolCall");async function $h(e){const t=e.input.trim()===""?{success:!0,value:{}}:await kt({text:e.input});if(t.success===!1)throw new nu({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}i($h,"parseProviderExecutedDynamicToolCall");async function Th({toolCall:e,tools:t}){const n=e.toolName,r=t[n];if(r==null){if(e.providerExecuted&&e.dynamic)return await $h(e);throw new ru({toolName:e.toolName,availableTools:Object.keys(t)})}const o=Zn(r.inputSchema),s=e.input.trim()===""?await xt({value:{},schema:o}):await kt({text:e.input,schema:o});if(s.success===!1)throw new nu({toolName:n,toolInput:e.input,cause:s.error});return r.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:r.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:r.title}}i(Th,"doParseToolCall");var M3=(Ir=class{constructor({stepNumber:t,model:n,functionId:r,metadata:o,experimental_context:s,content:a,finishReason:u,rawFinishReason:l,usage:c,warnings:d,request:f,response:h,providerMetadata:D}){this.stepNumber=t,this.model=n,this.functionId=r,this.metadata=o,this.experimental_context=s,this.content=a,this.finishReason=u,this.rawFinishReason=l,this.usage=c,this.warnings=d,this.request=f,this.response=h,this.providerMetadata=D}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}},i(Ir,"DefaultStepResult"),Ir);function j3(e){return({steps:t})=>t.length===e}i(j3,"stepCountIs");async function z3({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}i(z3,"isStopConditionMet");async function L3({content:e,tools:t}){const n=[],r=[];for(const s of e)if(s.type!=="source"&&!((s.type==="tool-result"||s.type==="tool-error")&&!s.providerExecuted)&&!(s.type==="text"&&s.text.length===0))switch(s.type){case"text":r.push({type:"text",text:s.text,providerOptions:s.providerMetadata});break;case"reasoning":r.push({type:"reasoning",text:s.text,providerOptions:s.providerMetadata});break;case"file":r.push({type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata});break;case"tool-call":r.push({type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata});break;case"tool-result":{const a=await qa({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.output,errorMode:"none"});r.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-error":{const a=await qa({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.error,errorMode:"json"});r.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-approval-request":r.push({type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId});break}r.length>0&&n.push({role:"assistant",content:r});const o=[];for(const s of e){if(!(s.type==="tool-result"||s.type==="tool-error")||s.providerExecuted)continue;const a=await qa({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return o.length>0&&n.push({role:"tool",content:o}),n}i(L3,"toResponseMessages");function q3(...e){const t=e.filter(r=>r!=null);if(t.length===0)return;if(t.length===1)return t[0];const n=new AbortController;for(const r of t){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>{n.abort(r.reason)},{once:!0})}return n.signal}i(q3,"mergeAbortSignals");var U3=bo({prefix:"aitxt",size:24});async function Ao({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:s,maxRetries:a,abortSignal:u,timeout:l,headers:c,stopWhen:d=j3(1),experimental_output:f,output:h=f,experimental_telemetry:D,providerOptions:m,experimental_activeTools:v,activeTools:y=v,experimental_prepareStep:b,prepareStep:C=b,experimental_repairToolCall:F,experimental_download:E,experimental_context:T,experimental_include:O,_internal:{generateId:$=U3}={},experimental_onStart:I,experimental_onStepStart:oe,experimental_onToolCallStart:k,experimental_onToolCallFinish:re,onStepFinish:B,onFinish:P,...z}){const U=fh(e),R=ou(d),Y=mh(l),me=U1(l),X=me!=null?new AbortController:void 0,de=q3(u,Y!=null?AbortSignal.timeout(Y):void 0,X?.signal),{maxRetries:pe,retry:H}=x3({maxRetries:a,abortSignal:de}),je=_h(z),xe=Dn(c??{},`ai/${hh}`),at=g3({model:U,telemetry:D,headers:xe,settings:{...je,maxRetries:pe}}),Ae={provider:U.provider,modelId:U.modelId},j=await h3({system:r,prompt:o,messages:s});try{await I?.({model:Ae,system:r,prompt:o,messages:s,tools:t,toolChoice:n,activeTools:y,maxOutputTokens:je.maxOutputTokens,temperature:je.temperature,topP:je.topP,topK:je.topK,presencePenalty:je.presencePenalty,frequencyPenalty:je.frequencyPenalty,stopSequences:je.stopSequences,seed:je.seed,maxRetries:pe,timeout:l,headers:c,providerOptions:m,stopWhen:d,output:h,abortSignal:u,include:O,functionId:D?.functionId,metadata:D?.metadata,experimental_context:T})}catch{}const te=_3(D);try{return await su({name:"ai.generateText",attributes:Gn({telemetry:D,attributes:{...au({operationId:"ai.generateText",telemetry:D}),...at,"ai.model.provider":U.provider,"ai.model.id":U.modelId,"ai.prompt":{input:i(()=>JSON.stringify({system:r,prompt:o,messages:s}),"input")}}}),tracer:te,fn:i(async Ge=>{var ve,Lr,qr,Ur,Zr,Vr,Gr,Wr,Hr,_,q,ze,st;const xn=j.messages,Jr=[],{approvedToolApprovals:tl,deniedToolApprovals:es}=k3({messages:xn}),nl=tl.filter(We=>!We.toolCall.providerExecuted);if(es.length>0||nl.length>0){const We=await Sh({toolCalls:nl.map(le=>le.toolCall),tools:t,tracer:te,telemetry:D,messages:xn,abortSignal:de,experimental_context:T,stepNumber:0,model:Ae,onToolCallStart:k,onToolCallFinish:re}),dt=[];for(const le of We){const _t=await qa({toolCallId:le.toolCallId,input:le.input,tool:t?.[le.toolName],output:le.type==="tool-result"?le.output:le.error,errorMode:le.type==="tool-error"?"json":"none"});dt.push({type:"tool-result",toolCallId:le.toolCallId,toolName:le.toolName,output:_t})}for(const le of es)dt.push({type:"tool-result",toolCallId:le.toolCall.toolCallId,toolName:le.toolCall.toolName,output:{type:"execution-denied",reason:le.approvalResponse.reason,...le.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:le.approvalResponse.approvalId}}}}});Jr.push({role:"tool",content:dt})}const rl=[...tl,...es].filter(We=>We.toolCall.providerExecuted);rl.length>0&&Jr.push({role:"tool",content:rl.map(We=>({type:"tool-approval-response",approvalId:We.approvalResponse.approvalId,approved:We.approvalResponse.approved,reason:We.approvalResponse.reason,providerExecuted:!0}))});const FD=_h(z);let Me,No=[],Kr=[];const ct=[],ts=new Map;do{const We=me!=null?setTimeout(()=>X.abort(),me):void 0;try{const dt=[...xn,...Jr],le=await C?.({model:U,steps:ct,stepNumber:ct.length,messages:dt,experimental_context:T}),_t=fh((ve=le?.model)!=null?ve:U),Yr={provider:_t.provider,modelId:_t.modelId},sl=await X1({prompt:{system:(Lr=le?.system)!=null?Lr:j.system,messages:(qr=le?.messages)!=null?qr:dt},supportedUrls:await _t.supportedUrls,download:E});T=(Ur=le?.experimental_context)!=null?Ur:T;const il=(Zr=le?.activeTools)!=null?Zr:y,{toolChoice:Po,tools:ns}=await r3({tools:t,toolChoice:(Vr=le?.toolChoice)!=null?Vr:n,activeTools:il}),ED=(Gr=le?.messages)!=null?Gr:dt,xD=(Wr=le?.system)!=null?Wr:j.system,ul=Eh(m,le?.providerOptions);try{await oe?.({stepNumber:ct.length,model:Yr,system:xD,messages:ED,tools:t,toolChoice:Po,activeTools:il,steps:[...ct],providerOptions:ul,timeout:l,headers:c,stopWhen:d,output:h,abortSignal:u,include:O,functionId:D?.functionId,metadata:D?.metadata,experimental_context:T})}catch{}Me=await H(()=>{var ue;return su({name:"ai.generateText.doGenerate",attributes:Gn({telemetry:D,attributes:{...au({operationId:"ai.generateText.doGenerate",telemetry:D}),...at,"ai.model.provider":_t.provider,"ai.model.id":_t.modelId,"ai.prompt.messages":{input:i(()=>b3(sl),"input")},"ai.prompt.tools":{input:i(()=>ns?.map(pt=>JSON.stringify(pt)),"input")},"ai.prompt.toolChoice":{input:i(()=>Po!=null?JSON.stringify(Po):void 0,"input")},"gen_ai.system":_t.provider,"gen_ai.request.model":_t.modelId,"gen_ai.request.frequency_penalty":z.frequencyPenalty,"gen_ai.request.max_tokens":z.maxOutputTokens,"gen_ai.request.presence_penalty":z.presencePenalty,"gen_ai.request.stop_sequences":z.stopSequences,"gen_ai.request.temperature":(ue=z.temperature)!=null?ue:void 0,"gen_ai.request.top_k":z.topK,"gen_ai.request.top_p":z.topP}}),tracer:te,fn:i(async pt=>{var os,Qr,dl,pl,fl,ml,hl,Dl;const Ye=await _t.doGenerate({...FD,tools:ns,toolChoice:Po,responseFormat:await h?.responseFormat,prompt:sl,providerOptions:ul,abortSignal:de,headers:xe}),kn={id:(Qr=(os=Ye.response)==null?void 0:os.id)!=null?Qr:$(),timestamp:(pl=(dl=Ye.response)==null?void 0:dl.timestamp)!=null?pl:new Date,modelId:(ml=(fl=Ye.response)==null?void 0:fl.modelId)!=null?ml:_t.modelId,headers:(hl=Ye.response)==null?void 0:hl.headers,body:(Dl=Ye.response)==null?void 0:Dl.body};return pt.setAttributes(await Gn({telemetry:D,attributes:{"ai.response.finishReason":Ye.finishReason.unified,"ai.response.text":{output:i(()=>Ih(Ye.content),"output")},"ai.response.reasoning":{output:i(()=>kh(Ye.content),"output")},"ai.response.toolCalls":{output:i(()=>{const gl=Bh(Ye.content);return gl==null?void 0:JSON.stringify(gl)},"output")},"ai.response.id":kn.id,"ai.response.model":kn.modelId,"ai.response.timestamp":kn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Ye.providerMetadata),"ai.usage.promptTokens":Ye.usage.inputTokens.total,"ai.usage.completionTokens":Ye.usage.outputTokens.total,"gen_ai.response.finish_reasons":[Ye.finishReason.unified],"gen_ai.response.id":kn.id,"gen_ai.response.model":kn.modelId,"gen_ai.usage.input_tokens":Ye.usage.inputTokens.total,"gen_ai.usage.output_tokens":Ye.usage.outputTokens.total}})),{...Ye,response:kn}},"fn")})});const Xr=await Promise.all(Me.content.filter(ue=>ue.type==="tool-call").map(ue=>P3({toolCall:ue,tools:t,repairToolCall:F,system:r,messages:dt}))),rs={};for(const ue of Xr){if(ue.invalid)continue;const pt=t?.[ue.toolName];pt!=null&&(pt?.onInputAvailable!=null&&await pt.onInputAvailable({input:ue.input,toolCallId:ue.toolCallId,messages:dt,abortSignal:de,experimental_context:T}),await $3({tool:pt,toolCall:ue,messages:dt,experimental_context:T})&&(rs[ue.toolCallId]={type:"tool-approval-request",approvalId:$(),toolCall:ue}))}const kD=Xr.filter(ue=>ue.invalid&&ue.dynamic);Kr=[];for(const ue of kD)Kr.push({type:"tool-error",toolCallId:ue.toolCallId,toolName:ue.toolName,input:ue.input,error:Df(ue.error),dynamic:!0});No=Xr.filter(ue=>!ue.providerExecuted),t!=null&&Kr.push(...await Sh({toolCalls:No.filter(ue=>!ue.invalid&&rs[ue.toolCallId]==null),tools:t,tracer:te,telemetry:D,messages:dt,abortSignal:de,experimental_context:T,stepNumber:ct.length,model:Yr,onToolCallStart:k,onToolCallFinish:re}));for(const ue of Xr){if(!ue.providerExecuted)continue;const pt=t?.[ue.toolName];pt?.type==="provider"&&pt.supportsDeferredResults&&(Me.content.some(Qr=>Qr.type==="tool-result"&&Qr.toolCallId===ue.toolCallId)||ts.set(ue.toolCallId,{toolName:ue.toolName}))}for(const ue of Me.content)ue.type==="tool-result"&&ts.delete(ue.toolCallId);const ll=V3({content:Me.content,toolCalls:Xr,toolOutputs:Kr,toolApprovalRequests:Object.values(rs),tools:t});Jr.push(...await L3({content:ll,tools:t}));const ID=(Hr=O?.requestBody)==null||Hr?(_=Me.request)!=null?_:{}:{...Me.request,body:void 0},AD={...Me.response,messages:structuredClone(Jr),body:(q=O?.responseBody)==null||q?(ze=Me.response)==null?void 0:ze.body:void 0},$D=ct.length,cl=new M3({stepNumber:$D,model:Yr,functionId:D?.functionId,metadata:D?.metadata,experimental_context:T,content:ll,finishReason:Me.finishReason.unified,rawFinishReason:Me.finishReason.raw,usage:C3(Me.usage),warnings:Me.warnings,providerMetadata:Me.providerMetadata,request:ID,response:AD});ch({warnings:(st=Me.warnings)!=null?st:[],provider:Yr.provider,model:Yr.modelId}),ct.push(cl),await B?.(cl)}finally{We!=null&&clearTimeout(We)}}while((No.length>0&&Kr.length===No.length||ts.size>0)&&!await z3({stopConditions:R,steps:ct}));Ge.setAttributes(await Gn({telemetry:D,attributes:{"ai.response.finishReason":Me.finishReason.unified,"ai.response.text":{output:i(()=>Ih(Me.content),"output")},"ai.response.reasoning":{output:i(()=>kh(Me.content),"output")},"ai.response.toolCalls":{output:i(()=>{const We=Bh(Me.content);return We==null?void 0:JSON.stringify(We)},"output")},"ai.response.providerMetadata":JSON.stringify(Me.providerMetadata),"ai.usage.promptTokens":Me.usage.inputTokens.total,"ai.usage.completionTokens":Me.usage.outputTokens.total}}));const ye=ct[ct.length-1],ol=ct.reduce((We,dt)=>w3(We,dt.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});await P?.({stepNumber:ye.stepNumber,model:ye.model,functionId:ye.functionId,metadata:ye.metadata,experimental_context:ye.experimental_context,finishReason:ye.finishReason,rawFinishReason:ye.rawFinishReason,usage:ye.usage,content:ye.content,text:ye.text,reasoningText:ye.reasoningText,reasoning:ye.reasoning,files:ye.files,sources:ye.sources,toolCalls:ye.toolCalls,staticToolCalls:ye.staticToolCalls,dynamicToolCalls:ye.dynamicToolCalls,toolResults:ye.toolResults,staticToolResults:ye.staticToolResults,dynamicToolResults:ye.dynamicToolResults,request:ye.request,response:ye.response,warnings:ye.warnings,providerMetadata:ye.providerMetadata,steps:ct,totalUsage:ol});let al;return ye.finishReason==="stop"&&(al=await(h??Ah()).parseCompleteOutput({text:ye.text},{response:ye.response,usage:ye.usage,finishReason:ye.finishReason})),new Z3({steps:ct,totalUsage:ol,output:al})},"fn")})}catch(Ge){throw D3(Ge)}}i(Ao,"generateText");async function Sh({toolCalls:e,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a,stepNumber:u,model:l,onToolCallStart:c,onToolCallFinish:d}){return(await Promise.all(e.map(async h=>I3({toolCall:h,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a,stepNumber:u,model:l,onToolCallStart:c,onToolCallFinish:d})))).filter(h=>h!=null)}i(Sh,"executeTools");var Z3=(Ar=class{constructor(t){this.steps=t.steps,this._output=t.output,this.totalUsage=t.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new A1;return this._output}},i(Ar,"DefaultGenerateTextResult"),Ar);function Bh(e){const t=e.filter(n=>n.type==="tool-call");if(t.length!==0)return t.map(n=>({toolCallId:n.toolCallId,toolName:n.toolName,input:n.input}))}i(Bh,"asToolCalls");function V3({content:e,toolCalls:t,toolOutputs:n,toolApprovalRequests:r,tools:o}){const s=[];for(const a of e)switch(a.type){case"text":case"reasoning":case"source":s.push(a);break;case"file":{s.push({type:"file",file:new A3(a),...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}});break}case"tool-call":{s.push(t.find(u=>u.toolCallId===a.toolCallId));break}case"tool-result":{const u=t.find(l=>l.toolCallId===a.toolCallId);if(u==null){const l=o?.[a.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${a.toolCallId} not found.`);a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,error:a.result,providerExecuted:!0,dynamic:a.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,output:a.result,providerExecuted:!0,dynamic:a.dynamic});break}a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:u.input,error:a.result,providerExecuted:!0,dynamic:u.dynamic}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:u.input,output:a.result,providerExecuted:!0,dynamic:u.dynamic});break}case"tool-approval-request":{const u=t.find(l=>l.toolCallId===a.toolCallId);if(u==null)throw new jm({toolCallId:a.toolCallId,approvalId:a.approvalId});s.push({type:"tool-approval-request",approvalId:a.approvalId,toolCall:u});break}}return[...s,...n,...r]}i(V3,"asContent"),class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
150
150
 
151
151
  `)},flush(e){e.enqueue(`data: [DONE]
152
152
 
153
- `)}})}},bo({prefix:"aitxt",size:24}),bo({prefix:"aiobj",size:24}),bo({prefix:"aiobj",size:24});var uu=g({error:g({message:p(),type:p().nullish(),param:et().nullish(),code:ee([p(),E()]).nullish()})}),$t=Dt({errorSchema:uu,errorToMessage:i(e=>e.error.message,"errorToMessage")});function Oh(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),r=e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("codex-mini")||e.startsWith("computer-use-preview")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),o=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2");return{supportsFlexProcessing:t,supportsPriorityProcessing:n,isReasoningModel:r,systemMessageMode:r?"developer":"system",supportsNonReasoningParameters:o}}i(Oh,"getOpenAILanguageModelCapabilities");function Rh(e){var t,n,r,o,s,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const u=(t=e.prompt_tokens)!=null?t:0,l=(n=e.completion_tokens)!=null?n:0,c=(o=(r=e.prompt_tokens_details)==null?void 0:r.cached_tokens)!=null?o:0,d=(a=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?a:0;return{inputTokens:{total:u,noCache:u-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-d,reasoning:d},raw:e}}i(Rh,"convertOpenAIChatUsage");function Z3({prompt:e,systemMessageMode:t="system"}){var n;const r=[],o=[];for(const{role:s,content:a}of e)switch(s){case"system":{switch(t){case"system":{r.push({role:"system",content:a});break}case"developer":{r.push({role:"developer",content:a});break}case"remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{const u=t;throw new Error(`Unsupported system message mode: ${u}`)}}break}case"user":{if(a.length===1&&a[0].type==="text"){r.push({role:"user",content:a[0].text});break}r.push({role:"user",content:a.map((u,l)=>{var c,d,f;switch(u.type){case"text":return{type:"text",text:u.text};case"file":if(u.mediaType.startsWith("image/")){const h=u.mediaType==="image/*"?"image/jpeg":u.mediaType;return{type:"image_url",image_url:{url:u.data instanceof URL?u.data.toString():`data:${h};base64,${zt(u.data)}`,detail:(d=(c=u.providerOptions)==null?void 0:c.openai)==null?void 0:d.imageDetail}}}else if(u.mediaType.startsWith("audio/")){if(u.data instanceof URL)throw new Qe({functionality:"audio file parts with URLs"});switch(u.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:zt(u.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:zt(u.data),format:"mp3"}};default:throw new Qe({functionality:`audio content parts with media type ${u.mediaType}`})}}else if(u.mediaType==="application/pdf"){if(u.data instanceof URL)throw new Qe({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof u.data=="string"&&u.data.startsWith("file-")?{file_id:u.data}:{filename:(f=u.filename)!=null?f:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${zt(u.data)}`}}}else throw new Qe({functionality:`file part media type ${u.mediaType}`})}})});break}case"assistant":{let u="";const l=[];for(const c of a)switch(c.type){case"text":{u+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}r.push({role:"assistant",content:u,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const u of a){if(u.type==="tool-approval-response")continue;const l=u.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(n=l.reason)!=null?n:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}r.push({role:"tool",tool_call_id:u.toolCallId,content:c})}break}default:{const u=s;throw new Error(`Unsupported role: ${u}`)}}return{messages:r,warnings:o}}i(Z3,"convertToOpenAIChatMessages");function lu({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n?new Date(n*1e3):void 0}}i(lu,"getResponseMetadata$1");function Nh(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(Nh,"mapOpenAIFinishReason");var V3=Y(()=>K(g({id:p().nullish(),created:E().nullish(),model:p().nullish(),choices:B(g({message:g({role:F("assistant").nullish(),content:p().nullish(),tool_calls:B(g({id:p().nullish(),type:F("function"),function:g({name:p(),arguments:p()})})).nullish(),annotations:B(g({type:F("url_citation"),url_citation:g({start_index:E(),end_index:E(),url:p(),title:p()})})).nullish()}),index:E(),logprobs:g({content:B(g({token:p(),logprob:E(),top_logprobs:B(g({token:p(),logprob:E()}))})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:g({prompt_tokens:E().nullish(),completion_tokens:E().nullish(),total_tokens:E().nullish(),prompt_tokens_details:g({cached_tokens:E().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:E().nullish(),accepted_prediction_tokens:E().nullish(),rejected_prediction_tokens:E().nullish()}).nullish()}).nullish()}))),G3=Y(()=>K(ee([g({id:p().nullish(),created:E().nullish(),model:p().nullish(),choices:B(g({delta:g({role:se(["assistant"]).nullish(),content:p().nullish(),tool_calls:B(g({index:E(),id:p().nullish(),type:F("function").nullish(),function:g({name:p().nullish(),arguments:p().nullish()})})).nullish(),annotations:B(g({type:F("url_citation"),url_citation:g({start_index:E(),end_index:E(),url:p(),title:p()})})).nullish()}).nullish(),logprobs:g({content:B(g({token:p(),logprob:E(),top_logprobs:B(g({token:p(),logprob:E()}))})).nullish()}).nullish(),finish_reason:p().nullish(),index:E()})),usage:g({prompt_tokens:E().nullish(),completion_tokens:E().nullish(),total_tokens:E().nullish(),prompt_tokens_details:g({cached_tokens:E().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:E().nullish(),accepted_prediction_tokens:E().nullish(),rejected_prediction_tokens:E().nullish()}).nullish()}).nullish()}),uu]))),W3=Y(()=>K(g({logitBias:be(Qw(),E()).optional(),logprobs:ee([Re(),E()]).optional(),parallelToolCalls:Re().optional(),user:p().optional(),reasoningEffort:se(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:E().optional(),store:Re().optional(),metadata:be(p().max(64),p().max(512)).optional(),prediction:be(p(),et()).optional(),serviceTier:se(["auto","flex","priority","default"]).optional(),strictJsonSchema:Re().optional(),textVerbosity:se(["low","medium","high"]).optional(),promptCacheKey:p().optional(),promptCacheRetention:se(["in_memory","24h"]).optional(),safetyIdentifier:p().optional(),systemMessageMode:se(["system","developer","remove"]).optional(),forceReasoning:Re().optional()})));function H3({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)switch(s.type){case"function":r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});break;default:n.push({type:"unsupported",feature:`tool type: ${s.type}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=o;throw new Qe({functionality:`tool choice type: ${s}`})}}}i(H3,"prepareChatTools");var J3=($r=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=n}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,stopSequences:l,responseFormat:c,seed:d,tools:f,toolChoice:h,providerOptions:D}){var m,v,y,b,w;const C=[],x=(m=await tt({provider:"openai",providerOptions:D,schema:W3}))!=null?m:{},T=Oh(this.modelId),O=(v=x.forceReasoning)!=null?v:T.isReasoningModel;s!=null&&C.push({type:"unsupported",feature:"topK"});const{messages:$,warnings:I}=Z3({prompt:t,systemMessageMode:(y=x.systemMessageMode)!=null?y:O?"developer":T.systemMessageMode});C.push(...I);const re=(b=x.strictJsonSchema)!=null?b:!0,k={model:this.modelId,logit_bias:x.logitBias,logprobs:x.logprobs===!0||typeof x.logprobs=="number"?!0:void 0,top_logprobs:typeof x.logprobs=="number"?x.logprobs:typeof x.logprobs=="boolean"&&x.logprobs?0:void 0,user:x.user,parallel_tool_calls:x.parallelToolCalls,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,response_format:c?.type==="json"?c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,strict:re,name:(w=c.name)!=null?w:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:d,verbosity:x.textVerbosity,max_completion_tokens:x.maxCompletionTokens,store:x.store,metadata:x.metadata,prediction:x.prediction,reasoning_effort:x.reasoningEffort,service_tier:x.serviceTier,prompt_cache_key:x.promptCacheKey,prompt_cache_retention:x.promptCacheRetention,safety_identifier:x.safetyIdentifier,messages:$};O?((x.reasoningEffort!=="none"||!T.supportsNonReasoningParameters)&&(k.temperature!=null&&(k.temperature=void 0,C.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),k.top_p!=null&&(k.top_p=void 0,C.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),k.logprobs!=null&&(k.logprobs=void 0,C.push({type:"other",message:"logprobs is not supported for reasoning models"}))),k.frequency_penalty!=null&&(k.frequency_penalty=void 0,C.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),k.presence_penalty!=null&&(k.presence_penalty=void 0,C.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),k.logit_bias!=null&&(k.logit_bias=void 0,C.push({type:"other",message:"logitBias is not supported for reasoning models"})),k.top_logprobs!=null&&(k.top_logprobs=void 0,C.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),k.max_tokens!=null&&(k.max_completion_tokens==null&&(k.max_completion_tokens=k.max_tokens),k.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&k.temperature!=null&&(k.temperature=void 0,C.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),x.serviceTier==="flex"&&!T.supportsFlexProcessing&&(C.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),k.service_tier=void 0),x.serviceTier==="priority"&&!T.supportsPriorityProcessing&&(C.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),k.service_tier=void 0);const{tools:X,toolChoice:S,toolWarnings:j}=H3({tools:f,toolChoice:h});return{args:{...k,tools:X,tool_choice:S},warnings:[...C,...j]}}async doGenerate(t){var n,r,o,s,a,u,l;const{args:c,warnings:d}=await this.getArgs(t),{responseHeaders:f,value:h,rawValue:D}=await qe({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:c,failedResponseHandler:$t,successfulResponseHandler:Ke(V3),abortSignal:t.abortSignal,fetch:this.config.fetch}),m=h.choices[0],v=[],y=m.message.content;y!=null&&y.length>0&&v.push({type:"text",text:y});for(const C of(n=m.message.tool_calls)!=null?n:[])v.push({type:"tool-call",toolCallId:(r=C.id)!=null?r:Ve(),toolName:C.function.name,input:C.function.arguments});for(const C of(o=m.message.annotations)!=null?o:[])v.push({type:"source",sourceType:"url",id:Ve(),url:C.url_citation.url,title:C.url_citation.title});const b=(s=h.usage)==null?void 0:s.completion_tokens_details;(a=h.usage)==null||a.prompt_tokens_details;const w={openai:{}};return b?.accepted_prediction_tokens!=null&&(w.openai.acceptedPredictionTokens=b?.accepted_prediction_tokens),b?.rejected_prediction_tokens!=null&&(w.openai.rejectedPredictionTokens=b?.rejected_prediction_tokens),((u=m.logprobs)==null?void 0:u.content)!=null&&(w.openai.logprobs=m.logprobs.content),{content:v,finishReason:{unified:Nh(m.finish_reason),raw:(l=m.finish_reason)!=null?l:void 0},usage:Rh(h.usage),request:{body:c},response:{...lu(h),headers:f,body:D},warnings:d,providerMetadata:w}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),o={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:a}=await qe({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:o,failedResponseHandler:$t,successfulResponseHandler:Vn(G3),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=[];let l={unified:"other",raw:void 0},c,d=!1,f=!1;const h={openai:{}};return{stream:a.pipeThrough(new TransformStream({start(D){D.enqueue({type:"stream-start",warnings:r})},transform(D,m){var v,y,b,w,C,x,T,O,$,I,re,k,X,S,j,z,Z;if(t.includeRawChunks&&m.enqueue({type:"raw",rawValue:D.rawValue}),!D.success){l={unified:"error",raw:void 0},m.enqueue({type:"error",error:D.error});return}const N=D.value;if("error"in N){l={unified:"error",raw:void 0},m.enqueue({type:"error",error:N.error});return}if(!d){const oe=lu(N);Object.values(oe).some(Boolean)&&(d=!0,m.enqueue({type:"response-metadata",...lu(N)}))}N.usage!=null&&(c=N.usage,((v=N.usage.completion_tokens_details)==null?void 0:v.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(y=N.usage.completion_tokens_details)==null?void 0:y.accepted_prediction_tokens),((b=N.usage.completion_tokens_details)==null?void 0:b.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(w=N.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens));const J=N.choices[0];if(J?.finish_reason!=null&&(l={unified:Nh(J.finish_reason),raw:J.finish_reason}),((C=J?.logprobs)==null?void 0:C.content)!=null&&(h.openai.logprobs=J.logprobs.content),J?.delta==null)return;const pe=J.delta;if(pe.content!=null&&(f||(m.enqueue({type:"text-start",id:"0"}),f=!0),m.enqueue({type:"text-delta",id:"0",delta:pe.content})),pe.tool_calls!=null)for(const oe of pe.tool_calls){const de=oe.index;if(u[de]==null){if(oe.type!=="function")throw new so({data:oe,message:"Expected 'function' type."});if(oe.id==null)throw new so({data:oe,message:"Expected 'id' to be a string."});if(((x=oe.function)==null?void 0:x.name)==null)throw new so({data:oe,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:oe.id,toolName:oe.function.name}),u[de]={id:oe.id,type:"function",function:{name:oe.function.name,arguments:(T=oe.function.arguments)!=null?T:""},hasFinished:!1};const H=u[de];((O=H.function)==null?void 0:O.name)!=null&&(($=H.function)==null?void 0:$.arguments)!=null&&(H.function.arguments.length>0&&m.enqueue({type:"tool-input-delta",id:H.id,delta:H.function.arguments}),ja(H.function.arguments)&&(m.enqueue({type:"tool-input-end",id:H.id}),m.enqueue({type:"tool-call",toolCallId:(I=H.id)!=null?I:Ve(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0));continue}const fe=u[de];fe.hasFinished||(((re=oe.function)==null?void 0:re.arguments)!=null&&(fe.function.arguments+=(X=(k=oe.function)==null?void 0:k.arguments)!=null?X:""),m.enqueue({type:"tool-input-delta",id:fe.id,delta:(S=oe.function.arguments)!=null?S:""}),((j=fe.function)==null?void 0:j.name)!=null&&((z=fe.function)==null?void 0:z.arguments)!=null&&ja(fe.function.arguments)&&(m.enqueue({type:"tool-input-end",id:fe.id}),m.enqueue({type:"tool-call",toolCallId:(Z=fe.id)!=null?Z:Ve(),toolName:fe.function.name,input:fe.function.arguments}),fe.hasFinished=!0))}if(pe.annotations!=null)for(const oe of pe.annotations)m.enqueue({type:"source",sourceType:"url",id:Ve(),url:oe.url_citation.url,title:oe.url_citation.title})},flush(D){f&&D.enqueue({type:"text-end",id:"0"}),D.enqueue({type:"finish",finishReason:l,usage:Rh(c),...h!=null?{providerMetadata:h}:{}})}})),request:{body:o},response:{headers:s}}}},i($r,"OpenAIChatLanguageModel"),$r);function Ph(e){var t,n,r,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=(t=e.prompt_tokens)!=null?t:0,a=(n=e.completion_tokens)!=null?n:0;return{inputTokens:{total:(r=e.prompt_tokens)!=null?r:void 0,noCache:s,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(o=e.completion_tokens)!=null?o:void 0,text:a,reasoning:void 0},raw:e}}i(Ph,"convertOpenAICompletionUsage");function K3({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
153
+ `)}})}},bo({prefix:"aitxt",size:24}),bo({prefix:"aiobj",size:24}),bo({prefix:"aiobj",size:24});var uu=g({error:g({message:p(),type:p().nullish(),param:et().nullish(),code:ee([p(),x()]).nullish()})}),$t=Dt({errorSchema:uu,errorToMessage:i(e=>e.error.message,"errorToMessage")});function Oh(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")||e.startsWith("o3")||e.startsWith("o4-mini"),r=e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("codex-mini")||e.startsWith("computer-use-preview")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),o=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2");return{supportsFlexProcessing:t,supportsPriorityProcessing:n,isReasoningModel:r,systemMessageMode:r?"developer":"system",supportsNonReasoningParameters:o}}i(Oh,"getOpenAILanguageModelCapabilities");function Rh(e){var t,n,r,o,s,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const u=(t=e.prompt_tokens)!=null?t:0,l=(n=e.completion_tokens)!=null?n:0,c=(o=(r=e.prompt_tokens_details)==null?void 0:r.cached_tokens)!=null?o:0,d=(a=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?a:0;return{inputTokens:{total:u,noCache:u-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-d,reasoning:d},raw:e}}i(Rh,"convertOpenAIChatUsage");function G3({prompt:e,systemMessageMode:t="system"}){var n;const r=[],o=[];for(const{role:s,content:a}of e)switch(s){case"system":{switch(t){case"system":{r.push({role:"system",content:a});break}case"developer":{r.push({role:"developer",content:a});break}case"remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{const u=t;throw new Error(`Unsupported system message mode: ${u}`)}}break}case"user":{if(a.length===1&&a[0].type==="text"){r.push({role:"user",content:a[0].text});break}r.push({role:"user",content:a.map((u,l)=>{var c,d,f;switch(u.type){case"text":return{type:"text",text:u.text};case"file":if(u.mediaType.startsWith("image/")){const h=u.mediaType==="image/*"?"image/jpeg":u.mediaType;return{type:"image_url",image_url:{url:u.data instanceof URL?u.data.toString():`data:${h};base64,${zt(u.data)}`,detail:(d=(c=u.providerOptions)==null?void 0:c.openai)==null?void 0:d.imageDetail}}}else if(u.mediaType.startsWith("audio/")){if(u.data instanceof URL)throw new Qe({functionality:"audio file parts with URLs"});switch(u.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:zt(u.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:zt(u.data),format:"mp3"}};default:throw new Qe({functionality:`audio content parts with media type ${u.mediaType}`})}}else if(u.mediaType==="application/pdf"){if(u.data instanceof URL)throw new Qe({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof u.data=="string"&&u.data.startsWith("file-")?{file_id:u.data}:{filename:(f=u.filename)!=null?f:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${zt(u.data)}`}}}else throw new Qe({functionality:`file part media type ${u.mediaType}`})}})});break}case"assistant":{let u="";const l=[];for(const c of a)switch(c.type){case"text":{u+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}r.push({role:"assistant",content:u,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const u of a){if(u.type==="tool-approval-response")continue;const l=u.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(n=l.reason)!=null?n:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}r.push({role:"tool",tool_call_id:u.toolCallId,content:c})}break}default:{const u=s;throw new Error(`Unsupported role: ${u}`)}}return{messages:r,warnings:o}}i(G3,"convertToOpenAIChatMessages");function lu({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n?new Date(n*1e3):void 0}}i(lu,"getResponseMetadata$1");function Nh(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(Nh,"mapOpenAIFinishReason");var W3=K(()=>J(g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({message:g({role:w("assistant").nullish(),content:p().nullish(),tool_calls:S(g({id:p().nullish(),type:w("function"),function:g({name:p(),arguments:p()})})).nullish(),annotations:S(g({type:w("url_citation"),url_citation:g({start_index:x(),end_index:x(),url:p(),title:p()})})).nullish()}),index:x(),logprobs:g({content:S(g({token:p(),logprob:x(),top_logprobs:S(g({token:p(),logprob:x()}))})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:g({prompt_tokens:x().nullish(),completion_tokens:x().nullish(),total_tokens:x().nullish(),prompt_tokens_details:g({cached_tokens:x().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:x().nullish(),accepted_prediction_tokens:x().nullish(),rejected_prediction_tokens:x().nullish()}).nullish()}).nullish()}))),H3=K(()=>J(ee([g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({delta:g({role:se(["assistant"]).nullish(),content:p().nullish(),tool_calls:S(g({index:x(),id:p().nullish(),type:w("function").nullish(),function:g({name:p().nullish(),arguments:p().nullish()})})).nullish(),annotations:S(g({type:w("url_citation"),url_citation:g({start_index:x(),end_index:x(),url:p(),title:p()})})).nullish()}).nullish(),logprobs:g({content:S(g({token:p(),logprob:x(),top_logprobs:S(g({token:p(),logprob:x()}))})).nullish()}).nullish(),finish_reason:p().nullish(),index:x()})),usage:g({prompt_tokens:x().nullish(),completion_tokens:x().nullish(),total_tokens:x().nullish(),prompt_tokens_details:g({cached_tokens:x().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:x().nullish(),accepted_prediction_tokens:x().nullish(),rejected_prediction_tokens:x().nullish()}).nullish()}).nullish()}),uu]))),J3=K(()=>J(g({logitBias:be(tF(),x()).optional(),logprobs:ee([Re(),x()]).optional(),parallelToolCalls:Re().optional(),user:p().optional(),reasoningEffort:se(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:x().optional(),store:Re().optional(),metadata:be(p().max(64),p().max(512)).optional(),prediction:be(p(),et()).optional(),serviceTier:se(["auto","flex","priority","default"]).optional(),strictJsonSchema:Re().optional(),textVerbosity:se(["low","medium","high"]).optional(),promptCacheKey:p().optional(),promptCacheRetention:se(["in_memory","24h"]).optional(),safetyIdentifier:p().optional(),systemMessageMode:se(["system","developer","remove"]).optional(),forceReasoning:Re().optional()})));function K3({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)switch(s.type){case"function":r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});break;default:n.push({type:"unsupported",feature:`tool type: ${s.type}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=o;throw new Qe({functionality:`tool choice type: ${s}`})}}}i(K3,"prepareChatTools");var Y3=($r=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=n}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,stopSequences:l,responseFormat:c,seed:d,tools:f,toolChoice:h,providerOptions:D}){var m,v,y,b,C;const F=[],E=(m=await tt({provider:"openai",providerOptions:D,schema:J3}))!=null?m:{},T=Oh(this.modelId),O=(v=E.forceReasoning)!=null?v:T.isReasoningModel;s!=null&&F.push({type:"unsupported",feature:"topK"});const{messages:$,warnings:I}=G3({prompt:t,systemMessageMode:(y=E.systemMessageMode)!=null?y:O?"developer":T.systemMessageMode});F.push(...I);const oe=(b=E.strictJsonSchema)!=null?b:!0,k={model:this.modelId,logit_bias:E.logitBias,logprobs:E.logprobs===!0||typeof E.logprobs=="number"?!0:void 0,top_logprobs:typeof E.logprobs=="number"?E.logprobs:typeof E.logprobs=="boolean"&&E.logprobs?0:void 0,user:E.user,parallel_tool_calls:E.parallelToolCalls,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,response_format:c?.type==="json"?c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,strict:oe,name:(C=c.name)!=null?C:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:d,verbosity:E.textVerbosity,max_completion_tokens:E.maxCompletionTokens,store:E.store,metadata:E.metadata,prediction:E.prediction,reasoning_effort:E.reasoningEffort,service_tier:E.serviceTier,prompt_cache_key:E.promptCacheKey,prompt_cache_retention:E.promptCacheRetention,safety_identifier:E.safetyIdentifier,messages:$};O?((E.reasoningEffort!=="none"||!T.supportsNonReasoningParameters)&&(k.temperature!=null&&(k.temperature=void 0,F.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),k.top_p!=null&&(k.top_p=void 0,F.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),k.logprobs!=null&&(k.logprobs=void 0,F.push({type:"other",message:"logprobs is not supported for reasoning models"}))),k.frequency_penalty!=null&&(k.frequency_penalty=void 0,F.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),k.presence_penalty!=null&&(k.presence_penalty=void 0,F.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),k.logit_bias!=null&&(k.logit_bias=void 0,F.push({type:"other",message:"logitBias is not supported for reasoning models"})),k.top_logprobs!=null&&(k.top_logprobs=void 0,F.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),k.max_tokens!=null&&(k.max_completion_tokens==null&&(k.max_completion_tokens=k.max_tokens),k.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&k.temperature!=null&&(k.temperature=void 0,F.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),E.serviceTier==="flex"&&!T.supportsFlexProcessing&&(F.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),k.service_tier=void 0),E.serviceTier==="priority"&&!T.supportsPriorityProcessing&&(F.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),k.service_tier=void 0);const{tools:re,toolChoice:B,toolWarnings:P}=K3({tools:f,toolChoice:h});return{args:{...k,tools:re,tool_choice:B},warnings:[...F,...P]}}async doGenerate(t){var n,r,o,s,a,u,l;const{args:c,warnings:d}=await this.getArgs(t),{responseHeaders:f,value:h,rawValue:D}=await qe({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:c,failedResponseHandler:$t,successfulResponseHandler:Ke(W3),abortSignal:t.abortSignal,fetch:this.config.fetch}),m=h.choices[0],v=[],y=m.message.content;y!=null&&y.length>0&&v.push({type:"text",text:y});for(const F of(n=m.message.tool_calls)!=null?n:[])v.push({type:"tool-call",toolCallId:(r=F.id)!=null?r:Ve(),toolName:F.function.name,input:F.function.arguments});for(const F of(o=m.message.annotations)!=null?o:[])v.push({type:"source",sourceType:"url",id:Ve(),url:F.url_citation.url,title:F.url_citation.title});const b=(s=h.usage)==null?void 0:s.completion_tokens_details;(a=h.usage)==null||a.prompt_tokens_details;const C={openai:{}};return b?.accepted_prediction_tokens!=null&&(C.openai.acceptedPredictionTokens=b?.accepted_prediction_tokens),b?.rejected_prediction_tokens!=null&&(C.openai.rejectedPredictionTokens=b?.rejected_prediction_tokens),((u=m.logprobs)==null?void 0:u.content)!=null&&(C.openai.logprobs=m.logprobs.content),{content:v,finishReason:{unified:Nh(m.finish_reason),raw:(l=m.finish_reason)!=null?l:void 0},usage:Rh(h.usage),request:{body:c},response:{...lu(h),headers:f,body:D},warnings:d,providerMetadata:C}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),o={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:a}=await qe({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:o,failedResponseHandler:$t,successfulResponseHandler:Vn(H3),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=[];let l={unified:"other",raw:void 0},c,d=!1,f=!1;const h={openai:{}};return{stream:a.pipeThrough(new TransformStream({start(D){D.enqueue({type:"stream-start",warnings:r})},transform(D,m){var v,y,b,C,F,E,T,O,$,I,oe,k,re,B,P,z,U;if(t.includeRawChunks&&m.enqueue({type:"raw",rawValue:D.rawValue}),!D.success){l={unified:"error",raw:void 0},m.enqueue({type:"error",error:D.error});return}const R=D.value;if("error"in R){l={unified:"error",raw:void 0},m.enqueue({type:"error",error:R.error});return}if(!d){const X=lu(R);Object.values(X).some(Boolean)&&(d=!0,m.enqueue({type:"response-metadata",...lu(R)}))}R.usage!=null&&(c=R.usage,((v=R.usage.completion_tokens_details)==null?void 0:v.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(y=R.usage.completion_tokens_details)==null?void 0:y.accepted_prediction_tokens),((b=R.usage.completion_tokens_details)==null?void 0:b.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(C=R.usage.completion_tokens_details)==null?void 0:C.rejected_prediction_tokens));const Y=R.choices[0];if(Y?.finish_reason!=null&&(l={unified:Nh(Y.finish_reason),raw:Y.finish_reason}),((F=Y?.logprobs)==null?void 0:F.content)!=null&&(h.openai.logprobs=Y.logprobs.content),Y?.delta==null)return;const me=Y.delta;if(me.content!=null&&(f||(m.enqueue({type:"text-start",id:"0"}),f=!0),m.enqueue({type:"text-delta",id:"0",delta:me.content})),me.tool_calls!=null)for(const X of me.tool_calls){const de=X.index;if(u[de]==null){if(X.type!=="function")throw new so({data:X,message:"Expected 'function' type."});if(X.id==null)throw new so({data:X,message:"Expected 'id' to be a string."});if(((E=X.function)==null?void 0:E.name)==null)throw new so({data:X,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:X.id,toolName:X.function.name}),u[de]={id:X.id,type:"function",function:{name:X.function.name,arguments:(T=X.function.arguments)!=null?T:""},hasFinished:!1};const H=u[de];((O=H.function)==null?void 0:O.name)!=null&&(($=H.function)==null?void 0:$.arguments)!=null&&(H.function.arguments.length>0&&m.enqueue({type:"tool-input-delta",id:H.id,delta:H.function.arguments}),ja(H.function.arguments)&&(m.enqueue({type:"tool-input-end",id:H.id}),m.enqueue({type:"tool-call",toolCallId:(I=H.id)!=null?I:Ve(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0));continue}const pe=u[de];pe.hasFinished||(((oe=X.function)==null?void 0:oe.arguments)!=null&&(pe.function.arguments+=(re=(k=X.function)==null?void 0:k.arguments)!=null?re:""),m.enqueue({type:"tool-input-delta",id:pe.id,delta:(B=X.function.arguments)!=null?B:""}),((P=pe.function)==null?void 0:P.name)!=null&&((z=pe.function)==null?void 0:z.arguments)!=null&&ja(pe.function.arguments)&&(m.enqueue({type:"tool-input-end",id:pe.id}),m.enqueue({type:"tool-call",toolCallId:(U=pe.id)!=null?U:Ve(),toolName:pe.function.name,input:pe.function.arguments}),pe.hasFinished=!0))}if(me.annotations!=null)for(const X of me.annotations)m.enqueue({type:"source",sourceType:"url",id:Ve(),url:X.url_citation.url,title:X.url_citation.title})},flush(D){f&&D.enqueue({type:"text-end",id:"0"}),D.enqueue({type:"finish",finishReason:l,usage:Rh(c),...h!=null?{providerMetadata:h}:{}})}})),request:{body:o},response:{headers:s}}}},i($r,"OpenAIChatLanguageModel"),$r);function Ph(e){var t,n,r,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=(t=e.prompt_tokens)!=null?t:0,a=(n=e.completion_tokens)!=null?n:0;return{inputTokens:{total:(r=e.prompt_tokens)!=null?r:void 0,noCache:s,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(o=e.completion_tokens)!=null?o:void 0,text:a,reasoning:void 0},raw:e}}i(Ph,"convertOpenAICompletionUsage");function X3({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
154
154
 
155
155
  `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new Gt({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const a=s.map(u=>{switch(u.type){case"text":return u.text}}).filter(Boolean).join("");r+=`${t}:
156
156
  ${a}
@@ -160,7 +160,7 @@ ${a}
160
160
 
161
161
  `;break}case"tool":throw new Qe({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return r+=`${n}:
162
162
  `,{prompt:r,stopSequences:[`
163
- ${t}:`]}}i(K3,"convertToOpenAICompletionPrompt");function Mh({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(Mh,"getResponseMetadata2$1");function jh(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(jh,"mapOpenAIFinishReason2");var Y3=Y(()=>K(g({id:p().nullish(),created:E().nullish(),model:p().nullish(),choices:B(g({text:p(),finish_reason:p(),logprobs:g({tokens:B(p()),token_logprobs:B(E()),top_logprobs:B(be(p(),E())).nullish()}).nullish()})),usage:g({prompt_tokens:E(),completion_tokens:E(),total_tokens:E()}).nullish()}))),X3=Y(()=>K(ee([g({id:p().nullish(),created:E().nullish(),model:p().nullish(),choices:B(g({text:p(),finish_reason:p().nullish(),index:E(),logprobs:g({tokens:B(p()),token_logprobs:B(E()),top_logprobs:B(be(p(),E())).nullish()}).nullish()})),usage:g({prompt_tokens:E(),completion_tokens:E(),total_tokens:E()}).nullish()}),uu]))),zh=Y(()=>K(g({echo:Re().optional(),logitBias:be(p(),E()).optional(),suffix:p().optional(),user:p().optional(),logprobs:ee([Re(),E()]).optional()}))),Q3=(Tr=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={},this.modelId=t,this.config=n}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,stopSequences:l,responseFormat:c,tools:d,toolChoice:f,seed:h,providerOptions:D}){const m=[],v={...await tt({provider:"openai",providerOptions:D,schema:zh}),...await tt({provider:this.providerOptionsName,providerOptions:D,schema:zh})};s!=null&&m.push({type:"unsupported",feature:"topK"}),d?.length&&m.push({type:"unsupported",feature:"tools"}),f!=null&&m.push({type:"unsupported",feature:"toolChoice"}),c!=null&&c.type!=="text"&&m.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:y,stopSequences:b}=K3({prompt:t}),w=[...b??[],...l??[]];return{args:{model:this.modelId,echo:v.echo,logit_bias:v.logitBias,logprobs:v?.logprobs===!0?0:v?.logprobs===!1?void 0:v?.logprobs,suffix:v.suffix,user:v.user,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,seed:h,prompt:y,stop:w.length>0?w:void 0},warnings:m}}async doGenerate(t){var n;const{args:r,warnings:o}=await this.getArgs(t),{responseHeaders:s,value:a,rawValue:u}=await qe({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:r,failedResponseHandler:$t,successfulResponseHandler:Ke(Y3),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=a.choices[0],c={openai:{}};return l.logprobs!=null&&(c.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:Ph(a.usage),finishReason:{unified:jh(l.finish_reason),raw:(n=l.finish_reason)!=null?n:void 0},request:{body:r},response:{...Mh(a),headers:s,body:u},providerMetadata:c,warnings:o}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),o={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:a}=await qe({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:o,failedResponseHandler:$t,successfulResponseHandler:Vn(X3),abortSignal:t.abortSignal,fetch:this.config.fetch});let u={unified:"other",raw:void 0};const l={openai:{}};let c,d=!0;return{stream:a.pipeThrough(new TransformStream({start(f){f.enqueue({type:"stream-start",warnings:r})},transform(f,h){if(t.includeRawChunks&&h.enqueue({type:"raw",rawValue:f.rawValue}),!f.success){u={unified:"error",raw:void 0},h.enqueue({type:"error",error:f.error});return}const D=f.value;if("error"in D){u={unified:"error",raw:void 0},h.enqueue({type:"error",error:D.error});return}d&&(d=!1,h.enqueue({type:"response-metadata",...Mh(D)}),h.enqueue({type:"text-start",id:"0"})),D.usage!=null&&(c=D.usage);const m=D.choices[0];m?.finish_reason!=null&&(u={unified:jh(m.finish_reason),raw:m.finish_reason}),m?.logprobs!=null&&(l.openai.logprobs=m.logprobs),m?.text!=null&&m.text.length>0&&h.enqueue({type:"text-delta",id:"0",delta:m.text})},flush(f){d||f.enqueue({type:"text-end",id:"0"}),f.enqueue({type:"finish",finishReason:u,providerMetadata:l,usage:Ph(c)})}})),request:{body:o},response:{headers:s}}}},i(Tr,"OpenAICompletionLanguageModel"),Tr),ex=Y(()=>K(g({dimensions:E().optional(),user:p().optional()}))),tx=Y(()=>K(g({data:B(g({embedding:B(E())})),usage:g({prompt_tokens:E()}).nullish()}))),nx=(Sr=class{constructor(t,n){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=n}get provider(){return this.config.provider}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:o}){var s;if(t.length>this.maxEmbeddingsPerCall)throw new tp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const a=(s=await tt({provider:"openai",providerOptions:o,schema:ex}))!=null?s:{},{responseHeaders:u,value:l,rawValue:c}=await qe({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Ne(this.config.headers(),n),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:a.dimensions,user:a.user},failedResponseHandler:$t,successfulResponseHandler:Ke(tx),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.data.map(d=>d.embedding),usage:l.usage?{tokens:l.usage.prompt_tokens}:void 0,response:{headers:u,body:c}}}},i(Sr,"OpenAIEmbeddingModel"),Sr),Lh=Y(()=>K(g({created:E().nullish(),data:B(g({b64_json:p(),revised_prompt:p().nullish()})),background:p().nullish(),output_format:p().nullish(),size:p().nullish(),quality:p().nullish(),usage:g({input_tokens:E().nullish(),output_tokens:E().nullish(),total_tokens:E().nullish(),input_tokens_details:g({image_tokens:E().nullish(),text_tokens:E().nullish()}).nullish()}).nullish()}))),rx={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},ox=["gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function ax(e){return ox.some(t=>e.startsWith(t))}i(ax,"hasDefaultResponseFormat");var sx=(Br=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=rx[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,files:n,mask:r,n:o,size:s,aspectRatio:a,seed:u,providerOptions:l,headers:c,abortSignal:d}){var f,h,D,m,v,y,b,w,C,x,T;const O=[];a!=null&&O.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),u!=null&&O.push({type:"unsupported",feature:"seed"});const $=(D=(h=(f=this.config._internal)==null?void 0:f.currentDate)==null?void 0:h.call(f))!=null?D:new Date;if(n!=null){const{value:k,responseHeaders:X}=await Mi({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:Ne(this.config.headers(),c),formData:cf({model:this.modelId,prompt:t,image:await Promise.all(n.map(S=>S.type==="file"?new Blob([S.data instanceof Uint8Array?new Blob([S.data],{type:S.mediaType}):new Blob([hn(S.data)],{type:S.mediaType})],{type:S.mediaType}):$i(S.url))),mask:r!=null?await ix(r):void 0,n:o,size:s,...(m=l.openai)!=null?m:{}}),failedResponseHandler:$t,successfulResponseHandler:Ke(Lh),abortSignal:d,fetch:this.config.fetch});return{images:k.data.map(S=>S.b64_json),warnings:O,usage:k.usage!=null?{inputTokens:(v=k.usage.input_tokens)!=null?v:void 0,outputTokens:(y=k.usage.output_tokens)!=null?y:void 0,totalTokens:(b=k.usage.total_tokens)!=null?b:void 0}:void 0,response:{timestamp:$,modelId:this.modelId,headers:X},providerMetadata:{openai:{images:k.data.map((S,j)=>{var z,Z,N,J,pe,oe;return{...S.revised_prompt?{revisedPrompt:S.revised_prompt}:{},created:(z=k.created)!=null?z:void 0,size:(Z=k.size)!=null?Z:void 0,quality:(N=k.quality)!=null?N:void 0,background:(J=k.background)!=null?J:void 0,outputFormat:(pe=k.output_format)!=null?pe:void 0,...qh((oe=k.usage)==null?void 0:oe.input_tokens_details,j,k.data.length)}})}}}}const{value:I,responseHeaders:re}=await qe({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Ne(this.config.headers(),c),body:{model:this.modelId,prompt:t,n:o,size:s,...(w=l.openai)!=null?w:{},...ax(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:$t,successfulResponseHandler:Ke(Lh),abortSignal:d,fetch:this.config.fetch});return{images:I.data.map(k=>k.b64_json),warnings:O,usage:I.usage!=null?{inputTokens:(C=I.usage.input_tokens)!=null?C:void 0,outputTokens:(x=I.usage.output_tokens)!=null?x:void 0,totalTokens:(T=I.usage.total_tokens)!=null?T:void 0}:void 0,response:{timestamp:$,modelId:this.modelId,headers:re},providerMetadata:{openai:{images:I.data.map((k,X)=>{var S,j,z,Z,N,J;return{...k.revised_prompt?{revisedPrompt:k.revised_prompt}:{},created:(S=I.created)!=null?S:void 0,size:(j=I.size)!=null?j:void 0,quality:(z=I.quality)!=null?z:void 0,background:(Z=I.background)!=null?Z:void 0,outputFormat:(N=I.output_format)!=null?N:void 0,...qh((J=I.usage)==null?void 0:J.input_tokens_details,X,I.data.length)}})}}}}},i(Br,"OpenAIImageModel"),Br);function qh(e,t,n){if(e==null)return{};const r={};if(e.image_tokens!=null){const o=Math.floor(e.image_tokens/n),s=e.image_tokens-o*(n-1);r.imageTokens=t===n-1?s:o}if(e.text_tokens!=null){const o=Math.floor(e.text_tokens/n),s=e.text_tokens-o*(n-1);r.textTokens=t===n-1?s:o}return r}i(qh,"distributeTokenDetails");async function ix(e){if(!e)return;if(e.type==="url")return $i(e.url);const t=e.data instanceof Uint8Array?e.data:hn(e.data);return new Blob([t],{type:e.mediaType})}i(ix,"fileToBlob$1");var Uh=Y(()=>K(g({callId:p(),operation:ge("type",[g({type:F("create_file"),path:p(),diff:p()}),g({type:F("delete_file"),path:p()}),g({type:F("update_file"),path:p(),diff:p()})])}))),Zh=Y(()=>K(g({status:se(["completed","failed"]),output:p().optional()}))),ux=It({id:"openai.apply_patch",inputSchema:Uh,outputSchema:Zh}),lx=ux,cx=Y(()=>K(g({code:p().nullish(),containerId:p()}))),dx=Y(()=>K(g({outputs:B(ge("type",[g({type:F("logs"),logs:p()}),g({type:F("image"),url:p()})])).nullish()}))),px=Y(()=>K(g({container:ee([p(),g({fileIds:B(p()).optional()})]).optional()}))),fx=It({id:"openai.code_interpreter",inputSchema:cx,outputSchema:dx}),mx=i((e={})=>fx(e),"codeInterpreter"),Vh=g({key:p(),type:se(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ee([p(),E(),Re(),B(p())])}),Gh=g({type:se(["and","or"]),filters:B(ee([Vh,yi(()=>Gh)]))}),hx=Y(()=>K(g({vectorStoreIds:B(p()),maxNumResults:E().optional(),ranking:g({ranker:p().optional(),scoreThreshold:E().optional()}).optional(),filters:ee([Vh,Gh]).optional()}))),Dx=Y(()=>K(g({queries:B(p()),results:B(g({attributes:be(p(),ut()),fileId:p(),filename:p(),score:E(),text:p()})).nullable()}))),gx=It({id:"openai.file_search",inputSchema:g({}),outputSchema:Dx}),vx=Y(()=>K(g({background:se(["auto","opaque","transparent"]).optional(),inputFidelity:se(["low","high"]).optional(),inputImageMask:g({fileId:p().optional(),imageUrl:p().optional()}).optional(),model:p().optional(),moderation:se(["auto"]).optional(),outputCompression:E().int().min(0).max(100).optional(),outputFormat:se(["png","jpeg","webp"]).optional(),partialImages:E().int().min(0).max(3).optional(),quality:se(["auto","low","medium","high"]).optional(),size:se(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),yx=Y(()=>K(g({}))),_x=Y(()=>K(g({result:p()}))),bx=It({id:"openai.image_generation",inputSchema:yx,outputSchema:_x}),Cx=i((e={})=>bx(e),"imageGeneration"),Wh=Y(()=>K(g({action:g({type:F("exec"),command:B(p()),timeoutMs:E().optional(),user:p().optional(),workingDirectory:p().optional(),env:be(p(),p()).optional()})}))),Hh=Y(()=>K(g({output:p()}))),wx=It({id:"openai.local_shell",inputSchema:Wh,outputSchema:Hh}),Jh=Y(()=>K(g({action:g({commands:B(p()),timeoutMs:E().optional(),maxOutputLength:E().optional()})}))),cu=Y(()=>K(g({output:B(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:F("timeout")}),g({type:F("exit"),exitCode:E()})])}))}))),Fx=B(ge("type",[g({type:F("skillReference"),skillId:p(),version:p().optional()}),g({type:F("inline"),name:p(),description:p(),source:g({type:F("base64"),mediaType:F("application/zip"),data:p()})})])).optional(),Ex=Y(()=>K(g({environment:ee([g({type:F("containerAuto"),fileIds:B(p()).optional(),memoryLimit:se(["1g","4g","16g","64g"]).optional(),networkPolicy:ge("type",[g({type:F("disabled")}),g({type:F("allowlist"),allowedDomains:B(p()),domainSecrets:B(g({domain:p(),name:p(),value:p()})).optional()})]).optional(),skills:Fx}),g({type:F("containerReference"),containerId:p()}),g({type:F("local").optional(),skills:B(g({name:p(),description:p(),path:p()})).optional()})]).optional()}))),xx=It({id:"openai.shell",inputSchema:Jh,outputSchema:cu}),kx=Y(()=>K(g({externalWebAccess:Re().optional(),filters:g({allowedDomains:B(p()).optional()}).optional(),searchContextSize:se(["low","medium","high"]).optional(),userLocation:g({type:F("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),Ix=Y(()=>K(g({}))),Ax=Y(()=>K(g({action:ge("type",[g({type:F("search"),query:p().optional()}),g({type:F("openPage"),url:p().nullish()}),g({type:F("findInPage"),url:p().nullish(),pattern:p().nullish()})]),sources:B(ge("type",[g({type:F("url"),url:p()}),g({type:F("api"),name:p()})])).optional()}))),$x=It({id:"openai.web_search",inputSchema:Ix,outputSchema:Ax}),Tx=i((e={})=>$x(e),"webSearch"),Sx=Y(()=>K(g({searchContextSize:se(["low","medium","high"]).optional(),userLocation:g({type:F("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),Bx=Y(()=>K(g({}))),Ox=Y(()=>K(g({action:ge("type",[g({type:F("search"),query:p().optional()}),g({type:F("openPage"),url:p().nullish()}),g({type:F("findInPage"),url:p().nullish(),pattern:p().nullish()})])}))),Rx=It({id:"openai.web_search_preview",inputSchema:Bx,outputSchema:Ox}),du=yi(()=>ee([p(),E(),Re(),Wp(),B(du),be(p(),du)])),Nx=Y(()=>K(g({serverLabel:p(),allowedTools:ee([B(p()),g({readOnly:Re().optional(),toolNames:B(p()).optional()})]).optional(),authorization:p().optional(),connectorId:p().optional(),headers:be(p(),p()).optional(),requireApproval:ee([se(["always","never"]),g({never:g({toolNames:B(p()).optional()}).optional()})]).optional(),serverDescription:p().optional(),serverUrl:p().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),Px=Y(()=>K(g({}))),Mx=Y(()=>K(g({type:F("call"),serverLabel:p(),name:p(),arguments:p(),output:p().nullish(),error:ee([p(),du]).optional()}))),jx=It({id:"openai.mcp",inputSchema:Px,outputSchema:Mx}),zx=i(e=>jx(e),"mcp"),Lx={applyPatch:lx,codeInterpreter:mx,fileSearch:gx,imageGeneration:Cx,localShell:wx,shell:xx,webSearchPreview:Rx,webSearch:Tx,mcp:zx};function Kh(e){var t,n,r,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=e.input_tokens,a=e.output_tokens,u=(n=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?n:0,l=(o=(r=e.output_tokens_details)==null?void 0:r.reasoning_tokens)!=null?o:0;return{inputTokens:{total:s,noCache:s-u,cacheRead:u,cacheWrite:void 0},outputTokens:{total:a,text:a-l,reasoning:l},raw:e}}i(Kh,"convertOpenAIResponsesUsage");function Yh(e,t){return t?t.some(n=>e.startsWith(n)):!1}i(Yh,"isFileId");async function qx({prompt:e,toolNameMapping:t,systemMessageMode:n,providerOptionsName:r,fileIdPrefixes:o,store:s,hasConversation:a=!1,hasLocalShellTool:u=!1,hasShellTool:l=!1,hasApplyPatchTool:c=!1}){var d,f,h,D,m,v,y,b,w,C,x,T,O;const $=[],I=[],re=new Set;for(const{role:k,content:X}of e)switch(k){case"system":{switch(n){case"system":{$.push({role:"system",content:X});break}case"developer":{$.push({role:"developer",content:X});break}case"remove":{I.push({type:"other",message:"system messages are removed for this model"});break}default:{const S=n;throw new Error(`Unsupported system message mode: ${S}`)}}break}case"user":{$.push({role:"user",content:X.map((S,j)=>{var z,Z,N;switch(S.type){case"text":return{type:"input_text",text:S.text};case"file":if(S.mediaType.startsWith("image/")){const J=S.mediaType==="image/*"?"image/jpeg":S.mediaType;return{type:"input_image",...S.data instanceof URL?{image_url:S.data.toString()}:typeof S.data=="string"&&Yh(S.data,o)?{file_id:S.data}:{image_url:`data:${J};base64,${zt(S.data)}`},detail:(Z=(z=S.providerOptions)==null?void 0:z[r])==null?void 0:Z.imageDetail}}else{if(S.mediaType==="application/pdf")return S.data instanceof URL?{type:"input_file",file_url:S.data.toString()}:{type:"input_file",...typeof S.data=="string"&&Yh(S.data,o)?{file_id:S.data}:{filename:(N=S.filename)!=null?N:`part-${j}.pdf`,file_data:`data:application/pdf;base64,${zt(S.data)}`}};throw new Qe({functionality:`file part media type ${S.mediaType}`})}}})});break}case"assistant":{const S={};for(const j of X)switch(j.type){case"text":{const z=(f=(d=j.providerOptions)==null?void 0:d[r])==null?void 0:f.itemId;if(a&&z!=null)break;if(s&&z!=null){$.push({type:"item_reference",id:z});break}$.push({role:"assistant",content:[{type:"output_text",text:j.text}],id:z});break}case"tool-call":{const z=(y=(D=(h=j.providerOptions)==null?void 0:h[r])==null?void 0:D.itemId)!=null?y:(v=(m=j.providerMetadata)==null?void 0:m[r])==null?void 0:v.itemId;if(a&&z!=null)break;if(j.providerExecuted){s&&z!=null&&$.push({type:"item_reference",id:z});break}if(s&&z!=null){$.push({type:"item_reference",id:z});break}const Z=t.toProviderToolName(j.toolName);if(u&&Z==="local_shell"){const N=await rt({value:j.input,schema:Wh});$.push({type:"local_shell_call",call_id:j.toolCallId,id:z,action:{type:"exec",command:N.action.command,timeout_ms:N.action.timeoutMs,user:N.action.user,working_directory:N.action.workingDirectory,env:N.action.env}});break}if(l&&Z==="shell"){const N=await rt({value:j.input,schema:Jh});$.push({type:"shell_call",call_id:j.toolCallId,id:z,status:"completed",action:{commands:N.action.commands,timeout_ms:N.action.timeoutMs,max_output_length:N.action.maxOutputLength}});break}if(c&&Z==="apply_patch"){const N=await rt({value:j.input,schema:Uh});$.push({type:"apply_patch_call",call_id:N.callId,id:z,status:"completed",operation:N.operation});break}$.push({type:"function_call",call_id:j.toolCallId,name:Z,arguments:JSON.stringify(j.input),id:z});break}case"tool-result":{if(j.output.type==="execution-denied"||j.output.type==="json"&&typeof j.output.value=="object"&&j.output.value!=null&&"type"in j.output.value&&j.output.value.type==="execution-denied"||a)break;const z=t.toProviderToolName(j.toolName);if(l&&z==="shell"){if(j.output.type==="json"){const Z=await rt({value:j.output.value,schema:cu});$.push({type:"shell_call_output",call_id:j.toolCallId,output:Z.output.map(N=>({stdout:N.stdout,stderr:N.stderr,outcome:N.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:N.outcome.exitCode}}))})}break}if(s){const Z=(C=(w=(b=j.providerOptions)==null?void 0:b[r])==null?void 0:w.itemId)!=null?C:j.toolCallId;$.push({type:"item_reference",id:Z})}else I.push({type:"other",message:`Results for OpenAI tool ${j.toolName} are not sent to the API when store is false`});break}case"reasoning":{const z=await tt({provider:r,providerOptions:j.providerOptions,schema:Ux}),Z=z?.itemId;if(a&&Z!=null)break;if(Z!=null){const N=S[Z];if(s)N===void 0&&($.push({type:"item_reference",id:Z}),S[Z]={type:"reasoning",id:Z,summary:[]});else{const J=[];j.text.length>0?J.push({type:"summary_text",text:j.text}):N!==void 0&&I.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(j)}.`}),N===void 0?(S[Z]={type:"reasoning",id:Z,encrypted_content:z?.reasoningEncryptedContent,summary:J},$.push(S[Z])):(N.summary.push(...J),z?.reasoningEncryptedContent!=null&&(N.encrypted_content=z.reasoningEncryptedContent))}}else I.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(j)}.`});break}}break}case"tool":{for(const S of X){if(S.type==="tool-approval-response"){const N=S;if(re.has(N.approvalId))continue;re.add(N.approvalId),s&&$.push({type:"item_reference",id:N.approvalId}),$.push({type:"mcp_approval_response",approval_request_id:N.approvalId,approve:N.approved});continue}const j=S.output;if(j.type==="execution-denied"&&((T=(x=j.providerOptions)==null?void 0:x.openai)==null?void 0:T.approvalId))continue;const z=t.toProviderToolName(S.toolName);if(u&&z==="local_shell"&&j.type==="json"){const N=await rt({value:j.value,schema:Hh});$.push({type:"local_shell_call_output",call_id:S.toolCallId,output:N.output});continue}if(l&&z==="shell"&&j.type==="json"){const N=await rt({value:j.value,schema:cu});$.push({type:"shell_call_output",call_id:S.toolCallId,output:N.output.map(J=>({stdout:J.stdout,stderr:J.stderr,outcome:J.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:J.outcome.exitCode}}))});continue}if(c&&S.toolName==="apply_patch"&&j.type==="json"){const N=await rt({value:j.value,schema:Zh});$.push({type:"apply_patch_call_output",call_id:S.toolCallId,status:N.status,output:N.output});continue}let Z;switch(j.type){case"text":case"error-text":Z=j.value;break;case"execution-denied":Z=(O=j.reason)!=null?O:"Tool execution denied.";break;case"json":case"error-json":Z=JSON.stringify(j.value);break;case"content":Z=j.value.map(N=>{var J;switch(N.type){case"text":return{type:"input_text",text:N.text};case"image-data":return{type:"input_image",image_url:`data:${N.mediaType};base64,${N.data}`};case"image-url":return{type:"input_image",image_url:N.url};case"file-data":return{type:"input_file",filename:(J=N.filename)!=null?J:"data",file_data:`data:${N.mediaType};base64,${N.data}`};default:{I.push({type:"other",message:`unsupported tool content part type: ${N.type}`});return}}}).filter(PF);break}$.push({type:"function_call_output",call_id:S.toolCallId,output:Z})}break}default:{const S=k;throw new Error(`Unsupported role: ${S}`)}}return{input:$,warnings:I}}i(qx,"convertToOpenAIResponsesInput");var Ux=g({itemId:p().nullish(),reasoningEncryptedContent:p().nullish()});function Xh({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"other"}}i(Xh,"mapOpenAIResponseFinishReason");var Zx=Y(()=>K(ee([g({type:F("response.output_text.delta"),item_id:p(),delta:p(),logprobs:B(g({token:p(),logprob:E(),top_logprobs:B(g({token:p(),logprob:E()}))})).nullish()}),g({type:se(["response.completed","response.incomplete"]),response:g({incomplete_details:g({reason:p()}).nullish(),usage:g({input_tokens:E(),input_tokens_details:g({cached_tokens:E().nullish()}).nullish(),output_tokens:E(),output_tokens_details:g({reasoning_tokens:E().nullish()}).nullish()}),service_tier:p().nullish()})}),g({type:F("response.created"),response:g({id:p(),created_at:E(),model:p(),service_tier:p().nullish()})}),g({type:F("response.output_item.added"),output_index:E(),item:ge("type",[g({type:F("message"),id:p()}),g({type:F("reasoning"),id:p(),encrypted_content:p().nullish()}),g({type:F("function_call"),id:p(),call_id:p(),name:p(),arguments:p()}),g({type:F("web_search_call"),id:p(),status:p()}),g({type:F("computer_call"),id:p(),status:p()}),g({type:F("file_search_call"),id:p()}),g({type:F("image_generation_call"),id:p()}),g({type:F("code_interpreter_call"),id:p(),container_id:p(),code:p().nullable(),outputs:B(ge("type",[g({type:F("logs"),logs:p()}),g({type:F("image"),url:p()})])).nullable(),status:p()}),g({type:F("mcp_call"),id:p(),status:p(),approval_request_id:p().nullish()}),g({type:F("mcp_list_tools"),id:p()}),g({type:F("mcp_approval_request"),id:p()}),g({type:F("apply_patch_call"),id:p(),call_id:p(),status:se(["in_progress","completed"]),operation:ge("type",[g({type:F("create_file"),path:p(),diff:p()}),g({type:F("delete_file"),path:p()}),g({type:F("update_file"),path:p(),diff:p()})])}),g({type:F("shell_call"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),action:g({commands:B(p())})}),g({type:F("shell_call_output"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),output:B(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:F("timeout")}),g({type:F("exit"),exit_code:E()})])}))})])}),g({type:F("response.output_item.done"),output_index:E(),item:ge("type",[g({type:F("message"),id:p()}),g({type:F("reasoning"),id:p(),encrypted_content:p().nullish()}),g({type:F("function_call"),id:p(),call_id:p(),name:p(),arguments:p(),status:F("completed")}),g({type:F("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:B(ge("type",[g({type:F("logs"),logs:p()}),g({type:F("image"),url:p()})])).nullable()}),g({type:F("image_generation_call"),id:p(),result:p()}),g({type:F("web_search_call"),id:p(),status:p(),action:ge("type",[g({type:F("search"),query:p().nullish(),sources:B(ge("type",[g({type:F("url"),url:p()}),g({type:F("api"),name:p()})])).nullish()}),g({type:F("open_page"),url:p().nullish()}),g({type:F("find_in_page"),url:p().nullish(),pattern:p().nullish()})])}),g({type:F("file_search_call"),id:p(),queries:B(p()),results:B(g({attributes:be(p(),ee([p(),E(),Re()])),file_id:p(),filename:p(),score:E(),text:p()})).nullish()}),g({type:F("local_shell_call"),id:p(),call_id:p(),action:g({type:F("exec"),command:B(p()),timeout_ms:E().optional(),user:p().optional(),working_directory:p().optional(),env:be(p(),p()).optional()})}),g({type:F("computer_call"),id:p(),status:F("completed")}),g({type:F("mcp_call"),id:p(),status:p(),arguments:p(),name:p(),server_label:p(),output:p().nullish(),error:ee([p(),g({type:p().optional(),code:ee([E(),p()]).optional(),message:p().optional()}).loose()]).nullish(),approval_request_id:p().nullish()}),g({type:F("mcp_list_tools"),id:p(),server_label:p(),tools:B(g({name:p(),description:p().optional(),input_schema:et(),annotations:be(p(),ut()).optional()})),error:ee([p(),g({type:p().optional(),code:ee([E(),p()]).optional(),message:p().optional()}).loose()]).optional()}),g({type:F("mcp_approval_request"),id:p(),server_label:p(),name:p(),arguments:p(),approval_request_id:p().optional()}),g({type:F("apply_patch_call"),id:p(),call_id:p(),status:se(["in_progress","completed"]),operation:ge("type",[g({type:F("create_file"),path:p(),diff:p()}),g({type:F("delete_file"),path:p()}),g({type:F("update_file"),path:p(),diff:p()})])}),g({type:F("shell_call"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),action:g({commands:B(p())})}),g({type:F("shell_call_output"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),output:B(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:F("timeout")}),g({type:F("exit"),exit_code:E()})])}))})])}),g({type:F("response.function_call_arguments.delta"),item_id:p(),output_index:E(),delta:p()}),g({type:F("response.image_generation_call.partial_image"),item_id:p(),output_index:E(),partial_image_b64:p()}),g({type:F("response.code_interpreter_call_code.delta"),item_id:p(),output_index:E(),delta:p()}),g({type:F("response.code_interpreter_call_code.done"),item_id:p(),output_index:E(),code:p()}),g({type:F("response.output_text.annotation.added"),annotation:ge("type",[g({type:F("url_citation"),start_index:E(),end_index:E(),url:p(),title:p()}),g({type:F("file_citation"),file_id:p(),filename:p(),index:E()}),g({type:F("container_file_citation"),container_id:p(),file_id:p(),filename:p(),start_index:E(),end_index:E()}),g({type:F("file_path"),file_id:p(),index:E()})])}),g({type:F("response.reasoning_summary_part.added"),item_id:p(),summary_index:E()}),g({type:F("response.reasoning_summary_text.delta"),item_id:p(),summary_index:E(),delta:p()}),g({type:F("response.reasoning_summary_part.done"),item_id:p(),summary_index:E()}),g({type:F("response.apply_patch_call_operation_diff.delta"),item_id:p(),output_index:E(),delta:p(),obfuscation:p().nullish()}),g({type:F("response.apply_patch_call_operation_diff.done"),item_id:p(),output_index:E(),diff:p()}),g({type:F("error"),sequence_number:E(),error:g({type:p(),code:p(),message:p(),param:p().nullish()})}),g({type:p()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),Vx=Y(()=>K(g({id:p().optional(),created_at:E().optional(),error:g({message:p(),type:p(),param:p().nullish(),code:p()}).nullish(),model:p().optional(),output:B(ge("type",[g({type:F("message"),role:F("assistant"),id:p(),content:B(g({type:F("output_text"),text:p(),logprobs:B(g({token:p(),logprob:E(),top_logprobs:B(g({token:p(),logprob:E()}))})).nullish(),annotations:B(ge("type",[g({type:F("url_citation"),start_index:E(),end_index:E(),url:p(),title:p()}),g({type:F("file_citation"),file_id:p(),filename:p(),index:E()}),g({type:F("container_file_citation"),container_id:p(),file_id:p(),filename:p(),start_index:E(),end_index:E()}),g({type:F("file_path"),file_id:p(),index:E()})]))}))}),g({type:F("web_search_call"),id:p(),status:p(),action:ge("type",[g({type:F("search"),query:p().nullish(),sources:B(ge("type",[g({type:F("url"),url:p()}),g({type:F("api"),name:p()})])).nullish()}),g({type:F("open_page"),url:p().nullish()}),g({type:F("find_in_page"),url:p().nullish(),pattern:p().nullish()})])}),g({type:F("file_search_call"),id:p(),queries:B(p()),results:B(g({attributes:be(p(),ee([p(),E(),Re()])),file_id:p(),filename:p(),score:E(),text:p()})).nullish()}),g({type:F("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:B(ge("type",[g({type:F("logs"),logs:p()}),g({type:F("image"),url:p()})])).nullable()}),g({type:F("image_generation_call"),id:p(),result:p()}),g({type:F("local_shell_call"),id:p(),call_id:p(),action:g({type:F("exec"),command:B(p()),timeout_ms:E().optional(),user:p().optional(),working_directory:p().optional(),env:be(p(),p()).optional()})}),g({type:F("function_call"),call_id:p(),name:p(),arguments:p(),id:p()}),g({type:F("computer_call"),id:p(),status:p().optional()}),g({type:F("reasoning"),id:p(),encrypted_content:p().nullish(),summary:B(g({type:F("summary_text"),text:p()}))}),g({type:F("mcp_call"),id:p(),status:p(),arguments:p(),name:p(),server_label:p(),output:p().nullish(),error:ee([p(),g({type:p().optional(),code:ee([E(),p()]).optional(),message:p().optional()}).loose()]).nullish(),approval_request_id:p().nullish()}),g({type:F("mcp_list_tools"),id:p(),server_label:p(),tools:B(g({name:p(),description:p().optional(),input_schema:et(),annotations:be(p(),ut()).optional()})),error:ee([p(),g({type:p().optional(),code:ee([E(),p()]).optional(),message:p().optional()}).loose()]).optional()}),g({type:F("mcp_approval_request"),id:p(),server_label:p(),name:p(),arguments:p(),approval_request_id:p().optional()}),g({type:F("apply_patch_call"),id:p(),call_id:p(),status:se(["in_progress","completed"]),operation:ge("type",[g({type:F("create_file"),path:p(),diff:p()}),g({type:F("delete_file"),path:p()}),g({type:F("update_file"),path:p(),diff:p()})])}),g({type:F("shell_call"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),action:g({commands:B(p())})}),g({type:F("shell_call_output"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),output:B(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:F("timeout")}),g({type:F("exit"),exit_code:E()})])}))})])).optional(),service_tier:p().nullish(),incomplete_details:g({reason:p()}).nullish(),usage:g({input_tokens:E(),input_tokens_details:g({cached_tokens:E().nullish()}).nullish(),output_tokens:E(),output_tokens_details:g({reasoning_tokens:E().nullish()}).nullish()}).optional()}))),Qh=20,eD=Y(()=>K(g({conversation:p().nullish(),include:B(se(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:p().nullish(),logprobs:ee([Re(),E().min(1).max(Qh)]).optional(),maxToolCalls:E().nullish(),metadata:et().nullish(),parallelToolCalls:Re().nullish(),previousResponseId:p().nullish(),promptCacheKey:p().nullish(),promptCacheRetention:se(["in_memory","24h"]).nullish(),reasoningEffort:p().nullish(),reasoningSummary:p().nullish(),safetyIdentifier:p().nullish(),serviceTier:se(["auto","flex","priority","default"]).nullish(),store:Re().nullish(),strictJsonSchema:Re().nullish(),textVerbosity:se(["low","medium","high"]).nullish(),truncation:se(["auto","disabled"]).nullish(),user:p().nullish(),systemMessageMode:se(["system","developer","remove"]).optional(),forceReasoning:Re().optional()})));async function Gx({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)switch(s.type){case"function":r.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}});break;case"provider":{switch(s.id){case"openai.file_search":{const a=await rt({value:s.args,schema:hx});r.push({type:"file_search",vector_store_ids:a.vectorStoreIds,max_num_results:a.maxNumResults,ranking_options:a.ranking?{ranker:a.ranking.ranker,score_threshold:a.ranking.scoreThreshold}:void 0,filters:a.filters});break}case"openai.local_shell":{r.push({type:"local_shell"});break}case"openai.shell":{const a=await rt({value:s.args,schema:Ex});r.push({type:"shell",...a.environment&&{environment:Wx(a.environment)}});break}case"openai.apply_patch":{r.push({type:"apply_patch"});break}case"openai.web_search_preview":{const a=await rt({value:s.args,schema:Sx});r.push({type:"web_search_preview",search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.web_search":{const a=await rt({value:s.args,schema:kx});r.push({type:"web_search",filters:a.filters!=null?{allowed_domains:a.filters.allowedDomains}:void 0,external_web_access:a.externalWebAccess,search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.code_interpreter":{const a=await rt({value:s.args,schema:px});r.push({type:"code_interpreter",container:a.container==null?{type:"auto",file_ids:void 0}:typeof a.container=="string"?a.container:{type:"auto",file_ids:a.container.fileIds}});break}case"openai.image_generation":{const a=await rt({value:s.args,schema:vx});r.push({type:"image_generation",background:a.background,input_fidelity:a.inputFidelity,input_image_mask:a.inputImageMask?{file_id:a.inputImageMask.fileId,image_url:a.inputImageMask.imageUrl}:void 0,model:a.model,moderation:a.moderation,partial_images:a.partialImages,quality:a.quality,output_compression:a.outputCompression,output_format:a.outputFormat,size:a.size});break}case"openai.mcp":{const a=await rt({value:s.args,schema:Nx}),u=i(d=>({tool_names:d.toolNames}),"mapApprovalFilter"),l=a.requireApproval,c=l==null?void 0:typeof l=="string"?l:l.never!=null?{never:u(l.never)}:void 0;r.push({type:"mcp",server_label:a.serverLabel,allowed_tools:Array.isArray(a.allowedTools)?a.allowedTools:a.allowedTools?{read_only:a.allowedTools.readOnly,tool_names:a.allowedTools.toolNames}:void 0,authorization:a.authorization,connector_id:a.connectorId,headers:a.headers,require_approval:c??"never",server_description:a.serverDescription,server_url:a.serverUrl});break}}break}default:n.push({type:"unsupported",feature:`function tool ${s}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"||t.toolName==="mcp"||t.toolName==="apply_patch"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:n};default:{const s=o;throw new Qe({functionality:`tool choice type: ${s}`})}}}i(Gx,"prepareResponsesTools");function Wx(e){if(e.type==="containerReference")return{type:"container_reference",container_id:e.containerId};if(e.type==="containerAuto"){const n=e;return{type:"container_auto",file_ids:n.fileIds,memory_limit:n.memoryLimit,network_policy:n.networkPolicy==null?void 0:n.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:n.networkPolicy.allowedDomains,domain_secrets:n.networkPolicy.domainSecrets},skills:Hx(n.skills)}}return{type:"local",skills:e.skills}}i(Wx,"mapShellEnvironment");function Hx(e){return e?.map(t=>t.type==="skillReference"?{type:"skill_reference",skill_id:t.skillId,version:t.version}:{type:"inline",name:t.name,description:t.description,source:{type:"base64",media_type:t.source.mediaType,data:t.source.data}})}i(Hx,"mapShellSkills");function tD(e){var t,n;const r={};for(const o of e)if(o.role==="assistant")for(const s of o.content){if(s.type!=="tool-call")continue;const a=(n=(t=s.providerOptions)==null?void 0:t.openai)==null?void 0:n.approvalRequestId;a!=null&&(r[a]=s.toolCallId)}return r}i(tD,"extractApprovalRequestIdToToolCallIdMapping");var Jx=(Or=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=n}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:n,stopSequences:r,topP:o,topK:s,presencePenalty:a,frequencyPenalty:u,seed:l,prompt:c,providerOptions:d,tools:f,toolChoice:h,responseFormat:D}){var m,v,y,b,w,C,x,T,O;const $=[],I=Oh(this.modelId);s!=null&&$.push({type:"unsupported",feature:"topK"}),l!=null&&$.push({type:"unsupported",feature:"seed"}),a!=null&&$.push({type:"unsupported",feature:"presencePenalty"}),u!=null&&$.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&$.push({type:"unsupported",feature:"stopSequences"});const re=this.config.provider.includes("azure")?"azure":"openai";let k=await tt({provider:re,providerOptions:d,schema:eD});k==null&&re!=="openai"&&(k=await tt({provider:"openai",providerOptions:d,schema:eD}));const X=(m=k?.forceReasoning)!=null?m:I.isReasoningModel;k?.conversation&&k?.previousResponseId&&$.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const S=kF({tools:f,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch"}}),{input:j,warnings:z}=await qx({prompt:c,toolNameMapping:S,systemMessageMode:(v=k?.systemMessageMode)!=null?v:X?"developer":I.systemMessageMode,providerOptionsName:re,fileIdPrefixes:this.config.fileIdPrefixes,store:(y=k?.store)!=null?y:!0,hasConversation:k?.conversation!=null,hasLocalShellTool:pe("openai.local_shell"),hasShellTool:pe("openai.shell"),hasApplyPatchTool:pe("openai.apply_patch")});$.push(...z);const Z=(b=k?.strictJsonSchema)!=null?b:!0;let N=k?.include;function J(te){N==null?N=[te]:N.includes(te)||(N=[...N,te])}i(J,"addInclude");function pe(te){return f?.find(Ge=>Ge.type==="provider"&&Ge.id===te)!=null}i(pe,"hasOpenAITool");const oe=typeof k?.logprobs=="number"?k?.logprobs:k?.logprobs===!0?Qh:void 0;oe&&J("message.output_text.logprobs");const de=(w=f?.find(te=>te.type==="provider"&&(te.id==="openai.web_search"||te.id==="openai.web_search_preview")))==null?void 0:w.name;de&&J("web_search_call.action.sources"),pe("openai.code_interpreter")&&J("code_interpreter_call.outputs");const fe=k?.store;fe===!1&&X&&J("reasoning.encrypted_content");const H={model:this.modelId,input:j,temperature:n,top_p:o,max_output_tokens:t,...(D?.type==="json"||k?.textVerbosity)&&{text:{...D?.type==="json"&&{format:D.schema!=null?{type:"json_schema",strict:Z,name:(C=D.name)!=null?C:"response",description:D.description,schema:D.schema}:{type:"json_object"}},...k?.textVerbosity&&{verbosity:k.textVerbosity}}},conversation:k?.conversation,max_tool_calls:k?.maxToolCalls,metadata:k?.metadata,parallel_tool_calls:k?.parallelToolCalls,previous_response_id:k?.previousResponseId,store:fe,user:k?.user,instructions:k?.instructions,service_tier:k?.serviceTier,include:N,prompt_cache_key:k?.promptCacheKey,prompt_cache_retention:k?.promptCacheRetention,safety_identifier:k?.safetyIdentifier,top_logprobs:oe,truncation:k?.truncation,...X&&(k?.reasoningEffort!=null||k?.reasoningSummary!=null)&&{reasoning:{...k?.reasoningEffort!=null&&{effort:k.reasoningEffort},...k?.reasoningSummary!=null&&{summary:k.reasoningSummary}}}};X?k?.reasoningEffort==="none"&&I.supportsNonReasoningParameters||(H.temperature!=null&&(H.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),H.top_p!=null&&(H.top_p=void 0,$.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(k?.reasoningEffort!=null&&$.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),k?.reasoningSummary!=null&&$.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),k?.serviceTier==="flex"&&!I.supportsFlexProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete H.service_tier),k?.serviceTier==="priority"&&!I.supportsPriorityProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete H.service_tier);const{tools:je,toolChoice:xe,toolWarnings:at}=await Gx({tools:f,toolChoice:h}),Ae=(O=(T=(x=f?.find(te=>te.type==="provider"&&te.id==="openai.shell"))==null?void 0:x.args)==null?void 0:T.environment)==null?void 0:O.type,M=Ae==="containerAuto"||Ae==="containerReference";return{webSearchToolName:de,args:{...H,tools:je,tool_choice:xe},warnings:[...$,...at],store:fe,toolNameMapping:S,providerOptionsName:re,isShellProviderExecuted:M}}async doGenerate(t){var n,r,o,s,a,u,l,c,d,f,h,D,m,v,y,b,w,C,x,T,O,$,I,re,k;const{args:X,warnings:S,webSearchToolName:j,toolNameMapping:z,providerOptionsName:Z,isShellProviderExecuted:N}=await this.getArgs(t),J=this.config.url({path:"/responses",modelId:this.modelId}),pe=tD(t.prompt),{responseHeaders:oe,value:de,rawValue:fe}=await qe({url:J,headers:Ne(this.config.headers(),t.headers),body:X,failedResponseHandler:$t,successfulResponseHandler:Ke(Vx),abortSignal:t.abortSignal,fetch:this.config.fetch});if(de.error)throw new Be({message:de.error.message,url:J,requestBodyValues:X,statusCode:400,responseHeaders:oe,responseBody:fe,isRetryable:!1});const H=[],je=[];let xe=!1;for(const M of de.output)switch(M.type){case"reasoning":{M.summary.length===0&&M.summary.push({type:"summary_text",text:""});for(const te of M.summary)H.push({type:"reasoning",text:te.text,providerMetadata:{[Z]:{itemId:M.id,reasoningEncryptedContent:(n=M.encrypted_content)!=null?n:null}}});break}case"image_generation_call":{H.push({type:"tool-call",toolCallId:M.id,toolName:z.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),H.push({type:"tool-result",toolCallId:M.id,toolName:z.toCustomToolName("image_generation"),result:{result:M.result}});break}case"local_shell_call":{H.push({type:"tool-call",toolCallId:M.call_id,toolName:z.toCustomToolName("local_shell"),input:JSON.stringify({action:M.action}),providerMetadata:{[Z]:{itemId:M.id}}});break}case"shell_call":{H.push({type:"tool-call",toolCallId:M.call_id,toolName:z.toCustomToolName("shell"),input:JSON.stringify({action:{commands:M.action.commands}}),...N&&{providerExecuted:!0},providerMetadata:{[Z]:{itemId:M.id}}});break}case"shell_call_output":{H.push({type:"tool-result",toolCallId:M.call_id,toolName:z.toCustomToolName("shell"),result:{output:M.output.map(te=>({stdout:te.stdout,stderr:te.stderr,outcome:te.outcome.type==="exit"?{type:"exit",exitCode:te.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const te of M.content){(o=(r=t.providerOptions)==null?void 0:r[Z])!=null&&o.logprobs&&te.logprobs&&je.push(te.logprobs);const Ge={itemId:M.id,...te.annotations.length>0&&{annotations:te.annotations}};H.push({type:"text",text:te.text,providerMetadata:{[Z]:Ge}});for(const ve of te.annotations)ve.type==="url_citation"?H.push({type:"source",sourceType:"url",id:(u=(a=(s=this.config).generateId)==null?void 0:a.call(s))!=null?u:Ve(),url:ve.url,title:ve.title}):ve.type==="file_citation"?H.push({type:"source",sourceType:"document",id:(d=(c=(l=this.config).generateId)==null?void 0:c.call(l))!=null?d:Ve(),mediaType:"text/plain",title:ve.filename,filename:ve.filename,providerMetadata:{[Z]:{type:ve.type,fileId:ve.file_id,index:ve.index}}}):ve.type==="container_file_citation"?H.push({type:"source",sourceType:"document",id:(D=(h=(f=this.config).generateId)==null?void 0:h.call(f))!=null?D:Ve(),mediaType:"text/plain",title:ve.filename,filename:ve.filename,providerMetadata:{[Z]:{type:ve.type,fileId:ve.file_id,containerId:ve.container_id}}}):ve.type==="file_path"&&H.push({type:"source",sourceType:"document",id:(y=(v=(m=this.config).generateId)==null?void 0:v.call(m))!=null?y:Ve(),mediaType:"application/octet-stream",title:ve.file_id,filename:ve.file_id,providerMetadata:{[Z]:{type:ve.type,fileId:ve.file_id,index:ve.index}}})}break}case"function_call":{xe=!0,H.push({type:"tool-call",toolCallId:M.call_id,toolName:M.name,input:M.arguments,providerMetadata:{[Z]:{itemId:M.id}}});break}case"web_search_call":{H.push({type:"tool-call",toolCallId:M.id,toolName:z.toCustomToolName(j??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),H.push({type:"tool-result",toolCallId:M.id,toolName:z.toCustomToolName(j??"web_search"),result:rD(M.action)});break}case"mcp_call":{const te=M.approval_request_id!=null&&(b=pe[M.approval_request_id])!=null?b:M.id,Ge=`mcp.${M.name}`;H.push({type:"tool-call",toolCallId:te,toolName:Ge,input:M.arguments,providerExecuted:!0,dynamic:!0}),H.push({type:"tool-result",toolCallId:te,toolName:Ge,result:{type:"call",serverLabel:M.server_label,name:M.name,arguments:M.arguments,...M.output!=null?{output:M.output}:{},...M.error!=null?{error:M.error}:{}},providerMetadata:{[Z]:{itemId:M.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const te=(w=M.approval_request_id)!=null?w:M.id,Ge=(T=(x=(C=this.config).generateId)==null?void 0:x.call(C))!=null?T:Ve(),ve=`mcp.${M.name}`;H.push({type:"tool-call",toolCallId:Ge,toolName:ve,input:M.arguments,providerExecuted:!0,dynamic:!0}),H.push({type:"tool-approval-request",approvalId:te,toolCallId:Ge});break}case"computer_call":{H.push({type:"tool-call",toolCallId:M.id,toolName:z.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),H.push({type:"tool-result",toolCallId:M.id,toolName:z.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:M.status||"completed"}});break}case"file_search_call":{H.push({type:"tool-call",toolCallId:M.id,toolName:z.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),H.push({type:"tool-result",toolCallId:M.id,toolName:z.toCustomToolName("file_search"),result:{queries:M.queries,results:($=(O=M.results)==null?void 0:O.map(te=>({attributes:te.attributes,fileId:te.file_id,filename:te.filename,score:te.score,text:te.text})))!=null?$:null}});break}case"code_interpreter_call":{H.push({type:"tool-call",toolCallId:M.id,toolName:z.toCustomToolName("code_interpreter"),input:JSON.stringify({code:M.code,containerId:M.container_id}),providerExecuted:!0}),H.push({type:"tool-result",toolCallId:M.id,toolName:z.toCustomToolName("code_interpreter"),result:{outputs:M.outputs}});break}case"apply_patch_call":{H.push({type:"tool-call",toolCallId:M.call_id,toolName:z.toCustomToolName("apply_patch"),input:JSON.stringify({callId:M.call_id,operation:M.operation}),providerMetadata:{[Z]:{itemId:M.id}}});break}}const at={[Z]:{responseId:de.id,...je.length>0?{logprobs:je}:{},...typeof de.service_tier=="string"?{serviceTier:de.service_tier}:{}}},Ae=de.usage;return{content:H,finishReason:{unified:Xh({finishReason:(I=de.incomplete_details)==null?void 0:I.reason,hasFunctionCall:xe}),raw:(k=(re=de.incomplete_details)==null?void 0:re.reason)!=null?k:void 0},usage:Kh(Ae),request:{body:X},response:{id:de.id,timestamp:new Date(de.created_at*1e3),modelId:de.model,headers:oe,body:fe},providerMetadata:at,warnings:S}}async doStream(t){const{args:n,warnings:r,webSearchToolName:o,toolNameMapping:s,store:a,providerOptionsName:u,isShellProviderExecuted:l}=await this.getArgs(t),{responseHeaders:c,value:d}=await qe({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:{...n,stream:!0},failedResponseHandler:$t,successfulResponseHandler:Vn(Zx),abortSignal:t.abortSignal,fetch:this.config.fetch}),f=this,h=tD(t.prompt),D=new Map;let m={unified:"other",raw:void 0},v;const y=[];let b=null;const w={},C=[];let x=!1;const T={};let O;return{stream:d.pipeThrough(new TransformStream({start($){$.enqueue({type:"stream-start",warnings:r})},transform($,I){var re,k,X,S,j,z,Z,N,J,pe,oe,de,fe,H,je,xe,at,Ae,M,te,Ge,ve,Lr,qr,Ur,Zr,Vr,Gr,Wr,Hr;if(t.includeRawChunks&&I.enqueue({type:"raw",rawValue:$.rawValue}),!$.success){m={unified:"error",raw:void 0},I.enqueue({type:"error",error:$.error});return}const _=$.value;if(nD(_)){if(_.item.type==="function_call")w[_.output_index]={toolName:_.item.name,toolCallId:_.item.call_id},I.enqueue({type:"tool-input-start",id:_.item.call_id,toolName:_.item.name});else if(_.item.type==="web_search_call")w[_.output_index]={toolName:s.toCustomToolName(o??"web_search"),toolCallId:_.item.id},I.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName(o??"web_search"),providerExecuted:!0}),I.enqueue({type:"tool-input-end",id:_.item.id}),I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName(o??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(_.item.type==="computer_call")w[_.output_index]={toolName:s.toCustomToolName("computer_use"),toolCallId:_.item.id},I.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName("computer_use"),providerExecuted:!0});else if(_.item.type==="code_interpreter_call")w[_.output_index]={toolName:s.toCustomToolName("code_interpreter"),toolCallId:_.item.id,codeInterpreter:{containerId:_.item.container_id}},I.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName("code_interpreter"),providerExecuted:!0}),I.enqueue({type:"tool-input-delta",id:_.item.id,delta:`{"containerId":"${_.item.container_id}","code":"`});else if(_.item.type==="file_search_call")I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(_.item.type==="image_generation_call")I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!(_.item.type==="mcp_call"||_.item.type==="mcp_list_tools"||_.item.type==="mcp_approval_request"))if(_.item.type==="apply_patch_call"){const{call_id:q,operation:ze}=_.item;if(w[_.output_index]={toolName:s.toCustomToolName("apply_patch"),toolCallId:q,applyPatch:{hasDiff:ze.type==="delete_file",endEmitted:ze.type==="delete_file"}},I.enqueue({type:"tool-input-start",id:q,toolName:s.toCustomToolName("apply_patch")}),ze.type==="delete_file"){const st=JSON.stringify({callId:q,operation:ze});I.enqueue({type:"tool-input-delta",id:q,delta:st}),I.enqueue({type:"tool-input-end",id:q})}else I.enqueue({type:"tool-input-delta",id:q,delta:`{"callId":"${_n(q)}","operation":{"type":"${_n(ze.type)}","path":"${_n(ze.path)}","diff":"`})}else _.item.type==="shell_call"?w[_.output_index]={toolName:s.toCustomToolName("shell"),toolCallId:_.item.call_id}:_.item.type==="shell_call_output"||(_.item.type==="message"?(C.splice(0,C.length),I.enqueue({type:"text-start",id:_.item.id,providerMetadata:{[u]:{itemId:_.item.id}}})):nD(_)&&_.item.type==="reasoning"&&(T[_.item.id]={encryptedContent:_.item.encrypted_content,summaryParts:{0:"active"}},I.enqueue({type:"reasoning-start",id:`${_.item.id}:0`,providerMetadata:{[u]:{itemId:_.item.id,reasoningEncryptedContent:(re=_.item.encrypted_content)!=null?re:null}}})))}else if(Yx(_)){if(_.item.type==="message")I.enqueue({type:"text-end",id:_.item.id,providerMetadata:{[u]:{itemId:_.item.id,...C.length>0&&{annotations:C}}}});else if(_.item.type==="function_call")w[_.output_index]=void 0,x=!0,I.enqueue({type:"tool-input-end",id:_.item.call_id}),I.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:_.item.name,input:_.item.arguments,providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="web_search_call")w[_.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName(o??"web_search"),result:rD(_.item.action)});else if(_.item.type==="computer_call")w[_.output_index]=void 0,I.enqueue({type:"tool-input-end",id:_.item.id}),I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:_.item.status||"completed"}});else if(_.item.type==="file_search_call")w[_.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("file_search"),result:{queries:_.item.queries,results:(X=(k=_.item.results)==null?void 0:k.map(q=>({attributes:q.attributes,fileId:q.file_id,filename:q.filename,score:q.score,text:q.text})))!=null?X:null}});else if(_.item.type==="code_interpreter_call")w[_.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("code_interpreter"),result:{outputs:_.item.outputs}});else if(_.item.type==="image_generation_call")I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("image_generation"),result:{result:_.item.result}});else if(_.item.type==="mcp_call"){w[_.output_index]=void 0;const q=(S=_.item.approval_request_id)!=null?S:void 0,ze=q!=null&&(z=(j=D.get(q))!=null?j:h[q])!=null?z:_.item.id,st=`mcp.${_.item.name}`;I.enqueue({type:"tool-call",toolCallId:ze,toolName:st,input:_.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-result",toolCallId:ze,toolName:st,result:{type:"call",serverLabel:_.item.server_label,name:_.item.name,arguments:_.item.arguments,..._.item.output!=null?{output:_.item.output}:{},..._.item.error!=null?{error:_.item.error}:{}},providerMetadata:{[u]:{itemId:_.item.id}}})}else if(_.item.type==="mcp_list_tools")w[_.output_index]=void 0;else if(_.item.type==="apply_patch_call"){const q=w[_.output_index];q?.applyPatch&&!q.applyPatch.endEmitted&&_.item.operation.type!=="delete_file"&&(q.applyPatch.hasDiff||I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:_n(_.item.operation.diff)}),I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:q.toolCallId}),q.applyPatch.endEmitted=!0),q&&_.item.status==="completed"&&I.enqueue({type:"tool-call",toolCallId:q.toolCallId,toolName:s.toCustomToolName("apply_patch"),input:JSON.stringify({callId:_.item.call_id,operation:_.item.operation}),providerMetadata:{[u]:{itemId:_.item.id}}}),w[_.output_index]=void 0}else if(_.item.type==="mcp_approval_request"){w[_.output_index]=void 0;const q=(J=(N=(Z=f.config).generateId)==null?void 0:N.call(Z))!=null?J:Ve(),ze=(pe=_.item.approval_request_id)!=null?pe:_.item.id;D.set(ze,q);const st=`mcp.${_.item.name}`;I.enqueue({type:"tool-call",toolCallId:q,toolName:st,input:_.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-approval-request",approvalId:ze,toolCallId:q})}else if(_.item.type==="local_shell_call")w[_.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:s.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:_.item.action.command,timeoutMs:_.item.action.timeout_ms,user:_.item.action.user,workingDirectory:_.item.action.working_directory,env:_.item.action.env}}),providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="shell_call")w[_.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:s.toCustomToolName("shell"),input:JSON.stringify({action:{commands:_.item.action.commands}}),...l&&{providerExecuted:!0},providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="shell_call_output")I.enqueue({type:"tool-result",toolCallId:_.item.call_id,toolName:s.toCustomToolName("shell"),result:{output:_.item.output.map(q=>({stdout:q.stdout,stderr:q.stderr,outcome:q.outcome.type==="exit"?{type:"exit",exitCode:q.outcome.exit_code}:{type:"timeout"}}))}});else if(_.item.type==="reasoning"){const q=T[_.item.id],ze=Object.entries(q.summaryParts).filter(([st,xn])=>xn==="active"||xn==="can-conclude").map(([st])=>st);for(const st of ze)I.enqueue({type:"reasoning-end",id:`${_.item.id}:${st}`,providerMetadata:{[u]:{itemId:_.item.id,reasoningEncryptedContent:(oe=_.item.encrypted_content)!=null?oe:null}}});delete T[_.item.id]}}else if(ek(_)){const q=w[_.output_index];q!=null&&I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:_.delta})}else if(ok(_)){const q=w[_.output_index];q?.applyPatch&&(I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:_n(_.delta)}),q.applyPatch.hasDiff=!0)}else if(ak(_)){const q=w[_.output_index];q?.applyPatch&&!q.applyPatch.endEmitted&&(q.applyPatch.hasDiff||(I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:_n(_.diff)}),q.applyPatch.hasDiff=!0),I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:q.toolCallId}),q.applyPatch.endEmitted=!0)}else if(tk(_))I.enqueue({type:"tool-result",toolCallId:_.item_id,toolName:s.toCustomToolName("image_generation"),result:{result:_.partial_image_b64},preliminary:!0});else if(nk(_)){const q=w[_.output_index];q!=null&&I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:_n(_.delta)})}else if(rk(_)){const q=w[_.output_index];q!=null&&(I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:'"}'}),I.enqueue({type:"tool-input-end",id:q.toolCallId}),I.enqueue({type:"tool-call",toolCallId:q.toolCallId,toolName:s.toCustomToolName("code_interpreter"),input:JSON.stringify({code:_.code,containerId:q.codeInterpreter.containerId}),providerExecuted:!0}))}else if(Qx(_))b=_.response.id,I.enqueue({type:"response-metadata",id:_.response.id,timestamp:new Date(_.response.created_at*1e3),modelId:_.response.model});else if(Kx(_))I.enqueue({type:"text-delta",id:_.item_id,delta:_.delta}),(fe=(de=t.providerOptions)==null?void 0:de[u])!=null&&fe.logprobs&&_.logprobs&&y.push(_.logprobs);else if(_.type==="response.reasoning_summary_part.added"){if(_.summary_index>0){const q=T[_.item_id];q.summaryParts[_.summary_index]="active";for(const ze of Object.keys(q.summaryParts))q.summaryParts[ze]==="can-conclude"&&(I.enqueue({type:"reasoning-end",id:`${_.item_id}:${ze}`,providerMetadata:{[u]:{itemId:_.item_id}}}),q.summaryParts[ze]="concluded");I.enqueue({type:"reasoning-start",id:`${_.item_id}:${_.summary_index}`,providerMetadata:{[u]:{itemId:_.item_id,reasoningEncryptedContent:(je=(H=T[_.item_id])==null?void 0:H.encryptedContent)!=null?je:null}}})}}else _.type==="response.reasoning_summary_text.delta"?I.enqueue({type:"reasoning-delta",id:`${_.item_id}:${_.summary_index}`,delta:_.delta,providerMetadata:{[u]:{itemId:_.item_id}}}):_.type==="response.reasoning_summary_part.done"?a?(I.enqueue({type:"reasoning-end",id:`${_.item_id}:${_.summary_index}`,providerMetadata:{[u]:{itemId:_.item_id}}}),T[_.item_id].summaryParts[_.summary_index]="concluded"):T[_.item_id].summaryParts[_.summary_index]="can-conclude":Xx(_)?(m={unified:Xh({finishReason:(xe=_.response.incomplete_details)==null?void 0:xe.reason,hasFunctionCall:x}),raw:(Ae=(at=_.response.incomplete_details)==null?void 0:at.reason)!=null?Ae:void 0},v=_.response.usage,typeof _.response.service_tier=="string"&&(O=_.response.service_tier)):sk(_)?(C.push(_.annotation),_.annotation.type==="url_citation"?I.enqueue({type:"source",sourceType:"url",id:(Ge=(te=(M=f.config).generateId)==null?void 0:te.call(M))!=null?Ge:Ve(),url:_.annotation.url,title:_.annotation.title}):_.annotation.type==="file_citation"?I.enqueue({type:"source",sourceType:"document",id:(qr=(Lr=(ve=f.config).generateId)==null?void 0:Lr.call(ve))!=null?qr:Ve(),mediaType:"text/plain",title:_.annotation.filename,filename:_.annotation.filename,providerMetadata:{[u]:{type:_.annotation.type,fileId:_.annotation.file_id,index:_.annotation.index}}}):_.annotation.type==="container_file_citation"?I.enqueue({type:"source",sourceType:"document",id:(Vr=(Zr=(Ur=f.config).generateId)==null?void 0:Zr.call(Ur))!=null?Vr:Ve(),mediaType:"text/plain",title:_.annotation.filename,filename:_.annotation.filename,providerMetadata:{[u]:{type:_.annotation.type,fileId:_.annotation.file_id,containerId:_.annotation.container_id}}}):_.annotation.type==="file_path"&&I.enqueue({type:"source",sourceType:"document",id:(Hr=(Wr=(Gr=f.config).generateId)==null?void 0:Wr.call(Gr))!=null?Hr:Ve(),mediaType:"application/octet-stream",title:_.annotation.file_id,filename:_.annotation.file_id,providerMetadata:{[u]:{type:_.annotation.type,fileId:_.annotation.file_id,index:_.annotation.index}}})):ik(_)&&I.enqueue({type:"error",error:_})},flush($){const I={[u]:{responseId:b,...y.length>0?{logprobs:y}:{},...O!==void 0?{serviceTier:O}:{}}};$.enqueue({type:"finish",finishReason:m,usage:Kh(v),providerMetadata:I})}})),request:{body:n},response:{headers:c}}}},i(Or,"OpenAIResponsesLanguageModel"),Or);function Kx(e){return e.type==="response.output_text.delta"}i(Kx,"isTextDeltaChunk");function Yx(e){return e.type==="response.output_item.done"}i(Yx,"isResponseOutputItemDoneChunk");function Xx(e){return e.type==="response.completed"||e.type==="response.incomplete"}i(Xx,"isResponseFinishedChunk");function Qx(e){return e.type==="response.created"}i(Qx,"isResponseCreatedChunk");function ek(e){return e.type==="response.function_call_arguments.delta"}i(ek,"isResponseFunctionCallArgumentsDeltaChunk");function tk(e){return e.type==="response.image_generation_call.partial_image"}i(tk,"isResponseImageGenerationCallPartialImageChunk");function nk(e){return e.type==="response.code_interpreter_call_code.delta"}i(nk,"isResponseCodeInterpreterCallCodeDeltaChunk");function rk(e){return e.type==="response.code_interpreter_call_code.done"}i(rk,"isResponseCodeInterpreterCallCodeDoneChunk");function ok(e){return e.type==="response.apply_patch_call_operation_diff.delta"}i(ok,"isResponseApplyPatchCallOperationDiffDeltaChunk");function ak(e){return e.type==="response.apply_patch_call_operation_diff.done"}i(ak,"isResponseApplyPatchCallOperationDiffDoneChunk");function nD(e){return e.type==="response.output_item.added"}i(nD,"isResponseOutputItemAddedChunk");function sk(e){return e.type==="response.output_text.annotation.added"}i(sk,"isResponseAnnotationAddedChunk");function ik(e){return e.type==="error"}i(ik,"isErrorChunk");function rD(e){var t;switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}i(rD,"mapWebSearchOutput");function _n(e){return JSON.stringify(e).slice(1,-1)}i(_n,"escapeJSONDelta");var uk=Y(()=>K(g({instructions:p().nullish(),speed:E().min(.25).max(4).default(1).nullish()}))),lk=(Rr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:t,voice:n="alloy",outputFormat:r="mp3",speed:o,instructions:s,language:a,providerOptions:u}){const l=[],c=await tt({provider:"openai",providerOptions:u,schema:uk}),d={model:this.modelId,input:t,voice:n,response_format:"mp3",speed:o,instructions:s};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?d.response_format=r:l.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),c){const f={};for(const h in f){const D=f[h];D!==void 0&&(d[h]=D)}}return a&&l.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:d,warnings:l}}async doGenerate(t){var n,r,o;const s=(o=(r=(n=this.config._internal)==null?void 0:n.currentDate)==null?void 0:r.call(n))!=null?o:new Date,{requestBody:a,warnings:u}=await this.getArgs(t),{value:l,responseHeaders:c,rawValue:d}=await qe({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:a,failedResponseHandler:$t,successfulResponseHandler:P2(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:l,warnings:u,request:{body:JSON.stringify(a)},response:{timestamp:s,modelId:this.modelId,headers:c,body:d}}}},i(Rr,"OpenAISpeechModel"),Rr),ck=Y(()=>K(g({text:p(),language:p().nullish(),duration:E().nullish(),words:B(g({word:p(),start:E(),end:E()})).nullish(),segments:B(g({id:E(),seek:E(),start:E(),end:E(),text:p(),tokens:B(E()),temperature:E(),avg_logprob:E(),compression_ratio:E(),no_speech_prob:E()})).nullish()}))),dk=Y(()=>K(g({include:B(p()).optional(),language:p().optional(),prompt:p().optional(),temperature:E().min(0).max(1).default(0).optional(),timestampGranularities:B(se(["word","segment"])).default(["segment"]).optional()}))),oD={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},pk=(Nr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:n,providerOptions:r}){const o=[],s=await tt({provider:"openai",providerOptions:r,schema:dk}),a=new FormData,u=t instanceof Uint8Array?new Blob([t]):new Blob([hn(t)]);a.append("model",this.modelId);const l=zF(n);if(a.append("file",new File([u],"audio",{type:n}),`audio.${l}`),s){const c={include:s.include,language:s.language,prompt:s.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:s.temperature,timestamp_granularities:s.timestampGranularities};for(const[d,f]of Object.entries(c))if(f!=null)if(Array.isArray(f))for(const h of f)a.append(`${d}[]`,String(h));else a.append(d,String(f))}return{formData:a,warnings:o}}async doGenerate(t){var n,r,o,s,a,u,l,c;const d=(o=(r=(n=this.config._internal)==null?void 0:n.currentDate)==null?void 0:r.call(n))!=null?o:new Date,{formData:f,warnings:h}=await this.getArgs(t),{value:D,responseHeaders:m,rawValue:v}=await Mi({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),formData:f,failedResponseHandler:$t,successfulResponseHandler:Ke(ck),abortSignal:t.abortSignal,fetch:this.config.fetch}),y=D.language!=null&&D.language in oD?oD[D.language]:void 0;return{text:D.text,segments:(l=(u=(s=D.segments)==null?void 0:s.map(b=>({text:b.text,startSecond:b.start,endSecond:b.end})))!=null?u:(a=D.words)==null?void 0:a.map(b=>({text:b.word,startSecond:b.start,endSecond:b.end})))!=null?l:[],language:y,durationInSeconds:(c=D.duration)!=null?c:void 0,warnings:h,response:{timestamp:d,modelId:this.modelId,headers:m,body:v}}}},i(Nr,"OpenAITranscriptionModel"),Nr),fk="3.0.30";function Va(e={}){var t,n;const r=(t=ji(Co({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(n=e.name)!=null?n:"openai",s=i(()=>Dn({Authorization:`Bearer ${jF({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${fk}`),"getHeaders"),a=i(v=>new J3(v,{provider:`${o}.chat`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createChatModel"),u=i(v=>new Q3(v,{provider:`${o}.completion`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createCompletionModel"),l=i(v=>new nx(v,{provider:`${o}.embedding`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createEmbeddingModel"),c=i(v=>new sx(v,{provider:`${o}.image`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createImageModel"),d=i(v=>new pk(v,{provider:`${o}.transcription`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createTranscriptionModel"),f=i(v=>new lk(v,{provider:`${o}.speech`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createSpeechModel"),h=i(v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return D(v)},"createLanguageModel"),D=i(v=>new Jx(v,{provider:`${o}.responses`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),"createResponsesModel"),m=i(function(v){return h(v)},"provider");return m.specificationVersion="v3",m.languageModel=h,m.chat=a,m.completion=u,m.responses=D,m.embedding=l,m.embeddingModel=l,m.textEmbedding=l,m.textEmbeddingModel=l,m.image=c,m.imageModel=c,m.transcription=d,m.transcriptionModel=d,m.speech=f,m.speechModel=f,m.tools=Lx,m}i(Va,"createOpenAI"),Va();var mk=g({error:g({message:p(),type:p().nullish(),param:et().nullish(),code:ee([p(),E()]).nullish()})}),$o={errorSchema:mk,errorToMessage:i(e=>e.error.message,"errorToMessage")};function aD(e){var t,n,r,o,s,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const u=(t=e.prompt_tokens)!=null?t:0,l=(n=e.completion_tokens)!=null?n:0,c=(o=(r=e.prompt_tokens_details)==null?void 0:r.cached_tokens)!=null?o:0,d=(a=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?a:0;return{inputTokens:{total:u,noCache:u-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-d,reasoning:d},raw:e}}i(aD,"convertOpenAICompatibleChatUsage");function To(e){var t,n;return(n=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?n:{}}i(To,"getOpenAIMetadata");function hk(e){switch(e){case"audio/wav":return"wav";case"audio/mp3":case"audio/mpeg":return"mp3";default:return null}}i(hk,"getAudioFormat");function Dk(e){var t,n,r;const o=[];for(const{role:s,content:a,...u}of e){const l=To({...u});switch(s){case"system":{o.push({role:"system",content:a,...l});break}case"user":{if(a.length===1&&a[0].type==="text"){o.push({role:"user",content:a[0].text,...To(a[0])});break}o.push({role:"user",content:a.map(c=>{var d;const f=To(c);switch(c.type){case"text":return{type:"text",text:c.text,...f};case"file":{if(c.mediaType.startsWith("image/")){const h=c.mediaType==="image/*"?"image/jpeg":c.mediaType;return{type:"image_url",image_url:{url:c.data instanceof URL?c.data.toString():`data:${h};base64,${zt(c.data)}`},...f}}if(c.mediaType.startsWith("audio/")){if(c.data instanceof URL)throw new Qe({functionality:"audio file parts with URLs"});const h=hk(c.mediaType);if(h===null)throw new Qe({functionality:`audio media type ${c.mediaType}`});return{type:"input_audio",input_audio:{data:zt(c.data),format:h},...f}}if(c.mediaType==="application/pdf"){if(c.data instanceof URL)throw new Qe({functionality:"PDF file parts with URLs"});return{type:"file",file:{filename:(d=c.filename)!=null?d:"document.pdf",file_data:`data:application/pdf;base64,${zt(c.data)}`},...f}}if(c.mediaType.startsWith("text/"))return{type:"text",text:c.data instanceof URL?c.data.toString():typeof c.data=="string"?c.data:new TextDecoder().decode(c.data),...f};throw new Qe({functionality:`file part media type ${c.mediaType}`})}}}),...l});break}case"assistant":{let c="",d="";const f=[];for(const h of a){const D=To(h);switch(h.type){case"text":{c+=h.text;break}case"reasoning":{d+=h.text;break}case"tool-call":{const m=(n=(t=h.providerOptions)==null?void 0:t.google)==null?void 0:n.thoughtSignature;f.push({id:h.toolCallId,type:"function",function:{name:h.toolName,arguments:JSON.stringify(h.input)},...D,...m?{extra_content:{google:{thought_signature:String(m)}}}:{}});break}}}o.push({role:"assistant",content:c,...d.length>0?{reasoning_content:d}:{},tool_calls:f.length>0?f:void 0,...l});break}case"tool":{for(const c of a){if(c.type==="tool-approval-response")continue;const d=c.output;let f;switch(d.type){case"text":case"error-text":f=d.value;break;case"execution-denied":f=(r=d.reason)!=null?r:"Tool execution denied.";break;case"content":case"json":case"error-json":f=JSON.stringify(d.value);break}const h=To(c);o.push({role:"tool",tool_call_id:c.toolCallId,content:f,...h})}break}default:{const c=s;throw new Error(`Unsupported role: ${c}`)}}}return o}i(Dk,"convertToOpenAICompatibleChatMessages");function sD({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(sD,"getResponseMetadata");function iD(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(iD,"mapOpenAICompatibleFinishReason");var Ga=g({user:p().optional(),reasoningEffort:p().optional(),textVerbosity:p().optional(),strictJsonSchema:Re().optional()});function gk({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)s.type==="provider"?n.push({type:"unsupported",feature:`provider-defined tool ${s.id}`}):r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=o;throw new Qe({functionality:`tool choice type: ${s}`})}}}i(gk,"prepareTools");var vk=(Pr=class{constructor(t,n){this.specificationVersion="v3";var r,o;this.modelId=t,this.config=n;const s=(r=n.errorStructure)!=null?r:$o;this.chunkSchema=bk(s.errorSchema),this.failedResponseHandler=Dt(s),this.supportsStructuredOutputs=(o=n.supportsStructuredOutputs)!=null?o:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,n,r;return(r=(n=(t=this.config).supportedUrls)==null?void 0:n.call(t))!=null?r:{}}transformRequestBody(t){var n,r,o;return(o=(r=(n=this.config).transformRequestBody)==null?void 0:r.call(n,t))!=null?o:t}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,providerOptions:l,stopSequences:c,responseFormat:d,seed:f,toolChoice:h,tools:D}){var m,v,y,b,w;const C=[],x=await tt({provider:"openai-compatible",providerOptions:l,schema:Ga});x!=null&&C.push({type:"other",message:"The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead."});const T=Object.assign(x??{},(m=await tt({provider:"openaiCompatible",providerOptions:l,schema:Ga}))!=null?m:{},(v=await tt({provider:this.providerOptionsName,providerOptions:l,schema:Ga}))!=null?v:{}),O=(y=T?.strictJsonSchema)!=null?y:!0;s!=null&&C.push({type:"unsupported",feature:"topK"}),d?.type==="json"&&d.schema!=null&&!this.supportsStructuredOutputs&&C.push({type:"unsupported",feature:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:$,toolChoice:I,toolWarnings:re}=gk({tools:D,toolChoice:h});return{args:{model:this.modelId,user:T.user,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,response_format:d?.type==="json"?this.supportsStructuredOutputs===!0&&d.schema!=null?{type:"json_schema",json_schema:{schema:d.schema,strict:O,name:(b=d.name)!=null?b:"response",description:d.description}}:{type:"json_object"}:void 0,stop:c,seed:f,...Object.fromEntries(Object.entries((w=l?.[this.providerOptionsName])!=null?w:{}).filter(([k])=>!Object.keys(Ga.shape).includes(k))),reasoning_effort:T.reasoningEffort,verbosity:T.textVerbosity,messages:Dk(t),tools:$,tool_choice:I},warnings:[...C,...re]}}async doGenerate(t){var n,r,o,s,a,u,l,c;const{args:d,warnings:f}=await this.getArgs({...t}),h=this.transformRequestBody(d),D=JSON.stringify(h),{responseHeaders:m,value:v,rawValue:y}=await qe({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:h,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Ke(yk),abortSignal:t.abortSignal,fetch:this.config.fetch}),b=v.choices[0],w=[],C=b.message.content;C!=null&&C.length>0&&w.push({type:"text",text:C});const x=(n=b.message.reasoning_content)!=null?n:b.message.reasoning;if(x!=null&&x.length>0&&w.push({type:"reasoning",text:x}),b.message.tool_calls!=null)for(const $ of b.message.tool_calls){const I=(o=(r=$.extra_content)==null?void 0:r.google)==null?void 0:o.thought_signature;w.push({type:"tool-call",toolCallId:(s=$.id)!=null?s:Ve(),toolName:$.function.name,input:$.function.arguments,...I?{providerMetadata:{[this.providerOptionsName]:{thoughtSignature:I}}}:{}})}const T={[this.providerOptionsName]:{},...await((u=(a=this.config.metadataExtractor)==null?void 0:a.extractMetadata)==null?void 0:u.call(a,{parsedBody:y}))},O=(l=v.usage)==null?void 0:l.completion_tokens_details;return O?.accepted_prediction_tokens!=null&&(T[this.providerOptionsName].acceptedPredictionTokens=O?.accepted_prediction_tokens),O?.rejected_prediction_tokens!=null&&(T[this.providerOptionsName].rejectedPredictionTokens=O?.rejected_prediction_tokens),{content:w,finishReason:{unified:iD(b.finish_reason),raw:(c=b.finish_reason)!=null?c:void 0},usage:aD(v.usage),providerMetadata:T,request:{body:D},response:{...sD(v),headers:m,body:y},warnings:f}}async doStream(t){var n;const{args:r,warnings:o}=await this.getArgs({...t}),s=this.transformRequestBody({...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0}),a=(n=this.config.metadataExtractor)==null?void 0:n.createStreamExtractor(),{responseHeaders:u,value:l}=await qe({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:s,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Vn(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=[];let d={unified:"other",raw:void 0},f,h=!0;const D=this.providerOptionsName;let m=!1,v=!1;return{stream:l.pipeThrough(new TransformStream({start(y){y.enqueue({type:"stream-start",warnings:o})},transform(y,b){var w,C,x,T,O,$,I,re,k,X,S,j,z,Z,N,J,pe,oe;if(t.includeRawChunks&&b.enqueue({type:"raw",rawValue:y.rawValue}),!y.success){d={unified:"error",raw:void 0},b.enqueue({type:"error",error:y.error});return}if(a?.processChunk(y.rawValue),"error"in y.value){d={unified:"error",raw:void 0},b.enqueue({type:"error",error:y.value.error.message});return}const de=y.value;h&&(h=!1,b.enqueue({type:"response-metadata",...sD(de)})),de.usage!=null&&(f=de.usage);const fe=de.choices[0];if(fe?.finish_reason!=null&&(d={unified:iD(fe.finish_reason),raw:(w=fe.finish_reason)!=null?w:void 0}),fe?.delta==null)return;const H=fe.delta,je=(C=H.reasoning_content)!=null?C:H.reasoning;if(je&&(m||(b.enqueue({type:"reasoning-start",id:"reasoning-0"}),m=!0),b.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:je})),H.content&&(m&&(b.enqueue({type:"reasoning-end",id:"reasoning-0"}),m=!1),v||(b.enqueue({type:"text-start",id:"txt-0"}),v=!0),b.enqueue({type:"text-delta",id:"txt-0",delta:H.content})),H.tool_calls!=null){m&&(b.enqueue({type:"reasoning-end",id:"reasoning-0"}),m=!1);for(const xe of H.tool_calls){const at=(x=xe.index)!=null?x:c.length;if(c[at]==null){if(xe.id==null)throw new so({data:xe,message:"Expected 'id' to be a string."});if(((T=xe.function)==null?void 0:T.name)==null)throw new so({data:xe,message:"Expected 'function.name' to be a string."});b.enqueue({type:"tool-input-start",id:xe.id,toolName:xe.function.name}),c[at]={id:xe.id,type:"function",function:{name:xe.function.name,arguments:(O=xe.function.arguments)!=null?O:""},hasFinished:!1,thoughtSignature:(re=(I=($=xe.extra_content)==null?void 0:$.google)==null?void 0:I.thought_signature)!=null?re:void 0};const M=c[at];((k=M.function)==null?void 0:k.name)!=null&&((X=M.function)==null?void 0:X.arguments)!=null&&(M.function.arguments.length>0&&b.enqueue({type:"tool-input-delta",id:M.id,delta:M.function.arguments}),ja(M.function.arguments)&&(b.enqueue({type:"tool-input-end",id:M.id}),b.enqueue({type:"tool-call",toolCallId:(S=M.id)!=null?S:Ve(),toolName:M.function.name,input:M.function.arguments,...M.thoughtSignature?{providerMetadata:{[D]:{thoughtSignature:M.thoughtSignature}}}:{}}),M.hasFinished=!0));continue}const Ae=c[at];Ae.hasFinished||(((j=xe.function)==null?void 0:j.arguments)!=null&&(Ae.function.arguments+=(Z=(z=xe.function)==null?void 0:z.arguments)!=null?Z:""),b.enqueue({type:"tool-input-delta",id:Ae.id,delta:(N=xe.function.arguments)!=null?N:""}),((J=Ae.function)==null?void 0:J.name)!=null&&((pe=Ae.function)==null?void 0:pe.arguments)!=null&&ja(Ae.function.arguments)&&(b.enqueue({type:"tool-input-end",id:Ae.id}),b.enqueue({type:"tool-call",toolCallId:(oe=Ae.id)!=null?oe:Ve(),toolName:Ae.function.name,input:Ae.function.arguments,...Ae.thoughtSignature?{providerMetadata:{[D]:{thoughtSignature:Ae.thoughtSignature}}}:{}}),Ae.hasFinished=!0))}}},flush(y){var b,w,C,x,T;m&&y.enqueue({type:"reasoning-end",id:"reasoning-0"}),v&&y.enqueue({type:"text-end",id:"txt-0"});for(const $ of c.filter(I=>!I.hasFinished))y.enqueue({type:"tool-input-end",id:$.id}),y.enqueue({type:"tool-call",toolCallId:(b=$.id)!=null?b:Ve(),toolName:$.function.name,input:$.function.arguments,...$.thoughtSignature?{providerMetadata:{[D]:{thoughtSignature:$.thoughtSignature}}}:{}});const O={[D]:{},...a?.buildMetadata()};((w=f?.completion_tokens_details)==null?void 0:w.accepted_prediction_tokens)!=null&&(O[D].acceptedPredictionTokens=(C=f?.completion_tokens_details)==null?void 0:C.accepted_prediction_tokens),((x=f?.completion_tokens_details)==null?void 0:x.rejected_prediction_tokens)!=null&&(O[D].rejectedPredictionTokens=(T=f?.completion_tokens_details)==null?void 0:T.rejected_prediction_tokens),y.enqueue({type:"finish",finishReason:d,usage:aD(f),providerMetadata:O})}})),request:{body:s},response:{headers:u}}}},i(Pr,"OpenAICompatibleChatLanguageModel"),Pr),uD=gi({prompt_tokens:E().nullish(),completion_tokens:E().nullish(),total_tokens:E().nullish(),prompt_tokens_details:g({cached_tokens:E().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:E().nullish(),accepted_prediction_tokens:E().nullish(),rejected_prediction_tokens:E().nullish()}).nullish()}).nullish(),yk=gi({id:p().nullish(),created:E().nullish(),model:p().nullish(),choices:B(g({message:g({role:F("assistant").nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:B(g({id:p().nullish(),function:g({name:p(),arguments:p()}),extra_content:g({google:g({thought_signature:p().nullish()}).nullish()}).nullish()})).nullish()}),finish_reason:p().nullish()})),usage:uD}),_k=gi({id:p().nullish(),created:E().nullish(),model:p().nullish(),choices:B(g({delta:g({role:se(["assistant"]).nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:B(g({index:E().nullish(),id:p().nullish(),function:g({name:p().nullish(),arguments:p().nullish()}),extra_content:g({google:g({thought_signature:p().nullish()}).nullish()}).nullish()})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:uD}),bk=i(e=>ee([_k,e]),"createOpenAICompatibleChatChunkSchema");function lD(e){var t,n;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const r=(t=e.prompt_tokens)!=null?t:0,o=(n=e.completion_tokens)!=null?n:0;return{inputTokens:{total:r,noCache:r,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:o,text:o,reasoning:void 0},raw:e}}i(lD,"convertOpenAICompatibleCompletionUsage");function Ck({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
163
+ ${t}:`]}}i(X3,"convertToOpenAICompletionPrompt");function Mh({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(Mh,"getResponseMetadata2$1");function jh(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(jh,"mapOpenAIFinishReason2");var Q3=K(()=>J(g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({text:p(),finish_reason:p(),logprobs:g({tokens:S(p()),token_logprobs:S(x()),top_logprobs:S(be(p(),x())).nullish()}).nullish()})),usage:g({prompt_tokens:x(),completion_tokens:x(),total_tokens:x()}).nullish()}))),ex=K(()=>J(ee([g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({text:p(),finish_reason:p().nullish(),index:x(),logprobs:g({tokens:S(p()),token_logprobs:S(x()),top_logprobs:S(be(p(),x())).nullish()}).nullish()})),usage:g({prompt_tokens:x(),completion_tokens:x(),total_tokens:x()}).nullish()}),uu]))),zh=K(()=>J(g({echo:Re().optional(),logitBias:be(p(),x()).optional(),suffix:p().optional(),user:p().optional(),logprobs:ee([Re(),x()]).optional()}))),tx=(Tr=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={},this.modelId=t,this.config=n}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,stopSequences:l,responseFormat:c,tools:d,toolChoice:f,seed:h,providerOptions:D}){const m=[],v={...await tt({provider:"openai",providerOptions:D,schema:zh}),...await tt({provider:this.providerOptionsName,providerOptions:D,schema:zh})};s!=null&&m.push({type:"unsupported",feature:"topK"}),d?.length&&m.push({type:"unsupported",feature:"tools"}),f!=null&&m.push({type:"unsupported",feature:"toolChoice"}),c!=null&&c.type!=="text"&&m.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:y,stopSequences:b}=X3({prompt:t}),C=[...b??[],...l??[]];return{args:{model:this.modelId,echo:v.echo,logit_bias:v.logitBias,logprobs:v?.logprobs===!0?0:v?.logprobs===!1?void 0:v?.logprobs,suffix:v.suffix,user:v.user,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,seed:h,prompt:y,stop:C.length>0?C:void 0},warnings:m}}async doGenerate(t){var n;const{args:r,warnings:o}=await this.getArgs(t),{responseHeaders:s,value:a,rawValue:u}=await qe({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:r,failedResponseHandler:$t,successfulResponseHandler:Ke(Q3),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=a.choices[0],c={openai:{}};return l.logprobs!=null&&(c.openai.logprobs=l.logprobs),{content:[{type:"text",text:l.text}],usage:Ph(a.usage),finishReason:{unified:jh(l.finish_reason),raw:(n=l.finish_reason)!=null?n:void 0},request:{body:r},response:{...Mh(a),headers:s,body:u},providerMetadata:c,warnings:o}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),o={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:s,value:a}=await qe({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:o,failedResponseHandler:$t,successfulResponseHandler:Vn(ex),abortSignal:t.abortSignal,fetch:this.config.fetch});let u={unified:"other",raw:void 0};const l={openai:{}};let c,d=!0;return{stream:a.pipeThrough(new TransformStream({start(f){f.enqueue({type:"stream-start",warnings:r})},transform(f,h){if(t.includeRawChunks&&h.enqueue({type:"raw",rawValue:f.rawValue}),!f.success){u={unified:"error",raw:void 0},h.enqueue({type:"error",error:f.error});return}const D=f.value;if("error"in D){u={unified:"error",raw:void 0},h.enqueue({type:"error",error:D.error});return}d&&(d=!1,h.enqueue({type:"response-metadata",...Mh(D)}),h.enqueue({type:"text-start",id:"0"})),D.usage!=null&&(c=D.usage);const m=D.choices[0];m?.finish_reason!=null&&(u={unified:jh(m.finish_reason),raw:m.finish_reason}),m?.logprobs!=null&&(l.openai.logprobs=m.logprobs),m?.text!=null&&m.text.length>0&&h.enqueue({type:"text-delta",id:"0",delta:m.text})},flush(f){d||f.enqueue({type:"text-end",id:"0"}),f.enqueue({type:"finish",finishReason:u,providerMetadata:l,usage:Ph(c)})}})),request:{body:o},response:{headers:s}}}},i(Tr,"OpenAICompletionLanguageModel"),Tr),nx=K(()=>J(g({dimensions:x().optional(),user:p().optional()}))),rx=K(()=>J(g({data:S(g({embedding:S(x())})),usage:g({prompt_tokens:x()}).nullish()}))),ox=(Sr=class{constructor(t,n){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=n}get provider(){return this.config.provider}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:o}){var s;if(t.length>this.maxEmbeddingsPerCall)throw new tp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const a=(s=await tt({provider:"openai",providerOptions:o,schema:nx}))!=null?s:{},{responseHeaders:u,value:l,rawValue:c}=await qe({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Ne(this.config.headers(),n),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:a.dimensions,user:a.user},failedResponseHandler:$t,successfulResponseHandler:Ke(rx),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.data.map(d=>d.embedding),usage:l.usage?{tokens:l.usage.prompt_tokens}:void 0,response:{headers:u,body:c}}}},i(Sr,"OpenAIEmbeddingModel"),Sr),Lh=K(()=>J(g({created:x().nullish(),data:S(g({b64_json:p(),revised_prompt:p().nullish()})),background:p().nullish(),output_format:p().nullish(),size:p().nullish(),quality:p().nullish(),usage:g({input_tokens:x().nullish(),output_tokens:x().nullish(),total_tokens:x().nullish(),input_tokens_details:g({image_tokens:x().nullish(),text_tokens:x().nullish()}).nullish()}).nullish()}))),ax={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10},sx=["gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function ix(e){return sx.some(t=>e.startsWith(t))}i(ix,"hasDefaultResponseFormat");var ux=(Br=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=ax[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,files:n,mask:r,n:o,size:s,aspectRatio:a,seed:u,providerOptions:l,headers:c,abortSignal:d}){var f,h,D,m,v,y,b,C,F,E,T;const O=[];a!=null&&O.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),u!=null&&O.push({type:"unsupported",feature:"seed"});const $=(D=(h=(f=this.config._internal)==null?void 0:f.currentDate)==null?void 0:h.call(f))!=null?D:new Date;if(n!=null){const{value:k,responseHeaders:re}=await Mi({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:Ne(this.config.headers(),c),formData:cf({model:this.modelId,prompt:t,image:await Promise.all(n.map(B=>B.type==="file"?new Blob([B.data instanceof Uint8Array?new Blob([B.data],{type:B.mediaType}):new Blob([hn(B.data)],{type:B.mediaType})],{type:B.mediaType}):$i(B.url))),mask:r!=null?await lx(r):void 0,n:o,size:s,...(m=l.openai)!=null?m:{}}),failedResponseHandler:$t,successfulResponseHandler:Ke(Lh),abortSignal:d,fetch:this.config.fetch});return{images:k.data.map(B=>B.b64_json),warnings:O,usage:k.usage!=null?{inputTokens:(v=k.usage.input_tokens)!=null?v:void 0,outputTokens:(y=k.usage.output_tokens)!=null?y:void 0,totalTokens:(b=k.usage.total_tokens)!=null?b:void 0}:void 0,response:{timestamp:$,modelId:this.modelId,headers:re},providerMetadata:{openai:{images:k.data.map((B,P)=>{var z,U,R,Y,me,X;return{...B.revised_prompt?{revisedPrompt:B.revised_prompt}:{},created:(z=k.created)!=null?z:void 0,size:(U=k.size)!=null?U:void 0,quality:(R=k.quality)!=null?R:void 0,background:(Y=k.background)!=null?Y:void 0,outputFormat:(me=k.output_format)!=null?me:void 0,...qh((X=k.usage)==null?void 0:X.input_tokens_details,P,k.data.length)}})}}}}const{value:I,responseHeaders:oe}=await qe({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Ne(this.config.headers(),c),body:{model:this.modelId,prompt:t,n:o,size:s,...(C=l.openai)!=null?C:{},...ix(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:$t,successfulResponseHandler:Ke(Lh),abortSignal:d,fetch:this.config.fetch});return{images:I.data.map(k=>k.b64_json),warnings:O,usage:I.usage!=null?{inputTokens:(F=I.usage.input_tokens)!=null?F:void 0,outputTokens:(E=I.usage.output_tokens)!=null?E:void 0,totalTokens:(T=I.usage.total_tokens)!=null?T:void 0}:void 0,response:{timestamp:$,modelId:this.modelId,headers:oe},providerMetadata:{openai:{images:I.data.map((k,re)=>{var B,P,z,U,R,Y;return{...k.revised_prompt?{revisedPrompt:k.revised_prompt}:{},created:(B=I.created)!=null?B:void 0,size:(P=I.size)!=null?P:void 0,quality:(z=I.quality)!=null?z:void 0,background:(U=I.background)!=null?U:void 0,outputFormat:(R=I.output_format)!=null?R:void 0,...qh((Y=I.usage)==null?void 0:Y.input_tokens_details,re,I.data.length)}})}}}}},i(Br,"OpenAIImageModel"),Br);function qh(e,t,n){if(e==null)return{};const r={};if(e.image_tokens!=null){const o=Math.floor(e.image_tokens/n),s=e.image_tokens-o*(n-1);r.imageTokens=t===n-1?s:o}if(e.text_tokens!=null){const o=Math.floor(e.text_tokens/n),s=e.text_tokens-o*(n-1);r.textTokens=t===n-1?s:o}return r}i(qh,"distributeTokenDetails");async function lx(e){if(!e)return;if(e.type==="url")return $i(e.url);const t=e.data instanceof Uint8Array?e.data:hn(e.data);return new Blob([t],{type:e.mediaType})}i(lx,"fileToBlob$1");var Uh=K(()=>J(g({callId:p(),operation:ge("type",[g({type:w("create_file"),path:p(),diff:p()}),g({type:w("delete_file"),path:p()}),g({type:w("update_file"),path:p(),diff:p()})])}))),Zh=K(()=>J(g({status:se(["completed","failed"]),output:p().optional()}))),cx=It({id:"openai.apply_patch",inputSchema:Uh,outputSchema:Zh}),dx=cx,px=K(()=>J(g({code:p().nullish(),containerId:p()}))),fx=K(()=>J(g({outputs:S(ge("type",[g({type:w("logs"),logs:p()}),g({type:w("image"),url:p()})])).nullish()}))),mx=K(()=>J(g({container:ee([p(),g({fileIds:S(p()).optional()})]).optional()}))),hx=It({id:"openai.code_interpreter",inputSchema:px,outputSchema:fx}),Dx=i((e={})=>hx(e),"codeInterpreter"),Vh=g({key:p(),type:se(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ee([p(),x(),Re(),S(p())])}),Gh=g({type:se(["and","or"]),filters:S(ee([Vh,yi(()=>Gh)]))}),gx=K(()=>J(g({vectorStoreIds:S(p()),maxNumResults:x().optional(),ranking:g({ranker:p().optional(),scoreThreshold:x().optional()}).optional(),filters:ee([Vh,Gh]).optional()}))),vx=K(()=>J(g({queries:S(p()),results:S(g({attributes:be(p(),ut()),fileId:p(),filename:p(),score:x(),text:p()})).nullable()}))),yx=It({id:"openai.file_search",inputSchema:g({}),outputSchema:vx}),_x=K(()=>J(g({background:se(["auto","opaque","transparent"]).optional(),inputFidelity:se(["low","high"]).optional(),inputImageMask:g({fileId:p().optional(),imageUrl:p().optional()}).optional(),model:p().optional(),moderation:se(["auto"]).optional(),outputCompression:x().int().min(0).max(100).optional(),outputFormat:se(["png","jpeg","webp"]).optional(),partialImages:x().int().min(0).max(3).optional(),quality:se(["auto","low","medium","high"]).optional(),size:se(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),bx=K(()=>J(g({}))),Cx=K(()=>J(g({result:p()}))),wx=It({id:"openai.image_generation",inputSchema:bx,outputSchema:Cx}),Fx=i((e={})=>wx(e),"imageGeneration"),Wh=K(()=>J(g({action:g({type:w("exec"),command:S(p()),timeoutMs:x().optional(),user:p().optional(),workingDirectory:p().optional(),env:be(p(),p()).optional()})}))),Hh=K(()=>J(g({output:p()}))),Ex=It({id:"openai.local_shell",inputSchema:Wh,outputSchema:Hh}),Jh=K(()=>J(g({action:g({commands:S(p()),timeoutMs:x().optional(),maxOutputLength:x().optional()})}))),cu=K(()=>J(g({output:S(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:w("timeout")}),g({type:w("exit"),exitCode:x()})])}))}))),xx=S(ge("type",[g({type:w("skillReference"),skillId:p(),version:p().optional()}),g({type:w("inline"),name:p(),description:p(),source:g({type:w("base64"),mediaType:w("application/zip"),data:p()})})])).optional(),kx=K(()=>J(g({environment:ee([g({type:w("containerAuto"),fileIds:S(p()).optional(),memoryLimit:se(["1g","4g","16g","64g"]).optional(),networkPolicy:ge("type",[g({type:w("disabled")}),g({type:w("allowlist"),allowedDomains:S(p()),domainSecrets:S(g({domain:p(),name:p(),value:p()})).optional()})]).optional(),skills:xx}),g({type:w("containerReference"),containerId:p()}),g({type:w("local").optional(),skills:S(g({name:p(),description:p(),path:p()})).optional()})]).optional()}))),Ix=It({id:"openai.shell",inputSchema:Jh,outputSchema:cu}),Ax=K(()=>J(g({externalWebAccess:Re().optional(),filters:g({allowedDomains:S(p()).optional()}).optional(),searchContextSize:se(["low","medium","high"]).optional(),userLocation:g({type:w("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),$x=K(()=>J(g({}))),Tx=K(()=>J(g({action:ge("type",[g({type:w("search"),query:p().optional()}),g({type:w("openPage"),url:p().nullish()}),g({type:w("findInPage"),url:p().nullish(),pattern:p().nullish()})]),sources:S(ge("type",[g({type:w("url"),url:p()}),g({type:w("api"),name:p()})])).optional()}))),Sx=It({id:"openai.web_search",inputSchema:$x,outputSchema:Tx}),Bx=i((e={})=>Sx(e),"webSearch"),Ox=K(()=>J(g({searchContextSize:se(["low","medium","high"]).optional(),userLocation:g({type:w("approximate"),country:p().optional(),city:p().optional(),region:p().optional(),timezone:p().optional()}).optional()}))),Rx=K(()=>J(g({}))),Nx=K(()=>J(g({action:ge("type",[g({type:w("search"),query:p().optional()}),g({type:w("openPage"),url:p().nullish()}),g({type:w("findInPage"),url:p().nullish(),pattern:p().nullish()})])}))),Px=It({id:"openai.web_search_preview",inputSchema:Rx,outputSchema:Nx}),du=yi(()=>ee([p(),x(),Re(),Wp(),S(du),be(p(),du)])),Mx=K(()=>J(g({serverLabel:p(),allowedTools:ee([S(p()),g({readOnly:Re().optional(),toolNames:S(p()).optional()})]).optional(),authorization:p().optional(),connectorId:p().optional(),headers:be(p(),p()).optional(),requireApproval:ee([se(["always","never"]),g({never:g({toolNames:S(p()).optional()}).optional()})]).optional(),serverDescription:p().optional(),serverUrl:p().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),jx=K(()=>J(g({}))),zx=K(()=>J(g({type:w("call"),serverLabel:p(),name:p(),arguments:p(),output:p().nullish(),error:ee([p(),du]).optional()}))),Lx=It({id:"openai.mcp",inputSchema:jx,outputSchema:zx}),qx=i(e=>Lx(e),"mcp"),Ux={applyPatch:dx,codeInterpreter:Dx,fileSearch:yx,imageGeneration:Fx,localShell:Ex,shell:Ix,webSearchPreview:Px,webSearch:Bx,mcp:qx};function Kh(e){var t,n,r,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=e.input_tokens,a=e.output_tokens,u=(n=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?n:0,l=(o=(r=e.output_tokens_details)==null?void 0:r.reasoning_tokens)!=null?o:0;return{inputTokens:{total:s,noCache:s-u,cacheRead:u,cacheWrite:void 0},outputTokens:{total:a,text:a-l,reasoning:l},raw:e}}i(Kh,"convertOpenAIResponsesUsage");function Yh(e,t){return t?t.some(n=>e.startsWith(n)):!1}i(Yh,"isFileId");async function Zx({prompt:e,toolNameMapping:t,systemMessageMode:n,providerOptionsName:r,fileIdPrefixes:o,store:s,hasConversation:a=!1,hasLocalShellTool:u=!1,hasShellTool:l=!1,hasApplyPatchTool:c=!1}){var d,f,h,D,m,v,y,b,C,F,E,T,O;const $=[],I=[],oe=new Set;for(const{role:k,content:re}of e)switch(k){case"system":{switch(n){case"system":{$.push({role:"system",content:re});break}case"developer":{$.push({role:"developer",content:re});break}case"remove":{I.push({type:"other",message:"system messages are removed for this model"});break}default:{const B=n;throw new Error(`Unsupported system message mode: ${B}`)}}break}case"user":{$.push({role:"user",content:re.map((B,P)=>{var z,U,R;switch(B.type){case"text":return{type:"input_text",text:B.text};case"file":if(B.mediaType.startsWith("image/")){const Y=B.mediaType==="image/*"?"image/jpeg":B.mediaType;return{type:"input_image",...B.data instanceof URL?{image_url:B.data.toString()}:typeof B.data=="string"&&Yh(B.data,o)?{file_id:B.data}:{image_url:`data:${Y};base64,${zt(B.data)}`},detail:(U=(z=B.providerOptions)==null?void 0:z[r])==null?void 0:U.imageDetail}}else{if(B.mediaType==="application/pdf")return B.data instanceof URL?{type:"input_file",file_url:B.data.toString()}:{type:"input_file",...typeof B.data=="string"&&Yh(B.data,o)?{file_id:B.data}:{filename:(R=B.filename)!=null?R:`part-${P}.pdf`,file_data:`data:application/pdf;base64,${zt(B.data)}`}};throw new Qe({functionality:`file part media type ${B.mediaType}`})}}})});break}case"assistant":{const B={};for(const P of re)switch(P.type){case"text":{const z=(f=(d=P.providerOptions)==null?void 0:d[r])==null?void 0:f.itemId;if(a&&z!=null)break;if(s&&z!=null){$.push({type:"item_reference",id:z});break}$.push({role:"assistant",content:[{type:"output_text",text:P.text}],id:z});break}case"tool-call":{const z=(y=(D=(h=P.providerOptions)==null?void 0:h[r])==null?void 0:D.itemId)!=null?y:(v=(m=P.providerMetadata)==null?void 0:m[r])==null?void 0:v.itemId;if(a&&z!=null)break;if(P.providerExecuted){s&&z!=null&&$.push({type:"item_reference",id:z});break}if(s&&z!=null){$.push({type:"item_reference",id:z});break}const U=t.toProviderToolName(P.toolName);if(u&&U==="local_shell"){const R=await rt({value:P.input,schema:Wh});$.push({type:"local_shell_call",call_id:P.toolCallId,id:z,action:{type:"exec",command:R.action.command,timeout_ms:R.action.timeoutMs,user:R.action.user,working_directory:R.action.workingDirectory,env:R.action.env}});break}if(l&&U==="shell"){const R=await rt({value:P.input,schema:Jh});$.push({type:"shell_call",call_id:P.toolCallId,id:z,status:"completed",action:{commands:R.action.commands,timeout_ms:R.action.timeoutMs,max_output_length:R.action.maxOutputLength}});break}if(c&&U==="apply_patch"){const R=await rt({value:P.input,schema:Uh});$.push({type:"apply_patch_call",call_id:R.callId,id:z,status:"completed",operation:R.operation});break}$.push({type:"function_call",call_id:P.toolCallId,name:U,arguments:JSON.stringify(P.input),id:z});break}case"tool-result":{if(P.output.type==="execution-denied"||P.output.type==="json"&&typeof P.output.value=="object"&&P.output.value!=null&&"type"in P.output.value&&P.output.value.type==="execution-denied"||a)break;const z=t.toProviderToolName(P.toolName);if(l&&z==="shell"){if(P.output.type==="json"){const U=await rt({value:P.output.value,schema:cu});$.push({type:"shell_call_output",call_id:P.toolCallId,output:U.output.map(R=>({stdout:R.stdout,stderr:R.stderr,outcome:R.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:R.outcome.exitCode}}))})}break}if(s){const U=(F=(C=(b=P.providerOptions)==null?void 0:b[r])==null?void 0:C.itemId)!=null?F:P.toolCallId;$.push({type:"item_reference",id:U})}else I.push({type:"other",message:`Results for OpenAI tool ${P.toolName} are not sent to the API when store is false`});break}case"reasoning":{const z=await tt({provider:r,providerOptions:P.providerOptions,schema:Vx}),U=z?.itemId;if(a&&U!=null)break;if(U!=null){const R=B[U];if(s)R===void 0&&($.push({type:"item_reference",id:U}),B[U]={type:"reasoning",id:U,summary:[]});else{const Y=[];P.text.length>0?Y.push({type:"summary_text",text:P.text}):R!==void 0&&I.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(P)}.`}),R===void 0?(B[U]={type:"reasoning",id:U,encrypted_content:z?.reasoningEncryptedContent,summary:Y},$.push(B[U])):(R.summary.push(...Y),z?.reasoningEncryptedContent!=null&&(R.encrypted_content=z.reasoningEncryptedContent))}}else I.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(P)}.`});break}}break}case"tool":{for(const B of re){if(B.type==="tool-approval-response"){const R=B;if(oe.has(R.approvalId))continue;oe.add(R.approvalId),s&&$.push({type:"item_reference",id:R.approvalId}),$.push({type:"mcp_approval_response",approval_request_id:R.approvalId,approve:R.approved});continue}const P=B.output;if(P.type==="execution-denied"&&((T=(E=P.providerOptions)==null?void 0:E.openai)==null?void 0:T.approvalId))continue;const z=t.toProviderToolName(B.toolName);if(u&&z==="local_shell"&&P.type==="json"){const R=await rt({value:P.value,schema:Hh});$.push({type:"local_shell_call_output",call_id:B.toolCallId,output:R.output});continue}if(l&&z==="shell"&&P.type==="json"){const R=await rt({value:P.value,schema:cu});$.push({type:"shell_call_output",call_id:B.toolCallId,output:R.output.map(Y=>({stdout:Y.stdout,stderr:Y.stderr,outcome:Y.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Y.outcome.exitCode}}))});continue}if(c&&B.toolName==="apply_patch"&&P.type==="json"){const R=await rt({value:P.value,schema:Zh});$.push({type:"apply_patch_call_output",call_id:B.toolCallId,status:R.status,output:R.output});continue}let U;switch(P.type){case"text":case"error-text":U=P.value;break;case"execution-denied":U=(O=P.reason)!=null?O:"Tool execution denied.";break;case"json":case"error-json":U=JSON.stringify(P.value);break;case"content":U=P.value.map(R=>{var Y;switch(R.type){case"text":return{type:"input_text",text:R.text};case"image-data":return{type:"input_image",image_url:`data:${R.mediaType};base64,${R.data}`};case"image-url":return{type:"input_image",image_url:R.url};case"file-data":return{type:"input_file",filename:(Y=R.filename)!=null?Y:"data",file_data:`data:${R.mediaType};base64,${R.data}`};default:{I.push({type:"other",message:`unsupported tool content part type: ${R.type}`});return}}}).filter(jF);break}$.push({type:"function_call_output",call_id:B.toolCallId,output:U})}break}default:{const B=k;throw new Error(`Unsupported role: ${B}`)}}return{input:$,warnings:I}}i(Zx,"convertToOpenAIResponsesInput");var Vx=g({itemId:p().nullish(),reasoningEncryptedContent:p().nullish()});function Xh({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"other"}}i(Xh,"mapOpenAIResponseFinishReason");var Gx=K(()=>J(ee([g({type:w("response.output_text.delta"),item_id:p(),delta:p(),logprobs:S(g({token:p(),logprob:x(),top_logprobs:S(g({token:p(),logprob:x()}))})).nullish()}),g({type:se(["response.completed","response.incomplete"]),response:g({incomplete_details:g({reason:p()}).nullish(),usage:g({input_tokens:x(),input_tokens_details:g({cached_tokens:x().nullish()}).nullish(),output_tokens:x(),output_tokens_details:g({reasoning_tokens:x().nullish()}).nullish()}),service_tier:p().nullish()})}),g({type:w("response.created"),response:g({id:p(),created_at:x(),model:p(),service_tier:p().nullish()})}),g({type:w("response.output_item.added"),output_index:x(),item:ge("type",[g({type:w("message"),id:p()}),g({type:w("reasoning"),id:p(),encrypted_content:p().nullish()}),g({type:w("function_call"),id:p(),call_id:p(),name:p(),arguments:p()}),g({type:w("web_search_call"),id:p(),status:p()}),g({type:w("computer_call"),id:p(),status:p()}),g({type:w("file_search_call"),id:p()}),g({type:w("image_generation_call"),id:p()}),g({type:w("code_interpreter_call"),id:p(),container_id:p(),code:p().nullable(),outputs:S(ge("type",[g({type:w("logs"),logs:p()}),g({type:w("image"),url:p()})])).nullable(),status:p()}),g({type:w("mcp_call"),id:p(),status:p(),approval_request_id:p().nullish()}),g({type:w("mcp_list_tools"),id:p()}),g({type:w("mcp_approval_request"),id:p()}),g({type:w("apply_patch_call"),id:p(),call_id:p(),status:se(["in_progress","completed"]),operation:ge("type",[g({type:w("create_file"),path:p(),diff:p()}),g({type:w("delete_file"),path:p()}),g({type:w("update_file"),path:p(),diff:p()})])}),g({type:w("shell_call"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),action:g({commands:S(p())})}),g({type:w("shell_call_output"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),output:S(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:w("timeout")}),g({type:w("exit"),exit_code:x()})])}))})])}),g({type:w("response.output_item.done"),output_index:x(),item:ge("type",[g({type:w("message"),id:p()}),g({type:w("reasoning"),id:p(),encrypted_content:p().nullish()}),g({type:w("function_call"),id:p(),call_id:p(),name:p(),arguments:p(),status:w("completed")}),g({type:w("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:S(ge("type",[g({type:w("logs"),logs:p()}),g({type:w("image"),url:p()})])).nullable()}),g({type:w("image_generation_call"),id:p(),result:p()}),g({type:w("web_search_call"),id:p(),status:p(),action:ge("type",[g({type:w("search"),query:p().nullish(),sources:S(ge("type",[g({type:w("url"),url:p()}),g({type:w("api"),name:p()})])).nullish()}),g({type:w("open_page"),url:p().nullish()}),g({type:w("find_in_page"),url:p().nullish(),pattern:p().nullish()})])}),g({type:w("file_search_call"),id:p(),queries:S(p()),results:S(g({attributes:be(p(),ee([p(),x(),Re()])),file_id:p(),filename:p(),score:x(),text:p()})).nullish()}),g({type:w("local_shell_call"),id:p(),call_id:p(),action:g({type:w("exec"),command:S(p()),timeout_ms:x().optional(),user:p().optional(),working_directory:p().optional(),env:be(p(),p()).optional()})}),g({type:w("computer_call"),id:p(),status:w("completed")}),g({type:w("mcp_call"),id:p(),status:p(),arguments:p(),name:p(),server_label:p(),output:p().nullish(),error:ee([p(),g({type:p().optional(),code:ee([x(),p()]).optional(),message:p().optional()}).loose()]).nullish(),approval_request_id:p().nullish()}),g({type:w("mcp_list_tools"),id:p(),server_label:p(),tools:S(g({name:p(),description:p().optional(),input_schema:et(),annotations:be(p(),ut()).optional()})),error:ee([p(),g({type:p().optional(),code:ee([x(),p()]).optional(),message:p().optional()}).loose()]).optional()}),g({type:w("mcp_approval_request"),id:p(),server_label:p(),name:p(),arguments:p(),approval_request_id:p().optional()}),g({type:w("apply_patch_call"),id:p(),call_id:p(),status:se(["in_progress","completed"]),operation:ge("type",[g({type:w("create_file"),path:p(),diff:p()}),g({type:w("delete_file"),path:p()}),g({type:w("update_file"),path:p(),diff:p()})])}),g({type:w("shell_call"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),action:g({commands:S(p())})}),g({type:w("shell_call_output"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),output:S(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:w("timeout")}),g({type:w("exit"),exit_code:x()})])}))})])}),g({type:w("response.function_call_arguments.delta"),item_id:p(),output_index:x(),delta:p()}),g({type:w("response.image_generation_call.partial_image"),item_id:p(),output_index:x(),partial_image_b64:p()}),g({type:w("response.code_interpreter_call_code.delta"),item_id:p(),output_index:x(),delta:p()}),g({type:w("response.code_interpreter_call_code.done"),item_id:p(),output_index:x(),code:p()}),g({type:w("response.output_text.annotation.added"),annotation:ge("type",[g({type:w("url_citation"),start_index:x(),end_index:x(),url:p(),title:p()}),g({type:w("file_citation"),file_id:p(),filename:p(),index:x()}),g({type:w("container_file_citation"),container_id:p(),file_id:p(),filename:p(),start_index:x(),end_index:x()}),g({type:w("file_path"),file_id:p(),index:x()})])}),g({type:w("response.reasoning_summary_part.added"),item_id:p(),summary_index:x()}),g({type:w("response.reasoning_summary_text.delta"),item_id:p(),summary_index:x(),delta:p()}),g({type:w("response.reasoning_summary_part.done"),item_id:p(),summary_index:x()}),g({type:w("response.apply_patch_call_operation_diff.delta"),item_id:p(),output_index:x(),delta:p(),obfuscation:p().nullish()}),g({type:w("response.apply_patch_call_operation_diff.done"),item_id:p(),output_index:x(),diff:p()}),g({type:w("error"),sequence_number:x(),error:g({type:p(),code:p(),message:p(),param:p().nullish()})}),g({type:p()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),Wx=K(()=>J(g({id:p().optional(),created_at:x().optional(),error:g({message:p(),type:p(),param:p().nullish(),code:p()}).nullish(),model:p().optional(),output:S(ge("type",[g({type:w("message"),role:w("assistant"),id:p(),content:S(g({type:w("output_text"),text:p(),logprobs:S(g({token:p(),logprob:x(),top_logprobs:S(g({token:p(),logprob:x()}))})).nullish(),annotations:S(ge("type",[g({type:w("url_citation"),start_index:x(),end_index:x(),url:p(),title:p()}),g({type:w("file_citation"),file_id:p(),filename:p(),index:x()}),g({type:w("container_file_citation"),container_id:p(),file_id:p(),filename:p(),start_index:x(),end_index:x()}),g({type:w("file_path"),file_id:p(),index:x()})]))}))}),g({type:w("web_search_call"),id:p(),status:p(),action:ge("type",[g({type:w("search"),query:p().nullish(),sources:S(ge("type",[g({type:w("url"),url:p()}),g({type:w("api"),name:p()})])).nullish()}),g({type:w("open_page"),url:p().nullish()}),g({type:w("find_in_page"),url:p().nullish(),pattern:p().nullish()})])}),g({type:w("file_search_call"),id:p(),queries:S(p()),results:S(g({attributes:be(p(),ee([p(),x(),Re()])),file_id:p(),filename:p(),score:x(),text:p()})).nullish()}),g({type:w("code_interpreter_call"),id:p(),code:p().nullable(),container_id:p(),outputs:S(ge("type",[g({type:w("logs"),logs:p()}),g({type:w("image"),url:p()})])).nullable()}),g({type:w("image_generation_call"),id:p(),result:p()}),g({type:w("local_shell_call"),id:p(),call_id:p(),action:g({type:w("exec"),command:S(p()),timeout_ms:x().optional(),user:p().optional(),working_directory:p().optional(),env:be(p(),p()).optional()})}),g({type:w("function_call"),call_id:p(),name:p(),arguments:p(),id:p()}),g({type:w("computer_call"),id:p(),status:p().optional()}),g({type:w("reasoning"),id:p(),encrypted_content:p().nullish(),summary:S(g({type:w("summary_text"),text:p()}))}),g({type:w("mcp_call"),id:p(),status:p(),arguments:p(),name:p(),server_label:p(),output:p().nullish(),error:ee([p(),g({type:p().optional(),code:ee([x(),p()]).optional(),message:p().optional()}).loose()]).nullish(),approval_request_id:p().nullish()}),g({type:w("mcp_list_tools"),id:p(),server_label:p(),tools:S(g({name:p(),description:p().optional(),input_schema:et(),annotations:be(p(),ut()).optional()})),error:ee([p(),g({type:p().optional(),code:ee([x(),p()]).optional(),message:p().optional()}).loose()]).optional()}),g({type:w("mcp_approval_request"),id:p(),server_label:p(),name:p(),arguments:p(),approval_request_id:p().optional()}),g({type:w("apply_patch_call"),id:p(),call_id:p(),status:se(["in_progress","completed"]),operation:ge("type",[g({type:w("create_file"),path:p(),diff:p()}),g({type:w("delete_file"),path:p()}),g({type:w("update_file"),path:p(),diff:p()})])}),g({type:w("shell_call"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),action:g({commands:S(p())})}),g({type:w("shell_call_output"),id:p(),call_id:p(),status:se(["in_progress","completed","incomplete"]),output:S(g({stdout:p(),stderr:p(),outcome:ge("type",[g({type:w("timeout")}),g({type:w("exit"),exit_code:x()})])}))})])).optional(),service_tier:p().nullish(),incomplete_details:g({reason:p()}).nullish(),usage:g({input_tokens:x(),input_tokens_details:g({cached_tokens:x().nullish()}).nullish(),output_tokens:x(),output_tokens_details:g({reasoning_tokens:x().nullish()}).nullish()}).optional()}))),Qh=20,eD=K(()=>J(g({conversation:p().nullish(),include:S(se(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:p().nullish(),logprobs:ee([Re(),x().min(1).max(Qh)]).optional(),maxToolCalls:x().nullish(),metadata:et().nullish(),parallelToolCalls:Re().nullish(),previousResponseId:p().nullish(),promptCacheKey:p().nullish(),promptCacheRetention:se(["in_memory","24h"]).nullish(),reasoningEffort:p().nullish(),reasoningSummary:p().nullish(),safetyIdentifier:p().nullish(),serviceTier:se(["auto","flex","priority","default"]).nullish(),store:Re().nullish(),strictJsonSchema:Re().nullish(),textVerbosity:se(["low","medium","high"]).nullish(),truncation:se(["auto","disabled"]).nullish(),user:p().nullish(),systemMessageMode:se(["system","developer","remove"]).optional(),forceReasoning:Re().optional()})));async function Hx({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)switch(s.type){case"function":r.push({type:"function",name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}});break;case"provider":{switch(s.id){case"openai.file_search":{const a=await rt({value:s.args,schema:gx});r.push({type:"file_search",vector_store_ids:a.vectorStoreIds,max_num_results:a.maxNumResults,ranking_options:a.ranking?{ranker:a.ranking.ranker,score_threshold:a.ranking.scoreThreshold}:void 0,filters:a.filters});break}case"openai.local_shell":{r.push({type:"local_shell"});break}case"openai.shell":{const a=await rt({value:s.args,schema:kx});r.push({type:"shell",...a.environment&&{environment:Jx(a.environment)}});break}case"openai.apply_patch":{r.push({type:"apply_patch"});break}case"openai.web_search_preview":{const a=await rt({value:s.args,schema:Ox});r.push({type:"web_search_preview",search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.web_search":{const a=await rt({value:s.args,schema:Ax});r.push({type:"web_search",filters:a.filters!=null?{allowed_domains:a.filters.allowedDomains}:void 0,external_web_access:a.externalWebAccess,search_context_size:a.searchContextSize,user_location:a.userLocation});break}case"openai.code_interpreter":{const a=await rt({value:s.args,schema:mx});r.push({type:"code_interpreter",container:a.container==null?{type:"auto",file_ids:void 0}:typeof a.container=="string"?a.container:{type:"auto",file_ids:a.container.fileIds}});break}case"openai.image_generation":{const a=await rt({value:s.args,schema:_x});r.push({type:"image_generation",background:a.background,input_fidelity:a.inputFidelity,input_image_mask:a.inputImageMask?{file_id:a.inputImageMask.fileId,image_url:a.inputImageMask.imageUrl}:void 0,model:a.model,moderation:a.moderation,partial_images:a.partialImages,quality:a.quality,output_compression:a.outputCompression,output_format:a.outputFormat,size:a.size});break}case"openai.mcp":{const a=await rt({value:s.args,schema:Mx}),u=i(d=>({tool_names:d.toolNames}),"mapApprovalFilter"),l=a.requireApproval,c=l==null?void 0:typeof l=="string"?l:l.never!=null?{never:u(l.never)}:void 0;r.push({type:"mcp",server_label:a.serverLabel,allowed_tools:Array.isArray(a.allowedTools)?a.allowedTools:a.allowedTools?{read_only:a.allowedTools.readOnly,tool_names:a.allowedTools.toolNames}:void 0,authorization:a.authorization,connector_id:a.connectorId,headers:a.headers,require_approval:c??"never",server_description:a.serverDescription,server_url:a.serverUrl});break}}break}default:n.push({type:"unsupported",feature:`function tool ${s}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"||t.toolName==="mcp"||t.toolName==="apply_patch"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:n};default:{const s=o;throw new Qe({functionality:`tool choice type: ${s}`})}}}i(Hx,"prepareResponsesTools");function Jx(e){if(e.type==="containerReference")return{type:"container_reference",container_id:e.containerId};if(e.type==="containerAuto"){const n=e;return{type:"container_auto",file_ids:n.fileIds,memory_limit:n.memoryLimit,network_policy:n.networkPolicy==null?void 0:n.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:n.networkPolicy.allowedDomains,domain_secrets:n.networkPolicy.domainSecrets},skills:Kx(n.skills)}}return{type:"local",skills:e.skills}}i(Jx,"mapShellEnvironment");function Kx(e){return e?.map(t=>t.type==="skillReference"?{type:"skill_reference",skill_id:t.skillId,version:t.version}:{type:"inline",name:t.name,description:t.description,source:{type:"base64",media_type:t.source.mediaType,data:t.source.data}})}i(Kx,"mapShellSkills");function tD(e){var t,n;const r={};for(const o of e)if(o.role==="assistant")for(const s of o.content){if(s.type!=="tool-call")continue;const a=(n=(t=s.providerOptions)==null?void 0:t.openai)==null?void 0:n.approvalRequestId;a!=null&&(r[a]=s.toolCallId)}return r}i(tD,"extractApprovalRequestIdToToolCallIdMapping");var Yx=(Or=class{constructor(t,n){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=n}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:n,stopSequences:r,topP:o,topK:s,presencePenalty:a,frequencyPenalty:u,seed:l,prompt:c,providerOptions:d,tools:f,toolChoice:h,responseFormat:D}){var m,v,y,b,C,F,E,T,O;const $=[],I=Oh(this.modelId);s!=null&&$.push({type:"unsupported",feature:"topK"}),l!=null&&$.push({type:"unsupported",feature:"seed"}),a!=null&&$.push({type:"unsupported",feature:"presencePenalty"}),u!=null&&$.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&$.push({type:"unsupported",feature:"stopSequences"});const oe=this.config.provider.includes("azure")?"azure":"openai";let k=await tt({provider:oe,providerOptions:d,schema:eD});k==null&&oe!=="openai"&&(k=await tt({provider:"openai",providerOptions:d,schema:eD}));const re=(m=k?.forceReasoning)!=null?m:I.isReasoningModel;k?.conversation&&k?.previousResponseId&&$.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const B=AF({tools:f,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch"}}),{input:P,warnings:z}=await Zx({prompt:c,toolNameMapping:B,systemMessageMode:(v=k?.systemMessageMode)!=null?v:re?"developer":I.systemMessageMode,providerOptionsName:oe,fileIdPrefixes:this.config.fileIdPrefixes,store:(y=k?.store)!=null?y:!0,hasConversation:k?.conversation!=null,hasLocalShellTool:me("openai.local_shell"),hasShellTool:me("openai.shell"),hasApplyPatchTool:me("openai.apply_patch")});$.push(...z);const U=(b=k?.strictJsonSchema)!=null?b:!0;let R=k?.include;function Y(te){R==null?R=[te]:R.includes(te)||(R=[...R,te])}i(Y,"addInclude");function me(te){return f?.find(Ge=>Ge.type==="provider"&&Ge.id===te)!=null}i(me,"hasOpenAITool");const X=typeof k?.logprobs=="number"?k?.logprobs:k?.logprobs===!0?Qh:void 0;X&&Y("message.output_text.logprobs");const de=(C=f?.find(te=>te.type==="provider"&&(te.id==="openai.web_search"||te.id==="openai.web_search_preview")))==null?void 0:C.name;de&&Y("web_search_call.action.sources"),me("openai.code_interpreter")&&Y("code_interpreter_call.outputs");const pe=k?.store;pe===!1&&re&&Y("reasoning.encrypted_content");const H={model:this.modelId,input:P,temperature:n,top_p:o,max_output_tokens:t,...(D?.type==="json"||k?.textVerbosity)&&{text:{...D?.type==="json"&&{format:D.schema!=null?{type:"json_schema",strict:U,name:(F=D.name)!=null?F:"response",description:D.description,schema:D.schema}:{type:"json_object"}},...k?.textVerbosity&&{verbosity:k.textVerbosity}}},conversation:k?.conversation,max_tool_calls:k?.maxToolCalls,metadata:k?.metadata,parallel_tool_calls:k?.parallelToolCalls,previous_response_id:k?.previousResponseId,store:pe,user:k?.user,instructions:k?.instructions,service_tier:k?.serviceTier,include:R,prompt_cache_key:k?.promptCacheKey,prompt_cache_retention:k?.promptCacheRetention,safety_identifier:k?.safetyIdentifier,top_logprobs:X,truncation:k?.truncation,...re&&(k?.reasoningEffort!=null||k?.reasoningSummary!=null)&&{reasoning:{...k?.reasoningEffort!=null&&{effort:k.reasoningEffort},...k?.reasoningSummary!=null&&{summary:k.reasoningSummary}}}};re?k?.reasoningEffort==="none"&&I.supportsNonReasoningParameters||(H.temperature!=null&&(H.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),H.top_p!=null&&(H.top_p=void 0,$.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(k?.reasoningEffort!=null&&$.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),k?.reasoningSummary!=null&&$.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),k?.serviceTier==="flex"&&!I.supportsFlexProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete H.service_tier),k?.serviceTier==="priority"&&!I.supportsPriorityProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete H.service_tier);const{tools:je,toolChoice:xe,toolWarnings:at}=await Hx({tools:f,toolChoice:h}),Ae=(O=(T=(E=f?.find(te=>te.type==="provider"&&te.id==="openai.shell"))==null?void 0:E.args)==null?void 0:T.environment)==null?void 0:O.type,j=Ae==="containerAuto"||Ae==="containerReference";return{webSearchToolName:de,args:{...H,tools:je,tool_choice:xe},warnings:[...$,...at],store:pe,toolNameMapping:B,providerOptionsName:oe,isShellProviderExecuted:j}}async doGenerate(t){var n,r,o,s,a,u,l,c,d,f,h,D,m,v,y,b,C,F,E,T,O,$,I,oe,k;const{args:re,warnings:B,webSearchToolName:P,toolNameMapping:z,providerOptionsName:U,isShellProviderExecuted:R}=await this.getArgs(t),Y=this.config.url({path:"/responses",modelId:this.modelId}),me=tD(t.prompt),{responseHeaders:X,value:de,rawValue:pe}=await qe({url:Y,headers:Ne(this.config.headers(),t.headers),body:re,failedResponseHandler:$t,successfulResponseHandler:Ke(Wx),abortSignal:t.abortSignal,fetch:this.config.fetch});if(de.error)throw new Be({message:de.error.message,url:Y,requestBodyValues:re,statusCode:400,responseHeaders:X,responseBody:pe,isRetryable:!1});const H=[],je=[];let xe=!1;for(const j of de.output)switch(j.type){case"reasoning":{j.summary.length===0&&j.summary.push({type:"summary_text",text:""});for(const te of j.summary)H.push({type:"reasoning",text:te.text,providerMetadata:{[U]:{itemId:j.id,reasoningEncryptedContent:(n=j.encrypted_content)!=null?n:null}}});break}case"image_generation_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName("image_generation"),result:{result:j.result}});break}case"local_shell_call":{H.push({type:"tool-call",toolCallId:j.call_id,toolName:z.toCustomToolName("local_shell"),input:JSON.stringify({action:j.action}),providerMetadata:{[U]:{itemId:j.id}}});break}case"shell_call":{H.push({type:"tool-call",toolCallId:j.call_id,toolName:z.toCustomToolName("shell"),input:JSON.stringify({action:{commands:j.action.commands}}),...R&&{providerExecuted:!0},providerMetadata:{[U]:{itemId:j.id}}});break}case"shell_call_output":{H.push({type:"tool-result",toolCallId:j.call_id,toolName:z.toCustomToolName("shell"),result:{output:j.output.map(te=>({stdout:te.stdout,stderr:te.stderr,outcome:te.outcome.type==="exit"?{type:"exit",exitCode:te.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const te of j.content){(o=(r=t.providerOptions)==null?void 0:r[U])!=null&&o.logprobs&&te.logprobs&&je.push(te.logprobs);const Ge={itemId:j.id,...te.annotations.length>0&&{annotations:te.annotations}};H.push({type:"text",text:te.text,providerMetadata:{[U]:Ge}});for(const ve of te.annotations)ve.type==="url_citation"?H.push({type:"source",sourceType:"url",id:(u=(a=(s=this.config).generateId)==null?void 0:a.call(s))!=null?u:Ve(),url:ve.url,title:ve.title}):ve.type==="file_citation"?H.push({type:"source",sourceType:"document",id:(d=(c=(l=this.config).generateId)==null?void 0:c.call(l))!=null?d:Ve(),mediaType:"text/plain",title:ve.filename,filename:ve.filename,providerMetadata:{[U]:{type:ve.type,fileId:ve.file_id,index:ve.index}}}):ve.type==="container_file_citation"?H.push({type:"source",sourceType:"document",id:(D=(h=(f=this.config).generateId)==null?void 0:h.call(f))!=null?D:Ve(),mediaType:"text/plain",title:ve.filename,filename:ve.filename,providerMetadata:{[U]:{type:ve.type,fileId:ve.file_id,containerId:ve.container_id}}}):ve.type==="file_path"&&H.push({type:"source",sourceType:"document",id:(y=(v=(m=this.config).generateId)==null?void 0:v.call(m))!=null?y:Ve(),mediaType:"application/octet-stream",title:ve.file_id,filename:ve.file_id,providerMetadata:{[U]:{type:ve.type,fileId:ve.file_id,index:ve.index}}})}break}case"function_call":{xe=!0,H.push({type:"tool-call",toolCallId:j.call_id,toolName:j.name,input:j.arguments,providerMetadata:{[U]:{itemId:j.id}}});break}case"web_search_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName(P??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName(P??"web_search"),result:rD(j.action)});break}case"mcp_call":{const te=j.approval_request_id!=null&&(b=me[j.approval_request_id])!=null?b:j.id,Ge=`mcp.${j.name}`;H.push({type:"tool-call",toolCallId:te,toolName:Ge,input:j.arguments,providerExecuted:!0,dynamic:!0}),H.push({type:"tool-result",toolCallId:te,toolName:Ge,result:{type:"call",serverLabel:j.server_label,name:j.name,arguments:j.arguments,...j.output!=null?{output:j.output}:{},...j.error!=null?{error:j.error}:{}},providerMetadata:{[U]:{itemId:j.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const te=(C=j.approval_request_id)!=null?C:j.id,Ge=(T=(E=(F=this.config).generateId)==null?void 0:E.call(F))!=null?T:Ve(),ve=`mcp.${j.name}`;H.push({type:"tool-call",toolCallId:Ge,toolName:ve,input:j.arguments,providerExecuted:!0,dynamic:!0}),H.push({type:"tool-approval-request",approvalId:te,toolCallId:Ge});break}case"computer_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:j.status||"completed"}});break}case"file_search_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName("file_search"),result:{queries:j.queries,results:($=(O=j.results)==null?void 0:O.map(te=>({attributes:te.attributes,fileId:te.file_id,filename:te.filename,score:te.score,text:te.text})))!=null?$:null}});break}case"code_interpreter_call":{H.push({type:"tool-call",toolCallId:j.id,toolName:z.toCustomToolName("code_interpreter"),input:JSON.stringify({code:j.code,containerId:j.container_id}),providerExecuted:!0}),H.push({type:"tool-result",toolCallId:j.id,toolName:z.toCustomToolName("code_interpreter"),result:{outputs:j.outputs}});break}case"apply_patch_call":{H.push({type:"tool-call",toolCallId:j.call_id,toolName:z.toCustomToolName("apply_patch"),input:JSON.stringify({callId:j.call_id,operation:j.operation}),providerMetadata:{[U]:{itemId:j.id}}});break}}const at={[U]:{responseId:de.id,...je.length>0?{logprobs:je}:{},...typeof de.service_tier=="string"?{serviceTier:de.service_tier}:{}}},Ae=de.usage;return{content:H,finishReason:{unified:Xh({finishReason:(I=de.incomplete_details)==null?void 0:I.reason,hasFunctionCall:xe}),raw:(k=(oe=de.incomplete_details)==null?void 0:oe.reason)!=null?k:void 0},usage:Kh(Ae),request:{body:re},response:{id:de.id,timestamp:new Date(de.created_at*1e3),modelId:de.model,headers:X,body:pe},providerMetadata:at,warnings:B}}async doStream(t){const{args:n,warnings:r,webSearchToolName:o,toolNameMapping:s,store:a,providerOptionsName:u,isShellProviderExecuted:l}=await this.getArgs(t),{responseHeaders:c,value:d}=await qe({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:{...n,stream:!0},failedResponseHandler:$t,successfulResponseHandler:Vn(Gx),abortSignal:t.abortSignal,fetch:this.config.fetch}),f=this,h=tD(t.prompt),D=new Map;let m={unified:"other",raw:void 0},v;const y=[];let b=null;const C={},F=[];let E=!1;const T={};let O;return{stream:d.pipeThrough(new TransformStream({start($){$.enqueue({type:"stream-start",warnings:r})},transform($,I){var oe,k,re,B,P,z,U,R,Y,me,X,de,pe,H,je,xe,at,Ae,j,te,Ge,ve,Lr,qr,Ur,Zr,Vr,Gr,Wr,Hr;if(t.includeRawChunks&&I.enqueue({type:"raw",rawValue:$.rawValue}),!$.success){m={unified:"error",raw:void 0},I.enqueue({type:"error",error:$.error});return}const _=$.value;if(nD(_)){if(_.item.type==="function_call")C[_.output_index]={toolName:_.item.name,toolCallId:_.item.call_id},I.enqueue({type:"tool-input-start",id:_.item.call_id,toolName:_.item.name});else if(_.item.type==="web_search_call")C[_.output_index]={toolName:s.toCustomToolName(o??"web_search"),toolCallId:_.item.id},I.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName(o??"web_search"),providerExecuted:!0}),I.enqueue({type:"tool-input-end",id:_.item.id}),I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName(o??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(_.item.type==="computer_call")C[_.output_index]={toolName:s.toCustomToolName("computer_use"),toolCallId:_.item.id},I.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName("computer_use"),providerExecuted:!0});else if(_.item.type==="code_interpreter_call")C[_.output_index]={toolName:s.toCustomToolName("code_interpreter"),toolCallId:_.item.id,codeInterpreter:{containerId:_.item.container_id}},I.enqueue({type:"tool-input-start",id:_.item.id,toolName:s.toCustomToolName("code_interpreter"),providerExecuted:!0}),I.enqueue({type:"tool-input-delta",id:_.item.id,delta:`{"containerId":"${_.item.container_id}","code":"`});else if(_.item.type==="file_search_call")I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(_.item.type==="image_generation_call")I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!(_.item.type==="mcp_call"||_.item.type==="mcp_list_tools"||_.item.type==="mcp_approval_request"))if(_.item.type==="apply_patch_call"){const{call_id:q,operation:ze}=_.item;if(C[_.output_index]={toolName:s.toCustomToolName("apply_patch"),toolCallId:q,applyPatch:{hasDiff:ze.type==="delete_file",endEmitted:ze.type==="delete_file"}},I.enqueue({type:"tool-input-start",id:q,toolName:s.toCustomToolName("apply_patch")}),ze.type==="delete_file"){const st=JSON.stringify({callId:q,operation:ze});I.enqueue({type:"tool-input-delta",id:q,delta:st}),I.enqueue({type:"tool-input-end",id:q})}else I.enqueue({type:"tool-input-delta",id:q,delta:`{"callId":"${_n(q)}","operation":{"type":"${_n(ze.type)}","path":"${_n(ze.path)}","diff":"`})}else _.item.type==="shell_call"?C[_.output_index]={toolName:s.toCustomToolName("shell"),toolCallId:_.item.call_id}:_.item.type==="shell_call_output"||(_.item.type==="message"?(F.splice(0,F.length),I.enqueue({type:"text-start",id:_.item.id,providerMetadata:{[u]:{itemId:_.item.id}}})):nD(_)&&_.item.type==="reasoning"&&(T[_.item.id]={encryptedContent:_.item.encrypted_content,summaryParts:{0:"active"}},I.enqueue({type:"reasoning-start",id:`${_.item.id}:0`,providerMetadata:{[u]:{itemId:_.item.id,reasoningEncryptedContent:(oe=_.item.encrypted_content)!=null?oe:null}}})))}else if(Qx(_)){if(_.item.type==="message")I.enqueue({type:"text-end",id:_.item.id,providerMetadata:{[u]:{itemId:_.item.id,...F.length>0&&{annotations:F}}}});else if(_.item.type==="function_call")C[_.output_index]=void 0,E=!0,I.enqueue({type:"tool-input-end",id:_.item.call_id}),I.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:_.item.name,input:_.item.arguments,providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="web_search_call")C[_.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName(o??"web_search"),result:rD(_.item.action)});else if(_.item.type==="computer_call")C[_.output_index]=void 0,I.enqueue({type:"tool-input-end",id:_.item.id}),I.enqueue({type:"tool-call",toolCallId:_.item.id,toolName:s.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:_.item.status||"completed"}});else if(_.item.type==="file_search_call")C[_.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("file_search"),result:{queries:_.item.queries,results:(re=(k=_.item.results)==null?void 0:k.map(q=>({attributes:q.attributes,fileId:q.file_id,filename:q.filename,score:q.score,text:q.text})))!=null?re:null}});else if(_.item.type==="code_interpreter_call")C[_.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("code_interpreter"),result:{outputs:_.item.outputs}});else if(_.item.type==="image_generation_call")I.enqueue({type:"tool-result",toolCallId:_.item.id,toolName:s.toCustomToolName("image_generation"),result:{result:_.item.result}});else if(_.item.type==="mcp_call"){C[_.output_index]=void 0;const q=(B=_.item.approval_request_id)!=null?B:void 0,ze=q!=null&&(z=(P=D.get(q))!=null?P:h[q])!=null?z:_.item.id,st=`mcp.${_.item.name}`;I.enqueue({type:"tool-call",toolCallId:ze,toolName:st,input:_.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-result",toolCallId:ze,toolName:st,result:{type:"call",serverLabel:_.item.server_label,name:_.item.name,arguments:_.item.arguments,..._.item.output!=null?{output:_.item.output}:{},..._.item.error!=null?{error:_.item.error}:{}},providerMetadata:{[u]:{itemId:_.item.id}}})}else if(_.item.type==="mcp_list_tools")C[_.output_index]=void 0;else if(_.item.type==="apply_patch_call"){const q=C[_.output_index];q?.applyPatch&&!q.applyPatch.endEmitted&&_.item.operation.type!=="delete_file"&&(q.applyPatch.hasDiff||I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:_n(_.item.operation.diff)}),I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:q.toolCallId}),q.applyPatch.endEmitted=!0),q&&_.item.status==="completed"&&I.enqueue({type:"tool-call",toolCallId:q.toolCallId,toolName:s.toCustomToolName("apply_patch"),input:JSON.stringify({callId:_.item.call_id,operation:_.item.operation}),providerMetadata:{[u]:{itemId:_.item.id}}}),C[_.output_index]=void 0}else if(_.item.type==="mcp_approval_request"){C[_.output_index]=void 0;const q=(Y=(R=(U=f.config).generateId)==null?void 0:R.call(U))!=null?Y:Ve(),ze=(me=_.item.approval_request_id)!=null?me:_.item.id;D.set(ze,q);const st=`mcp.${_.item.name}`;I.enqueue({type:"tool-call",toolCallId:q,toolName:st,input:_.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-approval-request",approvalId:ze,toolCallId:q})}else if(_.item.type==="local_shell_call")C[_.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:s.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:_.item.action.command,timeoutMs:_.item.action.timeout_ms,user:_.item.action.user,workingDirectory:_.item.action.working_directory,env:_.item.action.env}}),providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="shell_call")C[_.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:_.item.call_id,toolName:s.toCustomToolName("shell"),input:JSON.stringify({action:{commands:_.item.action.commands}}),...l&&{providerExecuted:!0},providerMetadata:{[u]:{itemId:_.item.id}}});else if(_.item.type==="shell_call_output")I.enqueue({type:"tool-result",toolCallId:_.item.call_id,toolName:s.toCustomToolName("shell"),result:{output:_.item.output.map(q=>({stdout:q.stdout,stderr:q.stderr,outcome:q.outcome.type==="exit"?{type:"exit",exitCode:q.outcome.exit_code}:{type:"timeout"}}))}});else if(_.item.type==="reasoning"){const q=T[_.item.id],ze=Object.entries(q.summaryParts).filter(([st,xn])=>xn==="active"||xn==="can-conclude").map(([st])=>st);for(const st of ze)I.enqueue({type:"reasoning-end",id:`${_.item.id}:${st}`,providerMetadata:{[u]:{itemId:_.item.id,reasoningEncryptedContent:(X=_.item.encrypted_content)!=null?X:null}}});delete T[_.item.id]}}else if(nk(_)){const q=C[_.output_index];q!=null&&I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:_.delta})}else if(sk(_)){const q=C[_.output_index];q?.applyPatch&&(I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:_n(_.delta)}),q.applyPatch.hasDiff=!0)}else if(ik(_)){const q=C[_.output_index];q?.applyPatch&&!q.applyPatch.endEmitted&&(q.applyPatch.hasDiff||(I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:_n(_.diff)}),q.applyPatch.hasDiff=!0),I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:q.toolCallId}),q.applyPatch.endEmitted=!0)}else if(rk(_))I.enqueue({type:"tool-result",toolCallId:_.item_id,toolName:s.toCustomToolName("image_generation"),result:{result:_.partial_image_b64},preliminary:!0});else if(ok(_)){const q=C[_.output_index];q!=null&&I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:_n(_.delta)})}else if(ak(_)){const q=C[_.output_index];q!=null&&(I.enqueue({type:"tool-input-delta",id:q.toolCallId,delta:'"}'}),I.enqueue({type:"tool-input-end",id:q.toolCallId}),I.enqueue({type:"tool-call",toolCallId:q.toolCallId,toolName:s.toCustomToolName("code_interpreter"),input:JSON.stringify({code:_.code,containerId:q.codeInterpreter.containerId}),providerExecuted:!0}))}else if(tk(_))b=_.response.id,I.enqueue({type:"response-metadata",id:_.response.id,timestamp:new Date(_.response.created_at*1e3),modelId:_.response.model});else if(Xx(_))I.enqueue({type:"text-delta",id:_.item_id,delta:_.delta}),(pe=(de=t.providerOptions)==null?void 0:de[u])!=null&&pe.logprobs&&_.logprobs&&y.push(_.logprobs);else if(_.type==="response.reasoning_summary_part.added"){if(_.summary_index>0){const q=T[_.item_id];q.summaryParts[_.summary_index]="active";for(const ze of Object.keys(q.summaryParts))q.summaryParts[ze]==="can-conclude"&&(I.enqueue({type:"reasoning-end",id:`${_.item_id}:${ze}`,providerMetadata:{[u]:{itemId:_.item_id}}}),q.summaryParts[ze]="concluded");I.enqueue({type:"reasoning-start",id:`${_.item_id}:${_.summary_index}`,providerMetadata:{[u]:{itemId:_.item_id,reasoningEncryptedContent:(je=(H=T[_.item_id])==null?void 0:H.encryptedContent)!=null?je:null}}})}}else _.type==="response.reasoning_summary_text.delta"?I.enqueue({type:"reasoning-delta",id:`${_.item_id}:${_.summary_index}`,delta:_.delta,providerMetadata:{[u]:{itemId:_.item_id}}}):_.type==="response.reasoning_summary_part.done"?a?(I.enqueue({type:"reasoning-end",id:`${_.item_id}:${_.summary_index}`,providerMetadata:{[u]:{itemId:_.item_id}}}),T[_.item_id].summaryParts[_.summary_index]="concluded"):T[_.item_id].summaryParts[_.summary_index]="can-conclude":ek(_)?(m={unified:Xh({finishReason:(xe=_.response.incomplete_details)==null?void 0:xe.reason,hasFunctionCall:E}),raw:(Ae=(at=_.response.incomplete_details)==null?void 0:at.reason)!=null?Ae:void 0},v=_.response.usage,typeof _.response.service_tier=="string"&&(O=_.response.service_tier)):uk(_)?(F.push(_.annotation),_.annotation.type==="url_citation"?I.enqueue({type:"source",sourceType:"url",id:(Ge=(te=(j=f.config).generateId)==null?void 0:te.call(j))!=null?Ge:Ve(),url:_.annotation.url,title:_.annotation.title}):_.annotation.type==="file_citation"?I.enqueue({type:"source",sourceType:"document",id:(qr=(Lr=(ve=f.config).generateId)==null?void 0:Lr.call(ve))!=null?qr:Ve(),mediaType:"text/plain",title:_.annotation.filename,filename:_.annotation.filename,providerMetadata:{[u]:{type:_.annotation.type,fileId:_.annotation.file_id,index:_.annotation.index}}}):_.annotation.type==="container_file_citation"?I.enqueue({type:"source",sourceType:"document",id:(Vr=(Zr=(Ur=f.config).generateId)==null?void 0:Zr.call(Ur))!=null?Vr:Ve(),mediaType:"text/plain",title:_.annotation.filename,filename:_.annotation.filename,providerMetadata:{[u]:{type:_.annotation.type,fileId:_.annotation.file_id,containerId:_.annotation.container_id}}}):_.annotation.type==="file_path"&&I.enqueue({type:"source",sourceType:"document",id:(Hr=(Wr=(Gr=f.config).generateId)==null?void 0:Wr.call(Gr))!=null?Hr:Ve(),mediaType:"application/octet-stream",title:_.annotation.file_id,filename:_.annotation.file_id,providerMetadata:{[u]:{type:_.annotation.type,fileId:_.annotation.file_id,index:_.annotation.index}}})):lk(_)&&I.enqueue({type:"error",error:_})},flush($){const I={[u]:{responseId:b,...y.length>0?{logprobs:y}:{},...O!==void 0?{serviceTier:O}:{}}};$.enqueue({type:"finish",finishReason:m,usage:Kh(v),providerMetadata:I})}})),request:{body:n},response:{headers:c}}}},i(Or,"OpenAIResponsesLanguageModel"),Or);function Xx(e){return e.type==="response.output_text.delta"}i(Xx,"isTextDeltaChunk");function Qx(e){return e.type==="response.output_item.done"}i(Qx,"isResponseOutputItemDoneChunk");function ek(e){return e.type==="response.completed"||e.type==="response.incomplete"}i(ek,"isResponseFinishedChunk");function tk(e){return e.type==="response.created"}i(tk,"isResponseCreatedChunk");function nk(e){return e.type==="response.function_call_arguments.delta"}i(nk,"isResponseFunctionCallArgumentsDeltaChunk");function rk(e){return e.type==="response.image_generation_call.partial_image"}i(rk,"isResponseImageGenerationCallPartialImageChunk");function ok(e){return e.type==="response.code_interpreter_call_code.delta"}i(ok,"isResponseCodeInterpreterCallCodeDeltaChunk");function ak(e){return e.type==="response.code_interpreter_call_code.done"}i(ak,"isResponseCodeInterpreterCallCodeDoneChunk");function sk(e){return e.type==="response.apply_patch_call_operation_diff.delta"}i(sk,"isResponseApplyPatchCallOperationDiffDeltaChunk");function ik(e){return e.type==="response.apply_patch_call_operation_diff.done"}i(ik,"isResponseApplyPatchCallOperationDiffDoneChunk");function nD(e){return e.type==="response.output_item.added"}i(nD,"isResponseOutputItemAddedChunk");function uk(e){return e.type==="response.output_text.annotation.added"}i(uk,"isResponseAnnotationAddedChunk");function lk(e){return e.type==="error"}i(lk,"isErrorChunk");function rD(e){var t;switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}i(rD,"mapWebSearchOutput");function _n(e){return JSON.stringify(e).slice(1,-1)}i(_n,"escapeJSONDelta");var ck=K(()=>J(g({instructions:p().nullish(),speed:x().min(.25).max(4).default(1).nullish()}))),dk=(Rr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:t,voice:n="alloy",outputFormat:r="mp3",speed:o,instructions:s,language:a,providerOptions:u}){const l=[],c=await tt({provider:"openai",providerOptions:u,schema:ck}),d={model:this.modelId,input:t,voice:n,response_format:"mp3",speed:o,instructions:s};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?d.response_format=r:l.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),c){const f={};for(const h in f){const D=f[h];D!==void 0&&(d[h]=D)}}return a&&l.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:d,warnings:l}}async doGenerate(t){var n,r,o;const s=(o=(r=(n=this.config._internal)==null?void 0:n.currentDate)==null?void 0:r.call(n))!=null?o:new Date,{requestBody:a,warnings:u}=await this.getArgs(t),{value:l,responseHeaders:c,rawValue:d}=await qe({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:a,failedResponseHandler:$t,successfulResponseHandler:j2(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:l,warnings:u,request:{body:JSON.stringify(a)},response:{timestamp:s,modelId:this.modelId,headers:c,body:d}}}},i(Rr,"OpenAISpeechModel"),Rr),pk=K(()=>J(g({text:p(),language:p().nullish(),duration:x().nullish(),words:S(g({word:p(),start:x(),end:x()})).nullish(),segments:S(g({id:x(),seek:x(),start:x(),end:x(),text:p(),tokens:S(x()),temperature:x(),avg_logprob:x(),compression_ratio:x(),no_speech_prob:x()})).nullish()}))),fk=K(()=>J(g({include:S(p()).optional(),language:p().optional(),prompt:p().optional(),temperature:x().min(0).max(1).default(0).optional(),timestampGranularities:S(se(["word","segment"])).default(["segment"]).optional()}))),oD={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},mk=(Nr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:n,providerOptions:r}){const o=[],s=await tt({provider:"openai",providerOptions:r,schema:fk}),a=new FormData,u=t instanceof Uint8Array?new Blob([t]):new Blob([hn(t)]);a.append("model",this.modelId);const l=qF(n);if(a.append("file",new File([u],"audio",{type:n}),`audio.${l}`),s){const c={include:s.include,language:s.language,prompt:s.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:s.temperature,timestamp_granularities:s.timestampGranularities};for(const[d,f]of Object.entries(c))if(f!=null)if(Array.isArray(f))for(const h of f)a.append(`${d}[]`,String(h));else a.append(d,String(f))}return{formData:a,warnings:o}}async doGenerate(t){var n,r,o,s,a,u,l,c;const d=(o=(r=(n=this.config._internal)==null?void 0:n.currentDate)==null?void 0:r.call(n))!=null?o:new Date,{formData:f,warnings:h}=await this.getArgs(t),{value:D,responseHeaders:m,rawValue:v}=await Mi({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),formData:f,failedResponseHandler:$t,successfulResponseHandler:Ke(pk),abortSignal:t.abortSignal,fetch:this.config.fetch}),y=D.language!=null&&D.language in oD?oD[D.language]:void 0;return{text:D.text,segments:(l=(u=(s=D.segments)==null?void 0:s.map(b=>({text:b.text,startSecond:b.start,endSecond:b.end})))!=null?u:(a=D.words)==null?void 0:a.map(b=>({text:b.word,startSecond:b.start,endSecond:b.end})))!=null?l:[],language:y,durationInSeconds:(c=D.duration)!=null?c:void 0,warnings:h,response:{timestamp:d,modelId:this.modelId,headers:m,body:v}}}},i(Nr,"OpenAITranscriptionModel"),Nr),hk="3.0.30";function Va(e={}){var t,n;const r=(t=ji(Co({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(n=e.name)!=null?n:"openai",s=i(()=>Dn({Authorization:`Bearer ${LF({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${hk}`),"getHeaders"),a=i(v=>new Y3(v,{provider:`${o}.chat`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createChatModel"),u=i(v=>new tx(v,{provider:`${o}.completion`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createCompletionModel"),l=i(v=>new ox(v,{provider:`${o}.embedding`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createEmbeddingModel"),c=i(v=>new ux(v,{provider:`${o}.image`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createImageModel"),d=i(v=>new mk(v,{provider:`${o}.transcription`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createTranscriptionModel"),f=i(v=>new dk(v,{provider:`${o}.speech`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch}),"createSpeechModel"),h=i(v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return D(v)},"createLanguageModel"),D=i(v=>new Yx(v,{provider:`${o}.responses`,url:i(({path:y})=>`${r}${y}`,"url"),headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),"createResponsesModel"),m=i(function(v){return h(v)},"provider");return m.specificationVersion="v3",m.languageModel=h,m.chat=a,m.completion=u,m.responses=D,m.embedding=l,m.embeddingModel=l,m.textEmbedding=l,m.textEmbeddingModel=l,m.image=c,m.imageModel=c,m.transcription=d,m.transcriptionModel=d,m.speech=f,m.speechModel=f,m.tools=Ux,m}i(Va,"createOpenAI"),Va();var Dk=g({error:g({message:p(),type:p().nullish(),param:et().nullish(),code:ee([p(),x()]).nullish()})}),$o={errorSchema:Dk,errorToMessage:i(e=>e.error.message,"errorToMessage")};function aD(e){var t,n,r,o,s,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const u=(t=e.prompt_tokens)!=null?t:0,l=(n=e.completion_tokens)!=null?n:0,c=(o=(r=e.prompt_tokens_details)==null?void 0:r.cached_tokens)!=null?o:0,d=(a=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?a:0;return{inputTokens:{total:u,noCache:u-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-d,reasoning:d},raw:e}}i(aD,"convertOpenAICompatibleChatUsage");function To(e){var t,n;return(n=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?n:{}}i(To,"getOpenAIMetadata");function gk(e){switch(e){case"audio/wav":return"wav";case"audio/mp3":case"audio/mpeg":return"mp3";default:return null}}i(gk,"getAudioFormat");function vk(e){var t,n,r;const o=[];for(const{role:s,content:a,...u}of e){const l=To({...u});switch(s){case"system":{o.push({role:"system",content:a,...l});break}case"user":{if(a.length===1&&a[0].type==="text"){o.push({role:"user",content:a[0].text,...To(a[0])});break}o.push({role:"user",content:a.map(c=>{var d;const f=To(c);switch(c.type){case"text":return{type:"text",text:c.text,...f};case"file":{if(c.mediaType.startsWith("image/")){const h=c.mediaType==="image/*"?"image/jpeg":c.mediaType;return{type:"image_url",image_url:{url:c.data instanceof URL?c.data.toString():`data:${h};base64,${zt(c.data)}`},...f}}if(c.mediaType.startsWith("audio/")){if(c.data instanceof URL)throw new Qe({functionality:"audio file parts with URLs"});const h=gk(c.mediaType);if(h===null)throw new Qe({functionality:`audio media type ${c.mediaType}`});return{type:"input_audio",input_audio:{data:zt(c.data),format:h},...f}}if(c.mediaType==="application/pdf"){if(c.data instanceof URL)throw new Qe({functionality:"PDF file parts with URLs"});return{type:"file",file:{filename:(d=c.filename)!=null?d:"document.pdf",file_data:`data:application/pdf;base64,${zt(c.data)}`},...f}}if(c.mediaType.startsWith("text/"))return{type:"text",text:c.data instanceof URL?c.data.toString():typeof c.data=="string"?c.data:new TextDecoder().decode(c.data),...f};throw new Qe({functionality:`file part media type ${c.mediaType}`})}}}),...l});break}case"assistant":{let c="",d="";const f=[];for(const h of a){const D=To(h);switch(h.type){case"text":{c+=h.text;break}case"reasoning":{d+=h.text;break}case"tool-call":{const m=(n=(t=h.providerOptions)==null?void 0:t.google)==null?void 0:n.thoughtSignature;f.push({id:h.toolCallId,type:"function",function:{name:h.toolName,arguments:JSON.stringify(h.input)},...D,...m?{extra_content:{google:{thought_signature:String(m)}}}:{}});break}}}o.push({role:"assistant",content:c,...d.length>0?{reasoning_content:d}:{},tool_calls:f.length>0?f:void 0,...l});break}case"tool":{for(const c of a){if(c.type==="tool-approval-response")continue;const d=c.output;let f;switch(d.type){case"text":case"error-text":f=d.value;break;case"execution-denied":f=(r=d.reason)!=null?r:"Tool execution denied.";break;case"content":case"json":case"error-json":f=JSON.stringify(d.value);break}const h=To(c);o.push({role:"tool",tool_call_id:c.toolCallId,content:f,...h})}break}default:{const c=s;throw new Error(`Unsupported role: ${c}`)}}}return o}i(vk,"convertToOpenAICompatibleChatMessages");function sD({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(sD,"getResponseMetadata");function iD(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(iD,"mapOpenAICompatibleFinishReason");var Ga=g({user:p().optional(),reasoningEffort:p().optional(),textVerbosity:p().optional(),strictJsonSchema:Re().optional()});function yk({tools:e,toolChoice:t}){e=e?.length?e:void 0;const n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const r=[];for(const s of e)s.type==="provider"?n.push({type:"unsupported",feature:`provider-defined tool ${s.id}`}):r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:r,toolChoice:o,toolWarnings:n};case"tool":return{tools:r,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:n};default:{const s=o;throw new Qe({functionality:`tool choice type: ${s}`})}}}i(yk,"prepareTools");var _k=(Pr=class{constructor(t,n){this.specificationVersion="v3";var r,o;this.modelId=t,this.config=n;const s=(r=n.errorStructure)!=null?r:$o;this.chunkSchema=wk(s.errorSchema),this.failedResponseHandler=Dt(s),this.supportsStructuredOutputs=(o=n.supportsStructuredOutputs)!=null?o:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,n,r;return(r=(n=(t=this.config).supportedUrls)==null?void 0:n.call(t))!=null?r:{}}transformRequestBody(t){var n,r,o;return(o=(r=(n=this.config).transformRequestBody)==null?void 0:r.call(n,t))!=null?o:t}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,providerOptions:l,stopSequences:c,responseFormat:d,seed:f,toolChoice:h,tools:D}){var m,v,y,b,C;const F=[],E=await tt({provider:"openai-compatible",providerOptions:l,schema:Ga});E!=null&&F.push({type:"other",message:"The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead."});const T=Object.assign(E??{},(m=await tt({provider:"openaiCompatible",providerOptions:l,schema:Ga}))!=null?m:{},(v=await tt({provider:this.providerOptionsName,providerOptions:l,schema:Ga}))!=null?v:{}),O=(y=T?.strictJsonSchema)!=null?y:!0;s!=null&&F.push({type:"unsupported",feature:"topK"}),d?.type==="json"&&d.schema!=null&&!this.supportsStructuredOutputs&&F.push({type:"unsupported",feature:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:$,toolChoice:I,toolWarnings:oe}=yk({tools:D,toolChoice:h});return{args:{model:this.modelId,user:T.user,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,response_format:d?.type==="json"?this.supportsStructuredOutputs===!0&&d.schema!=null?{type:"json_schema",json_schema:{schema:d.schema,strict:O,name:(b=d.name)!=null?b:"response",description:d.description}}:{type:"json_object"}:void 0,stop:c,seed:f,...Object.fromEntries(Object.entries((C=l?.[this.providerOptionsName])!=null?C:{}).filter(([k])=>!Object.keys(Ga.shape).includes(k))),reasoning_effort:T.reasoningEffort,verbosity:T.textVerbosity,messages:vk(t),tools:$,tool_choice:I},warnings:[...F,...oe]}}async doGenerate(t){var n,r,o,s,a,u,l,c;const{args:d,warnings:f}=await this.getArgs({...t}),h=this.transformRequestBody(d),D=JSON.stringify(h),{responseHeaders:m,value:v,rawValue:y}=await qe({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:h,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Ke(bk),abortSignal:t.abortSignal,fetch:this.config.fetch}),b=v.choices[0],C=[],F=b.message.content;F!=null&&F.length>0&&C.push({type:"text",text:F});const E=(n=b.message.reasoning_content)!=null?n:b.message.reasoning;if(E!=null&&E.length>0&&C.push({type:"reasoning",text:E}),b.message.tool_calls!=null)for(const $ of b.message.tool_calls){const I=(o=(r=$.extra_content)==null?void 0:r.google)==null?void 0:o.thought_signature;C.push({type:"tool-call",toolCallId:(s=$.id)!=null?s:Ve(),toolName:$.function.name,input:$.function.arguments,...I?{providerMetadata:{[this.providerOptionsName]:{thoughtSignature:I}}}:{}})}const T={[this.providerOptionsName]:{},...await((u=(a=this.config.metadataExtractor)==null?void 0:a.extractMetadata)==null?void 0:u.call(a,{parsedBody:y}))},O=(l=v.usage)==null?void 0:l.completion_tokens_details;return O?.accepted_prediction_tokens!=null&&(T[this.providerOptionsName].acceptedPredictionTokens=O?.accepted_prediction_tokens),O?.rejected_prediction_tokens!=null&&(T[this.providerOptionsName].rejectedPredictionTokens=O?.rejected_prediction_tokens),{content:C,finishReason:{unified:iD(b.finish_reason),raw:(c=b.finish_reason)!=null?c:void 0},usage:aD(v.usage),providerMetadata:T,request:{body:D},response:{...sD(v),headers:m,body:y},warnings:f}}async doStream(t){var n;const{args:r,warnings:o}=await this.getArgs({...t}),s=this.transformRequestBody({...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0}),a=(n=this.config.metadataExtractor)==null?void 0:n.createStreamExtractor(),{responseHeaders:u,value:l}=await qe({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:s,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Vn(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=[];let d={unified:"other",raw:void 0},f,h=!0;const D=this.providerOptionsName;let m=!1,v=!1;return{stream:l.pipeThrough(new TransformStream({start(y){y.enqueue({type:"stream-start",warnings:o})},transform(y,b){var C,F,E,T,O,$,I,oe,k,re,B,P,z,U,R,Y,me,X;if(t.includeRawChunks&&b.enqueue({type:"raw",rawValue:y.rawValue}),!y.success){d={unified:"error",raw:void 0},b.enqueue({type:"error",error:y.error});return}if(a?.processChunk(y.rawValue),"error"in y.value){d={unified:"error",raw:void 0},b.enqueue({type:"error",error:y.value.error.message});return}const de=y.value;h&&(h=!1,b.enqueue({type:"response-metadata",...sD(de)})),de.usage!=null&&(f=de.usage);const pe=de.choices[0];if(pe?.finish_reason!=null&&(d={unified:iD(pe.finish_reason),raw:(C=pe.finish_reason)!=null?C:void 0}),pe?.delta==null)return;const H=pe.delta,je=(F=H.reasoning_content)!=null?F:H.reasoning;if(je&&(m||(b.enqueue({type:"reasoning-start",id:"reasoning-0"}),m=!0),b.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:je})),H.content&&(m&&(b.enqueue({type:"reasoning-end",id:"reasoning-0"}),m=!1),v||(b.enqueue({type:"text-start",id:"txt-0"}),v=!0),b.enqueue({type:"text-delta",id:"txt-0",delta:H.content})),H.tool_calls!=null){m&&(b.enqueue({type:"reasoning-end",id:"reasoning-0"}),m=!1);for(const xe of H.tool_calls){const at=(E=xe.index)!=null?E:c.length;if(c[at]==null){if(xe.id==null)throw new so({data:xe,message:"Expected 'id' to be a string."});if(((T=xe.function)==null?void 0:T.name)==null)throw new so({data:xe,message:"Expected 'function.name' to be a string."});b.enqueue({type:"tool-input-start",id:xe.id,toolName:xe.function.name}),c[at]={id:xe.id,type:"function",function:{name:xe.function.name,arguments:(O=xe.function.arguments)!=null?O:""},hasFinished:!1,thoughtSignature:(oe=(I=($=xe.extra_content)==null?void 0:$.google)==null?void 0:I.thought_signature)!=null?oe:void 0};const j=c[at];((k=j.function)==null?void 0:k.name)!=null&&((re=j.function)==null?void 0:re.arguments)!=null&&(j.function.arguments.length>0&&b.enqueue({type:"tool-input-delta",id:j.id,delta:j.function.arguments}),ja(j.function.arguments)&&(b.enqueue({type:"tool-input-end",id:j.id}),b.enqueue({type:"tool-call",toolCallId:(B=j.id)!=null?B:Ve(),toolName:j.function.name,input:j.function.arguments,...j.thoughtSignature?{providerMetadata:{[D]:{thoughtSignature:j.thoughtSignature}}}:{}}),j.hasFinished=!0));continue}const Ae=c[at];Ae.hasFinished||(((P=xe.function)==null?void 0:P.arguments)!=null&&(Ae.function.arguments+=(U=(z=xe.function)==null?void 0:z.arguments)!=null?U:""),b.enqueue({type:"tool-input-delta",id:Ae.id,delta:(R=xe.function.arguments)!=null?R:""}),((Y=Ae.function)==null?void 0:Y.name)!=null&&((me=Ae.function)==null?void 0:me.arguments)!=null&&ja(Ae.function.arguments)&&(b.enqueue({type:"tool-input-end",id:Ae.id}),b.enqueue({type:"tool-call",toolCallId:(X=Ae.id)!=null?X:Ve(),toolName:Ae.function.name,input:Ae.function.arguments,...Ae.thoughtSignature?{providerMetadata:{[D]:{thoughtSignature:Ae.thoughtSignature}}}:{}}),Ae.hasFinished=!0))}}},flush(y){var b,C,F,E,T;m&&y.enqueue({type:"reasoning-end",id:"reasoning-0"}),v&&y.enqueue({type:"text-end",id:"txt-0"});for(const $ of c.filter(I=>!I.hasFinished))y.enqueue({type:"tool-input-end",id:$.id}),y.enqueue({type:"tool-call",toolCallId:(b=$.id)!=null?b:Ve(),toolName:$.function.name,input:$.function.arguments,...$.thoughtSignature?{providerMetadata:{[D]:{thoughtSignature:$.thoughtSignature}}}:{}});const O={[D]:{},...a?.buildMetadata()};((C=f?.completion_tokens_details)==null?void 0:C.accepted_prediction_tokens)!=null&&(O[D].acceptedPredictionTokens=(F=f?.completion_tokens_details)==null?void 0:F.accepted_prediction_tokens),((E=f?.completion_tokens_details)==null?void 0:E.rejected_prediction_tokens)!=null&&(O[D].rejectedPredictionTokens=(T=f?.completion_tokens_details)==null?void 0:T.rejected_prediction_tokens),y.enqueue({type:"finish",finishReason:d,usage:aD(f),providerMetadata:O})}})),request:{body:s},response:{headers:u}}}},i(Pr,"OpenAICompatibleChatLanguageModel"),Pr),uD=gi({prompt_tokens:x().nullish(),completion_tokens:x().nullish(),total_tokens:x().nullish(),prompt_tokens_details:g({cached_tokens:x().nullish()}).nullish(),completion_tokens_details:g({reasoning_tokens:x().nullish(),accepted_prediction_tokens:x().nullish(),rejected_prediction_tokens:x().nullish()}).nullish()}).nullish(),bk=gi({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({message:g({role:w("assistant").nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:S(g({id:p().nullish(),function:g({name:p(),arguments:p()}),extra_content:g({google:g({thought_signature:p().nullish()}).nullish()}).nullish()})).nullish()}),finish_reason:p().nullish()})),usage:uD}),Ck=gi({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({delta:g({role:se(["assistant"]).nullish(),content:p().nullish(),reasoning_content:p().nullish(),reasoning:p().nullish(),tool_calls:S(g({index:x().nullish(),id:p().nullish(),function:g({name:p().nullish(),arguments:p().nullish()}),extra_content:g({google:g({thought_signature:p().nullish()}).nullish()}).nullish()})).nullish()}).nullish(),finish_reason:p().nullish()})),usage:uD}),wk=i(e=>ee([Ck,e]),"createOpenAICompatibleChatChunkSchema");function lD(e){var t,n;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const r=(t=e.prompt_tokens)!=null?t:0,o=(n=e.completion_tokens)!=null?n:0;return{inputTokens:{total:r,noCache:r,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:o,text:o,reasoning:void 0},raw:e}}i(lD,"convertOpenAICompatibleCompletionUsage");function Fk({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
164
164
 
165
165
  `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new Gt({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const a=s.map(u=>{switch(u.type){case"text":return u.text}}).filter(Boolean).join("");r+=`${t}:
166
166
  ${a}
@@ -170,39 +170,39 @@ ${a}
170
170
 
171
171
  `;break}case"tool":throw new Qe({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return r+=`${n}:
172
172
  `,{prompt:r,stopSequences:[`
173
- ${t}:`]}}i(Ck,"convertToOpenAICompatibleCompletionPrompt");function cD({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(cD,"getResponseMetadata2");function dD(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(dD,"mapOpenAICompatibleFinishReason2");var wk=g({echo:Re().optional(),logitBias:be(p(),E()).optional(),suffix:p().optional(),user:p().optional()}),Fk=(Mr=class{constructor(t,n){this.specificationVersion="v3";var r;this.modelId=t,this.config=n;const o=(r=n.errorStructure)!=null?r:$o;this.chunkSchema=xk(o.errorSchema),this.failedResponseHandler=Dt(o)}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,n,r;return(r=(n=(t=this.config).supportedUrls)==null?void 0:n.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,stopSequences:l,responseFormat:c,seed:d,providerOptions:f,tools:h,toolChoice:D}){var m;const v=[],y=(m=await tt({provider:this.providerOptionsName,providerOptions:f,schema:wk}))!=null?m:{};s!=null&&v.push({type:"unsupported",feature:"topK"}),h?.length&&v.push({type:"unsupported",feature:"tools"}),D!=null&&v.push({type:"unsupported",feature:"toolChoice"}),c!=null&&c.type!=="text"&&v.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:b,stopSequences:w}=Ck({prompt:t}),C=[...w??[],...l??[]];return{args:{model:this.modelId,echo:y.echo,logit_bias:y.logitBias,suffix:y.suffix,user:y.user,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,seed:d,...f?.[this.providerOptionsName],prompt:b,stop:C.length>0?C:void 0},warnings:v}}async doGenerate(t){const{args:n,warnings:r}=await this.getArgs(t),{responseHeaders:o,value:s,rawValue:a}=await qe({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:n,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Ke(Ek),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=s.choices[0],l=[];return u.text!=null&&u.text.length>0&&l.push({type:"text",text:u.text}),{content:l,usage:lD(s.usage),finishReason:{unified:dD(u.finish_reason),raw:u.finish_reason},request:{body:n},response:{...cD(s),headers:o,body:a},warnings:r}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),o={...n,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},{responseHeaders:s,value:a}=await qe({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Vn(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch});let u={unified:"other",raw:void 0},l,c=!0;return{stream:a.pipeThrough(new TransformStream({start(d){d.enqueue({type:"stream-start",warnings:r})},transform(d,f){var h;if(t.includeRawChunks&&f.enqueue({type:"raw",rawValue:d.rawValue}),!d.success){u={unified:"error",raw:void 0},f.enqueue({type:"error",error:d.error});return}const D=d.value;if("error"in D){u={unified:"error",raw:void 0},f.enqueue({type:"error",error:D.error});return}c&&(c=!1,f.enqueue({type:"response-metadata",...cD(D)}),f.enqueue({type:"text-start",id:"0"})),D.usage!=null&&(l=D.usage);const m=D.choices[0];m?.finish_reason!=null&&(u={unified:dD(m.finish_reason),raw:(h=m.finish_reason)!=null?h:void 0}),m?.text!=null&&f.enqueue({type:"text-delta",id:"0",delta:m.text})},flush(d){c||d.enqueue({type:"text-end",id:"0"}),d.enqueue({type:"finish",finishReason:u,usage:lD(l)})}})),request:{body:o},response:{headers:s}}}},i(Mr,"OpenAICompatibleCompletionLanguageModel"),Mr),pD=g({prompt_tokens:E(),completion_tokens:E(),total_tokens:E()}),Ek=g({id:p().nullish(),created:E().nullish(),model:p().nullish(),choices:B(g({text:p(),finish_reason:p()})),usage:pD.nullish()}),xk=i(e=>ee([g({id:p().nullish(),created:E().nullish(),model:p().nullish(),choices:B(g({text:p(),finish_reason:p().nullish(),index:E()})),usage:pD.nullish()}),e]),"createOpenAICompatibleCompletionChunkSchema"),pu=g({dimensions:E().optional(),user:p().optional()}),kk=(jr=class{constructor(t,n){this.specificationVersion="v3",this.modelId=t,this.config=n}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){var t;return(t=this.config.maxEmbeddingsPerCall)!=null?t:2048}get supportsParallelCalls(){var t;return(t=this.config.supportsParallelCalls)!=null?t:!0}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:o}){var s,a,u;const l=[],c=await tt({provider:"openai-compatible",providerOptions:o,schema:pu});c!=null&&l.push({type:"other",message:"The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead."});const d=Object.assign(c??{},(s=await tt({provider:"openaiCompatible",providerOptions:o,schema:pu}))!=null?s:{},(a=await tt({provider:this.providerOptionsName,providerOptions:o,schema:pu}))!=null?a:{});if(t.length>this.maxEmbeddingsPerCall)throw new tp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const{responseHeaders:f,value:h,rawValue:D}=await qe({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Ne(this.config.headers(),n),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:d.dimensions,user:d.user},failedResponseHandler:Dt((u=this.config.errorStructure)!=null?u:$o),successfulResponseHandler:Ke(Ik),abortSignal:r,fetch:this.config.fetch});return{warnings:l,embeddings:h.data.map(m=>m.embedding),usage:h.usage?{tokens:h.usage.prompt_tokens}:void 0,providerMetadata:h.providerMetadata,response:{headers:f,body:D}}}},i(jr,"OpenAICompatibleEmbeddingModel"),jr),Ik=g({data:B(g({embedding:B(E())})),usage:g({prompt_tokens:E()}).nullish(),providerMetadata:be(p(),be(p(),et())).optional()}),Ak=(zr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxImagesPerCall=10}get provider(){return this.config.provider}get providerOptionsKey(){return this.config.provider.split(".")[0].trim()}getArgs(t){return{...t[this.providerOptionsKey],...t[$k(this.providerOptionsKey)]}}async doGenerate({prompt:t,n,size:r,aspectRatio:o,seed:s,providerOptions:a,headers:u,abortSignal:l,files:c,mask:d}){var f,h,D,m,v;const y=[];o!=null&&y.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&y.push({type:"unsupported",feature:"seed"});const b=(D=(h=(f=this.config._internal)==null?void 0:f.currentDate)==null?void 0:h.call(f))!=null?D:new Date,w=this.getArgs(a);if(c!=null&&c.length>0){const{value:T,responseHeaders:O}=await Mi({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:Ne(this.config.headers(),u),formData:cf({model:this.modelId,prompt:t,image:await Promise.all(c.map($=>mD($))),mask:d!=null?await mD(d):void 0,n,size:r,...w}),failedResponseHandler:Dt((m=this.config.errorStructure)!=null?m:$o),successfulResponseHandler:Ke(fD),abortSignal:l,fetch:this.config.fetch});return{images:T.data.map($=>$.b64_json),warnings:y,response:{timestamp:b,modelId:this.modelId,headers:O}}}const{value:C,responseHeaders:x}=await qe({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Ne(this.config.headers(),u),body:{model:this.modelId,prompt:t,n,size:r,...w,response_format:"b64_json"},failedResponseHandler:Dt((v=this.config.errorStructure)!=null?v:$o),successfulResponseHandler:Ke(fD),abortSignal:l,fetch:this.config.fetch});return{images:C.data.map(T=>T.b64_json),warnings:y,response:{timestamp:b,modelId:this.modelId,headers:x}}}},i(zr,"OpenAICompatibleImageModel"),zr),fD=g({data:B(g({b64_json:p()}))});async function mD(e){if(e.type==="url")return $i(e.url);const t=e.data instanceof Uint8Array?e.data:hn(e.data);return new Blob([t],{type:e.mediaType})}i(mD,"fileToBlob");function $k(e){return e.replace(/[_-]([a-z])/g,t=>t[1].toUpperCase())}i($k,"toCamelCase");var Tk="2.0.30";function fu(e){const t=ji(e.baseURL),n=e.name,r={...e.apiKey&&{Authorization:`Bearer ${e.apiKey}`},...e.headers},o=i(()=>Dn(r,`ai-sdk/openai-compatible/${Tk}`),"getHeaders"),s=i(h=>({provider:`${n}.${h}`,url:i(({path:D})=>{const m=new URL(`${t}${D}`);return e.queryParams&&(m.search=new URLSearchParams(e.queryParams).toString()),m.toString()},"url"),headers:o,fetch:e.fetch}),"getCommonModelConfig"),a=i(h=>u(h),"createLanguageModel"),u=i(h=>new vk(h,{...s("chat"),includeUsage:e.includeUsage,supportsStructuredOutputs:e.supportsStructuredOutputs,transformRequestBody:e.transformRequestBody,metadataExtractor:e.metadataExtractor}),"createChatModel"),l=i(h=>new Fk(h,{...s("completion"),includeUsage:e.includeUsage}),"createCompletionModel"),c=i(h=>new kk(h,{...s("embedding")}),"createEmbeddingModel"),d=i(h=>new Ak(h,s("image")),"createImageModel"),f=i(h=>a(h),"provider");return f.specificationVersion="v3",f.languageModel=a,f.chatModel=u,f.completionModel=l,f.embeddingModel=c,f.textEmbeddingModel=c,f.imageModel=d,f}i(fu,"createOpenAICompatible");const Sk={plain:"<commit message>",conventional:`<type>[optional (<scope>)]: <commit message>
174
- The commit message subject must start with a lowercase letter`,gitmoji:":emoji: <commit message>"},Bk=i(e=>`The output response must be in format:
175
- ${Sk[e]}`,"specifyCommitFormat"),Ok={plain:"",conventional:`Choose a type from the type-to-description JSON below that best describes the git diff. IMPORTANT: The type MUST be lowercase (e.g., "feat", not "Feat" or "FEAT"):
173
+ ${t}:`]}}i(Fk,"convertToOpenAICompatibleCompletionPrompt");function cD({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}i(cD,"getResponseMetadata2");function dD(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}i(dD,"mapOpenAICompatibleFinishReason2");var Ek=g({echo:Re().optional(),logitBias:be(p(),x()).optional(),suffix:p().optional(),user:p().optional()}),xk=(Mr=class{constructor(t,n){this.specificationVersion="v3";var r;this.modelId=t,this.config=n;const o=(r=n.errorStructure)!=null?r:$o;this.chunkSchema=Ik(o.errorSchema),this.failedResponseHandler=Dt(o)}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,n,r;return(r=(n=(t=this.config).supportedUrls)==null?void 0:n.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:s,frequencyPenalty:a,presencePenalty:u,stopSequences:l,responseFormat:c,seed:d,providerOptions:f,tools:h,toolChoice:D}){var m;const v=[],y=(m=await tt({provider:this.providerOptionsName,providerOptions:f,schema:Ek}))!=null?m:{};s!=null&&v.push({type:"unsupported",feature:"topK"}),h?.length&&v.push({type:"unsupported",feature:"tools"}),D!=null&&v.push({type:"unsupported",feature:"toolChoice"}),c!=null&&c.type!=="text"&&v.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:b,stopSequences:C}=Fk({prompt:t}),F=[...C??[],...l??[]];return{args:{model:this.modelId,echo:y.echo,logit_bias:y.logitBias,suffix:y.suffix,user:y.user,max_tokens:n,temperature:r,top_p:o,frequency_penalty:a,presence_penalty:u,seed:d,...f?.[this.providerOptionsName],prompt:b,stop:F.length>0?F:void 0},warnings:v}}async doGenerate(t){const{args:n,warnings:r}=await this.getArgs(t),{responseHeaders:o,value:s,rawValue:a}=await qe({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:n,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Ke(kk),abortSignal:t.abortSignal,fetch:this.config.fetch}),u=s.choices[0],l=[];return u.text!=null&&u.text.length>0&&l.push({type:"text",text:u.text}),{content:l,usage:lD(s.usage),finishReason:{unified:dD(u.finish_reason),raw:u.finish_reason},request:{body:n},response:{...cD(s),headers:o,body:a},warnings:r}}async doStream(t){const{args:n,warnings:r}=await this.getArgs(t),o={...n,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},{responseHeaders:s,value:a}=await qe({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Ne(this.config.headers(),t.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Vn(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch});let u={unified:"other",raw:void 0},l,c=!0;return{stream:a.pipeThrough(new TransformStream({start(d){d.enqueue({type:"stream-start",warnings:r})},transform(d,f){var h;if(t.includeRawChunks&&f.enqueue({type:"raw",rawValue:d.rawValue}),!d.success){u={unified:"error",raw:void 0},f.enqueue({type:"error",error:d.error});return}const D=d.value;if("error"in D){u={unified:"error",raw:void 0},f.enqueue({type:"error",error:D.error});return}c&&(c=!1,f.enqueue({type:"response-metadata",...cD(D)}),f.enqueue({type:"text-start",id:"0"})),D.usage!=null&&(l=D.usage);const m=D.choices[0];m?.finish_reason!=null&&(u={unified:dD(m.finish_reason),raw:(h=m.finish_reason)!=null?h:void 0}),m?.text!=null&&f.enqueue({type:"text-delta",id:"0",delta:m.text})},flush(d){c||d.enqueue({type:"text-end",id:"0"}),d.enqueue({type:"finish",finishReason:u,usage:lD(l)})}})),request:{body:o},response:{headers:s}}}},i(Mr,"OpenAICompatibleCompletionLanguageModel"),Mr),pD=g({prompt_tokens:x(),completion_tokens:x(),total_tokens:x()}),kk=g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({text:p(),finish_reason:p()})),usage:pD.nullish()}),Ik=i(e=>ee([g({id:p().nullish(),created:x().nullish(),model:p().nullish(),choices:S(g({text:p(),finish_reason:p().nullish(),index:x()})),usage:pD.nullish()}),e]),"createOpenAICompatibleCompletionChunkSchema"),pu=g({dimensions:x().optional(),user:p().optional()}),Ak=(jr=class{constructor(t,n){this.specificationVersion="v3",this.modelId=t,this.config=n}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){var t;return(t=this.config.maxEmbeddingsPerCall)!=null?t:2048}get supportsParallelCalls(){var t;return(t=this.config.supportsParallelCalls)!=null?t:!0}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:o}){var s,a,u;const l=[],c=await tt({provider:"openai-compatible",providerOptions:o,schema:pu});c!=null&&l.push({type:"other",message:"The 'openai-compatible' key in providerOptions is deprecated. Use 'openaiCompatible' instead."});const d=Object.assign(c??{},(s=await tt({provider:"openaiCompatible",providerOptions:o,schema:pu}))!=null?s:{},(a=await tt({provider:this.providerOptionsName,providerOptions:o,schema:pu}))!=null?a:{});if(t.length>this.maxEmbeddingsPerCall)throw new tp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const{responseHeaders:f,value:h,rawValue:D}=await qe({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Ne(this.config.headers(),n),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:d.dimensions,user:d.user},failedResponseHandler:Dt((u=this.config.errorStructure)!=null?u:$o),successfulResponseHandler:Ke($k),abortSignal:r,fetch:this.config.fetch});return{warnings:l,embeddings:h.data.map(m=>m.embedding),usage:h.usage?{tokens:h.usage.prompt_tokens}:void 0,providerMetadata:h.providerMetadata,response:{headers:f,body:D}}}},i(jr,"OpenAICompatibleEmbeddingModel"),jr),$k=g({data:S(g({embedding:S(x())})),usage:g({prompt_tokens:x()}).nullish(),providerMetadata:be(p(),be(p(),et())).optional()}),Tk=(zr=class{constructor(t,n){this.modelId=t,this.config=n,this.specificationVersion="v3",this.maxImagesPerCall=10}get provider(){return this.config.provider}get providerOptionsKey(){return this.config.provider.split(".")[0].trim()}getArgs(t){return{...t[this.providerOptionsKey],...t[Sk(this.providerOptionsKey)]}}async doGenerate({prompt:t,n,size:r,aspectRatio:o,seed:s,providerOptions:a,headers:u,abortSignal:l,files:c,mask:d}){var f,h,D,m,v;const y=[];o!=null&&y.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&y.push({type:"unsupported",feature:"seed"});const b=(D=(h=(f=this.config._internal)==null?void 0:f.currentDate)==null?void 0:h.call(f))!=null?D:new Date,C=this.getArgs(a);if(c!=null&&c.length>0){const{value:T,responseHeaders:O}=await Mi({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:Ne(this.config.headers(),u),formData:cf({model:this.modelId,prompt:t,image:await Promise.all(c.map($=>mD($))),mask:d!=null?await mD(d):void 0,n,size:r,...C}),failedResponseHandler:Dt((m=this.config.errorStructure)!=null?m:$o),successfulResponseHandler:Ke(fD),abortSignal:l,fetch:this.config.fetch});return{images:T.data.map($=>$.b64_json),warnings:y,response:{timestamp:b,modelId:this.modelId,headers:O}}}const{value:F,responseHeaders:E}=await qe({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Ne(this.config.headers(),u),body:{model:this.modelId,prompt:t,n,size:r,...C,response_format:"b64_json"},failedResponseHandler:Dt((v=this.config.errorStructure)!=null?v:$o),successfulResponseHandler:Ke(fD),abortSignal:l,fetch:this.config.fetch});return{images:F.data.map(T=>T.b64_json),warnings:y,response:{timestamp:b,modelId:this.modelId,headers:E}}}},i(zr,"OpenAICompatibleImageModel"),zr),fD=g({data:S(g({b64_json:p()}))});async function mD(e){if(e.type==="url")return $i(e.url);const t=e.data instanceof Uint8Array?e.data:hn(e.data);return new Blob([t],{type:e.mediaType})}i(mD,"fileToBlob");function Sk(e){return e.replace(/[_-]([a-z])/g,t=>t[1].toUpperCase())}i(Sk,"toCamelCase");var Bk="2.0.30";function fu(e){const t=ji(e.baseURL),n=e.name,r={...e.apiKey&&{Authorization:`Bearer ${e.apiKey}`},...e.headers},o=i(()=>Dn(r,`ai-sdk/openai-compatible/${Bk}`),"getHeaders"),s=i(h=>({provider:`${n}.${h}`,url:i(({path:D})=>{const m=new URL(`${t}${D}`);return e.queryParams&&(m.search=new URLSearchParams(e.queryParams).toString()),m.toString()},"url"),headers:o,fetch:e.fetch}),"getCommonModelConfig"),a=i(h=>u(h),"createLanguageModel"),u=i(h=>new _k(h,{...s("chat"),includeUsage:e.includeUsage,supportsStructuredOutputs:e.supportsStructuredOutputs,transformRequestBody:e.transformRequestBody,metadataExtractor:e.metadataExtractor}),"createChatModel"),l=i(h=>new xk(h,{...s("completion"),includeUsage:e.includeUsage}),"createCompletionModel"),c=i(h=>new Ak(h,{...s("embedding")}),"createEmbeddingModel"),d=i(h=>new Tk(h,s("image")),"createImageModel"),f=i(h=>a(h),"provider");return f.specificationVersion="v3",f.languageModel=a,f.chatModel=u,f.completionModel=l,f.embeddingModel=c,f.textEmbeddingModel=c,f.imageModel=d,f}i(fu,"createOpenAICompatible");const Ok={plain:"<commit message>",conventional:`<type>[optional (<scope>)]: <commit message>
174
+ The commit message subject must start with a lowercase letter`,gitmoji:":emoji: <commit message>"},Rk=i(e=>`The output response must be in format:
175
+ ${Ok[e]}`,"specifyCommitFormat"),Nk={plain:"",conventional:`Choose a type from the type-to-description JSON below that best describes the git diff. IMPORTANT: The type MUST be lowercase (e.g., "feat", not "Feat" or "FEAT"):
176
176
  ${JSON.stringify({docs:"Documentation only changes",style:"Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)",refactor:"A code change that improves code structure without changing functionality (renaming, restructuring classes/methods, extracting functions, etc)",perf:"A code change that improves performance",test:"Adding missing tests or correcting existing tests",build:"Changes that affect the build system or external dependencies",ci:"Changes to our CI configuration files and scripts",chore:"Other changes that don't modify src or test files",revert:"Reverts a previous commit",feat:"A new feature",fix:"A bug fix"},null,2)}`,gitmoji:`Choose an emoji from the emoji-to-description JSON below that best describes the git diff:
177
- ${JSON.stringify({"\u{1F3A8}":"Improve structure / format of the code","\u26A1":"Improve performance","\u{1F525}":"Remove code or files","\u{1F41B}":"Fix a bug","\u{1F691}":"Critical hotfix","\u2728":"Introduce new features","\u{1F4DD}":"Add or update documentation","\u{1F680}":"Deploy stuff","\u{1F484}":"Add or update the UI and style files","\u{1F389}":"Begin a project","\u2705":"Add, update, or pass tests","\u{1F512}":"Fix security or privacy issues","\u{1F510}":"Add or update secrets","\u{1F516}":"Release / Version tags","\u{1F6A8}":"Fix compiler / linter warnings","\u{1F6A7}":"Work in progress","\u{1F49A}":"Fix CI Build","\u2B07\uFE0F":"Downgrade dependencies","\u2B06\uFE0F":"Upgrade dependencies","\u{1F4CC}":"Pin dependencies to specific versions","\u{1F477}":"Add or update CI build system","\u{1F4C8}":"Add or update analytics or track code","\u267B\uFE0F":"Refactor code","\u2795":"Add a dependency","\u2796":"Remove a dependency","\u{1F527}":"Add or update configuration files","\u{1F528}":"Add or update development scripts","\u{1F310}":"Internationalization and localization","\u270F\uFE0F":"Fix typos","\u{1F4A9}":"Write bad code that needs to be improved","\u23EA":"Revert changes","\u{1F500}":"Merge branches","\u{1F4E6}":"Add or update compiled files or packages","\u{1F47D}":"Update code due to external API changes","\u{1F69A}":"Move or rename resources (e.g.: files, paths, routes)","\u{1F4C4}":"Add or update license","\u{1F4A5}":"Introduce breaking changes","\u{1F371}":"Add or update assets","\u267F":"Improve accessibility","\u{1F4A1}":"Add or update comments in source code","\u{1F37B}":"Write code drunkenly","\u{1F4AC}":"Add or update text and literals","\u{1F5C3}":"Perform database related changes","\u{1F50A}":"Add or update logs","\u{1F507}":"Remove logs","\u{1F465}":"Add or update contributor(s)","\u{1F6B8}":"Improve user experience / usability","\u{1F3D7}":"Make architectural changes","\u{1F4F1}":"Work on responsive design","\u{1F921}":"Mock things","\u{1F95A}":"Add or update an easter egg","\u{1F648}":"Add or update a .gitignore file","\u{1F4F8}":"Add or update snapshots","\u2697":"Perform experiments","\u{1F50D}":"Improve SEO","\u{1F3F7}":"Add or update types","\u{1F331}":"Add or update seed files","\u{1F6A9}":"Add, update, or remove feature flags","\u{1F945}":"Catch errors","\u{1F4AB}":"Add or update animations and transitions","\u{1F5D1}":"Deprecate code that needs to be cleaned up","\u{1F6C2}":"Work on code related to authorization, roles and permissions","\u{1FA79}":"Simple fix for a non-critical issue","\u{1F9D0}":"Data exploration/inspection","\u26B0":"Remove dead code","\u{1F9EA}":"Add a failing test","\u{1F454}":"Add or update business logic","\u{1FA7A}":"Add or update healthcheck","\u{1F9F1}":"Infrastructure related changes","\u{1F9D1}\u200D\u{1F4BB}":"Improve developer experience","\u{1F4B8}":"Add sponsorships or money related infrastructure","\u{1F9F5}":"Add or update code related to multithreading or concurrency","\u{1F9BA}":"Add or update code related to validation"},null,2)}`},Rk=i((e,t,n,r)=>["Generate a concise git commit message title in present tense that precisely describes the key changes in the following code diff. Focus on what was changed, not just file names. Provide only the title, no description or body.",`Message language: ${e}`,`Commit message must be a maximum of ${t} characters.`,"Exclude anything unnecessary such as translation. Your entire response will be passed directly into git commit.",`IMPORTANT: Do not include any explanations, introductions, or additional text. Do not wrap the commit message in quotes or any other formatting. The commit message must not exceed ${t} characters. Respond with ONLY the commit message text.`,"Be specific: include concrete details (package names, versions, functionality) rather than generic statements.",r,Ok[n],Bk(n)].filter(Boolean).join(`
178
- `),"generatePrompt"),Nk=i(e=>{const t=/<think>[\s\S]*?<\/think>/gi;let n=e.replace(t,"");return n=n.trim(),n},"extractResponseFromReasoning"),mu=i(e=>Nk(e).trim().split(`
179
- `)[0].replace(/(\w)\.$/,"$1").replace(/^["'`]|["'`]$/g,"").replace(/^<[^>]*>\s*/,""),"sanitizeMessage"),hD=i(e=>Array.from(new Set(e)),"deduplicateMessages"),DD=i(async(e,t,n,r,o)=>{const s=new AbortController,a=setTimeout(()=>s.abort(),o);try{const u=await Ao({model:e(t),system:`You are a tool that shortens git commit messages. Given a commit message, make it shorter while preserving the key information and format. The shortened message must be ${r} characters or less. Respond with ONLY the shortened commit message.`,prompt:n,temperature:.2,maxRetries:2,maxOutputTokens:500});return clearTimeout(a),mu(u.text)}catch(u){throw clearTimeout(a),u}},"shortenCommitMessage"),hu=i(async(e,t,n,r,o,s,a,u,l,c)=>{process.env.DEBUG&&(console.log("Diff being sent to AI:"),console.log(o));try{const d=e==="https://api.openai.com/v1"?Va({apiKey:t}):fu({name:"custom",apiKey:t,baseURL:e}),f=new AbortController,h=setTimeout(()=>f.abort(),l),D=Array.from({length:s},()=>Ao({model:d(n),system:Rk(r,a,u,c),prompt:o,temperature:.4,maxRetries:2,maxOutputTokens:2e3}).finally(()=>clearTimeout(h))),m=await Promise.all(D);let v=m.map(C=>C.text),y=hD(v.map(C=>mu(C)));const b=3;for(let C=0;C<b;C++){let x=!1;const T=await Promise.all(y.map(async O=>{if(O.length<=a)return O;x=!0;try{return await DD(d,n,O,a,l)}catch{return O}}));if(y=hD(T),!x)break}const w={prompt_tokens:m.reduce((C,x)=>C+(x.usage.promptTokens||0),0),completion_tokens:m.reduce((C,x)=>C+(x.usage.completionTokens||0),0),total_tokens:m.reduce((C,x)=>C+(x.usage.totalTokens||0),0)};return{messages:y,usage:w}}catch(d){const f=d;if(console.log(f),f.code==="ENOTFOUND")throw new he(`Error connecting to ${f.hostname} (${f.syscall}). Are you connected to the internet?`);if(f.status===429){const h=f.headers?.get("x-ratelimit-reset");let D="Rate limit exceeded";if(h){const m=parseInt(h),v=Date.now(),y=m-v,b=Math.ceil(y/1e3);if(b>0){let w;if(b<60)w=`${b} second${b===1?"":"s"}`;else if(b<3600){const C=Math.ceil(b/60);w=`${C} minute${C===1?"":"s"}`}else{const C=Math.ceil(b/3600);w=`${C} hour${C===1?"":"s"}`}D+=`. Retry in ${w}.`}}throw new he(D)}throw f}},"generateCommitMessage"),Pk=i(async(e,t,n,r,o,s,a,u,l)=>{try{const c=t==="https://api.openai.com/v1"?Va({apiKey:n}):fu({name:"custom",apiKey:n,baseURL:t}),d=new AbortController,f=setTimeout(()=>d.abort(),u),D=await Ao({model:c(r),system:`You are a tool that generates git commit messages. Your task is to combine multiple commit messages into one.
177
+ ${JSON.stringify({"\u{1F3A8}":"Improve structure / format of the code","\u26A1":"Improve performance","\u{1F525}":"Remove code or files","\u{1F41B}":"Fix a bug","\u{1F691}":"Critical hotfix","\u2728":"Introduce new features","\u{1F4DD}":"Add or update documentation","\u{1F680}":"Deploy stuff","\u{1F484}":"Add or update the UI and style files","\u{1F389}":"Begin a project","\u2705":"Add, update, or pass tests","\u{1F512}":"Fix security or privacy issues","\u{1F510}":"Add or update secrets","\u{1F516}":"Release / Version tags","\u{1F6A8}":"Fix compiler / linter warnings","\u{1F6A7}":"Work in progress","\u{1F49A}":"Fix CI Build","\u2B07\uFE0F":"Downgrade dependencies","\u2B06\uFE0F":"Upgrade dependencies","\u{1F4CC}":"Pin dependencies to specific versions","\u{1F477}":"Add or update CI build system","\u{1F4C8}":"Add or update analytics or track code","\u267B\uFE0F":"Refactor code","\u2795":"Add a dependency","\u2796":"Remove a dependency","\u{1F527}":"Add or update configuration files","\u{1F528}":"Add or update development scripts","\u{1F310}":"Internationalization and localization","\u270F\uFE0F":"Fix typos","\u{1F4A9}":"Write bad code that needs to be improved","\u23EA":"Revert changes","\u{1F500}":"Merge branches","\u{1F4E6}":"Add or update compiled files or packages","\u{1F47D}":"Update code due to external API changes","\u{1F69A}":"Move or rename resources (e.g.: files, paths, routes)","\u{1F4C4}":"Add or update license","\u{1F4A5}":"Introduce breaking changes","\u{1F371}":"Add or update assets","\u267F":"Improve accessibility","\u{1F4A1}":"Add or update comments in source code","\u{1F37B}":"Write code drunkenly","\u{1F4AC}":"Add or update text and literals","\u{1F5C3}":"Perform database related changes","\u{1F50A}":"Add or update logs","\u{1F507}":"Remove logs","\u{1F465}":"Add or update contributor(s)","\u{1F6B8}":"Improve user experience / usability","\u{1F3D7}":"Make architectural changes","\u{1F4F1}":"Work on responsive design","\u{1F921}":"Mock things","\u{1F95A}":"Add or update an easter egg","\u{1F648}":"Add or update a .gitignore file","\u{1F4F8}":"Add or update snapshots","\u2697":"Perform experiments","\u{1F50D}":"Improve SEO","\u{1F3F7}":"Add or update types","\u{1F331}":"Add or update seed files","\u{1F6A9}":"Add, update, or remove feature flags","\u{1F945}":"Catch errors","\u{1F4AB}":"Add or update animations and transitions","\u{1F5D1}":"Deprecate code that needs to be cleaned up","\u{1F6C2}":"Work on code related to authorization, roles and permissions","\u{1FA79}":"Simple fix for a non-critical issue","\u{1F9D0}":"Data exploration/inspection","\u26B0":"Remove dead code","\u{1F9EA}":"Add a failing test","\u{1F454}":"Add or update business logic","\u{1FA7A}":"Add or update healthcheck","\u{1F9F1}":"Infrastructure related changes","\u{1F9D1}\u200D\u{1F4BB}":"Improve developer experience","\u{1F4B8}":"Add sponsorships or money related infrastructure","\u{1F9F5}":"Add or update code related to multithreading or concurrency","\u{1F9BA}":"Add or update code related to validation"},null,2)}`},Pk=i((e,t,n,r)=>["Generate a concise git commit message title in present tense that precisely describes the key changes in the following code diff. Focus on what was changed, not just file names. Provide only the title, no description or body.",`Message language: ${e}`,`Commit message must be a maximum of ${t} characters.`,"Exclude anything unnecessary such as translation. Your entire response will be passed directly into git commit.",`IMPORTANT: Do not include any explanations, introductions, or additional text. Do not wrap the commit message in quotes or any other formatting. The commit message must not exceed ${t} characters. Respond with ONLY the commit message text.`,"Be specific: include concrete details (package names, versions, functionality) rather than generic statements.",r,Nk[n],Rk(n)].filter(Boolean).join(`
178
+ `),"generatePrompt"),Mk=i(e=>{const t=/<think>[\s\S]*?<\/think>/gi;let n=e.replace(t,"");return n=n.trim(),n},"extractResponseFromReasoning"),mu=i(e=>Mk(e).trim().split(`
179
+ `)[0].replace(/(\w)\.$/,"$1").replace(/^["'`]|["'`]$/g,"").replace(/^<[^>]*>\s*/,""),"sanitizeMessage"),hD=i(e=>Array.from(new Set(e)),"deduplicateMessages"),DD=i(async(e,t,n,r,o)=>{const s=new AbortController,a=setTimeout(()=>s.abort(),o);try{const u=await Ao({model:e(t),system:`You are a tool that shortens git commit messages. Given a commit message, make it shorter while preserving the key information and format. The shortened message must be ${r} characters or less. Respond with ONLY the shortened commit message.`,prompt:n,temperature:.2,maxRetries:2,maxOutputTokens:500,abortSignal:s.signal});return clearTimeout(a),mu(u.text)}catch(u){throw clearTimeout(a),u}},"shortenCommitMessage"),hu=i(async(e,t,n,r,o,s,a,u,l,c,d)=>{process.env.DEBUG&&(console.log("Diff being sent to AI:"),console.log(o));try{const f=e==="https://api.openai.com/v1"?Va({apiKey:t}):fu({name:"custom",apiKey:t,baseURL:e,headers:d}),h=new AbortController,D=setTimeout(()=>h.abort(),l),m=Array.from({length:s},()=>Ao({model:f(n),system:Pk(r,a,u,c),prompt:o,temperature:.4,maxRetries:2,maxOutputTokens:2e3,abortSignal:h.signal})),v=await(async()=>{try{return await Promise.all(m)}finally{clearTimeout(D)}})();let y=v.map(E=>E.text),b=hD(y.map(E=>mu(E)));const C=3;for(let E=0;E<C;E++){let T=!1;const O=await Promise.all(b.map(async $=>{if($.length<=a)return $;T=!0;try{return await DD(f,n,$,a,l)}catch{return $}}));if(b=hD(O),!T)break}const F={prompt_tokens:v.reduce((E,T)=>E+(T.usage.promptTokens||0),0),completion_tokens:v.reduce((E,T)=>E+(T.usage.completionTokens||0),0),total_tokens:v.reduce((E,T)=>E+(T.usage.totalTokens||0),0)};return{messages:b,usage:F}}catch(f){const h=f;if(console.log(h),h.code==="ENOTFOUND")throw new he(`Error connecting to ${h.hostname} (${h.syscall}). Are you connected to the internet?`);if(h.status===429){const D=h.headers?.get("x-ratelimit-reset");let m="Rate limit exceeded";if(D){const v=parseInt(D),y=Date.now(),b=v-y,C=Math.ceil(b/1e3);if(C>0){let F;if(C<60)F=`${C} second${C===1?"":"s"}`;else if(C<3600){const E=Math.ceil(C/60);F=`${E} minute${E===1?"":"s"}`}else{const E=Math.ceil(C/3600);F=`${E} hour${E===1?"":"s"}`}m+=`. Retry in ${F}.`}}throw new he(m)}throw h}},"generateCommitMessage"),jk=i(async(e,t,n,r,o,s,a,u,l,c)=>{try{const d=t==="https://api.openai.com/v1"?Va({apiKey:n}):fu({name:"custom",apiKey:n,baseURL:t,headers:c}),f=new AbortController,h=setTimeout(()=>f.abort(),u),m=await Ao({model:d(r),system:`You are a tool that generates git commit messages. Your task is to combine multiple commit messages into one.
180
180
 
181
181
  Input: Several commit messages separated by newlines.
182
182
  Output: A single commit message starting with type like 'feat:' or 'fix:'.
183
183
 
184
184
  Do not add thanks, explanations, or any text outside the commit message.`,prompt:e.join(`
185
- `),temperature:.4,maxRetries:2,maxOutputTokens:2e3});clearTimeout(f);let m=mu(D.text);if(m.length>s)try{m=await DD(c,r,m,s,u)}catch{}return{messages:[m],usage:D.usage}}catch(c){const d=c;throw console.log(d),d}},"combineCommitMessages"),Mk=i(async(e,t)=>{const{select:n,confirm:r,isCancel:o}=await Promise.resolve().then(function(){return ro}),{dim:s}=await Promise.resolve().then(function(){return Ay}),a=process.stdout.isTTY&&!process.env.CI;if(e.length===1){const[l]=e;if(t)return l;if(!a)throw new he("Interactive terminal required for commit message confirmation. Use --yes flag to skip confirmation.");console.log(`
185
+ `),temperature:.4,maxRetries:2,maxOutputTokens:2e3,abortSignal:f.signal});clearTimeout(h);let v=mu(m.text);if(v.length>s)try{v=await DD(d,r,v,s,u)}catch{}return{messages:[v],usage:m.usage}}catch(d){const f=d;throw console.log(f),f}},"combineCommitMessages"),zk=i(async(e,t)=>{const{select:n,confirm:r,isCancel:o}=await Promise.resolve().then(function(){return ro}),{dim:s}=await Promise.resolve().then(function(){return Ay}),a=process.stdout.isTTY&&!process.env.CI;if(e.length===1){const[l]=e;if(t)return l;if(!a)throw new he("Interactive terminal required for commit message confirmation. Use --yes flag to skip confirmation.");console.log(`
186
186
  \x1B[1m${l}\x1B[0m
187
- `);const c=await r({message:"Use this commit message?"});return c&&!o(c)?l:null}if(t)return e[0];if(!a)throw new he("Interactive terminal required for commit message selection. Use --yes flag to skip selection and use the first message.");const u=await n({message:`Pick a commit message to use: ${s("(Ctrl+c to exit)")}`,options:e.map(l=>({label:l,value:l}))});return o(u)?null:u},"getCommitMessage");var jk=i(async(e,t,n,r,o,s,a,u,l)=>(async()=>{na(Ko(Jo(" aicommits "))),await Qs();const c=Vt();n&&await Je("git",["add","--update"]),c.start("Detecting staged files");const d=await ld(t);if(!d)throw c.stop("Detecting staged files"),new he("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");d.files.length<=10?c.stop(`\u{1F4C1} ${cd(d.files)}:
187
+ `);const c=await r({message:"Use this commit message?"});return c&&!o(c)?l:null}if(t)return e[0];if(!a)throw new he("Interactive terminal required for commit message selection. Use --yes flag to skip selection and use the first message.");const u=await n({message:`Pick a commit message to use: ${s("(Ctrl+c to exit)")}`,options:e.map(l=>({label:l,value:l}))});return o(u)?null:u},"getCommitMessage");var Lk=i(async(e,t,n,r,o,s,a,u,l)=>(async()=>{na(Ko(Jo(" aicommits "))),await Qs();const c=Vt();n&&await Je("git",["add","--update"]),c.start("Detecting staged files");const d=await ld(t);if(!d)throw c.stop("Detecting staged files"),new he("No staged changes found. Stage your changes manually, or automatically stage all changes with the `--all` flag.");d.files.length<=10?c.stop(`\u{1F4C1} ${cd(d.files)}:
188
188
  ${d.files.map(I=>` ${I}`).join(`
189
- `)}`):c.stop(`\u{1F4C1} ${cd(d.files)}`);const{env:f}=process,h=await ln({generate:e?.toString(),type:r?.toString()}),D=Rn(h);if(!D)if(process.stdout.isTTY&&!process.env.CI){console.log("Welcome to aicommits! Let's set up your AI provider."),console.log("Run `aicommits setup` to configure your provider."),Ee("Setup required. Please run: aicommits setup");return}else throw new he("No configuration found. Run `aicommits setup` in an interactive terminal, or set environment variables (OPENAI_API_KEY, etc.)");const m=h.timeout||(D.name==="ollama"?3e4:1e4),v=D.validateConfig();if(!v.valid)throw new he(`Provider configuration issues: ${v.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);h.model=h.OPENAI_MODEL||D.getDefaultModel();const y=50,b=10;let w=!1;d.files.length>y&&(w=!0);const C=Vt();C.start(`\u{1F50D} Analyzing changes in ${d.files.length} file${d.files.length===1?"":"s"}`);const x=Date.now();let T,O;try{const I=D.getBaseUrl(),re=D.getApiKey()||"";if(w){const k=[];for(let z=0;z<d.files.length;z+=b)k.push(d.files.slice(z,z+b));const X=[];let S={promptTokens:0,completionTokens:0,totalTokens:0};for(const z of k){const Z=await f0(z,t);if(Z&&Z.diff){let J=Z.diff;J.length>3e4&&(J=J.substring(J.length-3e4)+`
190
-
191
- [Diff truncated due to size]`);const pe=await hu(I,re,h.model,h.locale,J,h.generate,h["max-length"],h.type,m,u);X.push(...pe.messages),pe.usage&&(S.promptTokens+=pe.usage.promptTokens||0,S.completionTokens+=pe.usage.completionTokens||0,S.totalTokens+=pe.usage.totalTokens||0)}}const j=await Pk(X,I,re,h.model,h.locale,h["max-length"],h.type,m,u);T=j.messages,j.usage&&(S.promptTokens+=j.usage.promptTokens||0,S.completionTokens+=j.usage.completionTokens||0,S.totalTokens+=j.usage.totalTokens||0),O=S}else{let X=d.diff;X.length>3e4&&(X=X.substring(X.length-3e4)+`
192
-
193
- [Diff truncated due to size]`);const S=await hu(I,re,h.model,h.locale,X,h.generate,h["max-length"],h.type,m,u);T=S.messages,O=S.usage}}finally{const I=Date.now()-x;let re="";if(O?.total_tokens){const k=O.total_tokens,X=k>=1e3?`${(k/1e3).toFixed(0)}k`:k.toString(),S=Math.round(k/(I/1e3));re=`, ${X} tokens (${S} tokens/s)`}C.stop(`\u2705 Changes analyzed in ${(I/1e3).toFixed(1)}s${re}`)}if(T.length===0)throw new he("No commit messages were generated. Try again.");const $=await Mk(T,o);if(!$){Ee("Commit cancelled");return}if(s){await zc($)&&Ee(`${St("\u2714")} Message copied to clipboard`);return}try{const I=["-m",$];a&&I.push("--no-verify"),await Je("git",["commit",...I,...l],{stdio:"inherit",cleanup:!0,timeout:1e4}),Ee(`${St("\u2714")} Successfully committed!`)}catch(I){if(I.timedOut){const re=await zc($);Ee(re?`${Ns("\u26A0")} Commit timed out after 10 seconds. Message copied to clipboard.`:`${Ns("\u26A0")} Commit timed out after 10 seconds. Could not copy to clipboard.`);return}throw I}})().catch(ra),"aicommits");const[Wa,zk]=process.argv.slice(2);var Lk=i(()=>(async()=>{if(!Wa)throw new he('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook');if(zk)return;const e=await ld();if(!e)return;na(Ko(Jo(" aicommits ")));const t=await ln({}),n=Rn(t);if(!n)throw new he("Invalid provider configuration. Run `aicommits setup` to reconfigure.");const r=n.validateConfig();if(!r.valid)throw new he(`Provider configuration issues: ${r.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);const o=n.getBaseUrl(),s=n.getApiKey()||"",a=t.timeout||(n.name==="ollama"?3e4:1e4);let u=t.OPENAI_MODEL||n.getDefaultModel();const l=Vt();l.start("The AI is analyzing your changes");let c;try{c=(await hu(o,s,u,t.locale,e.diff,t.generate,t["max-length"],t.type,a)).messages}finally{l.stop("Changes analyzed")}const f=await He.readFile(Wa,"utf8")!=="",h=c.length>1;let D="";f&&(D=`# \u{1F916} AI generated commit${h?"s":""}
194
- `),h?(f&&(D+=`# Select one of the following messages by uncommenting:
195
- `),D+=`
196
- ${c.map(y=>`# ${y}`).join(`
197
- `)}`):(f&&(D+=`# Edit the message below and commit:
198
- `),D+=`
199
- ${c[0]}
200
- `);const m=await He.readFile(Wa,"utf8"),v=D+`
201
- `+m;await He.writeFile(Wa,v),Ee(`${St("\u2714")} Saved commit message!`)})().catch(ra),"prepareCommitMessageHook"),qk=An({name:"config",description:"View or modify configuration settings",help:{description:"View or modify configuration settings"},parameters:["[mode]","[key=value...]"]},e=>{(async()=>{const[t,...n]=e._;if(!t){const r=await ln({},{},!0);console.log("Provider:",r.provider),r.OPENAI_API_KEY&&console.log("API Key:",`${r.OPENAI_API_KEY.substring(0,4)}****`),r.OPENAI_BASE_URL&&console.log("Base URL:",r.OPENAI_BASE_URL),r.OPENAI_MODEL&&console.log("Model:",r.OPENAI_MODEL);return}if(t==="get"){const r=await ln({},{},!0),o=["OPENAI_API_KEY","TOGETHER_API_KEY","api-key"];for(const s of n)if(ni(r,s)){const a=r[s],u=o.includes(s)?`${String(a).substring(0,4)}****`:String(a);console.log(`${s}=${u}`)}return}if(t==="set"){await oi(n.map(r=>r.split("=")));return}throw new he(`Invalid mode: ${t}`)})().catch(ra)}),Uk=An({name:"setup",description:"Configure your AI provider and settings",help:{description:"Configure your AI provider and settings"}},e=>{(async()=>{let t=await ln();const n=P0(),r=await Ys({message:"Choose your AI provider:",options:n,initialValue:t.provider});if(Bn(r)){Ee("Setup cancelled");return}const o=r;let s="";if(o==="custom"){const D=await ad({message:"Enter your custom API endpoint:",validate:i(m=>{if(!m)return"Endpoint is required";try{new URL(m)}catch{return"Invalid URL format"}},"validate")});if(Bn(D)){Ee("Setup cancelled");return}s=D}let a=s||M0(o);t.OPENAI_BASE_URL=a,t.OPENAI_API_KEY="",t.OPENAI_MODEL="";let u=Rn({...t,provider:o});if(!u){Ee("Invalid provider selected");return}try{const D=await u.setup();for(const[m,v]of D)t[m]=v}catch(D){if(D instanceof Error&&D.message==="Setup cancelled"){Ee("Setup cancelled");return}throw D}if(u=Rn({...t,provider:o}),!u){Ee("Invalid provider selected");return}const l=u.validateConfig();if(!l.valid){Ee(`Setup cancelled: ${l.errors.join(", ")}`);return}const{selectModel:c}=await Promise.resolve().then(function(){return O0}),d=await c(u.getBaseUrl(),u.getApiKey()||"",void 0,u.getDefinition());if(d)t.OPENAI_MODEL=d,console.log(`Model selected: ${d}`);else{Ee("Model selection cancelled.");return}const f=await Ys({message:"Choose commit message format:",options:[{value:"plain",label:"Plain - Simple format without structure"},{value:"conventional",label:"Conventional - Standard conventional commits"},{value:"gitmoji",label:"Gitmoji - Using emojis for commit types"}],initialValue:"plain"});if(Bn(f)){Ee("Setup cancelled");return}t.type=f;const h=Object.entries(t).filter(([D,m])=>D!=="provider"&&D!=="model"&&m!==void 0&&m!==""&&typeof m=="string");await oi(h),Ee(`\u2705 Setup complete! You're now using ${u.displayName}.`)})().catch(t=>{console.error(`\u274C Setup failed: ${t.message}`),process.exit(1)})}),Zk=An({name:"model",description:"Select or change your AI model",help:{description:"Select or change your AI model"},alias:["-m","models"]},()=>{(async()=>{const e=await ln();if(!e.provider){Ee("No provider configured. Run `aicommits setup` first.");return}const t=Rn(e);if(!t){Ee("Invalid provider configured. Run `aicommits setup` to reconfigure.");return}const n=e.OPENAI_MODEL,r=t.validateConfig();if(!r.valid){Ee(`Configuration issues: ${r.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);return}const o=await gd(t.getBaseUrl(),t.getApiKey()||"",n,t.getDefinition(),t.displayName);o?(await oi([["OPENAI_MODEL",o]]),Ee(`\u2705 Model updated to: ${o}`)):Ee("Model selection cancelled")})().catch(e=>{console.error(`\u274C Model selection failed: ${e.message}`),process.exit(1)})});const gD="prepare-commit-msg",vD=`.git/hooks/${gD}`,Ha=WD(new URL("cli.mjs",import.meta.url)),yD=process.argv[1].replace(/\\/g,"/").endsWith(`/${vD}`),_D=process.platform==="win32",bD=`
189
+ `)}`):c.stop(`\u{1F4C1} ${cd(d.files)}`);const{env:f}=process,h=await ln({generate:e?.toString(),type:r?.toString()}),D=Rn(h);if(!D)if(process.stdout.isTTY&&!process.env.CI){console.log("Welcome to aicommits! Let's set up your AI provider."),console.log("Run `aicommits setup` to configure your provider."),Ee("Setup required. Please run: aicommits setup");return}else throw new he("No configuration found. Run `aicommits setup` in an interactive terminal, or set environment variables (OPENAI_API_KEY, etc.)");const m=h.timeout||(D.name==="ollama"?3e4:1e4),v=D.validateConfig();if(!v.valid)throw new he(`Provider configuration issues: ${v.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);h.model=h.OPENAI_MODEL||D.getDefaultModel();const y=50,b=10;let C=!1;d.files.length>y&&(C=!0);const F=Vt();F.start(`\u{1F50D} Analyzing changes in ${d.files.length} file${d.files.length===1?"":"s"}`);const E=Date.now();let T,O;try{const I=D.getBaseUrl(),oe=D.getApiKey()||"",k=D.getHeaders();if(C){const re=[];for(let U=0;U<d.files.length;U+=b)re.push(d.files.slice(U,U+b));const B=[];let P={prompt_tokens:0,completion_tokens:0,total_tokens:0};for(const U of re){const R=await f0(U,t);if(R&&R.diff){let me=R.diff;me.length>3e4&&(me=me.substring(0,3e4)+`
190
+
191
+ [Diff truncated due to size]`);const X=await hu(I,oe,h.model,h.locale,me,h.generate,h["max-length"],h.type,m,u,k);B.push(...X.messages),X.usage&&(P.prompt_tokens+=X.usage.prompt_tokens||X.usage.promptTokens||0,P.completion_tokens+=X.usage.completion_tokens||X.usage.completionTokens||0,P.total_tokens+=X.usage.total_tokens||X.usage.totalTokens||0)}}const z=await jk(B,I,oe,h.model,h.locale,h["max-length"],h.type,m,u,k);T=z.messages,z.usage&&(P.prompt_tokens+=z.usage.prompt_tokens||z.usage.promptTokens||0,P.completion_tokens+=z.usage.completion_tokens||z.usage.completionTokens||0,P.total_tokens+=z.usage.total_tokens||z.usage.totalTokens||0),O=P}else{let B=d.diff;B.length>3e4&&(B=B.substring(0,3e4)+`
192
+
193
+ [Diff truncated due to size]`);const P=await hu(I,oe,h.model,h.locale,B,h.generate,h["max-length"],h.type,m,u,k);T=P.messages,O=P.usage}}finally{const I=Date.now()-E;let oe="";if(O?.total_tokens){const k=O.total_tokens,re=k>=1e3?`${(k/1e3).toFixed(0)}k`:k.toString(),B=Math.round(k/(I/1e3));oe=`, ${re} tokens (${B} tokens/s)`}F.stop(`\u2705 Changes analyzed in ${(I/1e3).toFixed(1)}s${oe}`)}if(T.length===0)throw new he("No commit messages were generated. Try again.");const $=await zk(T,o);if(!$){Ee("Commit cancelled");return}if(s){await zc($)&&Ee(`${St("\u2714")} Message copied to clipboard`);return}try{const I=["-m",$];a&&I.push("--no-verify"),await Je("git",["commit",...I,...l],{stdio:"inherit",cleanup:!0,timeout:1e4}),Ee(`${St("\u2714")} Successfully committed!`)}catch(I){if(I.timedOut){const oe=await zc($);Ee(oe?`${Ns("\u26A0")} Commit timed out after 10 seconds. Message copied to clipboard.`:`${Ns("\u26A0")} Commit timed out after 10 seconds. Could not copy to clipboard.`);return}throw I}})().catch(ra),"aicommits");const[Wa,qk]=process.argv.slice(2);var Uk=i(()=>(async()=>{if(!Wa)throw new he('Commit message file path is missing. This file should be called from the "prepare-commit-msg" git hook');if(qk)return;const e=await ld();if(!e)return;na(Ko(Jo(" aicommits ")));const t=await ln({}),n=Rn(t);if(!n)throw new he("Invalid provider configuration. Run `aicommits setup` to reconfigure.");const r=n.validateConfig();if(!r.valid)throw new he(`Provider configuration issues: ${r.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);const o=n.getBaseUrl(),s=n.getApiKey()||"",a=n.getHeaders(),u=t.timeout||(n.name==="ollama"?3e4:1e4);let l=t.OPENAI_MODEL||n.getDefaultModel();const c=Vt();c.start("The AI is analyzing your changes");let d;try{d=(await hu(o,s,l,t.locale,e.diff,t.generate,t["max-length"],t.type,u,void 0,a)).messages}finally{c.stop("Changes analyzed")}const h=await He.readFile(Wa,"utf8")!=="",D=d.length>1;let m="";h&&(m=`# \u{1F916} AI generated commit${D?"s":""}
194
+ `),D?(h&&(m+=`# Select one of the following messages by uncommenting:
195
+ `),m+=`
196
+ ${d.map(b=>`# ${b}`).join(`
197
+ `)}`):(h&&(m+=`# Edit the message below and commit:
198
+ `),m+=`
199
+ ${d[0]}
200
+ `);const v=await He.readFile(Wa,"utf8"),y=m+`
201
+ `+v;await He.writeFile(Wa,y),Ee(`${St("\u2714")} Saved commit message!`)})().catch(ra),"prepareCommitMessageHook"),Zk=An({name:"config",description:"View or modify configuration settings",help:{description:"View or modify configuration settings"},parameters:["[mode]","[key=value...]"]},e=>{(async()=>{const[t,...n]=e._;if(!t){const r=await ln({},{},!0);console.log("Provider:",r.provider),r.OPENAI_API_KEY&&console.log("API Key:",`${r.OPENAI_API_KEY.substring(0,4)}****`),r.OPENAI_BASE_URL&&console.log("Base URL:",r.OPENAI_BASE_URL),r.OPENAI_MODEL&&console.log("Model:",r.OPENAI_MODEL);return}if(t==="get"){const r=await ln({},{},!0),o=["OPENAI_API_KEY","TOGETHER_API_KEY","api-key"];for(const s of n)if(ni(r,s)){const a=r[s],u=o.includes(s)?`${String(a).substring(0,4)}****`:String(a);console.log(`${s}=${u}`)}return}if(t==="set"){await oi(n.map(r=>r.split("=")));return}throw new he(`Invalid mode: ${t}`)})().catch(ra)}),Vk=An({name:"setup",description:"Configure your AI provider and settings",help:{description:"Configure your AI provider and settings"}},e=>{(async()=>{let t=await ln();const n=j0(),r=await Ys({message:"Choose your AI provider:",options:n,initialValue:t.provider});if(Bn(r)){Ee("Setup cancelled");return}const o=r;let s="";if(o==="custom"){const D=await ad({message:"Enter your custom API endpoint:",validate:i(m=>{if(!m)return"Endpoint is required";try{new URL(m)}catch{return"Invalid URL format"}},"validate")});if(Bn(D)){Ee("Setup cancelled");return}s=D}let a=s||z0(o);t.OPENAI_BASE_URL=a,t.OPENAI_API_KEY="",t.OPENAI_MODEL="";let u=Rn({...t,provider:o});if(!u){Ee("Invalid provider selected");return}try{const D=await u.setup();for(const[m,v]of D)t[m]=v}catch(D){if(D instanceof Error&&D.message==="Setup cancelled"){Ee("Setup cancelled");return}throw D}if(u=Rn({...t,provider:o}),!u){Ee("Invalid provider selected");return}const l=u.validateConfig();if(!l.valid){Ee(`Setup cancelled: ${l.errors.join(", ")}`);return}const{selectModel:c}=await Promise.resolve().then(function(){return N0}),d=await c(u.getBaseUrl(),u.getApiKey()||"",void 0,u.getDefinition());if(d)t.OPENAI_MODEL=d,console.log(`Model selected: ${d}`);else{Ee("Model selection cancelled.");return}const f=await Ys({message:"Choose commit message format:",options:[{value:"plain",label:"Plain - Simple format without structure"},{value:"conventional",label:"Conventional - Standard conventional commits"},{value:"gitmoji",label:"Gitmoji - Using emojis for commit types"}],initialValue:"plain"});if(Bn(f)){Ee("Setup cancelled");return}t.type=f;const h=Object.entries(t).filter(([D,m])=>D!=="provider"&&D!=="model"&&m!==void 0&&m!==""&&typeof m=="string");await oi(h),Ee(`\u2705 Setup complete! You're now using ${u.displayName}.`)})().catch(t=>{console.error(`\u274C Setup failed: ${t.message}`),process.exit(1)})}),Gk=An({name:"model",description:"Select or change your AI model",help:{description:"Select or change your AI model"},alias:["-m","models"]},()=>{(async()=>{const e=await ln();if(!e.provider){Ee("No provider configured. Run `aicommits setup` first.");return}const t=Rn(e);if(!t){Ee("Invalid provider configured. Run `aicommits setup` to reconfigure.");return}const n=e.OPENAI_MODEL,r=t.validateConfig();if(!r.valid){Ee(`Configuration issues: ${r.errors.join(", ")}. Run \`aicommits setup\` to reconfigure.`);return}const o=await gd(t.getBaseUrl(),t.getApiKey()||"",n,t.getDefinition(),t.displayName);o?(await oi([["OPENAI_MODEL",o]]),Ee(`\u2705 Model updated to: ${o}`)):Ee("Model selection cancelled")})().catch(e=>{console.error(`\u274C Model selection failed: ${e.message}`),process.exit(1)})});const gD="prepare-commit-msg",vD=`.git/hooks/${gD}`,Ha=WD(new URL("cli.mjs",import.meta.url)),yD=process.argv[1].replace(/\\/g,"/").endsWith(`/${vD}`),_D=process.platform==="win32",bD=`
202
202
  #!/usr/bin/env node
203
203
  import(${JSON.stringify(HD(Ha))})
204
- `.trim();var Vk=An({name:"hook",description:"Install or uninstall the Git hook for automatic commit messages",help:{description:"Install or uninstall the Git hook for automatic commit messages"},parameters:["<install/uninstall>"]},e=>{(async()=>{const t=await Qs(),{installUninstall:n}=e._,r=bt.join(t,vD),o=await ti(r);if(n==="install"){if(o){if(await He.realpath(r).catch(()=>{})===Ha){console.warn("The hook is already installed");return}throw new he(`A different ${gD} hook seems to be installed. Please remove it before installing aicommits.`)}await He.mkdir(bt.dirname(r),{recursive:!0}),_D?await He.writeFile(r,bD):(await He.symlink(Ha,r,"file"),await He.chmod(r,493)),console.log(`${St("\u2714")} Hook installed`);return}if(n==="uninstall"){if(!o){console.warn("Hook is not installed");return}if(_D){if(await He.readFile(r,"utf8")!==bD){console.warn("Hook is not installed");return}}else if(await He.realpath(r)!==Ha){console.warn("Hook is not installed");return}await He.rm(r),console.log(`${St("\u2714")} Hook uninstalled`);return}throw new he(`Invalid mode: ${n}`)})().catch(t=>{console.error(`${Rs("\u2716")} ${t.message}`),sd(t),process.exit(1)})});function Gk(e){const t=e.match(/github\.com[\/:]([^\/]+)\/([^\/\.]+)/);if(t)return{provider:"github",owner:t[1],repo:t[2]};const n=e.match(/gitlab\.com[\/:]([^\/]+)\/([^\/\.]+)/);if(n)return{provider:"gitlab",owner:n[1],repo:n[2]};const r=e.match(/bitbucket\.org[\/:]([^\/]+)\/([^\/\.]+)/);if(r)return{provider:"bitbucket",owner:r[1],repo:r[2]};const o=e.match(/dev\.azure\.com[\/:]([^\/]+)\/([^\/\.]+)|vs-internal\.visualstudio\.com[\/:]([^\/]+)\/([^\/\.]+)/);if(o)return{provider:"azure",owner:o[1]||o[3],repo:o[2]||o[4]};throw new he(`Unsupported git provider. Supported: GitHub, GitLab, Bitbucket, Azure DevOps.
205
- Remote URL: ${e}`)}i(Gk,"parseRemoteUrl");function Wk(e,t,n,r,o,s,a){const u=encodeURIComponent(s),l=encodeURIComponent(a);switch(e){case"github":return`https://github.com/${t}/${n}/compare/${r}...${o}?expand=1&title=${u}&body=${l}`;case"gitlab":return`https://gitlab.com/${t}/${n}/-/merge_requests/new?merge_request[source_branch]=${encodeURIComponent(o)}&merge_request[target_branch]=${encodeURIComponent(r)}&merge_request[title]=${u}&merge_request[description]=${l}`;case"bitbucket":return`https://bitbucket.org/${t}/${n}/pull-requests/new?source=${encodeURIComponent(o)}&dest=${encodeURIComponent(r)}&title=${u}&description=${l}`;case"azure":return`https://dev.azure.com/${t}/${n}/_git/${n}/pullrequestcreate?sourceRef=${encodeURIComponent(o)}&targetRef=${encodeURIComponent(r)}&title=${u}&description=${l}`}}i(Wk,"getPrUrl");var Hk=An({name:"pr",description:"[beta \u{1F6A7}] Generate and create a PR (GitHub/GitLab/Bitbucket/Azure) based on branch diff",help:{description:"[beta \u{1F6A7}] Generate and create a PR (GitHub/GitLab/Bitbucket/Azure) based on branch diff"}},()=>{(async()=>{na(Ko(Jo(" aicommits pr "))),await Qs();const{stdout:e}=await Je("git",["branch","--show-current"]);if(!e.trim())throw new he("Not on a branch");const{stdout:t}=await Je("git",["remote","get-url","origin"]),n=Gk(t),{provider:r,owner:o,repo:s}=n;let a="main";try{const{stdout:S}=await Je("git",["symbolic-ref","refs/remotes/origin/HEAD"]);a=S.trim().replace("refs/remotes/origin/","")}catch{}if(e.trim()===a)throw new he("PR creation requires being on a feature branch, not the default branch. Please switch to a feature branch with changes.");let u;try{const{stdout:S}=await Je("git",["diff",`origin/${a}..HEAD`]);u=S}catch{throw new he(`Could not get diff from origin/${a}`)}if(!u)throw new he("No changes to create PR from");const l=u.split(`
206
- `).filter(S=>S.startsWith("diff --git")).length,c=3e4;u.length>c&&(u=u.substring(0,c)+`
204
+ `.trim();var Wk=An({name:"hook",description:"Install or uninstall the Git hook for automatic commit messages",help:{description:"Install or uninstall the Git hook for automatic commit messages"},parameters:["<install/uninstall>"]},e=>{(async()=>{const t=await Qs(),{installUninstall:n}=e._,r=bt.join(t,vD),o=await ti(r);if(n==="install"){if(o){if(await He.realpath(r).catch(()=>{})===Ha){console.warn("The hook is already installed");return}throw new he(`A different ${gD} hook seems to be installed. Please remove it before installing aicommits.`)}await He.mkdir(bt.dirname(r),{recursive:!0}),_D?await He.writeFile(r,bD):(await He.symlink(Ha,r,"file"),await He.chmod(r,493)),console.log(`${St("\u2714")} Hook installed`);return}if(n==="uninstall"){if(!o){console.warn("Hook is not installed");return}if(_D){if(await He.readFile(r,"utf8")!==bD){console.warn("Hook is not installed");return}}else if(await He.realpath(r)!==Ha){console.warn("Hook is not installed");return}await He.rm(r),console.log(`${St("\u2714")} Hook uninstalled`);return}throw new he(`Invalid mode: ${n}`)})().catch(t=>{console.error(`${Rs("\u2716")} ${t.message}`),sd(t),process.exit(1)})});function Hk(e){const t=e.match(/github\.com[\/:]([^\/]+)\/([^\/\.]+)/);if(t)return{provider:"github",owner:t[1],repo:t[2]};const n=e.match(/gitlab\.com[\/:]([^\/]+)\/([^\/\.]+)/);if(n)return{provider:"gitlab",owner:n[1],repo:n[2]};const r=e.match(/bitbucket\.org[\/:]([^\/]+)\/([^\/\.]+)/);if(r)return{provider:"bitbucket",owner:r[1],repo:r[2]};const o=e.match(/dev\.azure\.com[\/:]([^\/]+)\/([^\/\.]+)|vs-internal\.visualstudio\.com[\/:]([^\/]+)\/([^\/\.]+)/);if(o)return{provider:"azure",owner:o[1]||o[3],repo:o[2]||o[4]};throw new he(`Unsupported git provider. Supported: GitHub, GitLab, Bitbucket, Azure DevOps.
205
+ Remote URL: ${e}`)}i(Hk,"parseRemoteUrl");function Jk(e,t,n,r,o,s,a){const u=encodeURIComponent(s),l=encodeURIComponent(a);switch(e){case"github":return`https://github.com/${t}/${n}/compare/${r}...${o}?expand=1&title=${u}&body=${l}`;case"gitlab":return`https://gitlab.com/${t}/${n}/-/merge_requests/new?merge_request[source_branch]=${encodeURIComponent(o)}&merge_request[target_branch]=${encodeURIComponent(r)}&merge_request[title]=${u}&merge_request[description]=${l}`;case"bitbucket":return`https://bitbucket.org/${t}/${n}/pull-requests/new?source=${encodeURIComponent(o)}&dest=${encodeURIComponent(r)}&title=${u}&description=${l}`;case"azure":return`https://dev.azure.com/${t}/${n}/_git/${n}/pullrequestcreate?sourceRef=${encodeURIComponent(o)}&targetRef=${encodeURIComponent(r)}&title=${u}&description=${l}`}}i(Jk,"getPrUrl");var Kk=An({name:"pr",description:"[beta \u{1F6A7}] Generate and create a PR (GitHub/GitLab/Bitbucket/Azure) based on branch diff",help:{description:"[beta \u{1F6A7}] Generate and create a PR (GitHub/GitLab/Bitbucket/Azure) based on branch diff"}},()=>{(async()=>{na(Ko(Jo(" aicommits pr "))),await Qs();const{stdout:e}=await Je("git",["branch","--show-current"]);if(!e.trim())throw new he("Not on a branch");const{stdout:t}=await Je("git",["remote","get-url","origin"]),n=Hk(t),{provider:r,owner:o,repo:s}=n;let a="main";try{const{stdout:B}=await Je("git",["symbolic-ref","refs/remotes/origin/HEAD"]);a=B.trim().replace("refs/remotes/origin/","")}catch{}if(e.trim()===a)throw new he("PR creation requires being on a feature branch, not the default branch. Please switch to a feature branch with changes.");let u;try{const{stdout:B}=await Je("git",["diff",`origin/${a}..HEAD`]);u=B}catch{throw new he(`Could not get diff from origin/${a}`)}if(!u)throw new he("No changes to create PR from");const l=u.split(`
206
+ `).filter(B=>B.startsWith("diff --git")).length,c=3e4;u.length>c&&(u=u.substring(0,c)+`
207
207
 
208
- [Diff truncated due to size]`);const d=await ln(),f=await Rn(d);if(!f)throw new he("No provider configured");let h=f.getBaseUrl();if(!h||h==="")throw new he("Base URL not configured. Please run `aicommits setup` to configure your provider.");h.endsWith("/v1")||(h+="/v1");const D=f.getApiKey();if(!D)throw new he("API key not configured. Please run `aicommits setup` to configure your provider.");const m=h==="https://api.openai.com/v1"?Va({apiKey:D}):fu({name:"custom",apiKey:D,baseURL:h}),v=Vt();v.start(`Generating PR title and description (${l} files changed)`);const y=Date.now(),w=(await Ao({model:m(d.model),system:"Generate a concise PR title based on the following git diff. The title should be under 72 characters.",prompt:u,maxRetries:2})).text,x=(await Ao({model:m(d.model),system:"Generate a concise PR description based on the following git diff. Format using Markdown with headings like ### Summary, ### Changes, ### Review Notes. Provide a high-level summary of the changes, what was implemented or fixed, and any specific details reviewers should consider. Avoid listing individual files.",prompt:u,maxRetries:2})).text,T=Date.now(),O=Math.round((T-y)/1e3);v.stop(`Generated PR content for ${l} files in ${O}s`),console.log(`${St("Title:")} ${w.replace(/\n/g," ")}`),console.log(`${St("Body:")} ${x.length>100?x.substring(0,100)+"...":x}`);const{text:$}=await Promise.resolve().then(function(){return ro}),I=await $({message:"Press Enter to push and open PR creation in browser, or Ctrl+C to cancel",placeholder:"Press Enter"});if(Bn(I)){Ee("PR creation cancelled");return}const re=Vt();re.start(`Pushing branch to ${r}`);try{await Je("git",["push","-u","origin",e.trim()]),re.stop(`Branch pushed to ${r}`)}catch(S){throw re.stop("Failed to push branch"),new he(`Failed to push branch: ${S instanceof Error?S.message:String(S)}`)}const k=Wk(r,o,s,a,e.trim(),w,x),X=Vt();X.start("Opening PR creation page in browser");try{const S=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";await Je(S,[k]),X.stop("PR creation page opened in browser"),Ee(St("PR creation page opened! Please review and submit the PR."))}catch{X.stop("Failed to open browser"),Ee(`${St("PR URL:")} ${k}`),Ee("Please open the URL above in your browser to create the PR.")}})().catch(e=>{ra(e)})});const Jk=UD(bl);function CD(e){const n=e.replace(/^v/,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z]+)(?:\.(\d+))?)?$/);if(!n)return{major:0,minor:0,patch:0,prerelease:null,prereleaseNum:0};const[,r,o,s,a,u]=n;return{major:parseInt(r,10),minor:parseInt(o,10),patch:parseInt(s,10),prerelease:a||null,prereleaseNum:u?parseInt(u,10):0}}i(CD,"parseVersion");function Kk(e,t){const n=CD(e),r=CD(t);return n.major!==r.major?n.major>r.major?1:-1:n.minor!==r.minor?n.minor>r.minor?1:-1:n.patch!==r.patch?n.patch>r.patch?1:-1:!n.prerelease&&r.prerelease?1:n.prerelease&&!r.prerelease?-1:!n.prerelease&&!r.prerelease?0:n.prereleaseNum!==r.prereleaseNum?n.prereleaseNum>r.prereleaseNum?1:-1:0}i(Kk,"compareVersions");async function Yk(e,t){try{const n=await fetch(`https://registry.npmjs.org/${e}/${t}`,{headers:{Accept:"application/json"}});return n.ok&&(await n.json()).version||null}catch{return null}}i(Yk,"fetchLatestVersion");async function Xk(e){try{const{stdout:t}=await Jk(`npm list -g ${e} --depth=0`);return t.includes(e)}catch{return!1}}i(Xk,"checkIfGlobalInstallation");async function Qk(e,t){return new Promise((n,r)=>{const o=bl(`npm install -g ${e}@${t}`,{timeout:12e4,env:{...process.env,NPM_CONFIG_PROGRESS:"false"}});o.on("error",r),o.on("exit",s=>{s===0||s===null?n():r(new Error(`npm install exited with code ${s}`))})})}i(Qk,"runBackgroundUpdate");async function e8(e){const{pkg:t,distTag:n="latest"}=e;if(t.version==="0.0.0-semantic-release"||t.version.includes("semantic-release"))return;const r=t.version.includes("-")?"develop":n;(process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&(console.log(`[auto-update] Current version: ${t.version}`),console.log(`[auto-update] Checking ${r} tag...`));const o=await Yk(t.name,r);if(!o){(process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&console.log("[auto-update] Could not fetch latest version");return}if((process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&console.log(`[auto-update] Latest version: ${o}`),Kk(t.version,o)>=0){(process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&console.log("[auto-update] No update needed");return}if(console.log(`Updating aicommits from v${t.version} to v${o}...`),!await Xk(t.name)){console.log("Note: aicommits is installed locally. Auto-update skipped for local installations.");return}try{await Qk(t.name,r),console.log(`\u2713 aicommits updated to v${o}`),console.log("Please restart aic to use the new version.")}catch{console.log("Auto-update failed. You can manually update with:"),console.log(` npm install -g aicommits@${r}`)}}i(e8,"checkAndAutoUpdate"),globalThis.AI_SDK_LOG_WARNINGS=!1;const{description:t8,version:Du}=hs;if(!yD&&Du!=="0.0.0-semantic-release"){const e=Du.includes("-")?"develop":"latest";e8({pkg:hs,distTag:e})}const wD=process.argv.slice(2);cc({name:"aicommits",flags:{generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Git commit message format (default: plain). Supports plain, conventional, and gitmoji",alias:"t"},yes:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard instead of committing (default: false)",alias:"c",default:!1},noVerify:{type:Boolean,description:"Bypass pre-commit hooks while committing (default: false)",alias:"n",default:!1},prompt:{type:String,description:"Custom prompt to guide the LLM behavior (e.g., specific language, style instructions)",alias:"p"},version:{type:Boolean,description:"Show version number",alias:"v"}},commands:[qk,Uk,Zk,Vk,Hk],help:{description:t8},ignoreArgv:i(e=>e==="unknown-flag"||e==="argument","ignoreArgv")},e=>{e.flags.version&&(console.log(Du),process.exit(0)),yD?Lk():jk(e.flags.generate,e.flags.exclude,e.flags.all,e.flags.type,e.flags.yes,e.flags.clipboard,e.flags.noVerify,e.flags.prompt,wD)},wD);export{rn as g,Sf as r};
208
+ [Diff truncated due to size]`);const d=await ln(),f=await Rn(d);if(!f)throw new he("No provider configured");let h=f.getBaseUrl();if(!h||h==="")throw new he("Base URL not configured. Please run `aicommits setup` to configure your provider.");h.endsWith("/v1")||(h+="/v1");const D=f.getApiKey();if(!D)throw new he("API key not configured. Please run `aicommits setup` to configure your provider.");const m=h==="https://api.openai.com/v1"?Va({apiKey:D}):fu({name:"custom",apiKey:D,baseURL:h}),v=Vt();v.start(`Generating PR title and description (${l} files changed)`);const y=Date.now(),C=(await Ao({model:m(d.model),system:"Generate a concise PR title based on the following git diff. The title should be under 72 characters.",prompt:u,maxRetries:2})).text,E=(await Ao({model:m(d.model),system:"Generate a concise PR description based on the following git diff. Format using Markdown with headings like ### Summary, ### Changes, ### Review Notes. Provide a high-level summary of the changes, what was implemented or fixed, and any specific details reviewers should consider. Avoid listing individual files.",prompt:u,maxRetries:2})).text,T=Date.now(),O=Math.round((T-y)/1e3);v.stop(`Generated PR content for ${l} files in ${O}s`),console.log(`${St("Title:")} ${C.replace(/\n/g," ")}`),console.log(`${St("Body:")} ${E.length>100?E.substring(0,100)+"...":E}`);const{text:$}=await Promise.resolve().then(function(){return ro}),I=await $({message:"Press Enter to push and open PR creation in browser, or Ctrl+C to cancel",placeholder:"Press Enter"});if(Bn(I)){Ee("PR creation cancelled");return}const oe=Vt();oe.start(`Pushing branch to ${r}`);try{await Je("git",["push","-u","origin",e.trim()]),oe.stop(`Branch pushed to ${r}`)}catch(B){throw oe.stop("Failed to push branch"),new he(`Failed to push branch: ${B instanceof Error?B.message:String(B)}`)}const k=Jk(r,o,s,a,e.trim(),C,E),re=Vt();re.start("Opening PR creation page in browser");try{const B=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";await Je(B,[k]),re.stop("PR creation page opened in browser"),Ee(St("PR creation page opened! Please review and submit the PR."))}catch{re.stop("Failed to open browser"),Ee(`${St("PR URL:")} ${k}`),Ee("Please open the URL above in your browser to create the PR.")}})().catch(e=>{ra(e)})});const Yk=UD(bl);function CD(e){const n=e.replace(/^v/,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z]+)(?:\.(\d+))?)?$/);if(!n)return{major:0,minor:0,patch:0,prerelease:null,prereleaseNum:0};const[,r,o,s,a,u]=n;return{major:parseInt(r,10),minor:parseInt(o,10),patch:parseInt(s,10),prerelease:a||null,prereleaseNum:u?parseInt(u,10):0}}i(CD,"parseVersion");function Xk(e,t){const n=CD(e),r=CD(t);return n.major!==r.major?n.major>r.major?1:-1:n.minor!==r.minor?n.minor>r.minor?1:-1:n.patch!==r.patch?n.patch>r.patch?1:-1:!n.prerelease&&r.prerelease?1:n.prerelease&&!r.prerelease?-1:!n.prerelease&&!r.prerelease?0:n.prereleaseNum!==r.prereleaseNum?n.prereleaseNum>r.prereleaseNum?1:-1:0}i(Xk,"compareVersions");async function Qk(e,t){try{const n=await fetch(`https://registry.npmjs.org/${e}/${t}`,{headers:{Accept:"application/json"}});return n.ok&&(await n.json()).version||null}catch{return null}}i(Qk,"fetchLatestVersion");async function e8(e){try{const{stdout:t}=await Yk(`npm list -g ${e} --depth=0`);return t.includes(e)}catch{return!1}}i(e8,"checkIfGlobalInstallation");async function t8(e,t){return new Promise((n,r)=>{const o=bl(`npm install -g ${e}@${t}`,{timeout:12e4,env:{...process.env,NPM_CONFIG_PROGRESS:"false"}});o.on("error",r),o.on("exit",s=>{s===0||s===null?n():r(new Error(`npm install exited with code ${s}`))})})}i(t8,"runBackgroundUpdate");async function n8(e){const{pkg:t,distTag:n="latest"}=e;if(t.version==="0.0.0-semantic-release"||t.version.includes("semantic-release"))return;const r=t.version.includes("-")?"develop":n;(process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&(console.log(`[auto-update] Current version: ${t.version}`),console.log(`[auto-update] Checking ${r} tag...`));const o=await Qk(t.name,r);if(!o){(process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&console.log("[auto-update] Could not fetch latest version");return}if((process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&console.log(`[auto-update] Latest version: ${o}`),Xk(t.version,o)>=0){(process.env.DEBUG||process.env.AICOMMITS_DEBUG)&&console.log("[auto-update] No update needed");return}if(console.log(`Updating aicommits from v${t.version} to v${o}...`),!await e8(t.name)){console.log("Note: aicommits is installed locally. Auto-update skipped for local installations.");return}try{await t8(t.name,r),console.log(`\u2713 aicommits updated to v${o}`),console.log("Please restart aic to use the new version.")}catch{console.log("Auto-update failed. You can manually update with:"),console.log(` npm install -g aicommits@${r}`)}}i(n8,"checkAndAutoUpdate"),globalThis.AI_SDK_LOG_WARNINGS=!1;const{description:r8,version:Du}=hs;if(!yD&&Du!=="0.0.0-semantic-release"){const e=Du.includes("-")?"develop":"latest";n8({pkg:hs,distTag:e})}const wD=process.argv.slice(2);cc({name:"aicommits",flags:{generate:{type:Number,description:"Number of messages to generate (Warning: generating multiple costs more) (default: 1)",alias:"g"},exclude:{type:[String],description:"Files to exclude from AI analysis",alias:"x"},all:{type:Boolean,description:"Automatically stage changes in tracked files for the commit",alias:"a",default:!1},type:{type:String,description:"Git commit message format (default: plain). Supports plain, conventional, and gitmoji",alias:"t"},yes:{type:Boolean,description:"Skip confirmation when committing after message generation (default: false)",alias:"y",default:!1},clipboard:{type:Boolean,description:"Copy the selected message to the clipboard instead of committing (default: false)",alias:"c",default:!1},noVerify:{type:Boolean,description:"Bypass pre-commit hooks while committing (default: false)",alias:"n",default:!1},prompt:{type:String,description:"Custom prompt to guide the LLM behavior (e.g., specific language, style instructions)",alias:"p"},version:{type:Boolean,description:"Show version number",alias:"v"}},commands:[Zk,Vk,Gk,Wk,Kk],help:{description:r8},ignoreArgv:i(e=>e==="unknown-flag"||e==="argument","ignoreArgv")},e=>{e.flags.version&&(console.log(Du),process.exit(0)),yD?Uk():Lk(e.flags.generate,e.flags.exclude,e.flags.all,e.flags.type,e.flags.yes,e.flags.clipboard,e.flags.noVerify,e.flags.prompt,wD)},wD);export{rn as g,Sf as r};