@opentiny/next-sdk 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/webagent.js CHANGED
@@ -1,12 +1,12 @@
1
- (function(Rt,an){typeof exports=="object"&&typeof module<"u"?an(exports):typeof define=="function"&&define.amd?define(["exports"],an):(Rt=typeof globalThis<"u"?globalThis:Rt||self,an(Rt.WebAgent={}))})(this,function(Rt){"use strict";var an="vercel.ai.error",np=Symbol.for(an),ya,rp=class Qd extends Error{constructor({name:t,message:n,cause:r}){super(n),this[ya]=!0,this.name=t,this.cause=r}static isInstance(t){return Qd.hasMarker(t,an)}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}};ya=np;var G=rp,va="AI_APICallError",_a=`vercel.ai.error.${va}`,op=Symbol.for(_a),wa,pe=class extends G{constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:o,responseBody:s,cause:a,isRetryable:i=r!=null&&(r===408||r===409||r===429||r>=500),data:l}){super({name:va,message:e,cause:a}),this[wa]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=o,this.responseBody=s,this.isRetryable=i,this.data=l}static isInstance(e){return G.hasMarker(e,_a)}};wa=op;var ba="AI_EmptyResponseBodyError",xa=`vercel.ai.error.${ba}`,sp=Symbol.for(xa),ka,Ta=class extends G{constructor({message:e="Empty response body"}={}){super({name:ba,message:e}),this[ka]=!0}static isInstance(e){return G.hasMarker(e,xa)}};ka=sp;function ln(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Sa="AI_InvalidArgumentError",Ia=`vercel.ai.error.${Sa}`,ap=Symbol.for(Ia),Ca,_o=class extends G{constructor({message:t,cause:n,argument:r}){super({name:Sa,message:t,cause:n}),this[Ca]=!0,this.argument=r}static isInstance(t){return G.hasMarker(t,Ia)}};Ca=ap;var Ea="AI_InvalidPromptError",Ra=`vercel.ai.error.${Ea}`,ip=Symbol.for(Ra),Aa,Ht=class extends G{constructor({prompt:e,message:t,cause:n}){super({name:Ea,message:`Invalid prompt: ${t}`,cause:n}),this[Aa]=!0,this.prompt=e}static isInstance(e){return G.hasMarker(e,Ra)}};Aa=ip;var Oa="AI_InvalidResponseDataError",Na=`vercel.ai.error.${Oa}`,lp=Symbol.for(Na),Ma,In=class extends G{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Oa,message:t}),this[Ma]=!0,this.data=e}static isInstance(e){return G.hasMarker(e,Na)}};Ma=lp;var Pa="AI_JSONParseError",$a=`vercel.ai.error.${Pa}`,up=Symbol.for($a),za,zt=class extends G{constructor({text:e,cause:t}){super({name:Pa,message:`JSON parsing failed: Text: ${e}.
2
- Error message: ${ln(t)}`,cause:t}),this[za]=!0,this.text=e}static isInstance(e){return G.hasMarker(e,$a)}};za=up;var ja="AI_LoadAPIKeyError",Da=`vercel.ai.error.${ja}`,cp=Symbol.for(Da),Za,gr=class extends G{constructor({message:e}){super({name:ja,message:e}),this[Za]=!0}static isInstance(e){return G.hasMarker(e,Da)}};Za=cp;var Ua="AI_NoSuchModelError",La=`vercel.ai.error.${Ua}`,dp=Symbol.for(La),qa,wo=class extends G{constructor({errorName:e=Ua,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[qa]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return G.hasMarker(e,La)}};qa=dp;var Ba="AI_TooManyEmbeddingValuesForCallError",Va=`vercel.ai.error.${Ba}`,pp=Symbol.for(Va),Fa,hp=class extends G{constructor(e){super({name:Ba,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[Fa]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return G.hasMarker(e,Va)}};Fa=pp;var Ha="AI_TypeValidationError",Ja=`vercel.ai.error.${Ha}`,fp=Symbol.for(Ja),Ga,mp=class ga extends G{constructor({value:t,cause:n}){super({name:Ha,message:`Type validation failed: Value: ${JSON.stringify(t)}.
3
- Error message: ${ln(n)}`,cause:n}),this[Ga]=!0,this.value=t}static isInstance(t){return G.hasMarker(t,Ja)}static wrap({value:t,cause:n}){return ga.isInstance(n)&&n.value===t?n:new ga({value:t,cause:n})}};Ga=fp;var yt=mp,Wa="AI_UnsupportedFunctionalityError",Ka=`vercel.ai.error.${Wa}`,gp=Symbol.for(Ka),Ya,at=class extends G{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Wa,message:t}),this[Ya]=!0,this.functionality=e}static isInstance(e){return G.hasMarker(e,Ka)}};Ya=gp;class Xa 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}}function bo(e){}function yp(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=bo,onError:n=bo,onRetry:r=bo,onComment:o}=e;let s="",a=!0,i,l="",u="";function c(y){const v=a?y.replace(/^\xEF\xBB\xBF/,""):y,[p,b]=vp(`${s}${v}`);for(const g of p)w(g);s=b,a=!1}function w(y){if(y===""){d();return}if(y.startsWith(":")){o&&o(y.slice(y.startsWith(": ")?2:1));return}const v=y.indexOf(":");if(v!==-1){const p=y.slice(0,v),b=y[v+1]===" "?2:1,g=y.slice(v+b);_(p,g,y);return}_(y,"",y)}function _(y,v,p){switch(y){case"event":u=v;break;case"data":l=`${l}${v}
1
+ (function(Rt,an){typeof exports=="object"&&typeof module<"u"?an(exports):typeof define=="function"&&define.amd?define(["exports"],an):(Rt=typeof globalThis<"u"?globalThis:Rt||self,an(Rt.WebAgent={}))})(this,function(Rt){"use strict";var an="vercel.ai.error",tp=Symbol.for(an),ya,np=class Xd extends Error{constructor({name:t,message:n,cause:r}){super(n),this[ya]=!0,this.name=t,this.cause=r}static isInstance(t){return Xd.hasMarker(t,an)}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}};ya=tp;var G=np,va="AI_APICallError",_a=`vercel.ai.error.${va}`,rp=Symbol.for(_a),wa,pe=class extends G{constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:o,responseBody:s,cause:a,isRetryable:i=r!=null&&(r===408||r===409||r===429||r>=500),data:l}){super({name:va,message:e,cause:a}),this[wa]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=o,this.responseBody=s,this.isRetryable=i,this.data=l}static isInstance(e){return G.hasMarker(e,_a)}};wa=rp;var ba="AI_EmptyResponseBodyError",xa=`vercel.ai.error.${ba}`,op=Symbol.for(xa),ka,Ta=class extends G{constructor({message:e="Empty response body"}={}){super({name:ba,message:e}),this[ka]=!0}static isInstance(e){return G.hasMarker(e,xa)}};ka=op;function ln(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Sa="AI_InvalidArgumentError",Ia=`vercel.ai.error.${Sa}`,sp=Symbol.for(Ia),Ca,_o=class extends G{constructor({message:t,cause:n,argument:r}){super({name:Sa,message:t,cause:n}),this[Ca]=!0,this.argument=r}static isInstance(t){return G.hasMarker(t,Ia)}};Ca=sp;var Ea="AI_InvalidPromptError",Ra=`vercel.ai.error.${Ea}`,ap=Symbol.for(Ra),Aa,Ht=class extends G{constructor({prompt:e,message:t,cause:n}){super({name:Ea,message:`Invalid prompt: ${t}`,cause:n}),this[Aa]=!0,this.prompt=e}static isInstance(e){return G.hasMarker(e,Ra)}};Aa=ap;var Oa="AI_InvalidResponseDataError",Na=`vercel.ai.error.${Oa}`,ip=Symbol.for(Na),Ma,In=class extends G{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Oa,message:t}),this[Ma]=!0,this.data=e}static isInstance(e){return G.hasMarker(e,Na)}};Ma=ip;var Pa="AI_JSONParseError",$a=`vercel.ai.error.${Pa}`,lp=Symbol.for($a),za,zt=class extends G{constructor({text:e,cause:t}){super({name:Pa,message:`JSON parsing failed: Text: ${e}.
2
+ Error message: ${ln(t)}`,cause:t}),this[za]=!0,this.text=e}static isInstance(e){return G.hasMarker(e,$a)}};za=lp;var ja="AI_LoadAPIKeyError",Da=`vercel.ai.error.${ja}`,up=Symbol.for(Da),Za,gr=class extends G{constructor({message:e}){super({name:ja,message:e}),this[Za]=!0}static isInstance(e){return G.hasMarker(e,Da)}};Za=up;var Ua="AI_NoSuchModelError",La=`vercel.ai.error.${Ua}`,cp=Symbol.for(La),qa,wo=class extends G{constructor({errorName:e=Ua,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[qa]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return G.hasMarker(e,La)}};qa=cp;var Ba="AI_TooManyEmbeddingValuesForCallError",Va=`vercel.ai.error.${Ba}`,dp=Symbol.for(Va),Fa,pp=class extends G{constructor(e){super({name:Ba,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[Fa]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return G.hasMarker(e,Va)}};Fa=dp;var Ha="AI_TypeValidationError",Ja=`vercel.ai.error.${Ha}`,hp=Symbol.for(Ja),Ga,fp=class ga extends G{constructor({value:t,cause:n}){super({name:Ha,message:`Type validation failed: Value: ${JSON.stringify(t)}.
3
+ Error message: ${ln(n)}`,cause:n}),this[Ga]=!0,this.value=t}static isInstance(t){return G.hasMarker(t,Ja)}static wrap({value:t,cause:n}){return ga.isInstance(n)&&n.value===t?n:new ga({value:t,cause:n})}};Ga=hp;var yt=fp,Wa="AI_UnsupportedFunctionalityError",Ka=`vercel.ai.error.${Wa}`,mp=Symbol.for(Ka),Ya,at=class extends G{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Wa,message:t}),this[Ya]=!0,this.functionality=e}static isInstance(e){return G.hasMarker(e,Ka)}};Ya=mp;class Xa 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}}function bo(e){}function gp(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=bo,onError:n=bo,onRetry:r=bo,onComment:o}=e;let s="",a=!0,i,l="",u="";function c(y){const v=a?y.replace(/^\xEF\xBB\xBF/,""):y,[p,b]=yp(`${s}${v}`);for(const g of p)w(g);s=b,a=!1}function w(y){if(y===""){d();return}if(y.startsWith(":")){o&&o(y.slice(y.startsWith(": ")?2:1));return}const v=y.indexOf(":");if(v!==-1){const p=y.slice(0,v),b=y[v+1]===" "?2:1,g=y.slice(v+b);_(p,g,y);return}_(y,"",y)}function _(y,v,p){switch(y){case"event":u=v;break;case"data":l=`${l}${v}
4
4
  `;break;case"id":i=v.includes("\0")?void 0:v;break;case"retry":/^\d+$/.test(v)?r(parseInt(v,10)):n(new Xa(`Invalid \`retry\` value: "${v}"`,{type:"invalid-retry",value:v,line:p}));break;default:n(new Xa(`Unknown field "${y.length>20?`${y.slice(0,20)}…`:y}"`,{type:"unknown-field",field:y,value:v,line:p}));break}}function d(){l.length>0&&t({id:i,event:u||void 0,data:l.endsWith(`
5
- `)?l.slice(0,-1):l}),i=void 0,l="",u=""}function f(y={}){s&&y.consume&&w(s),a=!0,i=void 0,l="",u="",s=""}return{feed:c,reset:f}}function vp(e){const t=[];let n="",r=0;for(;r<e.length;){const o=e.indexOf("\r",r),s=e.indexOf(`
5
+ `)?l.slice(0,-1):l}),i=void 0,l="",u=""}function f(y={}){s&&y.consume&&w(s),a=!0,i=void 0,l="",u="",s=""}return{feed:c,reset:f}}function yp(e){const t=[];let n="",r=0;for(;r<e.length;){const o=e.indexOf("\r",r),s=e.indexOf(`
6
6
  `,r);let a=-1;if(o!==-1&&s!==-1?a=Math.min(o,s):o!==-1?a=o:s!==-1&&(a=s),a===-1){n=e.slice(r);break}else{const i=e.slice(r,a);t.push(i),r=a+1,e[r-1]==="\r"&&e[r]===`
7
- `&&r++}}return[t,n]}class yr extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let o;super({start(s){o=yp({onEvent:a=>{s.enqueue(a)},onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:n,onComment:r})},transform(s){o.feed(s)}})}}function C(e,t,n){function r(i,l){var u;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(u=i._zod).traits??(u.traits=new Set),i._zod.traits.add(e),t(i,l);for(const c in a.prototype)c in i||Object.defineProperty(i,c,{value:a.prototype[c].bind(i)});i._zod.constr=a,i._zod.def=l}const o=(n==null?void 0:n.Parent)??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function a(i){var l;const u=n!=null&&n.Parent?new s:this;r(u,i),(l=u._zod).deferred??(l.deferred=[]);for(const c of u._zod.deferred)c();return u}return Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>{var l,u;return n!=null&&n.Parent&&i instanceof n.Parent?!0:(u=(l=i==null?void 0:i._zod)==null?void 0:l.traits)==null?void 0:u.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}class Cn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Qa={};function jt(e){return Qa}function ei(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)}function _p(e,t){return typeof t=="bigint"?t.toString():t}function xo(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ko(e){return e==null}function To(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function wp(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}function le(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})}function En(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Rn(e){return JSON.stringify(e)}const ti=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function vr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const bp=xo(()=>{var e;if(typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function _r(e){if(vr(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(vr(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const xp=new Set(["string","number","symbol"]);function An(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Jt(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n!=null&&n.parent)&&(r._zod.parent=e),r}function U(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0: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:()=>t.error}:t}function kp(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Tp={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 Sp(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 Jt(e,{...e._zod.def,shape:n,checks:[]})}function Ip(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 Jt(e,{...e._zod.def,shape:n,checks:[]})}function Cp(e,t){if(!_r(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 En(this,"shape",r),r},checks:[]};return Jt(e,n)}function Ep(e,t){return Jt(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return En(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}function Rp(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 Jt(t,{...t._zod.def,shape:o,checks:[]})}function Ap(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 Jt(t,{...t._zod.def,shape:o,checks:[]})}function On(e,t=0){var n;for(let r=t;r<e.issues.length;r++)if(((n=e.issues[r])==null?void 0:n.continue)!==!0)return!0;return!1}function Gt(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function wr(e){return typeof e=="string"?e:e==null?void 0:e.message}function Dt(e,t,n){var o,s,a,i,l,u;const r={...e,path:e.path??[]};if(!e.message){const c=wr((a=(s=(o=e.inst)==null?void 0:o._zod.def)==null?void 0:s.error)==null?void 0:a.call(s,e))??wr((i=t==null?void 0:t.error)==null?void 0:i.call(t,e))??wr((l=n.customError)==null?void 0:l.call(n,e))??wr((u=n.localeError)==null?void 0:u.call(n,e))??"Invalid input";r.message=c}return delete r.inst,delete r.continue,t!=null&&t.reportInput||delete r.input,r}function So(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Nn(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const ni=(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,_p,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ri=C("$ZodError",ni),oi=C("$ZodError",ni,{Parent:Error});function Op(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}}function Np(e,t){const n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>o({issues:i}));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 i=r,l=0;for(;l<a.path.length;){const u=a.path[l];l===a.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(n(a))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return o(e),r}const Mp=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 Cn;if(a.issues.length){const i=new((o==null?void 0:o.Err)??e)(a.issues.map(l=>Dt(l,s,jt())));throw ti(i,o==null?void 0:o.callee),i}return a.value},Pp=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 i=new((o==null?void 0:o.Err)??e)(a.issues.map(l=>Dt(l,s,jt())));throw ti(i,o==null?void 0:o.callee),i}return a.value},si=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 Cn;return s.issues.length?{success:!1,error:new(e??ri)(s.issues.map(a=>Dt(a,o,jt())))}:{success:!0,data:s.value}},$p=si(oi),ai=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=>Dt(a,o,jt())))}:{success:!0,data:s.value}},zp=ai(oi),jp=/^[cC][^\s-]{8,}$/,Dp=/^[0-9a-z]+$/,Zp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Up=/^[0-9a-vA-V]{20}$/,Lp=/^[A-Za-z0-9]{27}$/,qp=/^[a-zA-Z0-9_-]{21}$/,Bp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Vp=/^([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})$/,ii=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)$/,Fp=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Hp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Jp(){return new RegExp(Hp,"u")}const Gp=/^(?:(?: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])$/,Wp=/^(([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})$/,Kp=/^((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])$/,Yp=/^(([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])$/,Xp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,li=/^[A-Za-z0-9_-]*$/,Qp=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,eh=/^\+(?:[0-9]){6,14}[0-9]$/,ui="(?:(?:\\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])))",th=new RegExp(`^${ui}$`);function ci(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+)?)?`}function nh(e){return new RegExp(`^${ci(e)}$`)}function rh(e){const t=ci({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(`^${ui}T(?:${r})$`)}const oh=e=>{const t=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},sh=/^\d+$/,ah=/^-?\d+(?:\.\d+)?/i,ih=/true|false/i,lh=/null/i,uh=/^[^A-Z]*$/,ch=/^[^a-z]*$/,Ge=C("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),di={number:"number",bigint:"bigint",object:"date"},pi=C("$ZodCheckLessThan",(e,t)=>{Ge.init(e,t);const n=di[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})}}),hi=C("$ZodCheckGreaterThan",(e,t)=>{Ge.init(e,t);const n=di[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})}}),dh=C("$ZodCheckMultipleOf",(e,t)=>{Ge.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):wp(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})}}),ph=C("$ZodCheckNumberFormat",(e,t)=>{var a;Ge.init(e,t),t.format=t.format||"float64";const n=(a=t.format)==null?void 0:a.includes("int"),r=n?"int":"number",[o,s]=Tp[t.format];e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,l.minimum=o,l.maximum=s,n&&(l.pattern=sh)}),e._zod.check=i=>{const l=i.value;if(n){if(!Number.isInteger(l)){i.issues.push({expected:r,format:t.format,code:"invalid_type",input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?i.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):i.issues.push({input:l,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}}l<o&&i.issues.push({origin:"number",input:l,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),l>s&&i.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inst:e})}}),hh=C("$ZodCheckMaxLength",(e,t)=>{var n;Ge.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ko(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=So(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),fh=C("$ZodCheckMinLength",(e,t)=>{var n;Ge.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ko(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=So(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),mh=C("$ZodCheckLengthEquals",(e,t)=>{var n;Ge.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ko(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=So(o),i=s>t.length;r.issues.push({origin:a,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),br=C("$ZodCheckStringFormat",(e,t)=>{var n,r;Ge.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=()=>{})}),gh=C("$ZodCheckRegex",(e,t)=>{br.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})}}),yh=C("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=uh),br.init(e,t)}),vh=C("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ch),br.init(e,t)}),_h=C("$ZodCheckIncludes",(e,t)=>{Ge.init(e,t);const n=An(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})}}),wh=C("$ZodCheckStartsWith",(e,t)=>{Ge.init(e,t);const n=new RegExp(`^${An(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})}}),bh=C("$ZodCheckEndsWith",(e,t)=>{Ge.init(e,t);const n=new RegExp(`.*${An(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})}}),xh=C("$ZodCheckOverwrite",(e,t)=>{Ge.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class kh{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(`
7
+ `&&r++}}return[t,n]}class yr extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let o;super({start(s){o=gp({onEvent:a=>{s.enqueue(a)},onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:n,onComment:r})},transform(s){o.feed(s)}})}}function C(e,t,n){function r(i,l){var u;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(u=i._zod).traits??(u.traits=new Set),i._zod.traits.add(e),t(i,l);for(const c in a.prototype)c in i||Object.defineProperty(i,c,{value:a.prototype[c].bind(i)});i._zod.constr=a,i._zod.def=l}const o=(n==null?void 0:n.Parent)??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function a(i){var l;const u=n!=null&&n.Parent?new s:this;r(u,i),(l=u._zod).deferred??(l.deferred=[]);for(const c of u._zod.deferred)c();return u}return Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>{var l,u;return n!=null&&n.Parent&&i instanceof n.Parent?!0:(u=(l=i==null?void 0:i._zod)==null?void 0:l.traits)==null?void 0:u.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}class Cn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Qa={};function jt(e){return Qa}function ei(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)}function vp(e,t){return typeof t=="bigint"?t.toString():t}function xo(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ko(e){return e==null}function To(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function _p(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}function le(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})}function En(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Rn(e){return JSON.stringify(e)}const ti=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function vr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const wp=xo(()=>{var e;if(typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function _r(e){if(vr(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(vr(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const bp=new Set(["string","number","symbol"]);function An(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Jt(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n!=null&&n.parent)&&(r._zod.parent=e),r}function U(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0: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:()=>t.error}:t}function xp(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const kp={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 Tp(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 Jt(e,{...e._zod.def,shape:n,checks:[]})}function Sp(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 Jt(e,{...e._zod.def,shape:n,checks:[]})}function Ip(e,t){if(!_r(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 En(this,"shape",r),r},checks:[]};return Jt(e,n)}function Cp(e,t){return Jt(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return En(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}function Ep(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 Jt(t,{...t._zod.def,shape:o,checks:[]})}function Rp(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 Jt(t,{...t._zod.def,shape:o,checks:[]})}function On(e,t=0){var n;for(let r=t;r<e.issues.length;r++)if(((n=e.issues[r])==null?void 0:n.continue)!==!0)return!0;return!1}function Gt(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function wr(e){return typeof e=="string"?e:e==null?void 0:e.message}function Dt(e,t,n){var o,s,a,i,l,u;const r={...e,path:e.path??[]};if(!e.message){const c=wr((a=(s=(o=e.inst)==null?void 0:o._zod.def)==null?void 0:s.error)==null?void 0:a.call(s,e))??wr((i=t==null?void 0:t.error)==null?void 0:i.call(t,e))??wr((l=n.customError)==null?void 0:l.call(n,e))??wr((u=n.localeError)==null?void 0:u.call(n,e))??"Invalid input";r.message=c}return delete r.inst,delete r.continue,t!=null&&t.reportInput||delete r.input,r}function So(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Nn(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const ni=(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,vp,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ri=C("$ZodError",ni),oi=C("$ZodError",ni,{Parent:Error});function Ap(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}}function Op(e,t){const n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>o({issues:i}));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 i=r,l=0;for(;l<a.path.length;){const u=a.path[l];l===a.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(n(a))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return o(e),r}const Np=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 Cn;if(a.issues.length){const i=new((o==null?void 0:o.Err)??e)(a.issues.map(l=>Dt(l,s,jt())));throw ti(i,o==null?void 0:o.callee),i}return a.value},Mp=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 i=new((o==null?void 0:o.Err)??e)(a.issues.map(l=>Dt(l,s,jt())));throw ti(i,o==null?void 0:o.callee),i}return a.value},si=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 Cn;return s.issues.length?{success:!1,error:new(e??ri)(s.issues.map(a=>Dt(a,o,jt())))}:{success:!0,data:s.value}},Pp=si(oi),ai=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=>Dt(a,o,jt())))}:{success:!0,data:s.value}},$p=ai(oi),zp=/^[cC][^\s-]{8,}$/,jp=/^[0-9a-z]+$/,Dp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Zp=/^[0-9a-vA-V]{20}$/,Up=/^[A-Za-z0-9]{27}$/,Lp=/^[a-zA-Z0-9_-]{21}$/,qp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Bp=/^([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})$/,ii=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)$/,Vp=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Fp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Hp(){return new RegExp(Fp,"u")}const Jp=/^(?:(?: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])$/,Gp=/^(([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})$/,Wp=/^((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])$/,Kp=/^(([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])$/,Yp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,li=/^[A-Za-z0-9_-]*$/,Xp=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Qp=/^\+(?:[0-9]){6,14}[0-9]$/,ui="(?:(?:\\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])))",eh=new RegExp(`^${ui}$`);function ci(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+)?)?`}function th(e){return new RegExp(`^${ci(e)}$`)}function nh(e){const t=ci({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(`^${ui}T(?:${r})$`)}const rh=e=>{const t=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},oh=/^\d+$/,sh=/^-?\d+(?:\.\d+)?/i,ah=/true|false/i,ih=/null/i,lh=/^[^A-Z]*$/,uh=/^[^a-z]*$/,Ge=C("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),di={number:"number",bigint:"bigint",object:"date"},pi=C("$ZodCheckLessThan",(e,t)=>{Ge.init(e,t);const n=di[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})}}),hi=C("$ZodCheckGreaterThan",(e,t)=>{Ge.init(e,t);const n=di[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})}}),ch=C("$ZodCheckMultipleOf",(e,t)=>{Ge.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):_p(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})}}),dh=C("$ZodCheckNumberFormat",(e,t)=>{var a;Ge.init(e,t),t.format=t.format||"float64";const n=(a=t.format)==null?void 0:a.includes("int"),r=n?"int":"number",[o,s]=kp[t.format];e._zod.onattach.push(i=>{const l=i._zod.bag;l.format=t.format,l.minimum=o,l.maximum=s,n&&(l.pattern=oh)}),e._zod.check=i=>{const l=i.value;if(n){if(!Number.isInteger(l)){i.issues.push({expected:r,format:t.format,code:"invalid_type",input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?i.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):i.issues.push({input:l,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}}l<o&&i.issues.push({origin:"number",input:l,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),l>s&&i.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inst:e})}}),ph=C("$ZodCheckMaxLength",(e,t)=>{var n;Ge.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ko(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=So(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),hh=C("$ZodCheckMinLength",(e,t)=>{var n;Ge.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ko(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=So(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),fh=C("$ZodCheckLengthEquals",(e,t)=>{var n;Ge.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!ko(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=So(o),i=s>t.length;r.issues.push({origin:a,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),br=C("$ZodCheckStringFormat",(e,t)=>{var n,r;Ge.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=()=>{})}),mh=C("$ZodCheckRegex",(e,t)=>{br.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})}}),gh=C("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=lh),br.init(e,t)}),yh=C("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=uh),br.init(e,t)}),vh=C("$ZodCheckIncludes",(e,t)=>{Ge.init(e,t);const n=An(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})}}),_h=C("$ZodCheckStartsWith",(e,t)=>{Ge.init(e,t);const n=new RegExp(`^${An(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})}}),wh=C("$ZodCheckEndsWith",(e,t)=>{Ge.init(e,t);const n=new RegExp(`.*${An(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})}}),bh=C("$ZodCheckOverwrite",(e,t)=>{Ge.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class xh{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(`
8
8
  `).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==null?void 0:this.args,o=[...((this==null?void 0:this.content)??[""]).map(s=>` ${s}`)];return new t(...n,o.join(`
9
- `))}}const Th={major:4,minor:0,patch:0},he=C("$ZodType",(e,t)=>{var o;var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Th;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const s of r)for(const a of s._zod.onattach)a(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),(o=e._zod.deferred)==null||o.push(()=>{e._zod.run=e._zod.parse});else{const s=(a,i,l)=>{let u=On(a),c;for(const w of i){if(w._zod.def.when){if(!w._zod.def.when(a))continue}else if(u)continue;const _=a.issues.length,d=w._zod.check(a);if(d instanceof Promise&&(l==null?void 0:l.async)===!1)throw new Cn;if(c||d instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await d,a.issues.length!==_&&(u||(u=On(a,_)))});else{if(a.issues.length===_)continue;u||(u=On(a,_))}}return c?c.then(()=>a):a};e._zod.run=(a,i)=>{const l=e._zod.parse(a,i);if(l instanceof Promise){if(i.async===!1)throw new Cn;return l.then(u=>s(u,r,i))}return s(l,r,i)}}e["~standard"]={validate:s=>{var a;try{const i=$p(e,s);return i.success?{value:i.data}:{issues:(a=i.error)==null?void 0:a.issues}}catch{return zp(e,s).then(l=>{var u;return l.success?{value:l.data}:{issues:(u=l.error)==null?void 0:u.issues}})}},vendor:"zod",version:1}}),Io=C("$ZodString",(e,t)=>{var n;he.init(e,t),e._zod.pattern=[...((n=e==null?void 0:e._zod.bag)==null?void 0:n.patterns)??[]].pop()??oh(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ve=C("$ZodStringFormat",(e,t)=>{br.init(e,t),Io.init(e,t)}),Sh=C("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Vp),ve.init(e,t)}),Ih=C("$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=ii(r))}else t.pattern??(t.pattern=ii());ve.init(e,t)}),Ch=C("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Fp),ve.init(e,t)}),Eh=C("$ZodURL",(e,t)=>{ve.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:Qp.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})}}}),Rh=C("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Jp()),ve.init(e,t)}),Ah=C("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=qp),ve.init(e,t)}),Oh=C("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=jp),ve.init(e,t)}),Nh=C("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Dp),ve.init(e,t)}),Mh=C("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Zp),ve.init(e,t)}),Ph=C("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Up),ve.init(e,t)}),$h=C("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Lp),ve.init(e,t)}),zh=C("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=rh(t)),ve.init(e,t)}),jh=C("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=th),ve.init(e,t)}),Dh=C("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=nh(t)),ve.init(e,t)}),Zh=C("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Bp),ve.init(e,t)}),Uh=C("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Gp),ve.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),Lh=C("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Wp),ve.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})}}}),qh=C("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Kp),ve.init(e,t)}),Bh=C("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Yp),ve.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 fi(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Vh=C("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Xp),ve.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{fi(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Fh(e){if(!li.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return fi(n)}const Hh=C("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=li),ve.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{Fh(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Jh=C("$ZodE164",(e,t)=>{t.pattern??(t.pattern=eh),ve.init(e,t)});function Gh(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==null?void 0:o.typ)!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const Wh=C("$ZodJWT",(e,t)=>{ve.init(e,t),e._zod.check=n=>{Gh(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),mi=C("$ZodNumber",(e,t)=>{he.init(e,t),e._zod.pattern=e._zod.bag.pattern??ah,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}}),Kh=C("$ZodNumber",(e,t)=>{ph.init(e,t),mi.init(e,t)}),Yh=C("$ZodBoolean",(e,t)=>{he.init(e,t),e._zod.pattern=ih,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}}),Xh=C("$ZodNull",(e,t)=>{he.init(e,t),e._zod.pattern=lh,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}}),Qh=C("$ZodAny",(e,t)=>{he.init(e,t),e._zod.parse=n=>n}),ef=C("$ZodUnknown",(e,t)=>{he.init(e,t),e._zod.parse=n=>n}),tf=C("$ZodNever",(e,t)=>{he.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function gi(e,t,n){e.issues.length&&t.issues.push(...Gt(n,e.issues)),t.value[n]=e.value}const nf=C("$ZodArray",(e,t)=>{he.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 i=o[a],l=t.element._zod.run({value:i,issues:[]},r);l instanceof Promise?s.push(l.then(u=>gi(u,n,a))):gi(l,n,a)}return s.length?Promise.all(s).then(()=>n):n}});function xr(e,t,n){e.issues.length&&t.issues.push(...Gt(n,e.issues)),t.value[n]=e.value}function yi(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(...Gt(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const rf=C("$ZodObject",(e,t)=>{he.init(e,t);const n=xo(()=>{const w=Object.keys(t.shape);for(const d of w)if(!(t.shape[d]instanceof he))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);const _=kp(t.shape);return{shape:t.shape,keys:w,keySet:new Set(w),numKeys:w.length,optionalKeys:new Set(_)}});le(e._zod,"propValues",()=>{const w=t.shape,_={};for(const d in w){const f=w[d]._zod;if(f.values){_[d]??(_[d]=new Set);for(const y of f.values)_[d].add(y)}}return _});const r=w=>{const _=new kh(["shape","payload","ctx"]),d=n.value,f=b=>{const g=Rn(b);return`shape[${g}]._zod.run({ value: input[${g}], issues: [] }, ctx)`};_.write("const input = payload.value;");const y=Object.create(null);let v=0;for(const b of d.keys)y[b]=`key_${v++}`;_.write("const newResult = {}");for(const b of d.keys)if(d.optionalKeys.has(b)){const g=y[b];_.write(`const ${g} = ${f(b)};`);const m=Rn(b);_.write(`
9
+ `))}}const kh={major:4,minor:0,patch:0},he=C("$ZodType",(e,t)=>{var o;var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=kh;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const s of r)for(const a of s._zod.onattach)a(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),(o=e._zod.deferred)==null||o.push(()=>{e._zod.run=e._zod.parse});else{const s=(a,i,l)=>{let u=On(a),c;for(const w of i){if(w._zod.def.when){if(!w._zod.def.when(a))continue}else if(u)continue;const _=a.issues.length,d=w._zod.check(a);if(d instanceof Promise&&(l==null?void 0:l.async)===!1)throw new Cn;if(c||d instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await d,a.issues.length!==_&&(u||(u=On(a,_)))});else{if(a.issues.length===_)continue;u||(u=On(a,_))}}return c?c.then(()=>a):a};e._zod.run=(a,i)=>{const l=e._zod.parse(a,i);if(l instanceof Promise){if(i.async===!1)throw new Cn;return l.then(u=>s(u,r,i))}return s(l,r,i)}}e["~standard"]={validate:s=>{var a;try{const i=Pp(e,s);return i.success?{value:i.data}:{issues:(a=i.error)==null?void 0:a.issues}}catch{return $p(e,s).then(l=>{var u;return l.success?{value:l.data}:{issues:(u=l.error)==null?void 0:u.issues}})}},vendor:"zod",version:1}}),Io=C("$ZodString",(e,t)=>{var n;he.init(e,t),e._zod.pattern=[...((n=e==null?void 0:e._zod.bag)==null?void 0:n.patterns)??[]].pop()??rh(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ve=C("$ZodStringFormat",(e,t)=>{br.init(e,t),Io.init(e,t)}),Th=C("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Bp),ve.init(e,t)}),Sh=C("$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=ii(r))}else t.pattern??(t.pattern=ii());ve.init(e,t)}),Ih=C("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Vp),ve.init(e,t)}),Ch=C("$ZodURL",(e,t)=>{ve.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:Xp.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})}}}),Eh=C("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Hp()),ve.init(e,t)}),Rh=C("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Lp),ve.init(e,t)}),Ah=C("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=zp),ve.init(e,t)}),Oh=C("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=jp),ve.init(e,t)}),Nh=C("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Dp),ve.init(e,t)}),Mh=C("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Zp),ve.init(e,t)}),Ph=C("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Up),ve.init(e,t)}),$h=C("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=nh(t)),ve.init(e,t)}),zh=C("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=eh),ve.init(e,t)}),jh=C("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=th(t)),ve.init(e,t)}),Dh=C("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=qp),ve.init(e,t)}),Zh=C("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Jp),ve.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),Uh=C("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Gp),ve.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})}}}),Lh=C("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Wp),ve.init(e,t)}),qh=C("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Kp),ve.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 fi(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Bh=C("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Yp),ve.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{fi(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Vh(e){if(!li.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return fi(n)}const Fh=C("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=li),ve.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{Vh(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Hh=C("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Qp),ve.init(e,t)});function Jh(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==null?void 0:o.typ)!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const Gh=C("$ZodJWT",(e,t)=>{ve.init(e,t),e._zod.check=n=>{Jh(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),mi=C("$ZodNumber",(e,t)=>{he.init(e,t),e._zod.pattern=e._zod.bag.pattern??sh,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}}),Wh=C("$ZodNumber",(e,t)=>{dh.init(e,t),mi.init(e,t)}),Kh=C("$ZodBoolean",(e,t)=>{he.init(e,t),e._zod.pattern=ah,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}}),Yh=C("$ZodNull",(e,t)=>{he.init(e,t),e._zod.pattern=ih,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}}),Xh=C("$ZodAny",(e,t)=>{he.init(e,t),e._zod.parse=n=>n}),Qh=C("$ZodUnknown",(e,t)=>{he.init(e,t),e._zod.parse=n=>n}),ef=C("$ZodNever",(e,t)=>{he.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function gi(e,t,n){e.issues.length&&t.issues.push(...Gt(n,e.issues)),t.value[n]=e.value}const tf=C("$ZodArray",(e,t)=>{he.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 i=o[a],l=t.element._zod.run({value:i,issues:[]},r);l instanceof Promise?s.push(l.then(u=>gi(u,n,a))):gi(l,n,a)}return s.length?Promise.all(s).then(()=>n):n}});function xr(e,t,n){e.issues.length&&t.issues.push(...Gt(n,e.issues)),t.value[n]=e.value}function yi(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(...Gt(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const nf=C("$ZodObject",(e,t)=>{he.init(e,t);const n=xo(()=>{const w=Object.keys(t.shape);for(const d of w)if(!(t.shape[d]instanceof he))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);const _=xp(t.shape);return{shape:t.shape,keys:w,keySet:new Set(w),numKeys:w.length,optionalKeys:new Set(_)}});le(e._zod,"propValues",()=>{const w=t.shape,_={};for(const d in w){const f=w[d]._zod;if(f.values){_[d]??(_[d]=new Set);for(const y of f.values)_[d].add(y)}}return _});const r=w=>{const _=new xh(["shape","payload","ctx"]),d=n.value,f=b=>{const g=Rn(b);return`shape[${g}]._zod.run({ value: input[${g}], issues: [] }, ctx)`};_.write("const input = payload.value;");const y=Object.create(null);let v=0;for(const b of d.keys)y[b]=`key_${v++}`;_.write("const newResult = {}");for(const b of d.keys)if(d.optionalKeys.has(b)){const g=y[b];_.write(`const ${g} = ${f(b)};`);const m=Rn(b);_.write(`
10
10
  if (${g}.issues.length) {
11
11
  if (input[${m}] === undefined) {
12
12
  if (${m} in input) {
@@ -29,13 +29,13 @@ Error message: ${ln(n)}`,cause:n}),this[Ga]=!0,this.value=t}static isInstance(t)
29
29
  if (${g}.issues.length) payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
30
30
  ...iss,
31
31
  path: iss.path ? [${Rn(b)}, ...iss.path] : [${Rn(b)}]
32
- })));`),_.write(`newResult[${Rn(b)}] = ${g}.value`)}_.write("payload.value = newResult;"),_.write("return payload;");const p=_.compile();return(b,g)=>p(w,b,g)};let o;const s=vr,a=!Qa.jitless,l=a&&bp.value,u=t.catchall;let c;e._zod.parse=(w,_)=>{c??(c=n.value);const d=w.value;if(!s(d))return w.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),w;const f=[];if(a&&l&&(_==null?void 0:_.async)===!1&&_.jitless!==!0)o||(o=r(t.shape)),w=o(w,_);else{w.value={};const g=c.shape;for(const m of c.keys){const E=g[m],S=E._zod.run({value:d[m],issues:[]},_),T=E._zod.optin==="optional"&&E._zod.optout==="optional";S instanceof Promise?f.push(S.then(P=>T?yi(P,w,m,d):xr(P,w,m))):T?yi(S,w,m,d):xr(S,w,m)}}if(!u)return f.length?Promise.all(f).then(()=>w):w;const y=[],v=c.keySet,p=u._zod,b=p.def.type;for(const g of Object.keys(d)){if(v.has(g))continue;if(b==="never"){y.push(g);continue}const m=p.run({value:d[g],issues:[]},_);m instanceof Promise?f.push(m.then(E=>xr(E,w,g))):xr(m,w,g)}return y.length&&w.issues.push({code:"unrecognized_keys",keys:y,input:d,inst:e}),f.length?Promise.all(f).then(()=>w):w}});function vi(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=>Dt(s,r,jt())))}),t}const _i=C("$ZodUnion",(e,t)=>{he.init(e,t),le(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),le(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),le(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),le(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=>To(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let o=!1;const s=[];for(const a of t.options){const i=a._zod.run({value:n.value,issues:[]},r);if(i instanceof Promise)s.push(i),o=!0;else{if(i.issues.length===0)return i;s.push(i)}}return o?Promise.all(s).then(a=>vi(a,n,e,r)):vi(s,n,e,r)}}),of=C("$ZodDiscriminatedUnion",(e,t)=>{_i.init(e,t);const n=e._zod.parse;le(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[i,l]of Object.entries(a)){o[i]||(o[i]=new Set);for(const u of l)o[i].add(u)}}return o});const r=xo(()=>{const o=t.options,s=new Map;for(const a of o){const i=a._zod.propValues[t.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const l of i){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(!vr(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const i=r.value.get(a==null?void 0:a[t.discriminator]);return i?i._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)}}),sf=C("$ZodIntersection",(e,t)=>{he.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,u])=>wi(n,l,u)):wi(n,s,a)}});function Co(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(_r(e)&&_r(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=Co(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=Co(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:[]}}function wi(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),On(e))return e;const r=Co(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const af=C("$ZodRecord",(e,t)=>{he.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!_r(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 u=t.valueType._zod.run({value:o[l],issues:[]},r);u instanceof Promise?s.push(u.then(c=>{c.issues.length&&n.issues.push(...Gt(l,c.issues)),n.value[l]=c.value})):(u.issues.length&&n.issues.push(...Gt(l,u.issues)),n.value[l]=u.value)}let i;for(const l in o)a.has(l)||(i=i??[],i.push(l));i&&i.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:i})}else{n.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const i=t.keyType._zod.run({value:a,issues:[]},r);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(u=>Dt(u,r,jt())),input:a,path:[a],inst:e}),n.value[i.value]=i.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},r);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&n.issues.push(...Gt(a,u.issues)),n.value[i.value]=u.value})):(l.issues.length&&n.issues.push(...Gt(a,l.issues)),n.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>n):n}}),lf=C("$ZodEnum",(e,t)=>{he.init(e,t);const n=ei(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>xp.has(typeof r)).map(r=>typeof r=="string"?An(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}}),uf=C("$ZodLiteral",(e,t)=>{he.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?An(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}}),cf=C("$ZodTransform",(e,t)=>{he.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 Cn;return n.value=o,n}}),df=C("$ZodOptional",(e,t)=>{he.init(e,t),e._zod.optin="optional",e._zod.optout="optional",le(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),le(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${To(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)}),pf=C("$ZodNullable",(e,t)=>{he.init(e,t),le(e._zod,"optin",()=>t.innerType._zod.optin),le(e._zod,"optout",()=>t.innerType._zod.optout),le(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${To(n.source)}|null)$`):void 0}),le(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)}),hf=C("$ZodDefault",(e,t)=>{he.init(e,t),e._zod.optin="optional",le(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=>bi(s,t)):bi(o,t)}});function bi(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const ff=C("$ZodPrefault",(e,t)=>{he.init(e,t),e._zod.optin="optional",le(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))}),mf=C("$ZodNonOptional",(e,t)=>{he.init(e,t),le(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=>xi(s,e)):xi(o,e)}});function xi(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const gf=C("$ZodCatch",(e,t)=>{he.init(e,t),e._zod.optin="optional",le(e._zod,"optout",()=>t.innerType._zod.optout),le(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=>Dt(a,r,jt()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>Dt(s,r,jt()))},input:n.value}),n.issues=[]),n)}}),yf=C("$ZodPipe",(e,t)=>{he.init(e,t),le(e._zod,"values",()=>t.in._zod.values),le(e._zod,"optin",()=>t.in._zod.optin),le(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=>ki(s,t,r)):ki(o,t,r)}});function ki(e,t,n){return On(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const vf=C("$ZodReadonly",(e,t)=>{he.init(e,t),le(e._zod,"propValues",()=>t.innerType._zod.propValues),le(e._zod,"values",()=>t.innerType._zod.values),le(e._zod,"optin",()=>t.innerType._zod.optin),le(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(Ti):Ti(o)}});function Ti(e){return e.value=Object.freeze(e.value),e}const _f=C("$ZodLazy",(e,t)=>{he.init(e,t),le(e._zod,"innerType",()=>t.getter()),le(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),le(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),le(e._zod,"optin",()=>e._zod.innerType._zod.optin),le(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),wf=C("$ZodCustom",(e,t)=>{Ge.init(e,t),he.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=>Si(s,n,r,e));Si(o,n,r,e)}});function Si(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(Nn(o))}}class Ii{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)}}function bf(){return new Ii}const Mn=bf();function xf(e,t){return new e({type:"string",...U(t)})}function kf(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...U(t)})}function Ci(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...U(t)})}function Tf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...U(t)})}function Sf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...U(t)})}function If(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...U(t)})}function Cf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...U(t)})}function Ef(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...U(t)})}function Rf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...U(t)})}function Af(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...U(t)})}function Of(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...U(t)})}function Nf(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...U(t)})}function Mf(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...U(t)})}function Pf(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...U(t)})}function $f(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...U(t)})}function zf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...U(t)})}function jf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...U(t)})}function Df(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...U(t)})}function Zf(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...U(t)})}function Ei(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...U(t)})}function Uf(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...U(t)})}function Lf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...U(t)})}function qf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...U(t)})}function Bf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...U(t)})}function Vf(e,t){return new e({type:"string",format:"date",check:"string_format",...U(t)})}function Ff(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...U(t)})}function Hf(e,t){return new e({type:"string",format:"duration",check:"string_format",...U(t)})}function Jf(e,t){return new e({type:"number",checks:[],...U(t)})}function Gf(e,t){return new e({type:"number",coerce:!0,checks:[],...U(t)})}function Wf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...U(t)})}function Kf(e,t){return new e({type:"boolean",...U(t)})}function Yf(e,t){return new e({type:"null",...U(t)})}function Xf(e){return new e({type:"any"})}function Qf(e){return new e({type:"unknown"})}function em(e,t){return new e({type:"never",...U(t)})}function Ri(e,t){return new pi({check:"less_than",...U(t),value:e,inclusive:!1})}function Eo(e,t){return new pi({check:"less_than",...U(t),value:e,inclusive:!0})}function Ai(e,t){return new hi({check:"greater_than",...U(t),value:e,inclusive:!1})}function Ro(e,t){return new hi({check:"greater_than",...U(t),value:e,inclusive:!0})}function Oi(e,t){return new dh({check:"multiple_of",...U(t),value:e})}function Ni(e,t){return new hh({check:"max_length",...U(t),maximum:e})}function kr(e,t){return new fh({check:"min_length",...U(t),minimum:e})}function Mi(e,t){return new mh({check:"length_equals",...U(t),length:e})}function tm(e,t){return new gh({check:"string_format",format:"regex",...U(t),pattern:e})}function nm(e){return new yh({check:"string_format",format:"lowercase",...U(e)})}function rm(e){return new vh({check:"string_format",format:"uppercase",...U(e)})}function om(e,t){return new _h({check:"string_format",format:"includes",...U(t),includes:e})}function sm(e,t){return new wh({check:"string_format",format:"starts_with",...U(t),prefix:e})}function am(e,t){return new bh({check:"string_format",format:"ends_with",...U(t),suffix:e})}function Pn(e){return new xh({check:"overwrite",tx:e})}function im(e){return Pn(t=>t.normalize(e))}function lm(){return Pn(e=>e.trim())}function um(){return Pn(e=>e.toLowerCase())}function cm(){return Pn(e=>e.toUpperCase())}function dm(e,t,n){return new e({type:"array",element:t,...U(n)})}function pm(e,t,n){const r=U(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function hm(e,t,n){return new e({type:"custom",check:"custom",fn:t,...U(n)})}class Pi{constructor(t){this.counter=0,this.metadataRegistry=(t==null?void 0:t.metadata)??Mn,this.target=(t==null?void 0:t.target)??"draft-2020-12",this.unrepresentable=(t==null?void 0:t.unrepresentable)??"throw",this.override=(t==null?void 0:t.override)??(()=>{}),this.io=(t==null?void 0:t.io)??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var w,_,d;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 i={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,i);const l=(_=(w=t._zod).toJSONSchema)==null?void 0:_.call(w);if(l)i.schema=l;else{const f={...n,schemaPath:[...n.schemaPath,t],path:n.path},y=t._zod.parent;if(y)i.ref=y,this.process(y,f),this.seen.get(y).isParent=!0;else{const v=i.schema;switch(o.type){case"string":{const p=v;p.type="string";const{minimum:b,maximum:g,format:m,patterns:E,contentEncoding:S}=t._zod.bag;if(typeof b=="number"&&(p.minLength=b),typeof g=="number"&&(p.maxLength=g),m&&(p.format=s[m]??m,p.format===""&&delete p.format),S&&(p.contentEncoding=S),E&&E.size>0){const T=[...E];T.length===1?p.pattern=T[0].source:T.length>1&&(i.schema.allOf=[...T.map(P=>({...this.target==="draft-7"?{type:"string"}:{},pattern:P.source}))])}break}case"number":{const p=v,{minimum:b,maximum:g,format:m,multipleOf:E,exclusiveMaximum:S,exclusiveMinimum:T}=t._zod.bag;typeof m=="string"&&m.includes("int")?p.type="integer":p.type="number",typeof T=="number"&&(p.exclusiveMinimum=T),typeof b=="number"&&(p.minimum=b,typeof T=="number"&&(T>=b?delete p.minimum:delete p.exclusiveMinimum)),typeof S=="number"&&(p.exclusiveMaximum=S),typeof g=="number"&&(p.maximum=g,typeof S=="number"&&(S<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof E=="number"&&(p.multipleOf=E);break}case"boolean":{const p=v;p.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":{v.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":{v.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const p=v,{minimum:b,maximum:g}=t._zod.bag;typeof b=="number"&&(p.minItems=b),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(o.element,{...f,path:[...f.path,"items"]});break}case"object":{const p=v;p.type="object",p.properties={};const b=o.shape;for(const E in b)p.properties[E]=this.process(b[E],{...f,path:[...f.path,"properties",E]});const g=new Set(Object.keys(b)),m=new Set([...g].filter(E=>{const S=o.shape[E]._zod;return this.io==="input"?S.optin===void 0:S.optout===void 0}));m.size>0&&(p.required=Array.from(m)),((d=o.catchall)==null?void 0:d._zod.def.type)==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...f,path:[...f.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{const p=v;p.anyOf=o.options.map((b,g)=>this.process(b,{...f,path:[...f.path,"anyOf",g]}));break}case"intersection":{const p=v,b=this.process(o.left,{...f,path:[...f.path,"allOf",0]}),g=this.process(o.right,{...f,path:[...f.path,"allOf",1]}),m=S=>"allOf"in S&&Object.keys(S).length===1,E=[...m(b)?b.allOf:[b],...m(g)?g.allOf:[g]];p.allOf=E;break}case"tuple":{const p=v;p.type="array";const b=o.items.map((E,S)=>this.process(E,{...f,path:[...f.path,"prefixItems",S]}));if(this.target==="draft-2020-12"?p.prefixItems=b:p.items=b,o.rest){const E=this.process(o.rest,{...f,path:[...f.path,"items"]});this.target==="draft-2020-12"?p.items=E:p.additionalItems=E}o.rest&&(p.items=this.process(o.rest,{...f,path:[...f.path,"items"]}));const{minimum:g,maximum:m}=t._zod.bag;typeof g=="number"&&(p.minItems=g),typeof m=="number"&&(p.maxItems=m);break}case"record":{const p=v;p.type="object",p.propertyNames=this.process(o.keyType,{...f,path:[...f.path,"propertyNames"]}),p.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 p=v,b=ei(o.entries);b.every(g=>typeof g=="number")&&(p.type="number"),b.every(g=>typeof g=="string")&&(p.type="string"),p.enum=b;break}case"literal":{const p=v,b=[];for(const g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");b.push(Number(g))}else b.push(g);if(b.length!==0)if(b.length===1){const g=b[0];p.type=g===null?"null":typeof g,p.const=g}else b.every(g=>typeof g=="number")&&(p.type="number"),b.every(g=>typeof g=="string")&&(p.type="string"),b.every(g=>typeof g=="boolean")&&(p.type="string"),b.every(g=>g===null)&&(p.type="null"),p.enum=b;break}case"file":{const p=v,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:m,mime:E}=t._zod.bag;g!==void 0&&(b.minLength=g),m!==void 0&&(b.maxLength=m),E?E.length===1?(b.contentMediaType=E[0],Object.assign(p,b)):p.anyOf=E.map(S=>({...b,contentMediaType:S})):Object.assign(p,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const p=this.process(o.innerType,f);v.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,f),i.ref=o.innerType;break}case"success":{const p=v;p.type="boolean";break}case"default":{this.process(o.innerType,f),i.ref=o.innerType,v.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,f),i.ref=o.innerType,this.io==="input"&&(v._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,f),i.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}v.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const p=v,b=t._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=b.source;break}case"pipe":{const p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,f),i.ref=p;break}case"readonly":{this.process(o.innerType,f),i.ref=o.innerType,v.readOnly=!0;break}case"promise":{this.process(o.innerType,f),i.ref=o.innerType;break}case"optional":{this.process(o.innerType,f),i.ref=o.innerType;break}case"lazy":{const p=t._zod.innerType;this.process(p,f),i.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const u=this.metadataRegistry.get(t);return u&&Object.assign(i.schema,u),this.io==="input"&&Ae(t)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(t).schema}emit(t,n){var c,w,_,d,f,y;const r={cycles:(n==null?void 0:n.cycles)??"ref",reused:(n==null?void 0:n.reused)??"inline",external:(n==null?void 0:n.external)??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=v=>{var E;const p=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const S=(E=r.external.registry.get(v[0]))==null?void 0:E.id,T=r.external.uri??(V=>V);if(S)return{ref:T(S)};const P=v[1].defId??v[1].schema.id??`schema${this.counter++}`;return v[1].defId=P,{defId:P,ref:`${T("__shared")}#/${p}/${P}`}}if(v[1]===o)return{ref:"#"};const g=`#/${p}/`,m=v[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:g+m}},a=v=>{if(v[1].schema.$ref)return;const p=v[1],{ref:b,defId:g}=s(v);p.def={...p.schema},g&&(p.defId=g);const m=p.schema;for(const E in m)delete m[E];m.$ref=b};if(r.cycles==="throw")for(const v of this.seen.entries()){const p=v[1];if(p.cycle)throw new Error(`Cycle detected: #/${(c=p.cycle)==null?void 0:c.join("/")}/<root>
32
+ })));`),_.write(`newResult[${Rn(b)}] = ${g}.value`)}_.write("payload.value = newResult;"),_.write("return payload;");const p=_.compile();return(b,g)=>p(w,b,g)};let o;const s=vr,a=!Qa.jitless,l=a&&wp.value,u=t.catchall;let c;e._zod.parse=(w,_)=>{c??(c=n.value);const d=w.value;if(!s(d))return w.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),w;const f=[];if(a&&l&&(_==null?void 0:_.async)===!1&&_.jitless!==!0)o||(o=r(t.shape)),w=o(w,_);else{w.value={};const g=c.shape;for(const m of c.keys){const E=g[m],S=E._zod.run({value:d[m],issues:[]},_),T=E._zod.optin==="optional"&&E._zod.optout==="optional";S instanceof Promise?f.push(S.then(P=>T?yi(P,w,m,d):xr(P,w,m))):T?yi(S,w,m,d):xr(S,w,m)}}if(!u)return f.length?Promise.all(f).then(()=>w):w;const y=[],v=c.keySet,p=u._zod,b=p.def.type;for(const g of Object.keys(d)){if(v.has(g))continue;if(b==="never"){y.push(g);continue}const m=p.run({value:d[g],issues:[]},_);m instanceof Promise?f.push(m.then(E=>xr(E,w,g))):xr(m,w,g)}return y.length&&w.issues.push({code:"unrecognized_keys",keys:y,input:d,inst:e}),f.length?Promise.all(f).then(()=>w):w}});function vi(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=>Dt(s,r,jt())))}),t}const _i=C("$ZodUnion",(e,t)=>{he.init(e,t),le(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),le(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),le(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),le(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=>To(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let o=!1;const s=[];for(const a of t.options){const i=a._zod.run({value:n.value,issues:[]},r);if(i instanceof Promise)s.push(i),o=!0;else{if(i.issues.length===0)return i;s.push(i)}}return o?Promise.all(s).then(a=>vi(a,n,e,r)):vi(s,n,e,r)}}),rf=C("$ZodDiscriminatedUnion",(e,t)=>{_i.init(e,t);const n=e._zod.parse;le(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[i,l]of Object.entries(a)){o[i]||(o[i]=new Set);for(const u of l)o[i].add(u)}}return o});const r=xo(()=>{const o=t.options,s=new Map;for(const a of o){const i=a._zod.propValues[t.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const l of i){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(!vr(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const i=r.value.get(a==null?void 0:a[t.discriminator]);return i?i._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)}}),of=C("$ZodIntersection",(e,t)=>{he.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,u])=>wi(n,l,u)):wi(n,s,a)}});function Co(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(_r(e)&&_r(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=Co(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=Co(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:[]}}function wi(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),On(e))return e;const r=Co(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const sf=C("$ZodRecord",(e,t)=>{he.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!_r(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 u=t.valueType._zod.run({value:o[l],issues:[]},r);u instanceof Promise?s.push(u.then(c=>{c.issues.length&&n.issues.push(...Gt(l,c.issues)),n.value[l]=c.value})):(u.issues.length&&n.issues.push(...Gt(l,u.issues)),n.value[l]=u.value)}let i;for(const l in o)a.has(l)||(i=i??[],i.push(l));i&&i.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:i})}else{n.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const i=t.keyType._zod.run({value:a,issues:[]},r);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(u=>Dt(u,r,jt())),input:a,path:[a],inst:e}),n.value[i.value]=i.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},r);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&n.issues.push(...Gt(a,u.issues)),n.value[i.value]=u.value})):(l.issues.length&&n.issues.push(...Gt(a,l.issues)),n.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>n):n}}),af=C("$ZodEnum",(e,t)=>{he.init(e,t);const n=ei(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>bp.has(typeof r)).map(r=>typeof r=="string"?An(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}}),lf=C("$ZodLiteral",(e,t)=>{he.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?An(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}}),uf=C("$ZodTransform",(e,t)=>{he.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 Cn;return n.value=o,n}}),cf=C("$ZodOptional",(e,t)=>{he.init(e,t),e._zod.optin="optional",e._zod.optout="optional",le(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),le(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${To(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)}),df=C("$ZodNullable",(e,t)=>{he.init(e,t),le(e._zod,"optin",()=>t.innerType._zod.optin),le(e._zod,"optout",()=>t.innerType._zod.optout),le(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${To(n.source)}|null)$`):void 0}),le(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)}),pf=C("$ZodDefault",(e,t)=>{he.init(e,t),e._zod.optin="optional",le(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=>bi(s,t)):bi(o,t)}});function bi(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const hf=C("$ZodPrefault",(e,t)=>{he.init(e,t),e._zod.optin="optional",le(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))}),ff=C("$ZodNonOptional",(e,t)=>{he.init(e,t),le(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=>xi(s,e)):xi(o,e)}});function xi(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const mf=C("$ZodCatch",(e,t)=>{he.init(e,t),e._zod.optin="optional",le(e._zod,"optout",()=>t.innerType._zod.optout),le(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=>Dt(a,r,jt()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>Dt(s,r,jt()))},input:n.value}),n.issues=[]),n)}}),gf=C("$ZodPipe",(e,t)=>{he.init(e,t),le(e._zod,"values",()=>t.in._zod.values),le(e._zod,"optin",()=>t.in._zod.optin),le(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=>ki(s,t,r)):ki(o,t,r)}});function ki(e,t,n){return On(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const yf=C("$ZodReadonly",(e,t)=>{he.init(e,t),le(e._zod,"propValues",()=>t.innerType._zod.propValues),le(e._zod,"values",()=>t.innerType._zod.values),le(e._zod,"optin",()=>t.innerType._zod.optin),le(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(Ti):Ti(o)}});function Ti(e){return e.value=Object.freeze(e.value),e}const vf=C("$ZodLazy",(e,t)=>{he.init(e,t),le(e._zod,"innerType",()=>t.getter()),le(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),le(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),le(e._zod,"optin",()=>e._zod.innerType._zod.optin),le(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),_f=C("$ZodCustom",(e,t)=>{Ge.init(e,t),he.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=>Si(s,n,r,e));Si(o,n,r,e)}});function Si(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(Nn(o))}}class Ii{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)}}function wf(){return new Ii}const Mn=wf();function bf(e,t){return new e({type:"string",...U(t)})}function xf(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...U(t)})}function Ci(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...U(t)})}function kf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...U(t)})}function Tf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...U(t)})}function Sf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...U(t)})}function If(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...U(t)})}function Cf(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...U(t)})}function Ef(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...U(t)})}function Rf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...U(t)})}function Af(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...U(t)})}function Of(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...U(t)})}function Nf(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...U(t)})}function Mf(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...U(t)})}function Pf(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...U(t)})}function $f(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...U(t)})}function zf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...U(t)})}function jf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...U(t)})}function Df(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...U(t)})}function Ei(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...U(t)})}function Zf(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...U(t)})}function Uf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...U(t)})}function Lf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...U(t)})}function qf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...U(t)})}function Bf(e,t){return new e({type:"string",format:"date",check:"string_format",...U(t)})}function Vf(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...U(t)})}function Ff(e,t){return new e({type:"string",format:"duration",check:"string_format",...U(t)})}function Hf(e,t){return new e({type:"number",checks:[],...U(t)})}function Jf(e,t){return new e({type:"number",coerce:!0,checks:[],...U(t)})}function Gf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...U(t)})}function Wf(e,t){return new e({type:"boolean",...U(t)})}function Kf(e,t){return new e({type:"null",...U(t)})}function Yf(e){return new e({type:"any"})}function Xf(e){return new e({type:"unknown"})}function Qf(e,t){return new e({type:"never",...U(t)})}function Ri(e,t){return new pi({check:"less_than",...U(t),value:e,inclusive:!1})}function Eo(e,t){return new pi({check:"less_than",...U(t),value:e,inclusive:!0})}function Ai(e,t){return new hi({check:"greater_than",...U(t),value:e,inclusive:!1})}function Ro(e,t){return new hi({check:"greater_than",...U(t),value:e,inclusive:!0})}function Oi(e,t){return new ch({check:"multiple_of",...U(t),value:e})}function Ni(e,t){return new ph({check:"max_length",...U(t),maximum:e})}function kr(e,t){return new hh({check:"min_length",...U(t),minimum:e})}function Mi(e,t){return new fh({check:"length_equals",...U(t),length:e})}function em(e,t){return new mh({check:"string_format",format:"regex",...U(t),pattern:e})}function tm(e){return new gh({check:"string_format",format:"lowercase",...U(e)})}function nm(e){return new yh({check:"string_format",format:"uppercase",...U(e)})}function rm(e,t){return new vh({check:"string_format",format:"includes",...U(t),includes:e})}function om(e,t){return new _h({check:"string_format",format:"starts_with",...U(t),prefix:e})}function sm(e,t){return new wh({check:"string_format",format:"ends_with",...U(t),suffix:e})}function Pn(e){return new bh({check:"overwrite",tx:e})}function am(e){return Pn(t=>t.normalize(e))}function im(){return Pn(e=>e.trim())}function lm(){return Pn(e=>e.toLowerCase())}function um(){return Pn(e=>e.toUpperCase())}function cm(e,t,n){return new e({type:"array",element:t,...U(n)})}function dm(e,t,n){const r=U(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function pm(e,t,n){return new e({type:"custom",check:"custom",fn:t,...U(n)})}class Pi{constructor(t){this.counter=0,this.metadataRegistry=(t==null?void 0:t.metadata)??Mn,this.target=(t==null?void 0:t.target)??"draft-2020-12",this.unrepresentable=(t==null?void 0:t.unrepresentable)??"throw",this.override=(t==null?void 0:t.override)??(()=>{}),this.io=(t==null?void 0:t.io)??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var w,_,d;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 i={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,i);const l=(_=(w=t._zod).toJSONSchema)==null?void 0:_.call(w);if(l)i.schema=l;else{const f={...n,schemaPath:[...n.schemaPath,t],path:n.path},y=t._zod.parent;if(y)i.ref=y,this.process(y,f),this.seen.get(y).isParent=!0;else{const v=i.schema;switch(o.type){case"string":{const p=v;p.type="string";const{minimum:b,maximum:g,format:m,patterns:E,contentEncoding:S}=t._zod.bag;if(typeof b=="number"&&(p.minLength=b),typeof g=="number"&&(p.maxLength=g),m&&(p.format=s[m]??m,p.format===""&&delete p.format),S&&(p.contentEncoding=S),E&&E.size>0){const T=[...E];T.length===1?p.pattern=T[0].source:T.length>1&&(i.schema.allOf=[...T.map(P=>({...this.target==="draft-7"?{type:"string"}:{},pattern:P.source}))])}break}case"number":{const p=v,{minimum:b,maximum:g,format:m,multipleOf:E,exclusiveMaximum:S,exclusiveMinimum:T}=t._zod.bag;typeof m=="string"&&m.includes("int")?p.type="integer":p.type="number",typeof T=="number"&&(p.exclusiveMinimum=T),typeof b=="number"&&(p.minimum=b,typeof T=="number"&&(T>=b?delete p.minimum:delete p.exclusiveMinimum)),typeof S=="number"&&(p.exclusiveMaximum=S),typeof g=="number"&&(p.maximum=g,typeof S=="number"&&(S<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof E=="number"&&(p.multipleOf=E);break}case"boolean":{const p=v;p.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":{v.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":{v.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const p=v,{minimum:b,maximum:g}=t._zod.bag;typeof b=="number"&&(p.minItems=b),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(o.element,{...f,path:[...f.path,"items"]});break}case"object":{const p=v;p.type="object",p.properties={};const b=o.shape;for(const E in b)p.properties[E]=this.process(b[E],{...f,path:[...f.path,"properties",E]});const g=new Set(Object.keys(b)),m=new Set([...g].filter(E=>{const S=o.shape[E]._zod;return this.io==="input"?S.optin===void 0:S.optout===void 0}));m.size>0&&(p.required=Array.from(m)),((d=o.catchall)==null?void 0:d._zod.def.type)==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...f,path:[...f.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{const p=v;p.anyOf=o.options.map((b,g)=>this.process(b,{...f,path:[...f.path,"anyOf",g]}));break}case"intersection":{const p=v,b=this.process(o.left,{...f,path:[...f.path,"allOf",0]}),g=this.process(o.right,{...f,path:[...f.path,"allOf",1]}),m=S=>"allOf"in S&&Object.keys(S).length===1,E=[...m(b)?b.allOf:[b],...m(g)?g.allOf:[g]];p.allOf=E;break}case"tuple":{const p=v;p.type="array";const b=o.items.map((E,S)=>this.process(E,{...f,path:[...f.path,"prefixItems",S]}));if(this.target==="draft-2020-12"?p.prefixItems=b:p.items=b,o.rest){const E=this.process(o.rest,{...f,path:[...f.path,"items"]});this.target==="draft-2020-12"?p.items=E:p.additionalItems=E}o.rest&&(p.items=this.process(o.rest,{...f,path:[...f.path,"items"]}));const{minimum:g,maximum:m}=t._zod.bag;typeof g=="number"&&(p.minItems=g),typeof m=="number"&&(p.maxItems=m);break}case"record":{const p=v;p.type="object",p.propertyNames=this.process(o.keyType,{...f,path:[...f.path,"propertyNames"]}),p.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 p=v,b=ei(o.entries);b.every(g=>typeof g=="number")&&(p.type="number"),b.every(g=>typeof g=="string")&&(p.type="string"),p.enum=b;break}case"literal":{const p=v,b=[];for(const g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");b.push(Number(g))}else b.push(g);if(b.length!==0)if(b.length===1){const g=b[0];p.type=g===null?"null":typeof g,p.const=g}else b.every(g=>typeof g=="number")&&(p.type="number"),b.every(g=>typeof g=="string")&&(p.type="string"),b.every(g=>typeof g=="boolean")&&(p.type="string"),b.every(g=>g===null)&&(p.type="null"),p.enum=b;break}case"file":{const p=v,b={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:m,mime:E}=t._zod.bag;g!==void 0&&(b.minLength=g),m!==void 0&&(b.maxLength=m),E?E.length===1?(b.contentMediaType=E[0],Object.assign(p,b)):p.anyOf=E.map(S=>({...b,contentMediaType:S})):Object.assign(p,b);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const p=this.process(o.innerType,f);v.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,f),i.ref=o.innerType;break}case"success":{const p=v;p.type="boolean";break}case"default":{this.process(o.innerType,f),i.ref=o.innerType,v.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,f),i.ref=o.innerType,this.io==="input"&&(v._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,f),i.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}v.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const p=v,b=t._zod.pattern;if(!b)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=b.source;break}case"pipe":{const p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,f),i.ref=p;break}case"readonly":{this.process(o.innerType,f),i.ref=o.innerType,v.readOnly=!0;break}case"promise":{this.process(o.innerType,f),i.ref=o.innerType;break}case"optional":{this.process(o.innerType,f),i.ref=o.innerType;break}case"lazy":{const p=t._zod.innerType;this.process(p,f),i.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const u=this.metadataRegistry.get(t);return u&&Object.assign(i.schema,u),this.io==="input"&&Ae(t)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(t).schema}emit(t,n){var c,w,_,d,f,y;const r={cycles:(n==null?void 0:n.cycles)??"ref",reused:(n==null?void 0:n.reused)??"inline",external:(n==null?void 0:n.external)??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=v=>{var E;const p=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const S=(E=r.external.registry.get(v[0]))==null?void 0:E.id,T=r.external.uri??(V=>V);if(S)return{ref:T(S)};const P=v[1].defId??v[1].schema.id??`schema${this.counter++}`;return v[1].defId=P,{defId:P,ref:`${T("__shared")}#/${p}/${P}`}}if(v[1]===o)return{ref:"#"};const g=`#/${p}/`,m=v[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:g+m}},a=v=>{if(v[1].schema.$ref)return;const p=v[1],{ref:b,defId:g}=s(v);p.def={...p.schema},g&&(p.defId=g);const m=p.schema;for(const E in m)delete m[E];m.$ref=b};if(r.cycles==="throw")for(const v of this.seen.entries()){const p=v[1];if(p.cycle)throw new Error(`Cycle detected: #/${(c=p.cycle)==null?void 0:c.join("/")}/<root>
33
33
 
34
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const v of this.seen.entries()){const p=v[1];if(t===v[0]){a(v);continue}if(r.external){const g=(w=r.external.registry.get(v[0]))==null?void 0:w.id;if(t!==v[0]&&g){a(v);continue}}if((_=this.metadataRegistry.get(v[0]))==null?void 0:_.id){a(v);continue}if(p.cycle){a(v);continue}if(p.count>1&&r.reused==="ref"){a(v);continue}}const i=(v,p)=>{const b=this.seen.get(v),g=b.def??b.schema,m={...g};if(b.ref===null)return;const E=b.ref;if(b.ref=null,E){i(E,p);const S=this.seen.get(E).schema;S.$ref&&p.target==="draft-7"?(g.allOf=g.allOf??[],g.allOf.push(S)):(Object.assign(g,S),Object.assign(g,m))}b.isParent||this.override({zodSchema:v,jsonSchema:g,path:b.path??[]})};for(const v of[...this.seen.entries()].reverse())i(v[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}`),(d=r.external)!=null&&d.uri){const v=(f=r.external.registry.get(t))==null?void 0:f.id;if(!v)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(v)}Object.assign(l,o.def);const u=((y=r.external)==null?void 0:y.defs)??{};for(const v of this.seen.entries()){const p=v[1];p.def&&p.defId&&(u[p.defId]=p.def)}r.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?l.$defs=u:l.definitions=u);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function fm(e,t){if(e instanceof Ii){const r=new Pi(t),o={};for(const i of e._idmap.entries()){const[l,u]=i;r.process(u)}const s={},a={registry:e,uri:t==null?void 0:t.uri,defs:o};for(const i of e._idmap.entries()){const[l,u]=i;s[l]=r.emit(u,{...t,external:a})}if(Object.keys(o).length>0){const i=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:o}}return{schemas:s}}const n=new Pi(t);return n.process(e),n.emit(e,t)}function Ae(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 Ae(o.element,n);case"object":{for(const s in o.shape)if(Ae(o.shape[s],n))return!0;return!1}case"union":{for(const s of o.options)if(Ae(s,n))return!0;return!1}case"intersection":return Ae(o.left,n)||Ae(o.right,n);case"tuple":{for(const s of o.items)if(Ae(s,n))return!0;return!!(o.rest&&Ae(o.rest,n))}case"record":return Ae(o.keyType,n)||Ae(o.valueType,n);case"map":return Ae(o.keyType,n)||Ae(o.valueType,n);case"set":return Ae(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ae(o.innerType,n);case"lazy":return Ae(o.getter(),n);case"default":return Ae(o.innerType,n);case"prefault":return Ae(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Ae(o.in,n)||Ae(o.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const mm=C("ZodISODateTime",(e,t)=>{zh.init(e,t),we.init(e,t)});function gm(e){return Bf(mm,e)}const ym=C("ZodISODate",(e,t)=>{jh.init(e,t),we.init(e,t)});function vm(e){return Vf(ym,e)}const _m=C("ZodISOTime",(e,t)=>{Dh.init(e,t),we.init(e,t)});function wm(e){return Ff(_m,e)}const bm=C("ZodISODuration",(e,t)=>{Zh.init(e,t),we.init(e,t)});function xm(e){return Hf(bm,e)}const Tr=C("ZodError",(e,t)=>{ri.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Np(e,n)},flatten:{value:n=>Op(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),km=Mp(Tr),Tm=Pp(Tr),Sm=si(Tr),$i=ai(Tr),ge=C("ZodType",(e,t)=>(he.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)=>Jt(e,n,r),e.brand=()=>e,e.register=(n,r)=>(n.add(e,r),e),e.parse=(n,r)=>km(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Sm(e,n,r),e.parseAsync=async(n,r)=>Tm(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>$i(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(vg(n,r)),e.superRefine=n=>e.check(_g(n)),e.overwrite=n=>e.check(Pn(n)),e.optional=()=>Ie(e),e.nullable=()=>Vi(e),e.nullish=()=>Ie(Vi(e)),e.nonoptional=n=>ug(e,n),e.array=()=>Z(e),e.or=n=>ee([e,n]),e.and=n=>Qm(e,n),e.transform=n=>Hi(e,rg(n)),e.default=n=>ag(e,n),e.prefault=n=>lg(e,n),e.catch=n=>dg(e,n),e.pipe=n=>Hi(e,n),e.readonly=()=>fg(e),e.describe=n=>{const r=e.clone();return Mn.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){var n;return(n=Mn.get(e))==null?void 0:n.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Mn.get(e);const r=e.clone();return Mn.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),zi=C("_ZodString",(e,t)=>{Io.init(e,t),ge.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(tm(...r)),e.includes=(...r)=>e.check(om(...r)),e.startsWith=(...r)=>e.check(sm(...r)),e.endsWith=(...r)=>e.check(am(...r)),e.min=(...r)=>e.check(kr(...r)),e.max=(...r)=>e.check(Ni(...r)),e.length=(...r)=>e.check(Mi(...r)),e.nonempty=(...r)=>e.check(kr(1,...r)),e.lowercase=r=>e.check(nm(r)),e.uppercase=r=>e.check(rm(r)),e.trim=()=>e.check(lm()),e.normalize=(...r)=>e.check(im(...r)),e.toLowerCase=()=>e.check(um()),e.toUpperCase=()=>e.check(cm())}),Im=C("ZodString",(e,t)=>{Io.init(e,t),zi.init(e,t),e.email=n=>e.check(kf(Cm,n)),e.url=n=>e.check(Ef(Em,n)),e.jwt=n=>e.check(qf(qm,n)),e.emoji=n=>e.check(Rf(Rm,n)),e.guid=n=>e.check(Ci(ji,n)),e.uuid=n=>e.check(Tf(Sr,n)),e.uuidv4=n=>e.check(Sf(Sr,n)),e.uuidv6=n=>e.check(If(Sr,n)),e.uuidv7=n=>e.check(Cf(Sr,n)),e.nanoid=n=>e.check(Af(Am,n)),e.guid=n=>e.check(Ci(ji,n)),e.cuid=n=>e.check(Of(Om,n)),e.cuid2=n=>e.check(Nf(Nm,n)),e.ulid=n=>e.check(Mf(Mm,n)),e.base64=n=>e.check(Ei(Di,n)),e.base64url=n=>e.check(Uf(Um,n)),e.xid=n=>e.check(Pf(Pm,n)),e.ksuid=n=>e.check($f($m,n)),e.ipv4=n=>e.check(zf(zm,n)),e.ipv6=n=>e.check(jf(jm,n)),e.cidrv4=n=>e.check(Df(Dm,n)),e.cidrv6=n=>e.check(Zf(Zm,n)),e.e164=n=>e.check(Lf(Lm,n)),e.datetime=n=>e.check(gm(n)),e.date=n=>e.check(vm(n)),e.time=n=>e.check(wm(n)),e.duration=n=>e.check(xm(n))});function h(e){return xf(Im,e)}const we=C("ZodStringFormat",(e,t)=>{ve.init(e,t),zi.init(e,t)}),Cm=C("ZodEmail",(e,t)=>{Ch.init(e,t),we.init(e,t)}),ji=C("ZodGUID",(e,t)=>{Sh.init(e,t),we.init(e,t)}),Sr=C("ZodUUID",(e,t)=>{Ih.init(e,t),we.init(e,t)}),Em=C("ZodURL",(e,t)=>{Eh.init(e,t),we.init(e,t)}),Rm=C("ZodEmoji",(e,t)=>{Rh.init(e,t),we.init(e,t)}),Am=C("ZodNanoID",(e,t)=>{Ah.init(e,t),we.init(e,t)}),Om=C("ZodCUID",(e,t)=>{Oh.init(e,t),we.init(e,t)}),Nm=C("ZodCUID2",(e,t)=>{Nh.init(e,t),we.init(e,t)}),Mm=C("ZodULID",(e,t)=>{Mh.init(e,t),we.init(e,t)}),Pm=C("ZodXID",(e,t)=>{Ph.init(e,t),we.init(e,t)}),$m=C("ZodKSUID",(e,t)=>{$h.init(e,t),we.init(e,t)}),zm=C("ZodIPv4",(e,t)=>{Uh.init(e,t),we.init(e,t)}),jm=C("ZodIPv6",(e,t)=>{Lh.init(e,t),we.init(e,t)}),Dm=C("ZodCIDRv4",(e,t)=>{qh.init(e,t),we.init(e,t)}),Zm=C("ZodCIDRv6",(e,t)=>{Bh.init(e,t),we.init(e,t)}),Di=C("ZodBase64",(e,t)=>{Vh.init(e,t),we.init(e,t)});function Zi(e){return Ei(Di,e)}const Um=C("ZodBase64URL",(e,t)=>{Hh.init(e,t),we.init(e,t)}),Lm=C("ZodE164",(e,t)=>{Jh.init(e,t),we.init(e,t)}),qm=C("ZodJWT",(e,t)=>{Wh.init(e,t),we.init(e,t)}),Ao=C("ZodNumber",(e,t)=>{mi.init(e,t),ge.init(e,t),e.gt=(r,o)=>e.check(Ai(r,o)),e.gte=(r,o)=>e.check(Ro(r,o)),e.min=(r,o)=>e.check(Ro(r,o)),e.lt=(r,o)=>e.check(Ri(r,o)),e.lte=(r,o)=>e.check(Eo(r,o)),e.max=(r,o)=>e.check(Eo(r,o)),e.int=r=>e.check(Ui(r)),e.safe=r=>e.check(Ui(r)),e.positive=r=>e.check(Ai(0,r)),e.nonnegative=r=>e.check(Ro(0,r)),e.negative=r=>e.check(Ri(0,r)),e.nonpositive=r=>e.check(Eo(0,r)),e.multipleOf=(r,o)=>e.check(Oi(r,o)),e.step=(r,o)=>e.check(Oi(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 R(e){return Jf(Ao,e)}const Bm=C("ZodNumberFormat",(e,t)=>{Kh.init(e,t),Ao.init(e,t)});function Ui(e){return Wf(Bm,e)}const Vm=C("ZodBoolean",(e,t)=>{Yh.init(e,t),ge.init(e,t)});function re(e){return Kf(Vm,e)}const Fm=C("ZodNull",(e,t)=>{Xh.init(e,t),ge.init(e,t)});function Hm(e){return Yf(Fm,e)}const Jm=C("ZodAny",(e,t)=>{Qh.init(e,t),ge.init(e,t)});function pt(){return Xf(Jm)}const Gm=C("ZodUnknown",(e,t)=>{ef.init(e,t),ge.init(e,t)});function Le(){return Qf(Gm)}const Wm=C("ZodNever",(e,t)=>{tf.init(e,t),ge.init(e,t)});function Li(e){return em(Wm,e)}const Km=C("ZodArray",(e,t)=>{nf.init(e,t),ge.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(kr(n,r)),e.nonempty=n=>e.check(kr(1,n)),e.max=(n,r)=>e.check(Ni(n,r)),e.length=(n,r)=>e.check(Mi(n,r)),e.unwrap=()=>e.element});function Z(e,t){return dm(Km,e,t)}const Oo=C("ZodObject",(e,t)=>{rf.init(e,t),ge.init(e,t),le(e,"shape",()=>t.shape),e.keyof=()=>qe(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Le()}),e.loose=()=>e.clone({...e._zod.def,catchall:Le()}),e.strict=()=>e.clone({...e._zod.def,catchall:Li()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>Cp(e,n),e.merge=n=>Ep(e,n),e.pick=n=>Sp(e,n),e.omit=n=>Ip(e,n),e.partial=(...n)=>Rp(Bi,e,n[0]),e.required=(...n)=>Ap(Fi,e,n[0])});function x(e,t){const n={type:"object",get shape(){return En(this,"shape",{...e}),this.shape},...U(t)};return new Oo(n)}function ye(e,t){return new Oo({type:"object",get shape(){return En(this,"shape",{...e}),this.shape},catchall:Li(),...U(t)})}function un(e,t){return new Oo({type:"object",get shape(){return En(this,"shape",{...e}),this.shape},catchall:Le(),...U(t)})}const qi=C("ZodUnion",(e,t)=>{_i.init(e,t),ge.init(e,t),e.options=t.options});function ee(e,t){return new qi({type:"union",options:e,...U(t)})}const Ym=C("ZodDiscriminatedUnion",(e,t)=>{qi.init(e,t),of.init(e,t)});function cn(e,t,n){return new Ym({type:"union",options:t,discriminator:e,...U(n)})}const Xm=C("ZodIntersection",(e,t)=>{sf.init(e,t),ge.init(e,t)});function Qm(e,t){return new Xm({type:"intersection",left:e,right:t})}const eg=C("ZodRecord",(e,t)=>{af.init(e,t),ge.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function We(e,t,n){return new eg({type:"record",keyType:e,valueType:t,...U(n)})}const No=C("ZodEnum",(e,t)=>{lf.init(e,t),ge.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 No({...t,checks:[],...U(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 No({...t,checks:[],...U(o),entries:s})}});function qe(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new No({type:"enum",entries:n,...U(t)})}const tg=C("ZodLiteral",(e,t)=>{uf.init(e,t),ge.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 A(e,t){return new tg({type:"literal",values:Array.isArray(e)?e:[e],...U(t)})}const ng=C("ZodTransform",(e,t)=>{cf.init(e,t),ge.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(Nn(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(Nn(a))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function rg(e){return new ng({type:"transform",transform:e})}const Bi=C("ZodOptional",(e,t)=>{df.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ie(e){return new Bi({type:"optional",innerType:e})}const og=C("ZodNullable",(e,t)=>{pf.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Vi(e){return new og({type:"nullable",innerType:e})}const sg=C("ZodDefault",(e,t)=>{hf.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ag(e,t){return new sg({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const ig=C("ZodPrefault",(e,t)=>{ff.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function lg(e,t){return new ig({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Fi=C("ZodNonOptional",(e,t)=>{mf.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ug(e,t){return new Fi({type:"nonoptional",innerType:e,...U(t)})}const cg=C("ZodCatch",(e,t)=>{gf.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function dg(e,t){return new cg({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const pg=C("ZodPipe",(e,t)=>{yf.init(e,t),ge.init(e,t),e.in=t.in,e.out=t.out});function Hi(e,t){return new pg({type:"pipe",in:e,out:t})}const hg=C("ZodReadonly",(e,t)=>{vf.init(e,t),ge.init(e,t)});function fg(e){return new hg({type:"readonly",innerType:e})}const mg=C("ZodLazy",(e,t)=>{_f.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Ji(e){return new mg({type:"lazy",getter:e})}const Mo=C("ZodCustom",(e,t)=>{wf.init(e,t),ge.init(e,t)});function gg(e){const t=new Ge({check:"custom"});return t._zod.check=e,t}function yg(e,t){return pm(Mo,e??(()=>!0),t)}function vg(e,t={}){return hm(Mo,e,t)}function _g(e){const t=gg(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Nn(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(Nn(o))}},e(n.value,n)));return t}function Ir(e,t={error:`Input not instance of ${e.name}`}){const n=new Mo({type:"custom",check:"custom",fn:r=>r instanceof e,abort:!0,...U(t)});return n._zod.bag.Class=e,n}function wg(e){return Gf(Ao,e)}const bg=Symbol("Let zodToJsonSchema decide on which parser to use"),Gi={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},xg=e=>typeof e=="string"?{...Gi,name:e}:{...Gi,...e},kg=e=>{const t=xg(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},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}]))}};function Wi(e,t,n,r){r!=null&&r.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function ue(e,t,n,r,o){e[t]=n,Wi(e,t,r,o)}const Ki=(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("/")};var te;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}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(i=>typeof o[o[i]]!="number"),a={};for(const i of s)a[i]=o[i];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)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(te||(te={}));var Yi;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Yi||(Yi={}));const j=te.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Zt=e=>{switch(typeof e){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(e)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":return Array.isArray(e)?j.array:e===null?j.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?j.promise:typeof Map<"u"&&e instanceof Map?j.map:typeof Set<"u"&&e instanceof Set?j.set:typeof Date<"u"&&e instanceof Date?j.date:j.object;default:return j.unknown}},N=te.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"]);class At 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=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 i=r,l=0;for(;l<a.path.length;){const u=a.path[l];l===a.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(n(a))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return o(this),r}static assert(t){if(!(t instanceof At))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,te.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()}}At.create=e=>new At(e);const Po=(e,t)=>{let n;switch(e.code){case N.invalid_type:e.received===j.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,te.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${te.joinValues(e.keys,", ")}`;break;case N.invalid_union:n="Invalid input";break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${te.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${te.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}"`:te.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,te.assertNever(e)}return{message:n}};let Tg=Po;function Sg(){return Tg}const Ig=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 i="";const l=r.filter(u=>!!u).slice().reverse();for(const u of l)i=u(a,{data:t,defaultError:i}).message;return{...o,path:s,message:i}};function z(e,t){const n=Sg(),r=Ig({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Po?void 0:Po].filter(o=>!!o)});e.common.issues.push(r)}class Be{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 W;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 Be.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 W;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}}}const W=Object.freeze({status:"aborted"}),$n=e=>({status:"dirty",value:e}),it=e=>({status:"valid",value:e}),Xi=e=>e.status==="aborted",Qi=e=>e.status==="dirty",dn=e=>e.status==="valid",Cr=e=>typeof Promise<"u"&&e instanceof Promise;var q;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(q||(q={}));class vt{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}}const el=(e,t)=>{if(dn(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 At(e.common.issues);return this._error=n,this._error}}};function Y(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:(a,i)=>{const{message:l}=e;return a.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??r??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:l??n??i.defaultError}},description:o}}class X{get description(){return this._def.description}_getType(t){return Zt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Zt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Be,ctx:{common:t.parent.common,data:t.data,parsedType:Zt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Cr(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==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Zt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return el(r,o)}"~validate"(t){var r,o;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Zt(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:n});return dn(s)?{value:s.value}:{issues:n.common.issues}}catch(s){(o=(r=s==null?void 0:s.message)==null?void 0:r.toLowerCase())!=null&&o.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(s=>dn(s)?{value:s.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==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Zt(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Cr(o)?o:Promise.resolve(o));return el(r,s)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{const a=t(o),i=()=>s.addIssue({code:N.custom,...r(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(i(),!1)):a?!0:(i(),!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:n=>this["~validate"](n)}}optional(){return Mt.create(this,this._def)}nullable(){return Xt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return _t.create(this)}promise(){return Mr.create(this,this._def)}or(t){return Rr.create([this,t],this._def)}and(t){return Ar.create(this,t,this._def)}transform(t){return new Yt({...Y(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Pr({...Y(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new ll({typeName:M.ZodBranded,type:this,...Y(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new $r({...Y(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 Fo.create(this,t)}readonly(){return zr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Cg=/^c[^\s-]{8,}$/i,Eg=/^[0-9a-z]+$/,Rg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ag=/^[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,Og=/^[a-z0-9_-]{21}$/i,Ng=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Mg=/^[-+]?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)?)??$/,Pg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,$g="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let $o;const zg=/^(?:(?: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])$/,jg=/^(?:(?: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])$/,Dg=/^(([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]))$/,Zg=/^(([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])$/,Ug=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Lg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,tl="((\\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])))",qg=new RegExp(`^${tl}$`);function nl(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}`}function Bg(e){return new RegExp(`^${nl(e)}$`)}function Vg(e){let t=`${tl}T${nl(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}$`)}function Fg(e,t){return!!((t==="v4"||!t)&&zg.test(e)||(t==="v6"||!t)&&Dg.test(e))}function Hg(e,t){if(!Ng.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==null?void 0:o.typ)!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Jg(e,t){return!!((t==="v4"||!t)&&jg.test(e)||(t==="v6"||!t)&&Zg.test(e))}class Ot extends X{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==j.string){const s=this._getOrReturnCtx(t);return z(s,{code:N.invalid_type,expected:j.string,received:s.parsedType}),W}const r=new Be;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,i=t.data.length<s.value;(a||i)&&(o=this._getOrReturnCtx(t,o),a?z(o,{code:N.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&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")Pg.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")$o||($o=new RegExp($g,"u")),$o.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")Ag.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")Og.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")Cg.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")Eg.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")Rg.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"?Vg(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"?qg.test(t.data)||(o=this._getOrReturnCtx(t,o),z(o,{code:N.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?Bg(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"?Mg.test(t.data)||(o=this._getOrReturnCtx(t,o),z(o,{validation:"duration",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?Fg(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"?Hg(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"?Jg(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"?Ug.test(t.data)||(o=this._getOrReturnCtx(t,o),z(o,{validation:"base64",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?Lg.test(t.data)||(o=this._getOrReturnCtx(t,o),z(o,{validation:"base64url",code:N.invalid_string,message:s.message}),r.dirty()):te.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,...q.errToObj(r)})}_addCheck(t){return new Ot({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...q.errToObj(t)})}url(t){return this._addCheck({kind:"url",...q.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...q.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...q.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...q.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...q.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...q.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...q.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...q.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...q.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...q.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...q.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...q.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==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(t==null?void 0:t.offset)??!1,local:(t==null?void 0:t.local)??!1,...q.errToObj(t==null?void 0: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==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...q.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...q.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...q.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...q.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...q.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...q.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...q.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...q.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...q.errToObj(n)})}nonempty(t){return this.min(1,q.errToObj(t))}trim(){return new Ot({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ot({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ot({...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}}Ot.create=e=>new Ot({checks:[],typeName:M.ZodString,coerce:(e==null?void 0:e.coerce)??!1,...Y(e)});function Gg(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}class pn extends X{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)!==j.number){const s=this._getOrReturnCtx(t);return z(s,{code:N.invalid_type,expected:j.number,received:s.parsedType}),W}let r;const o=new Be;for(const s of this._def.checks)s.kind==="int"?te.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"?Gg(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()):te.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,q.toString(n))}gt(t,n){return this.setLimit("min",t,!1,q.toString(n))}lte(t,n){return this.setLimit("max",t,!0,q.toString(n))}lt(t,n){return this.setLimit("max",t,!1,q.toString(n))}setLimit(t,n,r,o){return new pn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:q.toString(o)}]})}_addCheck(t){return new pn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:q.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:q.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:q.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.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"&&te.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)}}pn.create=e=>new pn({checks:[],typeName:M.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Y(e)});class zn extends X{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)!==j.bigint)return this._getInvalidInput(t);let r;const o=new Be;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()):te.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return z(n,{code:N.invalid_type,expected:j.bigint,received:n.parsedType}),W}gte(t,n){return this.setLimit("min",t,!0,q.toString(n))}gt(t,n){return this.setLimit("min",t,!1,q.toString(n))}lte(t,n){return this.setLimit("max",t,!0,q.toString(n))}lt(t,n){return this.setLimit("max",t,!1,q.toString(n))}setLimit(t,n,r,o){return new zn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:q.toString(o)}]})}_addCheck(t){return new zn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:q.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}}zn.create=e=>new zn({checks:[],typeName:M.ZodBigInt,coerce:(e==null?void 0:e.coerce)??!1,...Y(e)});class zo extends X{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==j.boolean){const r=this._getOrReturnCtx(t);return z(r,{code:N.invalid_type,expected:j.boolean,received:r.parsedType}),W}return it(t.data)}}zo.create=e=>new zo({typeName:M.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Y(e)});class Er extends X{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==j.date){const s=this._getOrReturnCtx(t);return z(s,{code:N.invalid_type,expected:j.date,received:s.parsedType}),W}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return z(s,{code:N.invalid_date}),W}const r=new Be;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()):te.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Er({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:q.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:q.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}}Er.create=e=>new Er({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:M.ZodDate,...Y(e)});class rl extends X{_parse(t){if(this._getType(t)!==j.symbol){const r=this._getOrReturnCtx(t);return z(r,{code:N.invalid_type,expected:j.symbol,received:r.parsedType}),W}return it(t.data)}}rl.create=e=>new rl({typeName:M.ZodSymbol,...Y(e)});class jo extends X{_parse(t){if(this._getType(t)!==j.undefined){const r=this._getOrReturnCtx(t);return z(r,{code:N.invalid_type,expected:j.undefined,received:r.parsedType}),W}return it(t.data)}}jo.create=e=>new jo({typeName:M.ZodUndefined,...Y(e)});class Do extends X{_parse(t){if(this._getType(t)!==j.null){const r=this._getOrReturnCtx(t);return z(r,{code:N.invalid_type,expected:j.null,received:r.parsedType}),W}return it(t.data)}}Do.create=e=>new Do({typeName:M.ZodNull,...Y(e)});class Zo extends X{constructor(){super(...arguments),this._any=!0}_parse(t){return it(t.data)}}Zo.create=e=>new Zo({typeName:M.ZodAny,...Y(e)});class Uo extends X{constructor(){super(...arguments),this._unknown=!0}_parse(t){return it(t.data)}}Uo.create=e=>new Uo({typeName:M.ZodUnknown,...Y(e)});class Ut extends X{_parse(t){const n=this._getOrReturnCtx(t);return z(n,{code:N.invalid_type,expected:j.never,received:n.parsedType}),W}}Ut.create=e=>new Ut({typeName:M.ZodNever,...Y(e)});class ol extends X{_parse(t){if(this._getType(t)!==j.undefined){const r=this._getOrReturnCtx(t);return z(r,{code:N.invalid_type,expected:j.void,received:r.parsedType}),W}return it(t.data)}}ol.create=e=>new ol({typeName:M.ZodVoid,...Y(e)});class _t extends X{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==j.array)return z(n,{code:N.invalid_type,expected:j.array,received:n.parsedType}),W;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,i=n.data.length<o.exactLength.value;(a||i)&&(z(n,{code:a?N.too_big:N.too_small,minimum:i?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,i)=>o.type._parseAsync(new vt(n,a,n.path,i)))).then(a=>Be.mergeArray(r,a));const s=[...n.data].map((a,i)=>o.type._parseSync(new vt(n,a,n.path,i)));return Be.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new _t({...this._def,minLength:{value:t,message:q.toString(n)}})}max(t,n){return new _t({...this._def,maxLength:{value:t,message:q.toString(n)}})}length(t,n){return new _t({...this._def,exactLength:{value:t,message:q.toString(n)}})}nonempty(t){return this.min(1,t)}}_t.create=(e,t)=>new _t({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...Y(t)});function hn(e){if(e instanceof Ce){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Mt.create(hn(r))}return new Ce({...e._def,shape:()=>t})}else return e instanceof _t?new _t({...e._def,type:hn(e.element)}):e instanceof Mt?Mt.create(hn(e.unwrap())):e instanceof Xt?Xt.create(hn(e.unwrap())):e instanceof Wt?Wt.create(e.items.map(t=>hn(t))):e}class Ce extends X{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=te.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==j.object){const u=this._getOrReturnCtx(t);return z(u,{code:N.invalid_type,expected:j.object,received:u.parsedType}),W}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Ut&&this._def.unknownKeys==="strip"))for(const u in o.data)a.includes(u)||i.push(u);const l=[];for(const u of a){const c=s[u],w=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new vt(o,w,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Ut){const u=this._def.unknownKeys;if(u==="passthrough")for(const c of i)l.push({key:{status:"valid",value:c},value:{status:"valid",value:o.data[c]}});else if(u==="strict")i.length>0&&(z(o,{code:N.unrecognized_keys,keys:i}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const c of i){const w=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new vt(o,w,o.path,c)),alwaysSet:c in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const u=[];for(const c of l){const w=await c.key,_=await c.value;u.push({key:w,value:_,alwaysSet:c.alwaysSet})}return u}).then(u=>Be.mergeObjectSync(r,u)):Be.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return q.errToObj,new Ce({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,a;const o=((a=(s=this._def).errorMap)==null?void 0:a.call(s,n,r).message)??r.defaultError;return n.code==="unrecognized_keys"?{message:q.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new Ce({...this._def,unknownKeys:"strip"})}passthrough(){return new Ce({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ce({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ce({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:M.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Ce({...this._def,catchall:t})}pick(t){const n={};for(const r of te.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new Ce({...this._def,shape:()=>n})}omit(t){const n={};for(const r of te.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new Ce({...this._def,shape:()=>n})}deepPartial(){return hn(this)}partial(t){const n={};for(const r of te.objectKeys(this.shape)){const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new Ce({...this._def,shape:()=>n})}required(t){const n={};for(const r of te.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Mt;)s=s._def.innerType;n[r]=s}return new Ce({...this._def,shape:()=>n})}keyof(){return al(te.objectKeys(this.shape))}}Ce.create=(e,t)=>new Ce({shape:()=>e,unknownKeys:"strip",catchall:Ut.create(),typeName:M.ZodObject,...Y(t)}),Ce.strictCreate=(e,t)=>new Ce({shape:()=>e,unknownKeys:"strict",catchall:Ut.create(),typeName:M.ZodObject,...Y(t)}),Ce.lazycreate=(e,t)=>new Ce({shape:e,unknownKeys:"strip",catchall:Ut.create(),typeName:M.ZodObject,...Y(t)});class Rr extends X{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(const i of s)if(i.result.status==="valid")return i.result;for(const i of s)if(i.result.status==="dirty")return n.common.issues.push(...i.ctx.common.issues),i.result;const a=s.map(i=>new At(i.ctx.common.issues));return z(n,{code:N.invalid_union,unionErrors:a}),W}if(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 u={...n,common:{...n.common,issues:[]},parent:null},c=l._parseSync({data:n.data,path:n.path,parent:u});if(c.status==="valid")return c;c.status==="dirty"&&!s&&(s={result:c,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const i=a.map(l=>new At(l));return z(n,{code:N.invalid_union,unionErrors:i}),W}}get options(){return this._def.options}}Rr.create=(e,t)=>new Rr({options:e,typeName:M.ZodUnion,...Y(t)});const Nt=e=>e instanceof Bo?Nt(e.schema):e instanceof Yt?Nt(e.innerType()):e instanceof Nr?[e.value]:e instanceof Kt?e.options:e instanceof Vo?te.objectValues(e.enum):e instanceof Pr?Nt(e._def.innerType):e instanceof jo?[void 0]:e instanceof Do?[null]:e instanceof Mt?[void 0,...Nt(e.unwrap())]:e instanceof Xt?[null,...Nt(e.unwrap())]:e instanceof ll||e instanceof zr?Nt(e.unwrap()):e instanceof $r?Nt(e._def.innerType):[];class Lo extends X{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==j.object)return z(n,{code:N.invalid_type,expected:j.object,received:n.parsedType}),W;const r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(z(n,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),W)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const s of n){const a=Nt(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const i of a){if(o.has(i))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(i)}`);o.set(i,s)}}return new Lo({typeName:M.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Y(r)})}}function qo(e,t){const n=Zt(e),r=Zt(t);if(e===t)return{valid:!0,data:e};if(n===j.object&&r===j.object){const o=te.objectKeys(t),s=te.objectKeys(e).filter(i=>o.indexOf(i)!==-1),a={...e,...t};for(const i of s){const l=qo(e[i],t[i]);if(!l.valid)return{valid:!1};a[i]=l.data}return{valid:!0,data:a}}else if(n===j.array&&r===j.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],i=t[s],l=qo(a,i);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===j.date&&r===j.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Ar extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=(s,a)=>{if(Xi(s)||Xi(a))return W;const i=qo(s.value,a.value);return i.valid?((Qi(s)||Qi(a))&&n.dirty(),{status:n.value,value:i.data}):(z(r,{code:N.invalid_intersection_types}),W)};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}))}}Ar.create=(e,t,n)=>new Ar({left:e,right:t,typeName:M.ZodIntersection,...Y(n)});class Wt extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==j.array)return z(r,{code:N.invalid_type,expected:j.array,received:r.parsedType}),W;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"}),W;!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,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new vt(r,a,r.path,i)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>Be.mergeArray(n,a)):Be.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new Wt({...this._def,rest:t})}}Wt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Wt({items:e,typeName:M.ZodTuple,rest:null,...Y(t)})};class Or extends X{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!==j.object)return z(r,{code:N.invalid_type,expected:j.object,received:r.parsedType}),W;const o=[],s=this._def.keyType,a=this._def.valueType;for(const i in r.data)o.push({key:s._parse(new vt(r,i,r.path,i)),value:a._parse(new vt(r,r.data[i],r.path,i)),alwaysSet:i in r.data});return r.common.async?Be.mergeObjectAsync(n,o):Be.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof X?new Or({keyType:t,valueType:n,typeName:M.ZodRecord,...Y(r)}):new Or({keyType:Ot.create(),valueType:t,typeName:M.ZodRecord,...Y(n)})}}class sl extends X{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!==j.map)return z(r,{code:N.invalid_type,expected:j.map,received:r.parsedType}),W;const o=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([i,l],u)=>({key:o._parse(new vt(r,i,r.path,[u,"key"])),value:s._parse(new vt(r,l,r.path,[u,"value"]))}));if(r.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of a){const u=await l.key,c=await l.value;if(u.status==="aborted"||c.status==="aborted")return W;(u.status==="dirty"||c.status==="dirty")&&n.dirty(),i.set(u.value,c.value)}return{status:n.value,value:i}})}else{const i=new Map;for(const l of a){const u=l.key,c=l.value;if(u.status==="aborted"||c.status==="aborted")return W;(u.status==="dirty"||c.status==="dirty")&&n.dirty(),i.set(u.value,c.value)}return{status:n.value,value:i}}}}sl.create=(e,t,n)=>new sl({valueType:t,keyType:e,typeName:M.ZodMap,...Y(n)});class jn extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==j.set)return z(r,{code:N.invalid_type,expected:j.set,received:r.parsedType}),W;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 u=new Set;for(const c of l){if(c.status==="aborted")return W;c.status==="dirty"&&n.dirty(),u.add(c.value)}return{status:n.value,value:u}}const i=[...r.data.values()].map((l,u)=>s._parse(new vt(r,l,r.path,u)));return r.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(t,n){return new jn({...this._def,minSize:{value:t,message:q.toString(n)}})}max(t,n){return new jn({...this._def,maxSize:{value:t,message:q.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}jn.create=(e,t)=>new jn({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...Y(t)});class Bo extends X{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})}}Bo.create=(e,t)=>new Bo({getter:e,typeName:M.ZodLazy,...Y(t)});class Nr extends X{_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}),W}return{status:"valid",value:t.data}}get value(){return this._def.value}}Nr.create=(e,t)=>new Nr({value:e,typeName:M.ZodLiteral,...Y(t)});function al(e,t){return new Kt({values:e,typeName:M.ZodEnum,...Y(t)})}class Kt extends X{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return z(n,{expected:te.joinValues(r),received:n.parsedType,code:N.invalid_type}),W}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}),W}return it(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 Kt.create(t,{...this._def,...n})}exclude(t,n=this._def){return Kt.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}Kt.create=al;class Vo extends X{_parse(t){const n=te.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==j.string&&r.parsedType!==j.number){const o=te.objectValues(n);return z(r,{expected:te.joinValues(o),received:r.parsedType,code:N.invalid_type}),W}if(this._cache||(this._cache=new Set(te.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=te.objectValues(n);return z(r,{received:r.data,code:N.invalid_enum_value,options:o}),W}return it(t.data)}get enum(){return this._def.values}}Vo.create=(e,t)=>new Vo({values:e,typeName:M.ZodNativeEnum,...Y(t)});class Mr extends X{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==j.promise&&n.common.async===!1)return z(n,{code:N.invalid_type,expected:j.promise,received:n.parsedType}),W;const r=n.parsedType===j.promise?n.data:Promise.resolve(n.data);return it(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Mr.create=(e,t)=>new Mr({type:e,typeName:M.ZodPromise,...Y(t)});class Yt extends X{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:a=>{z(r,a),a.fatal?n.abort():n.dirty()},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 i=>{if(n.value==="aborted")return W;const l=await this._def.schema._parseAsync({data:i,path:r.path,parent:r});return l.status==="aborted"?W:l.status==="dirty"||n.value==="dirty"?$n(l.value):l});{if(n.value==="aborted")return W;const i=this._def.schema._parseSync({data:a,path:r.path,parent:r});return i.status==="aborted"?W:i.status==="dirty"||n.value==="dirty"?$n(i.value):i}}if(o.type==="refinement"){const a=i=>{const l=o.refinement(i,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 i};if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?W:(i.status==="dirty"&&n.dirty(),a(i.value),{status:n.value,value:i.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>i.status==="aborted"?W:(i.status==="dirty"&&n.dirty(),a(i.value).then(()=>({status:n.value,value:i.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(!dn(a))return W;const i=o.transform(a.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:i}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>dn(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:n.value,value:i})):W);te.assertNever(o)}}Yt.create=(e,t,n)=>new Yt({schema:e,typeName:M.ZodEffects,effect:t,...Y(n)}),Yt.createWithPreprocess=(e,t,n)=>new Yt({schema:t,effect:{type:"preprocess",transform:e},typeName:M.ZodEffects,...Y(n)});class Mt extends X{_parse(t){return this._getType(t)===j.undefined?it(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Mt.create=(e,t)=>new Mt({innerType:e,typeName:M.ZodOptional,...Y(t)});class Xt extends X{_parse(t){return this._getType(t)===j.null?it(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Xt.create=(e,t)=>new Xt({innerType:e,typeName:M.ZodNullable,...Y(t)});class Pr extends X{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===j.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Pr.create=(e,t)=>new Pr({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Y(t)});class $r extends X{_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 Cr(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new At(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new At(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}$r.create=(e,t)=>new $r({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Y(t)});class il extends X{_parse(t){if(this._getType(t)!==j.nan){const r=this._getOrReturnCtx(t);return z(r,{code:N.invalid_type,expected:j.nan,received:r.parsedType}),W}return{status:"valid",value:t.data}}}il.create=e=>new il({typeName:M.ZodNaN,...Y(e)});class ll extends X{_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}}class Fo extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?W:s.status==="dirty"?(n.dirty(),$n(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?W: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 Fo({in:t,out:n,typeName:M.ZodPipeline})}}class zr extends X{_parse(t){const n=this._def.innerType._parse(t),r=o=>(dn(o)&&(o.value=Object.freeze(o.value)),o);return Cr(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}zr.create=(e,t)=>new zr({innerType:e,typeName:M.ZodReadonly,...Y(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 k=Ot.create,Pe=pn.create,Oe=zo.create,Wg=Zo.create,Dn=Uo.create;Ut.create;const L=_t.create,$=Ce.create,Ve=Rr.create,Kg=Lo.create;Ar.create,Wt.create;const Zn=Or.create,K=Nr.create,Pt=Kt.create;Mr.create;const O=Mt.create;Xt.create;function Ke(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Ki(t,e.currentPath):t.join("/")}}function Yg(e,t){var r,o,s;const n={type:"array"};return(r=e.type)!=null&&r._def&&((s=(o=e.type)==null?void 0:o._def)==null?void 0:s.typeName)!==M.ZodAny&&(n.items=ae(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&ue(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&ue(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(ue(n,"minItems",e.exactLength.value,e.exactLength.message,t),ue(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}function Xg(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":t.target==="jsonSchema7"?r.inclusive?ue(n,"minimum",r.value,r.message,t):ue(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),ue(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?ue(n,"maximum",r.value,r.message,t):ue(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),ue(n,"maximum",r.value,r.message,t));break;case"multipleOf":ue(n,"multipleOf",r.value,r.message,t);break}return n}function Qg(){return{type:"boolean"}}function ul(e,t){return ae(e.type._def,t)}const ey=(e,t)=>ae(e.innerType._def,t);function cl(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>cl(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 ty(e,t)}}const ty=(e,t)=>{const n={type:"integer",format:"unix-time"};if(t.target==="openApi3")return n;for(const r of e.checks)switch(r.kind){case"min":ue(n,"minimum",r.value,r.message,t);break;case"max":ue(n,"maximum",r.value,r.message,t);break}return n};function ny(e,t){return{...ae(e.innerType._def,t),default:e.defaultValue()}}function ry(e,t){return t.effectStrategy==="input"?ae(e.schema._def,t):Ke(t)}function oy(e){return{type:"string",enum:Array.from(e.values)}}const sy=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function ay(e,t){const n=[ae(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ae(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s);let r=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const o=[];return n.forEach(s=>{if(sy(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:i,...l}=s;a=l}else r=void 0;o.push(a)}}),o.length?{allOf:o,...r}:void 0}function iy(e,t){const n=typeof e.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[e.value]}:{type:n==="bigint"?"integer":n,const:e.value}}let Ho;const ht={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:()=>(Ho===void 0&&(Ho=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ho),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 dl(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":ue(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":ue(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":ft(n,"email",r.message,t);break;case"format:idn-email":ft(n,"idn-email",r.message,t);break;case"pattern:zod":Fe(n,ht.email,r.message,t);break}break;case"url":ft(n,"uri",r.message,t);break;case"uuid":ft(n,"uuid",r.message,t);break;case"regex":Fe(n,r.regex,r.message,t);break;case"cuid":Fe(n,ht.cuid,r.message,t);break;case"cuid2":Fe(n,ht.cuid2,r.message,t);break;case"startsWith":Fe(n,RegExp(`^${Jo(r.value,t)}`),r.message,t);break;case"endsWith":Fe(n,RegExp(`${Jo(r.value,t)}$`),r.message,t);break;case"datetime":ft(n,"date-time",r.message,t);break;case"date":ft(n,"date",r.message,t);break;case"time":ft(n,"time",r.message,t);break;case"duration":ft(n,"duration",r.message,t);break;case"length":ue(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t),ue(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":{Fe(n,RegExp(Jo(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&ft(n,"ipv4",r.message,t),r.version!=="v4"&&ft(n,"ipv6",r.message,t);break}case"base64url":Fe(n,ht.base64url,r.message,t);break;case"jwt":Fe(n,ht.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&Fe(n,ht.ipv4Cidr,r.message,t),r.version!=="v4"&&Fe(n,ht.ipv6Cidr,r.message,t);break}case"emoji":Fe(n,ht.emoji(),r.message,t);break;case"ulid":{Fe(n,ht.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{ft(n,"binary",r.message,t);break}case"contentEncoding:base64":{ue(n,"contentEncoding","base64",r.message,t);break}case"pattern:zod":{Fe(n,ht.base64,r.message,t);break}}break}case"nanoid":Fe(n,ht.nanoid,r.message,t)}return n}function Jo(e,t){return t.patternStrategy==="escape"?uy(e):e}const ly=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function uy(e){let t="";for(let n=0;n<e.length;n++)ly.has(e[n])||(t+="\\"),t+=e[n];return t}function ft(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,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):ue(e,"format",t,n,r)}function Fe(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,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:pl(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ue(e,"pattern",pl(t,r),n,r)}function pl(e,t){var l;if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},r=n.i?e.source.toLowerCase():e.source;let o="",s=!1,a=!1,i=!1;for(let u=0;u<r.length;u++){if(s){o+=r[u],s=!1;continue}if(n.i){if(a){if(r[u].match(/[a-z]/)){i?(o+=r[u],o+=`${r[u-2]}-${r[u]}`.toUpperCase(),i=!1):r[u+1]==="-"&&((l=r[u+2])!=null&&l.match(/[a-z]/))?(o+=r[u],i=!0):o+=`${r[u]}${r[u].toUpperCase()}`;continue}}else if(r[u].match(/[a-z]/)){o+=`[${r[u]}${r[u].toUpperCase()}]`;continue}}if(n.m){if(r[u]==="^"){o+=`(^|(?<=[\r
34
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const v of this.seen.entries()){const p=v[1];if(t===v[0]){a(v);continue}if(r.external){const g=(w=r.external.registry.get(v[0]))==null?void 0:w.id;if(t!==v[0]&&g){a(v);continue}}if((_=this.metadataRegistry.get(v[0]))==null?void 0:_.id){a(v);continue}if(p.cycle){a(v);continue}if(p.count>1&&r.reused==="ref"){a(v);continue}}const i=(v,p)=>{const b=this.seen.get(v),g=b.def??b.schema,m={...g};if(b.ref===null)return;const E=b.ref;if(b.ref=null,E){i(E,p);const S=this.seen.get(E).schema;S.$ref&&p.target==="draft-7"?(g.allOf=g.allOf??[],g.allOf.push(S)):(Object.assign(g,S),Object.assign(g,m))}b.isParent||this.override({zodSchema:v,jsonSchema:g,path:b.path??[]})};for(const v of[...this.seen.entries()].reverse())i(v[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}`),(d=r.external)!=null&&d.uri){const v=(f=r.external.registry.get(t))==null?void 0:f.id;if(!v)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(v)}Object.assign(l,o.def);const u=((y=r.external)==null?void 0:y.defs)??{};for(const v of this.seen.entries()){const p=v[1];p.def&&p.defId&&(u[p.defId]=p.def)}r.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?l.$defs=u:l.definitions=u);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function hm(e,t){if(e instanceof Ii){const r=new Pi(t),o={};for(const i of e._idmap.entries()){const[l,u]=i;r.process(u)}const s={},a={registry:e,uri:t==null?void 0:t.uri,defs:o};for(const i of e._idmap.entries()){const[l,u]=i;s[l]=r.emit(u,{...t,external:a})}if(Object.keys(o).length>0){const i=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:o}}return{schemas:s}}const n=new Pi(t);return n.process(e),n.emit(e,t)}function Ae(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 Ae(o.element,n);case"object":{for(const s in o.shape)if(Ae(o.shape[s],n))return!0;return!1}case"union":{for(const s of o.options)if(Ae(s,n))return!0;return!1}case"intersection":return Ae(o.left,n)||Ae(o.right,n);case"tuple":{for(const s of o.items)if(Ae(s,n))return!0;return!!(o.rest&&Ae(o.rest,n))}case"record":return Ae(o.keyType,n)||Ae(o.valueType,n);case"map":return Ae(o.keyType,n)||Ae(o.valueType,n);case"set":return Ae(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ae(o.innerType,n);case"lazy":return Ae(o.getter(),n);case"default":return Ae(o.innerType,n);case"prefault":return Ae(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Ae(o.in,n)||Ae(o.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const fm=C("ZodISODateTime",(e,t)=>{$h.init(e,t),we.init(e,t)});function mm(e){return qf(fm,e)}const gm=C("ZodISODate",(e,t)=>{zh.init(e,t),we.init(e,t)});function ym(e){return Bf(gm,e)}const vm=C("ZodISOTime",(e,t)=>{jh.init(e,t),we.init(e,t)});function _m(e){return Vf(vm,e)}const wm=C("ZodISODuration",(e,t)=>{Dh.init(e,t),we.init(e,t)});function bm(e){return Ff(wm,e)}const Tr=C("ZodError",(e,t)=>{ri.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Op(e,n)},flatten:{value:n=>Ap(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),xm=Np(Tr),km=Mp(Tr),Tm=si(Tr),$i=ai(Tr),ge=C("ZodType",(e,t)=>(he.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)=>Jt(e,n,r),e.brand=()=>e,e.register=(n,r)=>(n.add(e,r),e),e.parse=(n,r)=>xm(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Tm(e,n,r),e.parseAsync=async(n,r)=>km(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>$i(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(yg(n,r)),e.superRefine=n=>e.check(vg(n)),e.overwrite=n=>e.check(Pn(n)),e.optional=()=>Ie(e),e.nullable=()=>Vi(e),e.nullish=()=>Ie(Vi(e)),e.nonoptional=n=>lg(e,n),e.array=()=>Z(e),e.or=n=>ee([e,n]),e.and=n=>Xm(e,n),e.transform=n=>Hi(e,ng(n)),e.default=n=>sg(e,n),e.prefault=n=>ig(e,n),e.catch=n=>cg(e,n),e.pipe=n=>Hi(e,n),e.readonly=()=>hg(e),e.describe=n=>{const r=e.clone();return Mn.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){var n;return(n=Mn.get(e))==null?void 0:n.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Mn.get(e);const r=e.clone();return Mn.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),zi=C("_ZodString",(e,t)=>{Io.init(e,t),ge.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(em(...r)),e.includes=(...r)=>e.check(rm(...r)),e.startsWith=(...r)=>e.check(om(...r)),e.endsWith=(...r)=>e.check(sm(...r)),e.min=(...r)=>e.check(kr(...r)),e.max=(...r)=>e.check(Ni(...r)),e.length=(...r)=>e.check(Mi(...r)),e.nonempty=(...r)=>e.check(kr(1,...r)),e.lowercase=r=>e.check(tm(r)),e.uppercase=r=>e.check(nm(r)),e.trim=()=>e.check(im()),e.normalize=(...r)=>e.check(am(...r)),e.toLowerCase=()=>e.check(lm()),e.toUpperCase=()=>e.check(um())}),Sm=C("ZodString",(e,t)=>{Io.init(e,t),zi.init(e,t),e.email=n=>e.check(xf(Im,n)),e.url=n=>e.check(Cf(Cm,n)),e.jwt=n=>e.check(Lf(Lm,n)),e.emoji=n=>e.check(Ef(Em,n)),e.guid=n=>e.check(Ci(ji,n)),e.uuid=n=>e.check(kf(Sr,n)),e.uuidv4=n=>e.check(Tf(Sr,n)),e.uuidv6=n=>e.check(Sf(Sr,n)),e.uuidv7=n=>e.check(If(Sr,n)),e.nanoid=n=>e.check(Rf(Rm,n)),e.guid=n=>e.check(Ci(ji,n)),e.cuid=n=>e.check(Af(Am,n)),e.cuid2=n=>e.check(Of(Om,n)),e.ulid=n=>e.check(Nf(Nm,n)),e.base64=n=>e.check(Ei(Di,n)),e.base64url=n=>e.check(Zf(Zm,n)),e.xid=n=>e.check(Mf(Mm,n)),e.ksuid=n=>e.check(Pf(Pm,n)),e.ipv4=n=>e.check($f($m,n)),e.ipv6=n=>e.check(zf(zm,n)),e.cidrv4=n=>e.check(jf(jm,n)),e.cidrv6=n=>e.check(Df(Dm,n)),e.e164=n=>e.check(Uf(Um,n)),e.datetime=n=>e.check(mm(n)),e.date=n=>e.check(ym(n)),e.time=n=>e.check(_m(n)),e.duration=n=>e.check(bm(n))});function h(e){return bf(Sm,e)}const we=C("ZodStringFormat",(e,t)=>{ve.init(e,t),zi.init(e,t)}),Im=C("ZodEmail",(e,t)=>{Ih.init(e,t),we.init(e,t)}),ji=C("ZodGUID",(e,t)=>{Th.init(e,t),we.init(e,t)}),Sr=C("ZodUUID",(e,t)=>{Sh.init(e,t),we.init(e,t)}),Cm=C("ZodURL",(e,t)=>{Ch.init(e,t),we.init(e,t)}),Em=C("ZodEmoji",(e,t)=>{Eh.init(e,t),we.init(e,t)}),Rm=C("ZodNanoID",(e,t)=>{Rh.init(e,t),we.init(e,t)}),Am=C("ZodCUID",(e,t)=>{Ah.init(e,t),we.init(e,t)}),Om=C("ZodCUID2",(e,t)=>{Oh.init(e,t),we.init(e,t)}),Nm=C("ZodULID",(e,t)=>{Nh.init(e,t),we.init(e,t)}),Mm=C("ZodXID",(e,t)=>{Mh.init(e,t),we.init(e,t)}),Pm=C("ZodKSUID",(e,t)=>{Ph.init(e,t),we.init(e,t)}),$m=C("ZodIPv4",(e,t)=>{Zh.init(e,t),we.init(e,t)}),zm=C("ZodIPv6",(e,t)=>{Uh.init(e,t),we.init(e,t)}),jm=C("ZodCIDRv4",(e,t)=>{Lh.init(e,t),we.init(e,t)}),Dm=C("ZodCIDRv6",(e,t)=>{qh.init(e,t),we.init(e,t)}),Di=C("ZodBase64",(e,t)=>{Bh.init(e,t),we.init(e,t)});function Zi(e){return Ei(Di,e)}const Zm=C("ZodBase64URL",(e,t)=>{Fh.init(e,t),we.init(e,t)}),Um=C("ZodE164",(e,t)=>{Hh.init(e,t),we.init(e,t)}),Lm=C("ZodJWT",(e,t)=>{Gh.init(e,t),we.init(e,t)}),Ao=C("ZodNumber",(e,t)=>{mi.init(e,t),ge.init(e,t),e.gt=(r,o)=>e.check(Ai(r,o)),e.gte=(r,o)=>e.check(Ro(r,o)),e.min=(r,o)=>e.check(Ro(r,o)),e.lt=(r,o)=>e.check(Ri(r,o)),e.lte=(r,o)=>e.check(Eo(r,o)),e.max=(r,o)=>e.check(Eo(r,o)),e.int=r=>e.check(Ui(r)),e.safe=r=>e.check(Ui(r)),e.positive=r=>e.check(Ai(0,r)),e.nonnegative=r=>e.check(Ro(0,r)),e.negative=r=>e.check(Ri(0,r)),e.nonpositive=r=>e.check(Eo(0,r)),e.multipleOf=(r,o)=>e.check(Oi(r,o)),e.step=(r,o)=>e.check(Oi(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 R(e){return Hf(Ao,e)}const qm=C("ZodNumberFormat",(e,t)=>{Wh.init(e,t),Ao.init(e,t)});function Ui(e){return Gf(qm,e)}const Bm=C("ZodBoolean",(e,t)=>{Kh.init(e,t),ge.init(e,t)});function re(e){return Wf(Bm,e)}const Vm=C("ZodNull",(e,t)=>{Yh.init(e,t),ge.init(e,t)});function Fm(e){return Kf(Vm,e)}const Hm=C("ZodAny",(e,t)=>{Xh.init(e,t),ge.init(e,t)});function pt(){return Yf(Hm)}const Jm=C("ZodUnknown",(e,t)=>{Qh.init(e,t),ge.init(e,t)});function Le(){return Xf(Jm)}const Gm=C("ZodNever",(e,t)=>{ef.init(e,t),ge.init(e,t)});function Li(e){return Qf(Gm,e)}const Wm=C("ZodArray",(e,t)=>{tf.init(e,t),ge.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(kr(n,r)),e.nonempty=n=>e.check(kr(1,n)),e.max=(n,r)=>e.check(Ni(n,r)),e.length=(n,r)=>e.check(Mi(n,r)),e.unwrap=()=>e.element});function Z(e,t){return cm(Wm,e,t)}const Oo=C("ZodObject",(e,t)=>{nf.init(e,t),ge.init(e,t),le(e,"shape",()=>t.shape),e.keyof=()=>qe(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Le()}),e.loose=()=>e.clone({...e._zod.def,catchall:Le()}),e.strict=()=>e.clone({...e._zod.def,catchall:Li()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>Ip(e,n),e.merge=n=>Cp(e,n),e.pick=n=>Tp(e,n),e.omit=n=>Sp(e,n),e.partial=(...n)=>Ep(Bi,e,n[0]),e.required=(...n)=>Rp(Fi,e,n[0])});function x(e,t){const n={type:"object",get shape(){return En(this,"shape",{...e}),this.shape},...U(t)};return new Oo(n)}function ye(e,t){return new Oo({type:"object",get shape(){return En(this,"shape",{...e}),this.shape},catchall:Li(),...U(t)})}function un(e,t){return new Oo({type:"object",get shape(){return En(this,"shape",{...e}),this.shape},catchall:Le(),...U(t)})}const qi=C("ZodUnion",(e,t)=>{_i.init(e,t),ge.init(e,t),e.options=t.options});function ee(e,t){return new qi({type:"union",options:e,...U(t)})}const Km=C("ZodDiscriminatedUnion",(e,t)=>{qi.init(e,t),rf.init(e,t)});function cn(e,t,n){return new Km({type:"union",options:t,discriminator:e,...U(n)})}const Ym=C("ZodIntersection",(e,t)=>{of.init(e,t),ge.init(e,t)});function Xm(e,t){return new Ym({type:"intersection",left:e,right:t})}const Qm=C("ZodRecord",(e,t)=>{sf.init(e,t),ge.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function We(e,t,n){return new Qm({type:"record",keyType:e,valueType:t,...U(n)})}const No=C("ZodEnum",(e,t)=>{af.init(e,t),ge.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 No({...t,checks:[],...U(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 No({...t,checks:[],...U(o),entries:s})}});function qe(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new No({type:"enum",entries:n,...U(t)})}const eg=C("ZodLiteral",(e,t)=>{lf.init(e,t),ge.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 A(e,t){return new eg({type:"literal",values:Array.isArray(e)?e:[e],...U(t)})}const tg=C("ZodTransform",(e,t)=>{uf.init(e,t),ge.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(Nn(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(Nn(a))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function ng(e){return new tg({type:"transform",transform:e})}const Bi=C("ZodOptional",(e,t)=>{cf.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ie(e){return new Bi({type:"optional",innerType:e})}const rg=C("ZodNullable",(e,t)=>{df.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Vi(e){return new rg({type:"nullable",innerType:e})}const og=C("ZodDefault",(e,t)=>{pf.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function sg(e,t){return new og({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const ag=C("ZodPrefault",(e,t)=>{hf.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ig(e,t){return new ag({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Fi=C("ZodNonOptional",(e,t)=>{ff.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType});function lg(e,t){return new Fi({type:"nonoptional",innerType:e,...U(t)})}const ug=C("ZodCatch",(e,t)=>{mf.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function cg(e,t){return new ug({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const dg=C("ZodPipe",(e,t)=>{gf.init(e,t),ge.init(e,t),e.in=t.in,e.out=t.out});function Hi(e,t){return new dg({type:"pipe",in:e,out:t})}const pg=C("ZodReadonly",(e,t)=>{yf.init(e,t),ge.init(e,t)});function hg(e){return new pg({type:"readonly",innerType:e})}const fg=C("ZodLazy",(e,t)=>{vf.init(e,t),ge.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Ji(e){return new fg({type:"lazy",getter:e})}const Mo=C("ZodCustom",(e,t)=>{_f.init(e,t),ge.init(e,t)});function mg(e){const t=new Ge({check:"custom"});return t._zod.check=e,t}function gg(e,t){return dm(Mo,e??(()=>!0),t)}function yg(e,t={}){return pm(Mo,e,t)}function vg(e){const t=mg(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Nn(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(Nn(o))}},e(n.value,n)));return t}function Ir(e,t={error:`Input not instance of ${e.name}`}){const n=new Mo({type:"custom",check:"custom",fn:r=>r instanceof e,abort:!0,...U(t)});return n._zod.bag.Class=e,n}function _g(e){return Jf(Ao,e)}const wg=Symbol("Let zodToJsonSchema decide on which parser to use"),Gi={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},bg=e=>typeof e=="string"?{...Gi,name:e}:{...Gi,...e},xg=e=>{const t=bg(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},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}]))}};function Wi(e,t,n,r){r!=null&&r.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function ue(e,t,n,r,o){e[t]=n,Wi(e,t,r,o)}const Ki=(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("/")};var te;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}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(i=>typeof o[o[i]]!="number"),a={};for(const i of s)a[i]=o[i];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)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(te||(te={}));var Yi;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Yi||(Yi={}));const j=te.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Zt=e=>{switch(typeof e){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(e)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":return Array.isArray(e)?j.array:e===null?j.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?j.promise:typeof Map<"u"&&e instanceof Map?j.map:typeof Set<"u"&&e instanceof Set?j.set:typeof Date<"u"&&e instanceof Date?j.date:j.object;default:return j.unknown}},N=te.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"]);class At 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=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 i=r,l=0;for(;l<a.path.length;){const u=a.path[l];l===a.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(n(a))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return o(this),r}static assert(t){if(!(t instanceof At))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,te.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()}}At.create=e=>new At(e);const Po=(e,t)=>{let n;switch(e.code){case N.invalid_type:e.received===j.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,te.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${te.joinValues(e.keys,", ")}`;break;case N.invalid_union:n="Invalid input";break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${te.joinValues(e.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${te.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}"`:te.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,te.assertNever(e)}return{message:n}};let kg=Po;function Tg(){return kg}const Sg=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 i="";const l=r.filter(u=>!!u).slice().reverse();for(const u of l)i=u(a,{data:t,defaultError:i}).message;return{...o,path:s,message:i}};function z(e,t){const n=Tg(),r=Sg({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Po?void 0:Po].filter(o=>!!o)});e.common.issues.push(r)}class Be{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 W;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 Be.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 W;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}}}const W=Object.freeze({status:"aborted"}),$n=e=>({status:"dirty",value:e}),it=e=>({status:"valid",value:e}),Xi=e=>e.status==="aborted",Qi=e=>e.status==="dirty",dn=e=>e.status==="valid",Cr=e=>typeof Promise<"u"&&e instanceof Promise;var q;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(q||(q={}));class vt{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}}const el=(e,t)=>{if(dn(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 At(e.common.issues);return this._error=n,this._error}}};function Y(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:(a,i)=>{const{message:l}=e;return a.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??r??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:l??n??i.defaultError}},description:o}}class X{get description(){return this._def.description}_getType(t){return Zt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Zt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Be,ctx:{common:t.parent.common,data:t.data,parsedType:Zt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Cr(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==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Zt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return el(r,o)}"~validate"(t){var r,o;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Zt(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:n});return dn(s)?{value:s.value}:{issues:n.common.issues}}catch(s){(o=(r=s==null?void 0:s.message)==null?void 0:r.toLowerCase())!=null&&o.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(s=>dn(s)?{value:s.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==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Zt(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Cr(o)?o:Promise.resolve(o));return el(r,s)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{const a=t(o),i=()=>s.addIssue({code:N.custom,...r(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(i(),!1)):a?!0:(i(),!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:n=>this["~validate"](n)}}optional(){return Mt.create(this,this._def)}nullable(){return Xt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return _t.create(this)}promise(){return Mr.create(this,this._def)}or(t){return Rr.create([this,t],this._def)}and(t){return Ar.create(this,t,this._def)}transform(t){return new Yt({...Y(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Pr({...Y(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new ll({typeName:M.ZodBranded,type:this,...Y(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new $r({...Y(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 Fo.create(this,t)}readonly(){return zr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ig=/^c[^\s-]{8,}$/i,Cg=/^[0-9a-z]+$/,Eg=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Rg=/^[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,Ag=/^[a-z0-9_-]{21}$/i,Og=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ng=/^[-+]?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)?)??$/,Mg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Pg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let $o;const $g=/^(?:(?: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])$/,zg=/^(?:(?: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])$/,jg=/^(([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]))$/,Dg=/^(([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])$/,Zg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ug=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,tl="((\\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])))",Lg=new RegExp(`^${tl}$`);function nl(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}`}function qg(e){return new RegExp(`^${nl(e)}$`)}function Bg(e){let t=`${tl}T${nl(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}$`)}function Vg(e,t){return!!((t==="v4"||!t)&&$g.test(e)||(t==="v6"||!t)&&jg.test(e))}function Fg(e,t){if(!Og.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==null?void 0:o.typ)!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Hg(e,t){return!!((t==="v4"||!t)&&zg.test(e)||(t==="v6"||!t)&&Dg.test(e))}class Ot extends X{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==j.string){const s=this._getOrReturnCtx(t);return z(s,{code:N.invalid_type,expected:j.string,received:s.parsedType}),W}const r=new Be;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,i=t.data.length<s.value;(a||i)&&(o=this._getOrReturnCtx(t,o),a?z(o,{code:N.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&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")Mg.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")$o||($o=new RegExp(Pg,"u")),$o.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")Rg.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")Ag.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")Ig.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")Cg.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")Eg.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"?Bg(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"?Lg.test(t.data)||(o=this._getOrReturnCtx(t,o),z(o,{code:N.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?qg(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"?Ng.test(t.data)||(o=this._getOrReturnCtx(t,o),z(o,{validation:"duration",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?Vg(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"?Fg(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"?Hg(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"?Zg.test(t.data)||(o=this._getOrReturnCtx(t,o),z(o,{validation:"base64",code:N.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?Ug.test(t.data)||(o=this._getOrReturnCtx(t,o),z(o,{validation:"base64url",code:N.invalid_string,message:s.message}),r.dirty()):te.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,...q.errToObj(r)})}_addCheck(t){return new Ot({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...q.errToObj(t)})}url(t){return this._addCheck({kind:"url",...q.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...q.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...q.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...q.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...q.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...q.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...q.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...q.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...q.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...q.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...q.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...q.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==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(t==null?void 0:t.offset)??!1,local:(t==null?void 0:t.local)??!1,...q.errToObj(t==null?void 0: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==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...q.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...q.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...q.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...q.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...q.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...q.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...q.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...q.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...q.errToObj(n)})}nonempty(t){return this.min(1,q.errToObj(t))}trim(){return new Ot({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ot({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ot({...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}}Ot.create=e=>new Ot({checks:[],typeName:M.ZodString,coerce:(e==null?void 0:e.coerce)??!1,...Y(e)});function Jg(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}class pn extends X{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)!==j.number){const s=this._getOrReturnCtx(t);return z(s,{code:N.invalid_type,expected:j.number,received:s.parsedType}),W}let r;const o=new Be;for(const s of this._def.checks)s.kind==="int"?te.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"?Jg(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()):te.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,q.toString(n))}gt(t,n){return this.setLimit("min",t,!1,q.toString(n))}lte(t,n){return this.setLimit("max",t,!0,q.toString(n))}lt(t,n){return this.setLimit("max",t,!1,q.toString(n))}setLimit(t,n,r,o){return new pn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:q.toString(o)}]})}_addCheck(t){return new pn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:q.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:q.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:q.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.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"&&te.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)}}pn.create=e=>new pn({checks:[],typeName:M.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Y(e)});class zn extends X{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)!==j.bigint)return this._getInvalidInput(t);let r;const o=new Be;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()):te.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return z(n,{code:N.invalid_type,expected:j.bigint,received:n.parsedType}),W}gte(t,n){return this.setLimit("min",t,!0,q.toString(n))}gt(t,n){return this.setLimit("min",t,!1,q.toString(n))}lte(t,n){return this.setLimit("max",t,!0,q.toString(n))}lt(t,n){return this.setLimit("max",t,!1,q.toString(n))}setLimit(t,n,r,o){return new zn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:q.toString(o)}]})}_addCheck(t){return new zn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:q.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}}zn.create=e=>new zn({checks:[],typeName:M.ZodBigInt,coerce:(e==null?void 0:e.coerce)??!1,...Y(e)});class zo extends X{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==j.boolean){const r=this._getOrReturnCtx(t);return z(r,{code:N.invalid_type,expected:j.boolean,received:r.parsedType}),W}return it(t.data)}}zo.create=e=>new zo({typeName:M.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Y(e)});class Er extends X{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==j.date){const s=this._getOrReturnCtx(t);return z(s,{code:N.invalid_type,expected:j.date,received:s.parsedType}),W}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return z(s,{code:N.invalid_date}),W}const r=new Be;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()):te.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Er({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:q.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:q.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}}Er.create=e=>new Er({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:M.ZodDate,...Y(e)});class rl extends X{_parse(t){if(this._getType(t)!==j.symbol){const r=this._getOrReturnCtx(t);return z(r,{code:N.invalid_type,expected:j.symbol,received:r.parsedType}),W}return it(t.data)}}rl.create=e=>new rl({typeName:M.ZodSymbol,...Y(e)});class jo extends X{_parse(t){if(this._getType(t)!==j.undefined){const r=this._getOrReturnCtx(t);return z(r,{code:N.invalid_type,expected:j.undefined,received:r.parsedType}),W}return it(t.data)}}jo.create=e=>new jo({typeName:M.ZodUndefined,...Y(e)});class Do extends X{_parse(t){if(this._getType(t)!==j.null){const r=this._getOrReturnCtx(t);return z(r,{code:N.invalid_type,expected:j.null,received:r.parsedType}),W}return it(t.data)}}Do.create=e=>new Do({typeName:M.ZodNull,...Y(e)});class Zo extends X{constructor(){super(...arguments),this._any=!0}_parse(t){return it(t.data)}}Zo.create=e=>new Zo({typeName:M.ZodAny,...Y(e)});class Uo extends X{constructor(){super(...arguments),this._unknown=!0}_parse(t){return it(t.data)}}Uo.create=e=>new Uo({typeName:M.ZodUnknown,...Y(e)});class Ut extends X{_parse(t){const n=this._getOrReturnCtx(t);return z(n,{code:N.invalid_type,expected:j.never,received:n.parsedType}),W}}Ut.create=e=>new Ut({typeName:M.ZodNever,...Y(e)});class ol extends X{_parse(t){if(this._getType(t)!==j.undefined){const r=this._getOrReturnCtx(t);return z(r,{code:N.invalid_type,expected:j.void,received:r.parsedType}),W}return it(t.data)}}ol.create=e=>new ol({typeName:M.ZodVoid,...Y(e)});class _t extends X{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==j.array)return z(n,{code:N.invalid_type,expected:j.array,received:n.parsedType}),W;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,i=n.data.length<o.exactLength.value;(a||i)&&(z(n,{code:a?N.too_big:N.too_small,minimum:i?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,i)=>o.type._parseAsync(new vt(n,a,n.path,i)))).then(a=>Be.mergeArray(r,a));const s=[...n.data].map((a,i)=>o.type._parseSync(new vt(n,a,n.path,i)));return Be.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new _t({...this._def,minLength:{value:t,message:q.toString(n)}})}max(t,n){return new _t({...this._def,maxLength:{value:t,message:q.toString(n)}})}length(t,n){return new _t({...this._def,exactLength:{value:t,message:q.toString(n)}})}nonempty(t){return this.min(1,t)}}_t.create=(e,t)=>new _t({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...Y(t)});function hn(e){if(e instanceof Ce){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Mt.create(hn(r))}return new Ce({...e._def,shape:()=>t})}else return e instanceof _t?new _t({...e._def,type:hn(e.element)}):e instanceof Mt?Mt.create(hn(e.unwrap())):e instanceof Xt?Xt.create(hn(e.unwrap())):e instanceof Wt?Wt.create(e.items.map(t=>hn(t))):e}class Ce extends X{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=te.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==j.object){const u=this._getOrReturnCtx(t);return z(u,{code:N.invalid_type,expected:j.object,received:u.parsedType}),W}const{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof Ut&&this._def.unknownKeys==="strip"))for(const u in o.data)a.includes(u)||i.push(u);const l=[];for(const u of a){const c=s[u],w=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new vt(o,w,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Ut){const u=this._def.unknownKeys;if(u==="passthrough")for(const c of i)l.push({key:{status:"valid",value:c},value:{status:"valid",value:o.data[c]}});else if(u==="strict")i.length>0&&(z(o,{code:N.unrecognized_keys,keys:i}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const c of i){const w=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new vt(o,w,o.path,c)),alwaysSet:c in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const u=[];for(const c of l){const w=await c.key,_=await c.value;u.push({key:w,value:_,alwaysSet:c.alwaysSet})}return u}).then(u=>Be.mergeObjectSync(r,u)):Be.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return q.errToObj,new Ce({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,a;const o=((a=(s=this._def).errorMap)==null?void 0:a.call(s,n,r).message)??r.defaultError;return n.code==="unrecognized_keys"?{message:q.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new Ce({...this._def,unknownKeys:"strip"})}passthrough(){return new Ce({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ce({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ce({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:M.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Ce({...this._def,catchall:t})}pick(t){const n={};for(const r of te.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new Ce({...this._def,shape:()=>n})}omit(t){const n={};for(const r of te.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new Ce({...this._def,shape:()=>n})}deepPartial(){return hn(this)}partial(t){const n={};for(const r of te.objectKeys(this.shape)){const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new Ce({...this._def,shape:()=>n})}required(t){const n={};for(const r of te.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Mt;)s=s._def.innerType;n[r]=s}return new Ce({...this._def,shape:()=>n})}keyof(){return al(te.objectKeys(this.shape))}}Ce.create=(e,t)=>new Ce({shape:()=>e,unknownKeys:"strip",catchall:Ut.create(),typeName:M.ZodObject,...Y(t)}),Ce.strictCreate=(e,t)=>new Ce({shape:()=>e,unknownKeys:"strict",catchall:Ut.create(),typeName:M.ZodObject,...Y(t)}),Ce.lazycreate=(e,t)=>new Ce({shape:e,unknownKeys:"strip",catchall:Ut.create(),typeName:M.ZodObject,...Y(t)});class Rr extends X{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(const i of s)if(i.result.status==="valid")return i.result;for(const i of s)if(i.result.status==="dirty")return n.common.issues.push(...i.ctx.common.issues),i.result;const a=s.map(i=>new At(i.ctx.common.issues));return z(n,{code:N.invalid_union,unionErrors:a}),W}if(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 u={...n,common:{...n.common,issues:[]},parent:null},c=l._parseSync({data:n.data,path:n.path,parent:u});if(c.status==="valid")return c;c.status==="dirty"&&!s&&(s={result:c,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const i=a.map(l=>new At(l));return z(n,{code:N.invalid_union,unionErrors:i}),W}}get options(){return this._def.options}}Rr.create=(e,t)=>new Rr({options:e,typeName:M.ZodUnion,...Y(t)});const Nt=e=>e instanceof Bo?Nt(e.schema):e instanceof Yt?Nt(e.innerType()):e instanceof Nr?[e.value]:e instanceof Kt?e.options:e instanceof Vo?te.objectValues(e.enum):e instanceof Pr?Nt(e._def.innerType):e instanceof jo?[void 0]:e instanceof Do?[null]:e instanceof Mt?[void 0,...Nt(e.unwrap())]:e instanceof Xt?[null,...Nt(e.unwrap())]:e instanceof ll||e instanceof zr?Nt(e.unwrap()):e instanceof $r?Nt(e._def.innerType):[];class Lo extends X{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==j.object)return z(n,{code:N.invalid_type,expected:j.object,received:n.parsedType}),W;const r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(z(n,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),W)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const s of n){const a=Nt(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const i of a){if(o.has(i))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(i)}`);o.set(i,s)}}return new Lo({typeName:M.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Y(r)})}}function qo(e,t){const n=Zt(e),r=Zt(t);if(e===t)return{valid:!0,data:e};if(n===j.object&&r===j.object){const o=te.objectKeys(t),s=te.objectKeys(e).filter(i=>o.indexOf(i)!==-1),a={...e,...t};for(const i of s){const l=qo(e[i],t[i]);if(!l.valid)return{valid:!1};a[i]=l.data}return{valid:!0,data:a}}else if(n===j.array&&r===j.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],i=t[s],l=qo(a,i);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===j.date&&r===j.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Ar extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=(s,a)=>{if(Xi(s)||Xi(a))return W;const i=qo(s.value,a.value);return i.valid?((Qi(s)||Qi(a))&&n.dirty(),{status:n.value,value:i.data}):(z(r,{code:N.invalid_intersection_types}),W)};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}))}}Ar.create=(e,t,n)=>new Ar({left:e,right:t,typeName:M.ZodIntersection,...Y(n)});class Wt extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==j.array)return z(r,{code:N.invalid_type,expected:j.array,received:r.parsedType}),W;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"}),W;!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,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new vt(r,a,r.path,i)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>Be.mergeArray(n,a)):Be.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new Wt({...this._def,rest:t})}}Wt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Wt({items:e,typeName:M.ZodTuple,rest:null,...Y(t)})};class Or extends X{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!==j.object)return z(r,{code:N.invalid_type,expected:j.object,received:r.parsedType}),W;const o=[],s=this._def.keyType,a=this._def.valueType;for(const i in r.data)o.push({key:s._parse(new vt(r,i,r.path,i)),value:a._parse(new vt(r,r.data[i],r.path,i)),alwaysSet:i in r.data});return r.common.async?Be.mergeObjectAsync(n,o):Be.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof X?new Or({keyType:t,valueType:n,typeName:M.ZodRecord,...Y(r)}):new Or({keyType:Ot.create(),valueType:t,typeName:M.ZodRecord,...Y(n)})}}class sl extends X{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!==j.map)return z(r,{code:N.invalid_type,expected:j.map,received:r.parsedType}),W;const o=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([i,l],u)=>({key:o._parse(new vt(r,i,r.path,[u,"key"])),value:s._parse(new vt(r,l,r.path,[u,"value"]))}));if(r.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of a){const u=await l.key,c=await l.value;if(u.status==="aborted"||c.status==="aborted")return W;(u.status==="dirty"||c.status==="dirty")&&n.dirty(),i.set(u.value,c.value)}return{status:n.value,value:i}})}else{const i=new Map;for(const l of a){const u=l.key,c=l.value;if(u.status==="aborted"||c.status==="aborted")return W;(u.status==="dirty"||c.status==="dirty")&&n.dirty(),i.set(u.value,c.value)}return{status:n.value,value:i}}}}sl.create=(e,t,n)=>new sl({valueType:t,keyType:e,typeName:M.ZodMap,...Y(n)});class jn extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==j.set)return z(r,{code:N.invalid_type,expected:j.set,received:r.parsedType}),W;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 u=new Set;for(const c of l){if(c.status==="aborted")return W;c.status==="dirty"&&n.dirty(),u.add(c.value)}return{status:n.value,value:u}}const i=[...r.data.values()].map((l,u)=>s._parse(new vt(r,l,r.path,u)));return r.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(t,n){return new jn({...this._def,minSize:{value:t,message:q.toString(n)}})}max(t,n){return new jn({...this._def,maxSize:{value:t,message:q.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}jn.create=(e,t)=>new jn({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...Y(t)});class Bo extends X{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})}}Bo.create=(e,t)=>new Bo({getter:e,typeName:M.ZodLazy,...Y(t)});class Nr extends X{_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}),W}return{status:"valid",value:t.data}}get value(){return this._def.value}}Nr.create=(e,t)=>new Nr({value:e,typeName:M.ZodLiteral,...Y(t)});function al(e,t){return new Kt({values:e,typeName:M.ZodEnum,...Y(t)})}class Kt extends X{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return z(n,{expected:te.joinValues(r),received:n.parsedType,code:N.invalid_type}),W}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}),W}return it(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 Kt.create(t,{...this._def,...n})}exclude(t,n=this._def){return Kt.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}Kt.create=al;class Vo extends X{_parse(t){const n=te.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==j.string&&r.parsedType!==j.number){const o=te.objectValues(n);return z(r,{expected:te.joinValues(o),received:r.parsedType,code:N.invalid_type}),W}if(this._cache||(this._cache=new Set(te.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=te.objectValues(n);return z(r,{received:r.data,code:N.invalid_enum_value,options:o}),W}return it(t.data)}get enum(){return this._def.values}}Vo.create=(e,t)=>new Vo({values:e,typeName:M.ZodNativeEnum,...Y(t)});class Mr extends X{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==j.promise&&n.common.async===!1)return z(n,{code:N.invalid_type,expected:j.promise,received:n.parsedType}),W;const r=n.parsedType===j.promise?n.data:Promise.resolve(n.data);return it(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Mr.create=(e,t)=>new Mr({type:e,typeName:M.ZodPromise,...Y(t)});class Yt extends X{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:a=>{z(r,a),a.fatal?n.abort():n.dirty()},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 i=>{if(n.value==="aborted")return W;const l=await this._def.schema._parseAsync({data:i,path:r.path,parent:r});return l.status==="aborted"?W:l.status==="dirty"||n.value==="dirty"?$n(l.value):l});{if(n.value==="aborted")return W;const i=this._def.schema._parseSync({data:a,path:r.path,parent:r});return i.status==="aborted"?W:i.status==="dirty"||n.value==="dirty"?$n(i.value):i}}if(o.type==="refinement"){const a=i=>{const l=o.refinement(i,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 i};if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?W:(i.status==="dirty"&&n.dirty(),a(i.value),{status:n.value,value:i.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>i.status==="aborted"?W:(i.status==="dirty"&&n.dirty(),a(i.value).then(()=>({status:n.value,value:i.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(!dn(a))return W;const i=o.transform(a.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:i}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>dn(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:n.value,value:i})):W);te.assertNever(o)}}Yt.create=(e,t,n)=>new Yt({schema:e,typeName:M.ZodEffects,effect:t,...Y(n)}),Yt.createWithPreprocess=(e,t,n)=>new Yt({schema:t,effect:{type:"preprocess",transform:e},typeName:M.ZodEffects,...Y(n)});class Mt extends X{_parse(t){return this._getType(t)===j.undefined?it(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Mt.create=(e,t)=>new Mt({innerType:e,typeName:M.ZodOptional,...Y(t)});class Xt extends X{_parse(t){return this._getType(t)===j.null?it(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Xt.create=(e,t)=>new Xt({innerType:e,typeName:M.ZodNullable,...Y(t)});class Pr extends X{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===j.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Pr.create=(e,t)=>new Pr({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Y(t)});class $r extends X{_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 Cr(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new At(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new At(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}$r.create=(e,t)=>new $r({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Y(t)});class il extends X{_parse(t){if(this._getType(t)!==j.nan){const r=this._getOrReturnCtx(t);return z(r,{code:N.invalid_type,expected:j.nan,received:r.parsedType}),W}return{status:"valid",value:t.data}}}il.create=e=>new il({typeName:M.ZodNaN,...Y(e)});class ll extends X{_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}}class Fo extends X{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?W:s.status==="dirty"?(n.dirty(),$n(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?W: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 Fo({in:t,out:n,typeName:M.ZodPipeline})}}class zr extends X{_parse(t){const n=this._def.innerType._parse(t),r=o=>(dn(o)&&(o.value=Object.freeze(o.value)),o);return Cr(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}zr.create=(e,t)=>new zr({innerType:e,typeName:M.ZodReadonly,...Y(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 k=Ot.create,Pe=pn.create,Oe=zo.create,Gg=Zo.create,Dn=Uo.create;Ut.create;const L=_t.create,$=Ce.create,Ve=Rr.create,Wg=Lo.create;Ar.create,Wt.create;const Zn=Or.create,K=Nr.create,Pt=Kt.create;Mr.create;const O=Mt.create;Xt.create;function Ke(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Ki(t,e.currentPath):t.join("/")}}function Kg(e,t){var r,o,s;const n={type:"array"};return(r=e.type)!=null&&r._def&&((s=(o=e.type)==null?void 0:o._def)==null?void 0:s.typeName)!==M.ZodAny&&(n.items=ae(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&ue(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&ue(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(ue(n,"minItems",e.exactLength.value,e.exactLength.message,t),ue(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}function Yg(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":t.target==="jsonSchema7"?r.inclusive?ue(n,"minimum",r.value,r.message,t):ue(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),ue(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?ue(n,"maximum",r.value,r.message,t):ue(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),ue(n,"maximum",r.value,r.message,t));break;case"multipleOf":ue(n,"multipleOf",r.value,r.message,t);break}return n}function Xg(){return{type:"boolean"}}function ul(e,t){return ae(e.type._def,t)}const Qg=(e,t)=>ae(e.innerType._def,t);function cl(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>cl(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 ey(e,t)}}const ey=(e,t)=>{const n={type:"integer",format:"unix-time"};if(t.target==="openApi3")return n;for(const r of e.checks)switch(r.kind){case"min":ue(n,"minimum",r.value,r.message,t);break;case"max":ue(n,"maximum",r.value,r.message,t);break}return n};function ty(e,t){return{...ae(e.innerType._def,t),default:e.defaultValue()}}function ny(e,t){return t.effectStrategy==="input"?ae(e.schema._def,t):Ke(t)}function ry(e){return{type:"string",enum:Array.from(e.values)}}const oy=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function sy(e,t){const n=[ae(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),ae(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s);let r=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const o=[];return n.forEach(s=>{if(oy(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:i,...l}=s;a=l}else r=void 0;o.push(a)}}),o.length?{allOf:o,...r}:void 0}function ay(e,t){const n=typeof e.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[e.value]}:{type:n==="bigint"?"integer":n,const:e.value}}let Ho;const ht={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:()=>(Ho===void 0&&(Ho=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ho),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 dl(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":ue(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":ue(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":ft(n,"email",r.message,t);break;case"format:idn-email":ft(n,"idn-email",r.message,t);break;case"pattern:zod":Fe(n,ht.email,r.message,t);break}break;case"url":ft(n,"uri",r.message,t);break;case"uuid":ft(n,"uuid",r.message,t);break;case"regex":Fe(n,r.regex,r.message,t);break;case"cuid":Fe(n,ht.cuid,r.message,t);break;case"cuid2":Fe(n,ht.cuid2,r.message,t);break;case"startsWith":Fe(n,RegExp(`^${Jo(r.value,t)}`),r.message,t);break;case"endsWith":Fe(n,RegExp(`${Jo(r.value,t)}$`),r.message,t);break;case"datetime":ft(n,"date-time",r.message,t);break;case"date":ft(n,"date",r.message,t);break;case"time":ft(n,"time",r.message,t);break;case"duration":ft(n,"duration",r.message,t);break;case"length":ue(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t),ue(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":{Fe(n,RegExp(Jo(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&ft(n,"ipv4",r.message,t),r.version!=="v4"&&ft(n,"ipv6",r.message,t);break}case"base64url":Fe(n,ht.base64url,r.message,t);break;case"jwt":Fe(n,ht.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&Fe(n,ht.ipv4Cidr,r.message,t),r.version!=="v4"&&Fe(n,ht.ipv6Cidr,r.message,t);break}case"emoji":Fe(n,ht.emoji(),r.message,t);break;case"ulid":{Fe(n,ht.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{ft(n,"binary",r.message,t);break}case"contentEncoding:base64":{ue(n,"contentEncoding","base64",r.message,t);break}case"pattern:zod":{Fe(n,ht.base64,r.message,t);break}}break}case"nanoid":Fe(n,ht.nanoid,r.message,t)}return n}function Jo(e,t){return t.patternStrategy==="escape"?ly(e):e}const iy=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ly(e){let t="";for(let n=0;n<e.length;n++)iy.has(e[n])||(t+="\\"),t+=e[n];return t}function ft(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,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):ue(e,"format",t,n,r)}function Fe(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,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:pl(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ue(e,"pattern",pl(t,r),n,r)}function pl(e,t){var l;if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},r=n.i?e.source.toLowerCase():e.source;let o="",s=!1,a=!1,i=!1;for(let u=0;u<r.length;u++){if(s){o+=r[u],s=!1;continue}if(n.i){if(a){if(r[u].match(/[a-z]/)){i?(o+=r[u],o+=`${r[u-2]}-${r[u]}`.toUpperCase(),i=!1):r[u+1]==="-"&&((l=r[u+2])!=null&&l.match(/[a-z]/))?(o+=r[u],i=!0):o+=`${r[u]}${r[u].toUpperCase()}`;continue}}else if(r[u].match(/[a-z]/)){o+=`[${r[u]}${r[u].toUpperCase()}]`;continue}}if(n.m){if(r[u]==="^"){o+=`(^|(?<=[\r
35
35
  ]))`;continue}else if(r[u]==="$"){o+=`($|(?=[\r
36
36
  ]))`;continue}}if(n.s&&r[u]==="."){o+=a?`${r[u]}\r
37
37
  `:`[${r[u]}\r
38
- ]`;continue}o+=r[u],r[u]==="\\"?s=!0:a&&r[u]==="]"?a=!1:!a&&r[u]==="["&&(a=!0)}try{new RegExp(o)}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 o}function hl(e,t){var r,o,s,a,i,l;if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&((r=e.keyType)==null?void 0:r._def.typeName)===M.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((u,c)=>({...u,[c]:ae(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",c]})??Ke(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:ae(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(((o=e.keyType)==null?void 0:o._def.typeName)===M.ZodString&&((s=e.keyType._def.checks)!=null&&s.length)){const{type:u,...c}=dl(e.keyType._def,t);return{...n,propertyNames:c}}else{if(((a=e.keyType)==null?void 0:a._def.typeName)===M.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(((i=e.keyType)==null?void 0:i._def.typeName)===M.ZodBranded&&e.keyType._def.type._def.typeName===M.ZodString&&((l=e.keyType._def.type._def.checks)!=null&&l.length)){const{type:u,...c}=ul(e.keyType._def,t);return{...n,propertyNames:c}}}return n}function cy(e,t){if(t.mapStrategy==="record")return hl(e,t);const n=ae(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ke(t),r=ae(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ke(t);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function dy(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}}function py(e){return e.target==="openAi"?void 0:{not:Ke({...e,currentPath:[...e.currentPath,"not"]})}}function hy(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const jr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function fy(e,t){if(t.target==="openApi3")return fl(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in jr&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,s)=>{const a=jr[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,i)=>i.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 fl(e,t)}const fl=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,o)=>ae(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};function my(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:jr[e.innerType._def.typeName],nullable:!0}:{type:[jr[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const r=ae(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=ae(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function gy(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",Wi(n,"type",r.message,t);break;case"min":t.target==="jsonSchema7"?r.inclusive?ue(n,"minimum",r.value,r.message,t):ue(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),ue(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?ue(n,"maximum",r.value,r.message,t):ue(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),ue(n,"maximum",r.value,r.message,t));break;case"multipleOf":ue(n,"multipleOf",r.value,r.message,t);break}return n}function yy(e,t){const n=t.target==="openAi",r={type:"object",properties:{}},o=[],s=e.shape();for(const i in s){let l=s[i];if(l===void 0||l._def===void 0)continue;let u=_y(l);u&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);const c=ae(l._def,{...t,currentPath:[...t.currentPath,"properties",i],propertyPath:[...t.currentPath,"properties",i]});c!==void 0&&(r.properties[i]=c,u||o.push(i))}o.length&&(r.required=o);const a=vy(e,t);return a!==void 0&&(r.additionalProperties=a),r}function vy(e,t){if(e.catchall._def.typeName!=="ZodNever")return ae(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}}function _y(e){try{return e.isOptional()}catch{return!0}}const wy=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return ae(e.innerType._def,t);const n=ae(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Ke(t)},n]}:Ke(t)},by=(e,t)=>{if(t.pipeStrategy==="input")return ae(e.in._def,t);if(t.pipeStrategy==="output")return ae(e.out._def,t);const n=ae(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=ae(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}};function xy(e,t){return ae(e.type._def,t)}function ky(e,t){const r={type:"array",uniqueItems:!0,items:ae(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ue(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ue(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function Ty(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>ae(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:ae(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>ae(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function Sy(e){return{not:Ke(e)}}function Iy(e){return Ke(e)}const Cy=(e,t)=>ae(e.innerType._def,t),Ey=(e,t,n)=>{switch(t){case M.ZodString:return dl(e,n);case M.ZodNumber:return gy(e,n);case M.ZodObject:return yy(e,n);case M.ZodBigInt:return Xg(e,n);case M.ZodBoolean:return Qg();case M.ZodDate:return cl(e,n);case M.ZodUndefined:return Sy(n);case M.ZodNull:return hy(n);case M.ZodArray:return Yg(e,n);case M.ZodUnion:case M.ZodDiscriminatedUnion:return fy(e,n);case M.ZodIntersection:return ay(e,n);case M.ZodTuple:return Ty(e,n);case M.ZodRecord:return hl(e,n);case M.ZodLiteral:return iy(e,n);case M.ZodEnum:return oy(e);case M.ZodNativeEnum:return dy(e);case M.ZodNullable:return my(e,n);case M.ZodOptional:return wy(e,n);case M.ZodMap:return cy(e,n);case M.ZodSet:return ky(e,n);case M.ZodLazy:return()=>e.getter()._def;case M.ZodPromise:return xy(e,n);case M.ZodNaN:case M.ZodNever:return py(n);case M.ZodEffects:return ry(e,n);case M.ZodAny:return Ke(n);case M.ZodUnknown:return Iy(n);case M.ZodDefault:return ny(e,n);case M.ZodBranded:return ul(e,n);case M.ZodReadonly:return Cy(e,n);case M.ZodCatch:return ey(e,n);case M.ZodPipeline:return by(e,n);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(r=>{})()}};function ae(e,t,n=!1){var i;const r=t.seen.get(e);if(t.override){const l=(i=t.override)==null?void 0:i.call(t,e,t,r,n);if(l!==bg)return l}if(r&&!n){const l=Ry(r,t);if(l!==void 0)return l}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const s=Ey(e,e.typeName,t),a=typeof s=="function"?ae(s(),t):s;if(a&&Ay(e,t,a),t.postProcess){const l=t.postProcess(a,e,t);return o.jsonSchema=a,l}return o.jsonSchema=a,a}const Ry=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Ki(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`),Ke(t)):t.$refStrategy==="seen"?Ke(t):void 0}},Ay=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Oy=(e,t)=>{const n=kg(t);let r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[u,c])=>({...l,[u]:ae(c._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??Ke(n)}),{}):void 0;const o=typeof t=="string"?t:(t==null?void 0:t.nameStrategy)==="title"||t==null?void 0:t.name,s=ae(e._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??Ke(n),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(s.title=a),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const i=o===void 0?r?{...s,[n.definitionPath]:r}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:s}};return n.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function Go(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}async function Ny(e,t){if(e==null)return Promise.resolve();const n=t==null?void 0:t.abortSignal;return new Promise((r,o)=>{if(n!=null&&n.aborted){o(ml());return}const s=setTimeout(()=>{a(),r()},e),a=()=>{clearTimeout(s),n==null||n.removeEventListener("abort",i)},i=()=>{a(),o(ml())};n==null||n.addEventListener("abort",i)})}function ml(){return new DOMException("Delay was aborted","AbortError")}function Un(e){return Object.fromEntries([...e.headers])}var Ln=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const s=n.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=n[Math.random()*s|0];return a.join("")};if(e==null)return o;if(n.includes(r))throw new _o({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},My=Ln();function Wo(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function Qt(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var Py=["fetch failed","failed to fetch"];function gl({error:e,url:t,requestBodyValues:n}){if(Qt(e))return e;if(e instanceof TypeError&&Py.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new pe({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}function yl(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!=null))}var $y=()=>globalThis.fetch,zy=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:o,fetch:s=$y()})=>{try{const a=await s(e,{method:"GET",headers:yl(t),signal:o}),i=Un(a);if(!a.ok){let l;try{l=await r({response:a,url:e,requestBodyValues:{}})}catch(u){throw Qt(u)||pe.isInstance(u)?u:new pe({message:"Failed to process error response",cause:u,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await n({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Qt(l)||pe.isInstance(l))?l:new pe({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw gl({error:a,url:e,requestBodyValues:{}})}};function jy({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))}function Dr({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}var Dy=/"__proto__"\s*:/,Zy=/"constructor"\s*:/;function Uy(e){const t=JSON.parse(e);return t===null||typeof t!="object"||Dy.test(e)===!1&&Zy.test(e)===!1?t:Ly(t)}function Ly(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}function vl(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Uy(e)}finally{Error.stackTraceLimit=t}}var Zr=Symbol.for("vercel.ai.validator");function qy(e){return{[Zr]:!0,validate:e}}function By(e){return typeof e=="object"&&e!==null&&Zr in e&&e[Zr]===!0&&"validate"in e}function Vy(e){return By(e)?e:Fy(e)}function Fy(e){return qy(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new yt({value:t,cause:n.issues})}})}async function Ko({value:e,schema:t}){const n=await qn({value:e,schema:t});if(!n.success)throw yt.wrap({value:e,cause:n.error});return n.value}async function qn({value:e,schema:t}){const n=Vy(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const r=await n.validate(e);return r.success?{success:!0,value:r.value,rawValue:e}:{success:!1,error:yt.wrap({value:e,cause:r.error}),rawValue:e}}catch(r){return{success:!1,error:yt.wrap({value:e,cause:r}),rawValue:e}}}async function Hy({text:e,schema:t}){try{const n=vl(e);return t==null?n:Ko({value:n,schema:t})}catch(n){throw zt.isInstance(n)||yt.isInstance(n)?n:new zt({text:e,cause:n})}}async function fn({text:e,schema:t}){try{const n=vl(e);return t==null?{success:!0,value:n,rawValue:n}:await qn({value:n,schema:t})}catch(n){return{success:!1,error:zt.isInstance(n)?n:new zt({text:e,cause:n}),rawValue:void 0}}}function Jy({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new yr).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await fn({text:n,schema:t}))}}))}var Gy=()=>globalThis.fetch,Yo=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Wy({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),Wy=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:s,fetch:a=Gy()})=>{try{const i=await a(e,{method:"POST",headers:yl(t),body:n.content,signal:s}),l=Un(i);if(!i.ok){let u;try{u=await o({response:i,url:e,requestBodyValues:n.values})}catch(c){throw Qt(c)||pe.isInstance(c)?c:new pe({message:"Failed to process error response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw u.value}try{return await r({response:i,url:e,requestBodyValues:n.values})}catch(u){throw u instanceof Error&&(Qt(u)||pe.isInstance(u))?u:new pe({message:"Failed to process successful response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(i){throw gl({error:i,url:e,requestBodyValues:n.values})}};function YT(e){return e}function _l(e){return{...e,type:"dynamic"}}async function en(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var Ur=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:s})=>{const a=await r.text(),i=Un(r);if(a.trim()==="")return{responseHeaders:i,value:new pe({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,isRetryable:n==null?void 0:n(r)})};try{const l=await Hy({text:a,schema:e});return{responseHeaders:i,value:new pe({message:t(l),url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,data:l,isRetryable:n==null?void 0:n(r,l)})}}catch{return{responseHeaders:i,value:new pe({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,isRetryable:n==null?void 0:n(r)})}}},Ky=e=>async({response:t})=>{const n=Un(t);if(t.body==null)throw new Ta({});return{responseHeaders:n,value:Jy({stream:t.body,schema:e})}},Xo=e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),s=await fn({text:o,schema:e}),a=Un(t);if(!s.success)throw new pe({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}};function Yy(e,t){var n;const r=(n=void 0)!=null?n:!1;return Bn(Oy(e,{$refStrategy:r?"root":"none",target:"jsonSchema7"}),{validate:async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function Xy(e,t){var n;const r=(n=void 0)!=null?n:!1,o=fm(e,{target:"draft-7",io:"output",reused:r?"ref":"inline"});return Bn(o,{validate:async s=>{const a=await $i(e,s);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function Qy(e){return"_zod"in e}function ev(e,t){return Qy(e)?Xy(e):Yy(e)}var Qo=Symbol.for("vercel.ai.schema");function Bn(e,{validate:t}={}){return{[Qo]:!0,_type:void 0,[Zr]:!0,jsonSchema:e,validate:t}}function tv(e){return typeof e=="object"&&e!==null&&Qo in e&&e[Qo]===!0&&"jsonSchema"in e&&"validate"in e}function Lr(e){return e==null?Bn({properties:{},additionalProperties:!1}):tv(e)?e:ev(e)}var{btoa:nv,atob:rv}=globalThis;function wl(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=rv(t);return Uint8Array.from(n,r=>r.codePointAt(0))}function es(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return nv(t)}function ov(e){return e==null?void 0:e.replace(/\/$/,"")}function sv(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*bl({execute:e,input:t,options:n}){const r=e(t,n);if(sv(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}}var av="vercel.ai.gateway.error",ts=Symbol.for(av),xl,kl,Qe=class ep extends(kl=Error,xl=ts,kl){constructor({message:t,statusCode:n=500,cause:r}){super(t),this[xl]=!0,this.statusCode=n,this.cause=r}static isInstance(t){return ep.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&ts in t&&t[ts]===!0}},Tl="GatewayAuthenticationError",iv=`vercel.ai.gateway.error.${Tl}`,Sl=Symbol.for(iv),Il,Cl,qr=class tp extends(Cl=Qe,Il=Sl,Cl){constructor({message:t="Authentication failed",statusCode:n=401,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[Il]=!0,this.name=Tl,this.type="authentication_error"}static isInstance(t){return Qe.hasMarker(t)&&Sl in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r="Authentication failed",statusCode:o=401,cause:s}){let a;return t?a=`AI Gateway authentication failed: Invalid API key provided.
38
+ ]`;continue}o+=r[u],r[u]==="\\"?s=!0:a&&r[u]==="]"?a=!1:!a&&r[u]==="["&&(a=!0)}try{new RegExp(o)}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 o}function hl(e,t){var r,o,s,a,i,l;if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&((r=e.keyType)==null?void 0:r._def.typeName)===M.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((u,c)=>({...u,[c]:ae(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",c]})??Ke(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:ae(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(((o=e.keyType)==null?void 0:o._def.typeName)===M.ZodString&&((s=e.keyType._def.checks)!=null&&s.length)){const{type:u,...c}=dl(e.keyType._def,t);return{...n,propertyNames:c}}else{if(((a=e.keyType)==null?void 0:a._def.typeName)===M.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(((i=e.keyType)==null?void 0:i._def.typeName)===M.ZodBranded&&e.keyType._def.type._def.typeName===M.ZodString&&((l=e.keyType._def.type._def.checks)!=null&&l.length)){const{type:u,...c}=ul(e.keyType._def,t);return{...n,propertyNames:c}}}return n}function uy(e,t){if(t.mapStrategy==="record")return hl(e,t);const n=ae(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ke(t),r=ae(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ke(t);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function cy(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}}function dy(e){return e.target==="openAi"?void 0:{not:Ke({...e,currentPath:[...e.currentPath,"not"]})}}function py(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const jr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function hy(e,t){if(t.target==="openApi3")return fl(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in jr&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,s)=>{const a=jr[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,i)=>i.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 fl(e,t)}const fl=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,o)=>ae(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};function fy(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:jr[e.innerType._def.typeName],nullable:!0}:{type:[jr[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const r=ae(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=ae(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function my(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",Wi(n,"type",r.message,t);break;case"min":t.target==="jsonSchema7"?r.inclusive?ue(n,"minimum",r.value,r.message,t):ue(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),ue(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?ue(n,"maximum",r.value,r.message,t):ue(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),ue(n,"maximum",r.value,r.message,t));break;case"multipleOf":ue(n,"multipleOf",r.value,r.message,t);break}return n}function gy(e,t){const n=t.target==="openAi",r={type:"object",properties:{}},o=[],s=e.shape();for(const i in s){let l=s[i];if(l===void 0||l._def===void 0)continue;let u=vy(l);u&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);const c=ae(l._def,{...t,currentPath:[...t.currentPath,"properties",i],propertyPath:[...t.currentPath,"properties",i]});c!==void 0&&(r.properties[i]=c,u||o.push(i))}o.length&&(r.required=o);const a=yy(e,t);return a!==void 0&&(r.additionalProperties=a),r}function yy(e,t){if(e.catchall._def.typeName!=="ZodNever")return ae(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}}function vy(e){try{return e.isOptional()}catch{return!0}}const _y=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return ae(e.innerType._def,t);const n=ae(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Ke(t)},n]}:Ke(t)},wy=(e,t)=>{if(t.pipeStrategy==="input")return ae(e.in._def,t);if(t.pipeStrategy==="output")return ae(e.out._def,t);const n=ae(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=ae(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}};function by(e,t){return ae(e.type._def,t)}function xy(e,t){const r={type:"array",uniqueItems:!0,items:ae(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ue(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ue(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function ky(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>ae(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:ae(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>ae(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function Ty(e){return{not:Ke(e)}}function Sy(e){return Ke(e)}const Iy=(e,t)=>ae(e.innerType._def,t),Cy=(e,t,n)=>{switch(t){case M.ZodString:return dl(e,n);case M.ZodNumber:return my(e,n);case M.ZodObject:return gy(e,n);case M.ZodBigInt:return Yg(e,n);case M.ZodBoolean:return Xg();case M.ZodDate:return cl(e,n);case M.ZodUndefined:return Ty(n);case M.ZodNull:return py(n);case M.ZodArray:return Kg(e,n);case M.ZodUnion:case M.ZodDiscriminatedUnion:return hy(e,n);case M.ZodIntersection:return sy(e,n);case M.ZodTuple:return ky(e,n);case M.ZodRecord:return hl(e,n);case M.ZodLiteral:return ay(e,n);case M.ZodEnum:return ry(e);case M.ZodNativeEnum:return cy(e);case M.ZodNullable:return fy(e,n);case M.ZodOptional:return _y(e,n);case M.ZodMap:return uy(e,n);case M.ZodSet:return xy(e,n);case M.ZodLazy:return()=>e.getter()._def;case M.ZodPromise:return by(e,n);case M.ZodNaN:case M.ZodNever:return dy(n);case M.ZodEffects:return ny(e,n);case M.ZodAny:return Ke(n);case M.ZodUnknown:return Sy(n);case M.ZodDefault:return ty(e,n);case M.ZodBranded:return ul(e,n);case M.ZodReadonly:return Iy(e,n);case M.ZodCatch:return Qg(e,n);case M.ZodPipeline:return wy(e,n);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(r=>{})()}};function ae(e,t,n=!1){var i;const r=t.seen.get(e);if(t.override){const l=(i=t.override)==null?void 0:i.call(t,e,t,r,n);if(l!==wg)return l}if(r&&!n){const l=Ey(r,t);if(l!==void 0)return l}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const s=Cy(e,e.typeName,t),a=typeof s=="function"?ae(s(),t):s;if(a&&Ry(e,t,a),t.postProcess){const l=t.postProcess(a,e,t);return o.jsonSchema=a,l}return o.jsonSchema=a,a}const Ey=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Ki(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`),Ke(t)):t.$refStrategy==="seen"?Ke(t):void 0}},Ry=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Ay=(e,t)=>{const n=xg(t);let r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[u,c])=>({...l,[u]:ae(c._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??Ke(n)}),{}):void 0;const o=typeof t=="string"?t:(t==null?void 0:t.nameStrategy)==="title"||t==null?void 0:t.name,s=ae(e._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??Ke(n),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(s.title=a),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const i=o===void 0?r?{...s,[n.definitionPath]:r}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:s}};return n.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function Go(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}async function Oy(e,t){if(e==null)return Promise.resolve();const n=t==null?void 0:t.abortSignal;return new Promise((r,o)=>{if(n!=null&&n.aborted){o(ml());return}const s=setTimeout(()=>{a(),r()},e),a=()=>{clearTimeout(s),n==null||n.removeEventListener("abort",i)},i=()=>{a(),o(ml())};n==null||n.addEventListener("abort",i)})}function ml(){return new DOMException("Delay was aborted","AbortError")}function Un(e){return Object.fromEntries([...e.headers])}var Ln=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const s=n.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=n[Math.random()*s|0];return a.join("")};if(e==null)return o;if(n.includes(r))throw new _o({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},Ny=Ln();function Wo(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function Qt(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var My=["fetch failed","failed to fetch"];function gl({error:e,url:t,requestBodyValues:n}){if(Qt(e))return e;if(e instanceof TypeError&&My.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new pe({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}function yl(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!=null))}var Py=()=>globalThis.fetch,$y=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:o,fetch:s=Py()})=>{try{const a=await s(e,{method:"GET",headers:yl(t),signal:o}),i=Un(a);if(!a.ok){let l;try{l=await r({response:a,url:e,requestBodyValues:{}})}catch(u){throw Qt(u)||pe.isInstance(u)?u:new pe({message:"Failed to process error response",cause:u,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await n({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Qt(l)||pe.isInstance(l))?l:new pe({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw gl({error:a,url:e,requestBodyValues:{}})}};function zy({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))}function Dr({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}var jy=/"__proto__"\s*:/,Dy=/"constructor"\s*:/;function Zy(e){const t=JSON.parse(e);return t===null||typeof t!="object"||jy.test(e)===!1&&Dy.test(e)===!1?t:Uy(t)}function Uy(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}function vl(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Zy(e)}finally{Error.stackTraceLimit=t}}var Zr=Symbol.for("vercel.ai.validator");function Ly(e){return{[Zr]:!0,validate:e}}function qy(e){return typeof e=="object"&&e!==null&&Zr in e&&e[Zr]===!0&&"validate"in e}function By(e){return qy(e)?e:Vy(e)}function Vy(e){return Ly(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new yt({value:t,cause:n.issues})}})}async function Ko({value:e,schema:t}){const n=await qn({value:e,schema:t});if(!n.success)throw yt.wrap({value:e,cause:n.error});return n.value}async function qn({value:e,schema:t}){const n=By(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const r=await n.validate(e);return r.success?{success:!0,value:r.value,rawValue:e}:{success:!1,error:yt.wrap({value:e,cause:r.error}),rawValue:e}}catch(r){return{success:!1,error:yt.wrap({value:e,cause:r}),rawValue:e}}}async function Fy({text:e,schema:t}){try{const n=vl(e);return t==null?n:Ko({value:n,schema:t})}catch(n){throw zt.isInstance(n)||yt.isInstance(n)?n:new zt({text:e,cause:n})}}async function fn({text:e,schema:t}){try{const n=vl(e);return t==null?{success:!0,value:n,rawValue:n}:await qn({value:n,schema:t})}catch(n){return{success:!1,error:zt.isInstance(n)?n:new zt({text:e,cause:n}),rawValue:void 0}}}function Hy({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new yr).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await fn({text:n,schema:t}))}}))}var Jy=()=>globalThis.fetch,Yo=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Gy({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),Gy=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:s,fetch:a=Jy()})=>{try{const i=await a(e,{method:"POST",headers:yl(t),body:n.content,signal:s}),l=Un(i);if(!i.ok){let u;try{u=await o({response:i,url:e,requestBodyValues:n.values})}catch(c){throw Qt(c)||pe.isInstance(c)?c:new pe({message:"Failed to process error response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw u.value}try{return await r({response:i,url:e,requestBodyValues:n.values})}catch(u){throw u instanceof Error&&(Qt(u)||pe.isInstance(u))?u:new pe({message:"Failed to process successful response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(i){throw gl({error:i,url:e,requestBodyValues:n.values})}};function YT(e){return e}function _l(e){return{...e,type:"dynamic"}}async function en(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var Ur=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:s})=>{const a=await r.text(),i=Un(r);if(a.trim()==="")return{responseHeaders:i,value:new pe({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,isRetryable:n==null?void 0:n(r)})};try{const l=await Fy({text:a,schema:e});return{responseHeaders:i,value:new pe({message:t(l),url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,data:l,isRetryable:n==null?void 0:n(r,l)})}}catch{return{responseHeaders:i,value:new pe({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,isRetryable:n==null?void 0:n(r)})}}},Wy=e=>async({response:t})=>{const n=Un(t);if(t.body==null)throw new Ta({});return{responseHeaders:n,value:Hy({stream:t.body,schema:e})}},Xo=e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),s=await fn({text:o,schema:e}),a=Un(t);if(!s.success)throw new pe({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}};function Ky(e,t){var n;const r=(n=void 0)!=null?n:!1;return Bn(Ay(e,{$refStrategy:r?"root":"none",target:"jsonSchema7"}),{validate:async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function Yy(e,t){var n;const r=(n=void 0)!=null?n:!1,o=hm(e,{target:"draft-7",io:"output",reused:r?"ref":"inline"});return Bn(o,{validate:async s=>{const a=await $i(e,s);return a.success?{success:!0,value:a.data}:{success:!1,error:a.error}}})}function Xy(e){return"_zod"in e}function Qy(e,t){return Xy(e)?Yy(e):Ky(e)}var Qo=Symbol.for("vercel.ai.schema");function Bn(e,{validate:t}={}){return{[Qo]:!0,_type:void 0,[Zr]:!0,jsonSchema:e,validate:t}}function ev(e){return typeof e=="object"&&e!==null&&Qo in e&&e[Qo]===!0&&"jsonSchema"in e&&"validate"in e}function Lr(e){return e==null?Bn({properties:{},additionalProperties:!1}):ev(e)?e:Qy(e)}var{btoa:tv,atob:nv}=globalThis;function wl(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=nv(t);return Uint8Array.from(n,r=>r.codePointAt(0))}function es(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return tv(t)}function rv(e){return e==null?void 0:e.replace(/\/$/,"")}function ov(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*bl({execute:e,input:t,options:n}){const r=e(t,n);if(ov(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}}var sv="vercel.ai.gateway.error",ts=Symbol.for(sv),xl,kl,Qe=class Qd extends(kl=Error,xl=ts,kl){constructor({message:t,statusCode:n=500,cause:r}){super(t),this[xl]=!0,this.statusCode=n,this.cause=r}static isInstance(t){return Qd.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&ts in t&&t[ts]===!0}},Tl="GatewayAuthenticationError",av=`vercel.ai.gateway.error.${Tl}`,Sl=Symbol.for(av),Il,Cl,qr=class ep extends(Cl=Qe,Il=Sl,Cl){constructor({message:t="Authentication failed",statusCode:n=401,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[Il]=!0,this.name=Tl,this.type="authentication_error"}static isInstance(t){return Qe.hasMarker(t)&&Sl in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r="Authentication failed",statusCode:o=401,cause:s}){let a;return t?a=`AI Gateway authentication failed: Invalid API key provided.
39
39
 
40
40
  The token is expected to be provided via the 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:n?a=`AI Gateway authentication failed: Invalid OIDC token provided.
41
41
 
@@ -59,11 +59,11 @@ The token is expected to be provided via the 'VERCEL_OIDC_TOKEN' environment var
59
59
  - make sure your Vercel project settings have OIDC enabled
60
60
  - if running locally with 'vercel dev', the token is automatically obtained and refreshed
61
61
  - if running locally with your own dev server, run 'vercel env pull' to fetch the token
62
- - in production/preview, the token is automatically obtained and refreshed`,new tp({message:a,statusCode:o,cause:s})}},El="GatewayInvalidRequestError",lv=`vercel.ai.gateway.error.${El}`,Rl=Symbol.for(lv),Al,Ol,uv=class extends(Ol=Qe,Al=Rl,Ol){constructor({message:e="Invalid request",statusCode:t=400,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Al]=!0,this.name=El,this.type="invalid_request_error"}static isInstance(e){return Qe.hasMarker(e)&&Rl in e}},Nl="GatewayRateLimitError",cv=`vercel.ai.gateway.error.${Nl}`,Ml=Symbol.for(cv),Pl,$l,dv=class extends($l=Qe,Pl=Ml,$l){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Pl]=!0,this.name=Nl,this.type="rate_limit_exceeded"}static isInstance(e){return Qe.hasMarker(e)&&Ml in e}},zl="GatewayModelNotFoundError",pv=`vercel.ai.gateway.error.${zl}`,jl=Symbol.for(pv),hv=x({modelId:h()}),Dl,Zl,Ul=class extends(Zl=Qe,Dl=jl,Zl){constructor({message:e="Model not found",statusCode:t=404,modelId:n,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Dl]=!0,this.name=zl,this.type="model_not_found",this.modelId=n}static isInstance(e){return Qe.hasMarker(e)&&jl in e}},Ll="GatewayInternalServerError",fv=`vercel.ai.gateway.error.${Ll}`,ql=Symbol.for(fv),Bl,Vl,Fl=class extends(Vl=Qe,Bl=ql,Vl){constructor({message:e="Internal server error",statusCode:t=500,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Bl]=!0,this.name=Ll,this.type="internal_server_error"}static isInstance(e){return Qe.hasMarker(e)&&ql in e}},Hl="GatewayResponseError",mv=`vercel.ai.gateway.error.${Hl}`,Jl=Symbol.for(mv),Gl,Wl,gv=class extends(Wl=Qe,Gl=Jl,Wl){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:n,validationError:r,cause:o}={}){super({message:e,statusCode:t,cause:o}),this[Gl]=!0,this.name=Hl,this.type="response_error",this.response=n,this.validationError=r}static isInstance(e){return Qe.hasMarker(e)&&Jl in e}};function Kl({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:r,authMethod:o}){const s=yv.safeParse(e);if(!s.success)return new gv({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:s.error,cause:r});const a=s.data,i=a.error.type,l=a.error.message;switch(i){case"authentication_error":return qr.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:r});case"invalid_request_error":return new uv({message:l,statusCode:t,cause:r});case"rate_limit_exceeded":return new dv({message:l,statusCode:t,cause:r});case"model_not_found":{const u=hv.safeParse(a.error.param);return new Ul({message:l,statusCode:t,modelId:u.success?u.data.modelId:void 0,cause:r})}case"internal_server_error":return new Fl({message:l,statusCode:t,cause:r});default:return new Fl({message:l,statusCode:t,cause:r})}}var yv=x({error:x({message:h(),type:h().nullish(),param:Le().nullish(),code:ee([h(),R()]).nullish()})});function Vn(e,t){var n;return Qe.isInstance(e)?e:pe.isInstance(e)?Kl({response:vv(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):Kl({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function vv(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var Yl="ai-gateway-auth-method";function Br(e){const t=_v.safeParse(e[Yl]);return t.success?t.data:void 0}var _v=ee([A("api-key"),A("oidc")]),wv=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await zy({url:`${this.config.baseURL}/config`,headers:await en(this.config.headers()),successfulResponseHandler:Xo(Tv),failedResponseHandler:Ur({errorSchema:pt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw Vn(e)}}},bv=x({specificationVersion:A("v2"),provider:h(),modelId:h()}),xv=x({input:h(),output:h()}),kv=x({id:h(),name:h(),description:h().nullish(),pricing:xv.nullish(),specification:bv}),Tv=x({models:Z(kv)}),Sv=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...n}=e;return{args:this.maybeEncodeFileParts(n),warnings:[]}}async doGenerate(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,o=await en(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await Yo({url:this.getUrl(),headers:Go(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await en(this.config.o11yHeaders)),body:t,successfulResponseHandler:Xo(pt()),failedResponseHandler:Ur({errorSchema:pt(),errorToMessage:l=>l}),...r&&{abortSignal:r},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:s,body:i},warnings:n}}catch(s){throw Vn(s,Br(o))}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,o=await en(this.config.headers());try{const{value:s,responseHeaders:a}=await Yo({url:this.getUrl(),headers:Go(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await en(this.config.o11yHeaders)),body:t,successfulResponseHandler:Ky(pt()),failedResponseHandler:Ur({errorSchema:pt(),errorToMessage:i=>i}),...r&&{abortSignal:r},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(i){n.length>0&&i.enqueue({type:"stream-start",warnings:n})},transform(i,l){if(i.success){const u=i.value;if(u.type==="raw"&&!e.includeRawChunks)return;u.type==="response-metadata"&&u.timestamp&&typeof u.timestamp=="string"&&(u.timestamp=new Date(u.timestamp)),l.enqueue(u)}else l.error(i.error)}})),request:{body:t},response:{headers:a}}}catch(s){throw Vn(s,Br(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const n of t.content)if(this.isFilePart(n)){const r=n;if(r.data instanceof Uint8Array){const o=Uint8Array.from(r.data),s=Buffer.from(o).toString("base64");r.data=new URL(`data:${r.mediaType||"application/octet-stream"};base64,${s}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"2","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},Iv=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;const s=await en(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await Yo({url:this.getUrl(),headers:Go(s,t??{},this.getModelConfigHeaders(),await en(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...r??{}},successfulResponseHandler:Xo(Cv),failedResponseHandler:Ur({errorSchema:pt(),errorToMessage:u=>u}),...n&&{abortSignal:n},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(o=i.usage)!=null?o:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:l}}}catch(a){throw Vn(a,Br(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},Cv=x({embeddings:Z(Z(R())),usage:x({tokens:R()}).nullish(),providerMetadata:We(h(),We(h(),Le())).optional()});async function Ev(){var e,t;const n=(t=(e=Xl().headers)==null?void 0:e["x-vercel-oidc-token"])!=null?t:process.env.VERCEL_OIDC_TOKEN;if(!n)throw new qr({message:"OIDC token not available",statusCode:401});return n}async function Rv(){var e;return(e=Xl().headers)==null?void 0:e["x-vercel-id"]}var Av=Symbol.for("@vercel/request-context");function Xl(){var e,t,n;return(n=(t=(e=globalThis[Av])==null?void 0:e.get)==null?void 0:t.call(e))!=null?n:{}}var Ov="0.0.1";function Nv(e={}){var t,n;let r=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const i=(n=ov(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const d=await Pv(e);if(d)return{Authorization:`Bearer ${d.token}`,"ai-gateway-protocol-version":Ov,[Yl]:d.authMethod,...e.headers};throw qr.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},u=()=>{const d=Dr({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),f=Dr({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),y=Dr({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const v=await Rv();return{...d&&{"ai-o11y-deployment-id":d},...f&&{"ai-o11y-environment":f},...y&&{"ai-o11y-region":y},...v&&{"ai-o11y-request-id":v}}}},c=d=>new Sv(d,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:u()}),w=async()=>{var d,f,y;const v=(y=(f=(d=e._internal)==null?void 0:d.currentDate)==null?void 0:f.call(d).getTime())!=null?y:Date.now();return(!r||v-a>s)&&(a=v,r=new wv({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(p=>(o=p,p)).catch(async p=>{throw Vn(p,Br(await l()))})),o?Promise.resolve(o):r},_=function(d){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return c(d)};return _.getAvailableModels=w,_.imageModel=d=>{throw new wo({modelId:d,modelType:"imageModel"})},_.languageModel=c,_.textEmbeddingModel=d=>new Iv(d,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:u()}),_}var Mv=Nv();async function Pv(e){const t=Dr({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await Ev(),authMethod:"oidc"}}catch{return null}}var $v=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},tn="1.9.0",Ql=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function zv(e){var t=new Set([e]),n=new Set,r=e.match(Ql);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 function(l){return l===e};function s(i){return n.add(i),!1}function a(i){return t.add(i),!0}return function(l){if(t.has(l))return!0;if(n.has(l))return!1;var u=l.match(Ql);if(!u)return s(l);var c={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return c.prerelease!=null||o.major!==c.major?s(l):o.major===0?o.minor===c.minor&&o.patch<=c.patch?a(l):s(l):o.minor<=c.minor?a(l):s(l)}}var jv=zv(tn),Dv=tn.split(".")[0],Fn=Symbol.for("opentelemetry.js.api."+Dv),Hn=$v;function Jn(e,t,n,r){var o;r===void 0&&(r=!1);var s=Hn[Fn]=(o=Hn[Fn])!==null&&o!==void 0?o:{version:tn};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!==tn){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+tn);return n.error(a.stack||a.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+tn+"."),!0}function nn(e){var t,n,r=(t=Hn[Fn])===null||t===void 0?void 0:t.version;if(!(!r||!jv(r)))return(n=Hn[Fn])===null||n===void 0?void 0:n[e]}function Gn(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+tn+".");var n=Hn[Fn];n&&delete n[e]}var Zv=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(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},Uv=function(e,t,n){if(n||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))},Lv=function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Wn("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Wn("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Wn("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Wn("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Wn("verbose",this._namespace,t)},e}();function Wn(e,t,n){var r=nn("diag");if(r)return n.unshift(t),r[e].apply(r,Uv([],Zv(n),!1))}var et;(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"})(et||(et={}));function qv(e,t){e<et.NONE?e=et.NONE:e>et.ALL&&(e=et.ALL),t=t||{};function n(r,o){var s=t[r];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return{error:n("error",et.ERROR),warn:n("warn",et.WARN),info:n("info",et.INFO),debug:n("debug",et.DEBUG),verbose:n("verbose",et.VERBOSE)}}var Bv=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(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},Vv=function(e,t,n){if(n||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))},Fv="diag",wt=function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=nn("diag");if(i)return i[o].apply(i,Vv([],Bv(s),!1))}}var n=this,r=function(o,s){var a,i,l;if(s===void 0&&(s={logLevel:et.INFO}),o===n){var u=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=u.stack)!==null&&a!==void 0?a:u.message),!1}typeof s=="number"&&(s={logLevel:s});var c=nn("diag"),w=qv((i=s.logLevel)!==null&&i!==void 0?i:et.INFO,o);if(c&&!s.suppressOverrideMessage){var _=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";c.warn("Current logger will be overwritten from "+_),w.warn("Current logger will overwrite one already registered from "+_)}return Jn("diag",w,n,!0)};n.setLogger=r,n.disable=function(){Gn(Fv,n)},n.createComponentLogger=function(o){return new Lv(o)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e}(),Hv=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(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},Jv=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},Gv=function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var n=this._entries.get(t);if(n)return Object.assign({},n)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var n=Hv(t,2),r=n[0],o=n[1];return[r,o]})},e.prototype.setEntry=function(t,n){var r=new e(this._entries);return r._entries.set(t,n),r},e.prototype.removeEntry=function(t){var n=new e(this._entries);return n._entries.delete(t),n},e.prototype.removeEntries=function(){for(var t,n,r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];var s=new e(this._entries);try{for(var a=Jv(r),i=a.next();!i.done;i=a.next()){var l=i.value;s._entries.delete(l)}}catch(u){t={error:u}}finally{try{i&&!i.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return s},e.prototype.clear=function(){return new e},e}();wt.instance();function Wv(e){return e===void 0&&(e={}),new Gv(new Map(Object.entries(e)))}function eu(e){return Symbol.for(e)}var Kv=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 e}(),Yv=new Kv,rn=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(r[s]=o[s])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}(),Xv=function(){function e(){}return e.prototype.createGauge=function(t,n){return l_},e.prototype.createHistogram=function(t,n){return u_},e.prototype.createCounter=function(t,n){return i_},e.prototype.createUpDownCounter=function(t,n){return c_},e.prototype.createObservableGauge=function(t,n){return p_},e.prototype.createObservableCounter=function(t,n){return d_},e.prototype.createObservableUpDownCounter=function(t,n){return h_},e.prototype.addBatchObservableCallback=function(t,n){},e.prototype.removeBatchObservableCallback=function(t){},e}(),Vr=function(){function e(){}return e}(),Qv=function(e){rn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(n,r){},t}(Vr),e_=function(e){rn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(n,r){},t}(Vr),t_=function(e){rn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(n,r){},t}(Vr),n_=function(e){rn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(n,r){},t}(Vr),ns=function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e}(),r_=function(e){rn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(ns),o_=function(e){rn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(ns),s_=function(e){rn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(ns),a_=new Xv,i_=new Qv,l_=new t_,u_=new n_,c_=new e_,d_=new r_,p_=new o_,h_=new s_,f_={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},m_={set:function(e,t,n){e!=null&&(e[t]=n)}},g_=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(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},y_=function(e,t,n){if(n||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))},v_=function(){function e(){}return e.prototype.active=function(){return Yv},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,y_([r],g_(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}(),__=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(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},w_=function(e,t,n){if(n||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))},rs="context",b_=new v_,Fr=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Jn(rs,t,wt.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,w_([t,n,r],__(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return nn(rs)||b_},e.prototype.disable=function(){this._getContextManager().disable(),Gn(rs,wt.instance())},e}(),os;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(os||(os={}));var tu="0000000000000000",nu="00000000000000000000000000000000",x_={traceId:nu,spanId:tu,traceFlags:os.NONE},Kn=function(){function e(t){t===void 0&&(t=x_),this._spanContext=t}return 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}(),ss=eu("OpenTelemetry Context Key SPAN");function as(e){return e.getValue(ss)||void 0}function k_(){return as(Fr.getInstance().active())}function is(e,t){return e.setValue(ss,t)}function T_(e){return e.deleteValue(ss)}function S_(e,t){return is(e,new Kn(t))}function ru(e){var t;return(t=as(e))===null||t===void 0?void 0:t.spanContext()}var I_=/^([0-9a-f]{32})$/i,C_=/^[0-9a-f]{16}$/i;function E_(e){return I_.test(e)&&e!==nu}function R_(e){return C_.test(e)&&e!==tu}function ou(e){return E_(e.traceId)&&R_(e.spanId)}function A_(e){return new Kn(e)}var ls=Fr.getInstance(),su=function(){function e(){}return e.prototype.startSpan=function(t,n,r){r===void 0&&(r=ls.active());var o=!!(n!=null&&n.root);if(o)return new Kn;var s=r&&ru(r);return O_(s)&&ou(s)?new Kn(s):new Kn},e.prototype.startActiveSpan=function(t,n,r,o){var s,a,i;if(!(arguments.length<2)){arguments.length===2?i=n:arguments.length===3?(s=n,i=r):(s=n,a=r,i=o);var l=a??ls.active(),u=this.startSpan(t,s,l),c=is(l,u);return ls.with(c,i,void 0,u)}},e}();function O_(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var N_=new su,M_=function(){function e(t,n,r,o){this._provider=t,this.name=n,this.version=r,this.options=o}return 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):N_},e}(),P_=function(){function e(){}return e.prototype.getTracer=function(t,n,r){return new su},e}(),$_=new P_,au=function(){function e(){}return e.prototype.getTracer=function(t,n,r){var o;return(o=this.getDelegateTracer(t,n,r))!==null&&o!==void 0?o:new M_(this,t,n,r)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:$_},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}(),Hr;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Hr||(Hr={})),Fr.getInstance(),wt.instance();var z_=function(){function e(){}return e.prototype.getMeter=function(t,n,r){return a_},e}(),j_=new z_,us="metrics",D_=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Jn(us,t,wt.instance())},e.prototype.getMeterProvider=function(){return nn(us)||j_},e.prototype.getMeter=function(t,n,r){return this.getMeterProvider().getMeter(t,n,r)},e.prototype.disable=function(){Gn(us,wt.instance())},e}();D_.getInstance();var Z_=function(){function e(){}return e.prototype.inject=function(t,n){},e.prototype.extract=function(t,n){return t},e.prototype.fields=function(){return[]},e}(),cs=eu("OpenTelemetry Baggage Key");function iu(e){return e.getValue(cs)||void 0}function U_(){return iu(Fr.getInstance().active())}function L_(e,t){return e.setValue(cs,t)}function q_(e){return e.deleteValue(cs)}var ds="propagation",B_=new Z_,V_=function(){function e(){this.createBaggage=Wv,this.getBaggage=iu,this.getActiveBaggage=U_,this.setBaggage=L_,this.deleteBaggage=q_}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Jn(ds,t,wt.instance())},e.prototype.inject=function(t,n,r){return r===void 0&&(r=m_),this._getGlobalPropagator().inject(t,n,r)},e.prototype.extract=function(t,n,r){return r===void 0&&(r=f_),this._getGlobalPropagator().extract(t,n,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Gn(ds,wt.instance())},e.prototype._getGlobalPropagator=function(){return nn(ds)||B_},e}();V_.getInstance();var ps="trace",F_=function(){function e(){this._proxyTracerProvider=new au,this.wrapSpanContext=A_,this.isSpanContextValid=ou,this.deleteSpan=T_,this.getSpan=as,this.getActiveSpan=k_,this.getSpanContext=ru,this.setSpan=is,this.setSpanContext=S_}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=Jn(ps,this._proxyTracerProvider,wt.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return nn(ps)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){Gn(ps,wt.instance()),this._proxyTracerProvider=new au},e}(),H_=F_.getInstance(),J_=Object.defineProperty,G_=(e,t)=>{for(var n in t)J_(e,n,{get:t[n],enumerable:!0})},lu="AI_NoOutputSpecifiedError",uu=`vercel.ai.error.${lu}`,W_=Symbol.for(uu),cu,du=class extends G{constructor({message:e="No output specified."}={}){super({name:lu,message:e}),this[cu]=!0}static isInstance(e){return G.hasMarker(e,uu)}};cu=W_;var pu="AI_InvalidArgumentError",hu=`vercel.ai.error.${pu}`,K_=Symbol.for(hu),fu,bt=class extends G{constructor({parameter:e,value:t,message:n}){super({name:pu,message:`Invalid argument for parameter ${e}: ${n}`}),this[fu]=!0,this.parameter=e,this.value=t}static isInstance(e){return G.hasMarker(e,hu)}};fu=K_;var mu="AI_InvalidToolInputError",gu=`vercel.ai.error.${mu}`,Y_=Symbol.for(gu),yu,vu=class extends G{constructor({toolInput:e,toolName:t,cause:n,message:r=`Invalid input for tool ${t}: ${ln(n)}`}){super({name:mu,message:r,cause:n}),this[yu]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return G.hasMarker(e,gu)}};yu=Y_;var X_="AI_MCPClientError",_u=`vercel.ai.error.${X_}`,Q_=Symbol.for(_u),wu,$e=class extends G{constructor({name:e="MCPClientError",message:t,cause:n}){super({name:e,message:t,cause:n}),this[wu]=!0}static isInstance(e){return G.hasMarker(e,_u)}};wu=Q_;var bu="AI_NoObjectGeneratedError",xu=`vercel.ai.error.${bu}`,ew=Symbol.for(xu),ku,Tu=class extends G{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:o,finishReason:s}){super({name:bu,message:e,cause:t}),this[ku]=!0,this.text=n,this.response=r,this.usage=o,this.finishReason=s}static isInstance(e){return G.hasMarker(e,xu)}};ku=ew;var Su="AI_NoOutputGeneratedError",Iu=`vercel.ai.error.${Su}`,tw=Symbol.for(Iu),Cu,nw=class extends G{constructor({message:e="No output generated.",cause:t}={}){super({name:Su,message:e,cause:t}),this[Cu]=!0}static isInstance(e){return G.hasMarker(e,Iu)}};Cu=tw;var Eu="AI_NoSuchToolError",Ru=`vercel.ai.error.${Eu}`,rw=Symbol.for(Ru),Au,hs=class extends G{constructor({toolName:e,availableTools:t=void 0,message:n=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:Eu,message:n}),this[Au]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return G.hasMarker(e,Ru)}};Au=rw;var Ou="AI_ToolCallRepairError",Nu=`vercel.ai.error.${Ou}`,ow=Symbol.for(Nu),Mu,sw=class extends G{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${ln(e)}`}){super({name:Ou,message:n,cause:e}),this[Mu]=!0,this.originalError=t}static isInstance(e){return G.hasMarker(e,Nu)}};Mu=ow;var aw=class extends G{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},Pu="AI_InvalidMessageRoleError",$u=`vercel.ai.error.${Pu}`,iw=Symbol.for($u),zu,lw=class extends G{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Pu,message:t}),this[zu]=!0,this.role=e}static isInstance(e){return G.hasMarker(e,$u)}};zu=iw;var ju="AI_DownloadError",Du=`vercel.ai.error.${ju}`,uw=Symbol.for(Du),Zu,fs=class extends G{constructor({url:e,statusCode:t,statusText:n,cause:r,message:o=r==null?`Failed to download ${e}: ${t} ${n}`:`Failed to download ${e}: ${r}`}){super({name:ju,message:o,cause:r}),this[Zu]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return G.hasMarker(e,Du)}};Zu=uw;var Uu="AI_RetryError",Lu=`vercel.ai.error.${Uu}`,cw=Symbol.for(Lu),qu,Bu=class extends G{constructor({message:e,reason:t,errors:n}){super({name:Uu,message:e}),this[qu]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return G.hasMarker(e,Lu)}};qu=cw;function Jr(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new aw({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return dw().languageModel(e)}function dw(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:Mv}var pw=[{mediaType:"image/gif",bytesPrefix:[71,73,70],base64Prefix:"R0lG"},{mediaType:"image/png",bytesPrefix:[137,80,78,71],base64Prefix:"iVBORw"},{mediaType:"image/jpeg",bytesPrefix:[255,216],base64Prefix:"/9j/"},{mediaType:"image/webp",bytesPrefix:[82,73,70,70],base64Prefix:"UklGRg"},{mediaType:"image/bmp",bytesPrefix:[66,77],base64Prefix:"Qk"},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0],base64Prefix:"SUkqAA"},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42],base64Prefix:"TU0AKg"},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102],base64Prefix:"AAAAIGZ0eXBhdmlm"},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99],base64Prefix:"AAAAIGZ0eXBoZWlj"}],hw=e=>{const t=typeof e=="string"?wl(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function fw(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?hw(e):e}function mw({data:e,signatures:t}){const n=fw(e);for(const r of t)if(typeof n=="string"?n.startsWith(r.base64Prefix):n.length>=r.bytesPrefix.length&&r.bytesPrefix.every((o,s)=>n[s]===o))return r.mediaType}async function gw({url:e}){var t;const n=e.toString();try{const r=await fetch(n);if(!r.ok)throw new fs({url:n,statusCode:r.status,statusText:r.statusText});return{data:new Uint8Array(await r.arrayBuffer()),mediaType:(t=r.headers.get("content-type"))!=null?t:void 0}}catch(r){throw fs.isInstance(r)?r:new fs({url:n,cause:r})}}function yw(e){try{const[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}var Vu=ee([h(),Ir(Uint8Array),Ir(ArrayBuffer),yg(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function Fu(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}=yw(e.toString());if(t==null||n==null)throw new G({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}function vw(e){return typeof e=="string"?e:e instanceof ArrayBuffer?es(new Uint8Array(e)):es(e)}async function Hu({prompt:e,supportedUrls:t,downloadImplementation:n=gw}){const r=await ww(e.messages,n,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(o=>_w({message:o,downloadedAssets:r}))]}function _w({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=>bw(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!=="").map(r=>{const o=r.providerOptions;switch(r.type){case"file":{const{data:s,mediaType:a}=Fu(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:r.output,providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.map(r=>({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:r.output,providerOptions:r.providerOptions})),providerOptions:e.providerOptions};default:{const r=n;throw new lw({role:r})}}}async function ww(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 i=(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:i,data:l}}).filter(s=>s.data instanceof URL&&s.mediaType!=null&&!jy({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:n})).map(s=>s.data),o=await Promise.all(r.map(async s=>({url:s,data:await t({url:s})})));return Object.fromEntries(o.map(({url:s,data:a})=>[s.toString(),a]))}function bw(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}=Fu(r);let i=a??e.mediaType,l=s;if(l instanceof URL){const u=t[l.toString()];u&&(l=u.data,i??(i=u.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(n=mw({data:l,signatures:pw}))!=null?n:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function ms({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,seed:a,stopSequences:i}){if(e!=null){if(!Number.isInteger(e))throw new bt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new bt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new bt({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new bt({parameter:"topP",value:n,message:"topP must be a number"});if(r!=null&&typeof r!="number")throw new bt({parameter:"topK",value:r,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new bt({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new bt({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new bt({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,stopSequences:i,seed:a}}function xw(e){return e!=null&&Object.keys(e).length>0}function Ju({tools:e,toolChoice:t,activeTools:n}){return xw(e)?{tools:(n!=null?Object.entries(e).filter(([o])=>n.includes(o)):Object.entries(e)).map(([o,s])=>{const a=s.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:o,description:s.description,inputSchema:Lr(s.inputSchema).jsonSchema,providerOptions:s.providerOptions};case"provider-defined":return{type:"provider-defined",name:o,id:s.id,args:s.args};default:{const i=a;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var Yn=Ji(()=>ee([Hm(),h(),R(),re(),We(h(),Yn),Z(Yn)])),xe=We(h(),We(h(),Yn)),Gu=x({type:A("text"),text:h(),providerOptions:xe.optional()}),kw=x({type:A("image"),image:ee([Vu,Ir(URL)]),mediaType:h().optional(),providerOptions:xe.optional()}),Wu=x({type:A("file"),data:ee([Vu,Ir(URL)]),filename:h().optional(),mediaType:h(),providerOptions:xe.optional()}),Tw=x({type:A("reasoning"),text:h(),providerOptions:xe.optional()}),Sw=x({type:A("tool-call"),toolCallId:h(),toolName:h(),input:Le(),providerOptions:xe.optional(),providerExecuted:re().optional()}),Iw=cn("type",[x({type:A("text"),value:h()}),x({type:A("json"),value:Yn}),x({type:A("error-text"),value:h()}),x({type:A("error-json"),value:Yn}),x({type:A("content"),value:Z(ee([x({type:A("text"),text:h()}),x({type:A("media"),data:h(),mediaType:h()})]))})]),Ku=x({type:A("tool-result"),toolCallId:h(),toolName:h(),output:Iw,providerOptions:xe.optional()}),Cw=x({role:A("system"),content:h(),providerOptions:xe.optional()}),Ew=x({role:A("user"),content:ee([h(),Z(ee([Gu,kw,Wu]))]),providerOptions:xe.optional()}),Rw=x({role:A("assistant"),content:ee([h(),Z(ee([Gu,Wu,Tw,Sw,Ku]))]),providerOptions:xe.optional()}),Aw=x({role:A("tool"),content:Z(Ku),providerOptions:xe.optional()}),Ow=ee([Cw,Ew,Rw,Aw]);async function Yu(e){if(e.prompt==null&&e.messages==null)throw new Ht({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Ht({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string")throw new Ht({prompt:e,message:"system must be a string"});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 Ht({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Ht({prompt:e,message:"messages must not be empty"});const n=await qn({value:t,schema:Z(Ow)});if(!n.success)throw new Ht({prompt:e,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:n.error});return{messages:t,system:e.system}}function Xu(e){return qr.isInstance(e)||Ul.isInstance(e)?new G({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:e}):e}function mn({operationId:e,telemetry:t}){return{"operation.name":`${e}${(t==null?void 0:t.functionId)!=null?` ${t.functionId}`:""}`,"resource.name":t==null?void 0:t.functionId,"ai.operationId":e,"ai.telemetry.functionId":t==null?void 0:t.functionId}}function Qu({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,i])=>(s[`ai.settings.${a}`]=i,s),{}),...Object.entries((o=n==null?void 0:n.metadata)!=null?o:{}).reduce((s,[a,i])=>(s[`ai.telemetry.metadata.${a}`]=i,s),{}),...Object.entries(r??{}).reduce((s,[a,i])=>(i!==void 0&&(s[`ai.request.headers.${a}`]=i),s),{})}}var Nw={startSpan(){return Gr},startActiveSpan(e,t,n,r){if(typeof t=="function")return t(Gr);if(typeof n=="function")return n(Gr);if(typeof r=="function")return r(Gr)}},Gr={spanContext(){return Mw},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}},Mw={traceId:"",spanId:"",traceFlags:0};function ec({isEnabled:e=!1,tracer:t}={}){return e?t||H_.getTracer("ai"):Nw}function gn({name:e,tracer:t,attributes:n,fn:r,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:n},async s=>{try{const a=await r(s);return o&&s.end(),a}catch(a){try{gs(s,a)}finally{s.end()}throw a}})}function gs(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Hr.ERROR,message:t.message})):e.setStatus({code:Hr.ERROR})}function lt({telemetry:e,attributes:t}){return(e==null?void 0:e.isEnabled)!==!0?{}:Object.entries(t).reduce((n,[r,o])=>{if(o==null)return n;if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if((e==null?void 0:e.recordInputs)===!1)return n;const s=o.input();return s==null?n:{...n,[r]:s}}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if((e==null?void 0:e.recordOutputs)===!1)return n;const s=o.output();return s==null?n:{...n,[r]:s}}return{...n,[r]:o}},{})}function tc(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?vw(n.data):n.data}:n)})))}function nc(e,t){return{inputTokens:Xn(e.inputTokens,t.inputTokens),outputTokens:Xn(e.outputTokens,t.outputTokens),totalTokens:Xn(e.totalTokens,t.totalTokens),reasoningTokens:Xn(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:Xn(e.cachedInputTokens,t.cachedInputTokens)}}function Xn(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function ys(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function Pw({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}var $w=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async o=>rc(o,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r});async function rc(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:o},s=[]){try{return await e()}catch(a){if(Qt(a)||t===0)throw a;const i=Wo(a),l=[...s,a],u=l.length;if(u>t)throw new Bu({message:`Failed after ${u} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&pe.isInstance(a)&&a.isRetryable===!0&&u<=t)return await Ny(Pw({error:a,exponentialBackoffDelay:n}),{abortSignal:o}),rc(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:o},l);throw u===1?a:new Bu({message:`Failed after ${u} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function oc({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new bt({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new bt({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const n=e??2;return{maxRetries:n,retry:$w({maxRetries:n,abortSignal:t})}}function sc(e){const t=e.filter(n=>n.type==="text");if(t.length!==0)return t.map(n=>n.text).join("")}var ac=class{constructor({data:e,mediaType:t}){const n=e instanceof Uint8Array;this.base64Data=n?void 0:e,this.uint8ArrayData=n?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=es(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=wl(this.base64Data)),this.uint8ArrayData}},zw=class extends ac{constructor(e){super(e),this.type="file"}};async function ic({toolCall:e,tools:t,repairToolCall:n,system:r,messages:o}){try{if(t==null)throw new hs({toolName:e.toolName});try{return await lc({toolCall:e,tools:t})}catch(s){if(n==null||!(hs.isInstance(s)||vu.isInstance(s)))throw s;let a=null;try{a=await n({toolCall:e,tools:t,inputSchema:({toolName:i})=>{const{inputSchema:l}=t[i];return Lr(l).jsonSchema},system:r,messages:o,error:s})}catch(i){throw new sw({cause:i,originalError:s})}if(a==null)throw s;return await lc({toolCall:a,tools:t})}}catch(s){return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,dynamic:!0,invalid:!0,error:s}}}async function lc({toolCall:e,tools:t}){const n=e.toolName,r=t[n];if(r==null)throw new hs({toolName:e.toolName,availableTools:Object.keys(t)});const o=Lr(r.inputSchema),s=e.input.trim()===""?await qn({value:{},schema:o}):await fn({text:e.input,schema:o});if(s.success===!1)throw new vu({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}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var uc=class{constructor({content:e,finishReason:t,usage:n,warnings:r,request:o,response:s,providerMetadata:a}){this.content=e,this.finishReason=t,this.usage=n,this.warnings=r,this.request=o,this.response=s,this.providerMetadata=a}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!1)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic===!1)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function vs(e){return({steps:t})=>t.length===e}async function cc({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}function _s({output:e,tool:t,errorMode:n}){return n==="text"?{type:"error-text",value:ln(e)}:n==="json"?{type:"error-json",value:dc(e)}:t!=null&&t.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:dc(e)}}function dc(e){return e===void 0?null:e}function ws({content:e,tools:t}){const n=[],r=e.filter(s=>s.type!=="source").filter(s=>(s.type!=="tool-result"||s.providerExecuted)&&(s.type!=="tool-error"||s.providerExecuted)).filter(s=>s.type!=="text"||s.text.length>0).map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,providerOptions:s.providerMetadata};case"reasoning":return{type:"reasoning",text:s.text,providerOptions:s.providerMetadata};case"file":return{type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:_s({tool:t==null?void 0:t[s.toolName],output:s.output,errorMode:"none"}),providerExecuted:!0,providerOptions:s.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:_s({tool:t==null?void 0:t[s.toolName],output:s.error,errorMode:"json"}),providerOptions:s.providerMetadata}}});r.length>0&&n.push({role:"assistant",content:r});const o=e.filter(s=>s.type==="tool-result"||s.type==="tool-error").filter(s=>!s.providerExecuted).map(s=>({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:_s({tool:t==null?void 0:t[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"})}));return o.length>0&&n.push({role:"tool",content:o}),n}var jw=Ln({prefix:"aitxt",size:24});async function Dw({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:s,maxRetries:a,abortSignal:i,headers:l,stopWhen:u=vs(1),experimental_output:c,experimental_telemetry:w,providerOptions:_,experimental_activeTools:d,activeTools:f=d,experimental_prepareStep:y,prepareStep:v=y,experimental_repairToolCall:p,experimental_context:b,_internal:{generateId:g=jw,currentDate:m=()=>new Date}={},onStepFinish:E,...S}){const T=Jr(e),P=ys(u),{maxRetries:V,retry:H}=oc({maxRetries:a,abortSignal:i}),B=ms(S),oe=Qu({model:T,telemetry:w,headers:l,settings:{...B,maxRetries:V}}),F=await Yu({system:r,prompt:o,messages:s}),be=ec(w);try{return await gn({name:"ai.generateText",attributes:lt({telemetry:w,attributes:{...mn({operationId:"ai.generateText",telemetry:w}),...oe,"ai.model.provider":T.provider,"ai.model.id":T.modelId,"ai.prompt":{input:()=>JSON.stringify({system:r,prompt:o,messages:s})}}}),tracer:be,fn:async Ee=>{var Ne,Xe,I,ie,me,de;const Q=ms(S);let fe,Ze=[],se=[];const It=[],Se=[];do{const ze=[...F.messages,...It],rt=await(v==null?void 0:v({model:T,steps:Se,stepNumber:Se.length,messages:ze})),He=await Hu({prompt:{system:(Ne=rt==null?void 0:rt.system)!=null?Ne:F.system,messages:(Xe=rt==null?void 0:rt.messages)!=null?Xe:ze},supportedUrls:await T.supportedUrls}),ke=Jr((I=rt==null?void 0:rt.model)!=null?I:T),{toolChoice:_e,tools:Ue}=Ju({tools:t,toolChoice:(ie=rt==null?void 0:rt.toolChoice)!=null?ie:n,activeTools:(me=rt==null?void 0:rt.activeTools)!=null?me:f});fe=await H(()=>{var ce;return gn({name:"ai.generateText.doGenerate",attributes:lt({telemetry:w,attributes:{...mn({operationId:"ai.generateText.doGenerate",telemetry:w}),...oe,"ai.model.provider":ke.provider,"ai.model.id":ke.modelId,"ai.prompt.messages":{input:()=>tc(He)},"ai.prompt.tools":{input:()=>Ue==null?void 0:Ue.map(Ct=>JSON.stringify(Ct))},"ai.prompt.toolChoice":{input:()=>_e!=null?JSON.stringify(_e):void 0},"gen_ai.system":ke.provider,"gen_ai.request.model":ke.modelId,"gen_ai.request.frequency_penalty":S.frequencyPenalty,"gen_ai.request.max_tokens":S.maxOutputTokens,"gen_ai.request.presence_penalty":S.presencePenalty,"gen_ai.request.stop_sequences":S.stopSequences,"gen_ai.request.temperature":(ce=S.temperature)!=null?ce:void 0,"gen_ai.request.top_k":S.topK,"gen_ai.request.top_p":S.topP}}),tracer:be,fn:async Ct=>{var ur,cr,dr,Bt,st,pr,Vt,kn;const Me=await ke.doGenerate({...Q,tools:Ue,toolChoice:_e,responseFormat:c==null?void 0:c.responseFormat,prompt:He,providerOptions:_,abortSignal:i,headers:l}),Ft={id:(cr=(ur=Me.response)==null?void 0:ur.id)!=null?cr:g(),timestamp:(Bt=(dr=Me.response)==null?void 0:dr.timestamp)!=null?Bt:m(),modelId:(pr=(st=Me.response)==null?void 0:st.modelId)!=null?pr:ke.modelId,headers:(Vt=Me.response)==null?void 0:Vt.headers,body:(kn=Me.response)==null?void 0:kn.body};return Ct.setAttributes(lt({telemetry:w,attributes:{"ai.response.finishReason":Me.finishReason,"ai.response.text":{output:()=>sc(Me.content)},"ai.response.toolCalls":{output:()=>{const hr=pc(Me.content);return hr==null?void 0:JSON.stringify(hr)}},"ai.response.id":Ft.id,"ai.response.model":Ft.modelId,"ai.response.timestamp":Ft.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Me.providerMetadata),"ai.usage.promptTokens":Me.usage.inputTokens,"ai.usage.completionTokens":Me.usage.outputTokens,"gen_ai.response.finish_reasons":[Me.finishReason],"gen_ai.response.id":Ft.id,"gen_ai.response.model":Ft.modelId,"gen_ai.usage.input_tokens":Me.usage.inputTokens,"gen_ai.usage.output_tokens":Me.usage.outputTokens}})),{...Me,response:Ft}}})});const ne=await Promise.all(fe.content.filter(ce=>ce.type==="tool-call").map(ce=>ic({toolCall:ce,tools:t,repairToolCall:p,system:r,messages:ze})));for(const ce of ne){if(ce.invalid)continue;const Ct=t[ce.toolName];(Ct==null?void 0:Ct.onInputAvailable)!=null&&await Ct.onInputAvailable({input:ce.input,toolCallId:ce.toolCallId,messages:ze,abortSignal:i,experimental_context:b})}const ot=ne.filter(ce=>ce.invalid&&ce.dynamic);se=[];for(const ce of ot)se.push({type:"tool-error",toolCallId:ce.toolCallId,toolName:ce.toolName,input:ce.input,error:Wo(ce.error),dynamic:!0});Ze=ne.filter(ce=>!ce.providerExecuted),t!=null&&se.push(...await Zw({toolCalls:Ze.filter(ce=>!ce.invalid),tools:t,tracer:be,telemetry:w,messages:ze,abortSignal:i,experimental_context:b}));const D=Lw({content:fe.content,toolCalls:ne,toolOutputs:se});It.push(...ws({content:D,tools:t}));const Te=new uc({content:D,finishReason:fe.finishReason,usage:fe.usage,warnings:fe.warnings,providerMetadata:fe.providerMetadata,request:(de=fe.request)!=null?de:{},response:{...fe.response,messages:structuredClone(It)}});Se.push(Te),await(E==null?void 0:E(Te))}while(Ze.length>0&&se.length===Ze.length&&!await cc({stopConditions:P,steps:Se}));Ee.setAttributes(lt({telemetry:w,attributes:{"ai.response.finishReason":fe.finishReason,"ai.response.text":{output:()=>sc(fe.content)},"ai.response.toolCalls":{output:()=>{const ze=pc(fe.content);return ze==null?void 0:JSON.stringify(ze)}},"ai.response.providerMetadata":JSON.stringify(fe.providerMetadata),"ai.usage.promptTokens":fe.usage.inputTokens,"ai.usage.completionTokens":fe.usage.outputTokens}}));const Re=Se[Se.length-1];return new Uw({steps:Se,resolvedOutput:await(c==null?void 0:c.parseOutput({text:Re.text},{response:Re.response,usage:Re.usage,finishReason:Re.finishReason}))})}})}catch(Ee){throw Xu(Ee)}}async function Zw({toolCalls:e,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a}){return(await Promise.all(e.map(async({toolCallId:l,toolName:u,input:c})=>{const w=t[u];if((w==null?void 0:w.execute)!=null)return gn({name:"ai.toolCall",attributes:lt({telemetry:r,attributes:{...mn({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":u,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(c)}}}),tracer:n,fn:async _=>{try{const d=bl({execute:w.execute.bind(w),input:c,options:{toolCallId:l,messages:o,abortSignal:s,experimental_context:a}});let f;for await(const y of d)y.type==="final"&&(f=y.output);try{_.setAttributes(lt({telemetry:r,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(f)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:u,input:c,output:f,dynamic:w.type==="dynamic"}}catch(d){return gs(_,d),{type:"tool-error",toolCallId:l,toolName:u,input:c,error:d,dynamic:w.type==="dynamic"}}}})}))).filter(l=>l!=null)}var Uw=class{constructor(e){this.steps=e.steps,this.resolvedOutput=e.resolvedOutput}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 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 totalUsage(){return this.steps.reduce((e,t)=>nc(e,t.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new du;return this.resolvedOutput}};function pc(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}))}function Lw({content:e,toolCalls:t,toolOutputs:n}){return[...e.map(r=>{switch(r.type){case"text":case"reasoning":case"source":return r;case"file":return{type:"file",file:new ac(r)};case"tool-call":return t.find(o=>o.toolCallId===r.toolCallId);case"tool-result":{const o=t.find(s=>s.toolCallId===r.toolCallId);if(o==null)throw new Error(`Tool call ${r.toolCallId} not found.`);return r.isError?{type:"tool-error",toolCallId:r.toolCallId,toolName:r.toolName,input:o.input,error:r.result,providerExecuted:!0,dynamic:o.dynamic}:{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,input:o.input,output:r.result,providerExecuted:!0,dynamic:o.dynamic}}}}),...n]}function Wr(e,t){const n=new Headers(e??{});for(const[r,o]of Object.entries(t))n.has(r)||n.set(r,o);return n}function qw({status:e,statusText:t,headers:n,textStream:r}){return new Response(r.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:Wr(n,{"content-type":"text/plain; charset=utf-8"})})}function hc({response:e,status:t,statusText:n,headers:r,stream:o}){e.writeHead(t??200,n,r);const s=o.getReader();(async()=>{try{for(;;){const{done:i,value:l}=await s.read();if(i)break;e.write(l)}}catch(i){throw i}finally{e.end()}})()}function Bw({response:e,status:t,statusText:n,headers:r,textStream:o}){hc({response:e,status:t,statusText:n,headers:Object.fromEntries(Wr(r,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var fc=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
62
+ - in production/preview, the token is automatically obtained and refreshed`,new ep({message:a,statusCode:o,cause:s})}},El="GatewayInvalidRequestError",iv=`vercel.ai.gateway.error.${El}`,Rl=Symbol.for(iv),Al,Ol,lv=class extends(Ol=Qe,Al=Rl,Ol){constructor({message:e="Invalid request",statusCode:t=400,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Al]=!0,this.name=El,this.type="invalid_request_error"}static isInstance(e){return Qe.hasMarker(e)&&Rl in e}},Nl="GatewayRateLimitError",uv=`vercel.ai.gateway.error.${Nl}`,Ml=Symbol.for(uv),Pl,$l,cv=class extends($l=Qe,Pl=Ml,$l){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Pl]=!0,this.name=Nl,this.type="rate_limit_exceeded"}static isInstance(e){return Qe.hasMarker(e)&&Ml in e}},zl="GatewayModelNotFoundError",dv=`vercel.ai.gateway.error.${zl}`,jl=Symbol.for(dv),pv=x({modelId:h()}),Dl,Zl,Ul=class extends(Zl=Qe,Dl=jl,Zl){constructor({message:e="Model not found",statusCode:t=404,modelId:n,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[Dl]=!0,this.name=zl,this.type="model_not_found",this.modelId=n}static isInstance(e){return Qe.hasMarker(e)&&jl in e}},Ll="GatewayInternalServerError",hv=`vercel.ai.gateway.error.${Ll}`,ql=Symbol.for(hv),Bl,Vl,Fl=class extends(Vl=Qe,Bl=ql,Vl){constructor({message:e="Internal server error",statusCode:t=500,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Bl]=!0,this.name=Ll,this.type="internal_server_error"}static isInstance(e){return Qe.hasMarker(e)&&ql in e}},Hl="GatewayResponseError",fv=`vercel.ai.gateway.error.${Hl}`,Jl=Symbol.for(fv),Gl,Wl,mv=class extends(Wl=Qe,Gl=Jl,Wl){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:n,validationError:r,cause:o}={}){super({message:e,statusCode:t,cause:o}),this[Gl]=!0,this.name=Hl,this.type="response_error",this.response=n,this.validationError=r}static isInstance(e){return Qe.hasMarker(e)&&Jl in e}};function Kl({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:r,authMethod:o}){const s=gv.safeParse(e);if(!s.success)return new mv({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:s.error,cause:r});const a=s.data,i=a.error.type,l=a.error.message;switch(i){case"authentication_error":return qr.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:r});case"invalid_request_error":return new lv({message:l,statusCode:t,cause:r});case"rate_limit_exceeded":return new cv({message:l,statusCode:t,cause:r});case"model_not_found":{const u=pv.safeParse(a.error.param);return new Ul({message:l,statusCode:t,modelId:u.success?u.data.modelId:void 0,cause:r})}case"internal_server_error":return new Fl({message:l,statusCode:t,cause:r});default:return new Fl({message:l,statusCode:t,cause:r})}}var gv=x({error:x({message:h(),type:h().nullish(),param:Le().nullish(),code:ee([h(),R()]).nullish()})});function Vn(e,t){var n;return Qe.isInstance(e)?e:pe.isInstance(e)?Kl({response:yv(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):Kl({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function yv(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var Yl="ai-gateway-auth-method";function Br(e){const t=vv.safeParse(e[Yl]);return t.success?t.data:void 0}var vv=ee([A("api-key"),A("oidc")]),_v=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await $y({url:`${this.config.baseURL}/config`,headers:await en(this.config.headers()),successfulResponseHandler:Xo(kv),failedResponseHandler:Ur({errorSchema:pt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw Vn(e)}}},wv=x({specificationVersion:A("v2"),provider:h(),modelId:h()}),bv=x({input:h(),output:h()}),xv=x({id:h(),name:h(),description:h().nullish(),pricing:bv.nullish(),specification:wv}),kv=x({models:Z(xv)}),Tv=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...n}=e;return{args:this.maybeEncodeFileParts(n),warnings:[]}}async doGenerate(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,o=await en(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await Yo({url:this.getUrl(),headers:Go(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await en(this.config.o11yHeaders)),body:t,successfulResponseHandler:Xo(pt()),failedResponseHandler:Ur({errorSchema:pt(),errorToMessage:l=>l}),...r&&{abortSignal:r},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:s,body:i},warnings:n}}catch(s){throw Vn(s,Br(o))}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,o=await en(this.config.headers());try{const{value:s,responseHeaders:a}=await Yo({url:this.getUrl(),headers:Go(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await en(this.config.o11yHeaders)),body:t,successfulResponseHandler:Wy(pt()),failedResponseHandler:Ur({errorSchema:pt(),errorToMessage:i=>i}),...r&&{abortSignal:r},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(i){n.length>0&&i.enqueue({type:"stream-start",warnings:n})},transform(i,l){if(i.success){const u=i.value;if(u.type==="raw"&&!e.includeRawChunks)return;u.type==="response-metadata"&&u.timestamp&&typeof u.timestamp=="string"&&(u.timestamp=new Date(u.timestamp)),l.enqueue(u)}else l.error(i.error)}})),request:{body:t},response:{headers:a}}}catch(s){throw Vn(s,Br(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const n of t.content)if(this.isFilePart(n)){const r=n;if(r.data instanceof Uint8Array){const o=Uint8Array.from(r.data),s=Buffer.from(o).toString("base64");r.data=new URL(`data:${r.mediaType||"application/octet-stream"};base64,${s}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"2","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},Sv=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;const s=await en(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await Yo({url:this.getUrl(),headers:Go(s,t??{},this.getModelConfigHeaders(),await en(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...r??{}},successfulResponseHandler:Xo(Iv),failedResponseHandler:Ur({errorSchema:pt(),errorToMessage:u=>u}),...n&&{abortSignal:n},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(o=i.usage)!=null?o:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:l}}}catch(a){throw Vn(a,Br(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},Iv=x({embeddings:Z(Z(R())),usage:x({tokens:R()}).nullish(),providerMetadata:We(h(),We(h(),Le())).optional()});async function Cv(){var e,t;const n=(t=(e=Xl().headers)==null?void 0:e["x-vercel-oidc-token"])!=null?t:process.env.VERCEL_OIDC_TOKEN;if(!n)throw new qr({message:"OIDC token not available",statusCode:401});return n}async function Ev(){var e;return(e=Xl().headers)==null?void 0:e["x-vercel-id"]}var Rv=Symbol.for("@vercel/request-context");function Xl(){var e,t,n;return(n=(t=(e=globalThis[Rv])==null?void 0:e.get)==null?void 0:t.call(e))!=null?n:{}}var Av="0.0.1";function Ov(e={}){var t,n;let r=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const i=(n=rv(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const d=await Mv(e);if(d)return{Authorization:`Bearer ${d.token}`,"ai-gateway-protocol-version":Av,[Yl]:d.authMethod,...e.headers};throw qr.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},u=()=>{const d=Dr({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),f=Dr({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),y=Dr({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const v=await Ev();return{...d&&{"ai-o11y-deployment-id":d},...f&&{"ai-o11y-environment":f},...y&&{"ai-o11y-region":y},...v&&{"ai-o11y-request-id":v}}}},c=d=>new Tv(d,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:u()}),w=async()=>{var d,f,y;const v=(y=(f=(d=e._internal)==null?void 0:d.currentDate)==null?void 0:f.call(d).getTime())!=null?y:Date.now();return(!r||v-a>s)&&(a=v,r=new _v({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(p=>(o=p,p)).catch(async p=>{throw Vn(p,Br(await l()))})),o?Promise.resolve(o):r},_=function(d){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return c(d)};return _.getAvailableModels=w,_.imageModel=d=>{throw new wo({modelId:d,modelType:"imageModel"})},_.languageModel=c,_.textEmbeddingModel=d=>new Sv(d,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:u()}),_}var Nv=Ov();async function Mv(e){const t=Dr({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await Cv(),authMethod:"oidc"}}catch{return null}}var Pv=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},tn="1.9.0",Ql=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function $v(e){var t=new Set([e]),n=new Set,r=e.match(Ql);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 function(l){return l===e};function s(i){return n.add(i),!1}function a(i){return t.add(i),!0}return function(l){if(t.has(l))return!0;if(n.has(l))return!1;var u=l.match(Ql);if(!u)return s(l);var c={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return c.prerelease!=null||o.major!==c.major?s(l):o.major===0?o.minor===c.minor&&o.patch<=c.patch?a(l):s(l):o.minor<=c.minor?a(l):s(l)}}var zv=$v(tn),jv=tn.split(".")[0],Fn=Symbol.for("opentelemetry.js.api."+jv),Hn=Pv;function Jn(e,t,n,r){var o;r===void 0&&(r=!1);var s=Hn[Fn]=(o=Hn[Fn])!==null&&o!==void 0?o:{version:tn};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!==tn){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+tn);return n.error(a.stack||a.message),!1}return s[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+tn+"."),!0}function nn(e){var t,n,r=(t=Hn[Fn])===null||t===void 0?void 0:t.version;if(!(!r||!zv(r)))return(n=Hn[Fn])===null||n===void 0?void 0:n[e]}function Gn(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+tn+".");var n=Hn[Fn];n&&delete n[e]}var Dv=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(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},Zv=function(e,t,n){if(n||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))},Uv=function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Wn("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Wn("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Wn("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Wn("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return Wn("verbose",this._namespace,t)},e}();function Wn(e,t,n){var r=nn("diag");if(r)return n.unshift(t),r[e].apply(r,Zv([],Dv(n),!1))}var et;(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"})(et||(et={}));function Lv(e,t){e<et.NONE?e=et.NONE:e>et.ALL&&(e=et.ALL),t=t||{};function n(r,o){var s=t[r];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return{error:n("error",et.ERROR),warn:n("warn",et.WARN),info:n("info",et.INFO),debug:n("debug",et.DEBUG),verbose:n("verbose",et.VERBOSE)}}var qv=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(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},Bv=function(e,t,n){if(n||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))},Vv="diag",wt=function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=nn("diag");if(i)return i[o].apply(i,Bv([],qv(s),!1))}}var n=this,r=function(o,s){var a,i,l;if(s===void 0&&(s={logLevel:et.INFO}),o===n){var u=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=u.stack)!==null&&a!==void 0?a:u.message),!1}typeof s=="number"&&(s={logLevel:s});var c=nn("diag"),w=Lv((i=s.logLevel)!==null&&i!==void 0?i:et.INFO,o);if(c&&!s.suppressOverrideMessage){var _=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";c.warn("Current logger will be overwritten from "+_),w.warn("Current logger will overwrite one already registered from "+_)}return Jn("diag",w,n,!0)};n.setLogger=r,n.disable=function(){Gn(Vv,n)},n.createComponentLogger=function(o){return new Uv(o)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e}(),Fv=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(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},Hv=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},Jv=function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var n=this._entries.get(t);if(n)return Object.assign({},n)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var n=Fv(t,2),r=n[0],o=n[1];return[r,o]})},e.prototype.setEntry=function(t,n){var r=new e(this._entries);return r._entries.set(t,n),r},e.prototype.removeEntry=function(t){var n=new e(this._entries);return n._entries.delete(t),n},e.prototype.removeEntries=function(){for(var t,n,r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];var s=new e(this._entries);try{for(var a=Hv(r),i=a.next();!i.done;i=a.next()){var l=i.value;s._entries.delete(l)}}catch(u){t={error:u}}finally{try{i&&!i.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return s},e.prototype.clear=function(){return new e},e}();wt.instance();function Gv(e){return e===void 0&&(e={}),new Jv(new Map(Object.entries(e)))}function eu(e){return Symbol.for(e)}var Wv=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 e}(),Kv=new Wv,rn=function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(r[s]=o[s])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}(),Yv=function(){function e(){}return e.prototype.createGauge=function(t,n){return i_},e.prototype.createHistogram=function(t,n){return l_},e.prototype.createCounter=function(t,n){return a_},e.prototype.createUpDownCounter=function(t,n){return u_},e.prototype.createObservableGauge=function(t,n){return d_},e.prototype.createObservableCounter=function(t,n){return c_},e.prototype.createObservableUpDownCounter=function(t,n){return p_},e.prototype.addBatchObservableCallback=function(t,n){},e.prototype.removeBatchObservableCallback=function(t){},e}(),Vr=function(){function e(){}return e}(),Xv=function(e){rn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(n,r){},t}(Vr),Qv=function(e){rn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(n,r){},t}(Vr),e_=function(e){rn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(n,r){},t}(Vr),t_=function(e){rn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(n,r){},t}(Vr),ns=function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e}(),n_=function(e){rn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(ns),r_=function(e){rn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(ns),o_=function(e){rn(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(ns),s_=new Yv,a_=new Xv,i_=new e_,l_=new t_,u_=new Qv,c_=new n_,d_=new r_,p_=new o_,h_={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},f_={set:function(e,t,n){e!=null&&(e[t]=n)}},m_=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(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},g_=function(e,t,n){if(n||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))},y_=function(){function e(){}return e.prototype.active=function(){return Kv},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,g_([r],m_(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e}(),v_=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(i){a={error:i}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s},__=function(e,t,n){if(n||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))},rs="context",w_=new y_,Fr=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Jn(rs,t,wt.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,__([t,n,r],v_(s),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return nn(rs)||w_},e.prototype.disable=function(){this._getContextManager().disable(),Gn(rs,wt.instance())},e}(),os;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(os||(os={}));var tu="0000000000000000",nu="00000000000000000000000000000000",b_={traceId:nu,spanId:tu,traceFlags:os.NONE},Kn=function(){function e(t){t===void 0&&(t=b_),this._spanContext=t}return 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}(),ss=eu("OpenTelemetry Context Key SPAN");function as(e){return e.getValue(ss)||void 0}function x_(){return as(Fr.getInstance().active())}function is(e,t){return e.setValue(ss,t)}function k_(e){return e.deleteValue(ss)}function T_(e,t){return is(e,new Kn(t))}function ru(e){var t;return(t=as(e))===null||t===void 0?void 0:t.spanContext()}var S_=/^([0-9a-f]{32})$/i,I_=/^[0-9a-f]{16}$/i;function C_(e){return S_.test(e)&&e!==nu}function E_(e){return I_.test(e)&&e!==tu}function ou(e){return C_(e.traceId)&&E_(e.spanId)}function R_(e){return new Kn(e)}var ls=Fr.getInstance(),su=function(){function e(){}return e.prototype.startSpan=function(t,n,r){r===void 0&&(r=ls.active());var o=!!(n!=null&&n.root);if(o)return new Kn;var s=r&&ru(r);return A_(s)&&ou(s)?new Kn(s):new Kn},e.prototype.startActiveSpan=function(t,n,r,o){var s,a,i;if(!(arguments.length<2)){arguments.length===2?i=n:arguments.length===3?(s=n,i=r):(s=n,a=r,i=o);var l=a??ls.active(),u=this.startSpan(t,s,l),c=is(l,u);return ls.with(c,i,void 0,u)}},e}();function A_(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var O_=new su,N_=function(){function e(t,n,r,o){this._provider=t,this.name=n,this.version=r,this.options=o}return 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):O_},e}(),M_=function(){function e(){}return e.prototype.getTracer=function(t,n,r){return new su},e}(),P_=new M_,au=function(){function e(){}return e.prototype.getTracer=function(t,n,r){var o;return(o=this.getDelegateTracer(t,n,r))!==null&&o!==void 0?o:new N_(this,t,n,r)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:P_},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}(),Hr;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Hr||(Hr={})),Fr.getInstance(),wt.instance();var $_=function(){function e(){}return e.prototype.getMeter=function(t,n,r){return s_},e}(),z_=new $_,us="metrics",j_=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Jn(us,t,wt.instance())},e.prototype.getMeterProvider=function(){return nn(us)||z_},e.prototype.getMeter=function(t,n,r){return this.getMeterProvider().getMeter(t,n,r)},e.prototype.disable=function(){Gn(us,wt.instance())},e}();j_.getInstance();var D_=function(){function e(){}return e.prototype.inject=function(t,n){},e.prototype.extract=function(t,n){return t},e.prototype.fields=function(){return[]},e}(),cs=eu("OpenTelemetry Baggage Key");function iu(e){return e.getValue(cs)||void 0}function Z_(){return iu(Fr.getInstance().active())}function U_(e,t){return e.setValue(cs,t)}function L_(e){return e.deleteValue(cs)}var ds="propagation",q_=new D_,B_=function(){function e(){this.createBaggage=Gv,this.getBaggage=iu,this.getActiveBaggage=Z_,this.setBaggage=U_,this.deleteBaggage=L_}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Jn(ds,t,wt.instance())},e.prototype.inject=function(t,n,r){return r===void 0&&(r=f_),this._getGlobalPropagator().inject(t,n,r)},e.prototype.extract=function(t,n,r){return r===void 0&&(r=h_),this._getGlobalPropagator().extract(t,n,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Gn(ds,wt.instance())},e.prototype._getGlobalPropagator=function(){return nn(ds)||q_},e}();B_.getInstance();var ps="trace",V_=function(){function e(){this._proxyTracerProvider=new au,this.wrapSpanContext=R_,this.isSpanContextValid=ou,this.deleteSpan=k_,this.getSpan=as,this.getActiveSpan=x_,this.getSpanContext=ru,this.setSpan=is,this.setSpanContext=T_}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=Jn(ps,this._proxyTracerProvider,wt.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return nn(ps)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){Gn(ps,wt.instance()),this._proxyTracerProvider=new au},e}(),F_=V_.getInstance(),H_=Object.defineProperty,J_=(e,t)=>{for(var n in t)H_(e,n,{get:t[n],enumerable:!0})},lu="AI_NoOutputSpecifiedError",uu=`vercel.ai.error.${lu}`,G_=Symbol.for(uu),cu,du=class extends G{constructor({message:e="No output specified."}={}){super({name:lu,message:e}),this[cu]=!0}static isInstance(e){return G.hasMarker(e,uu)}};cu=G_;var pu="AI_InvalidArgumentError",hu=`vercel.ai.error.${pu}`,W_=Symbol.for(hu),fu,bt=class extends G{constructor({parameter:e,value:t,message:n}){super({name:pu,message:`Invalid argument for parameter ${e}: ${n}`}),this[fu]=!0,this.parameter=e,this.value=t}static isInstance(e){return G.hasMarker(e,hu)}};fu=W_;var mu="AI_InvalidToolInputError",gu=`vercel.ai.error.${mu}`,K_=Symbol.for(gu),yu,vu=class extends G{constructor({toolInput:e,toolName:t,cause:n,message:r=`Invalid input for tool ${t}: ${ln(n)}`}){super({name:mu,message:r,cause:n}),this[yu]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return G.hasMarker(e,gu)}};yu=K_;var Y_="AI_MCPClientError",_u=`vercel.ai.error.${Y_}`,X_=Symbol.for(_u),wu,$e=class extends G{constructor({name:e="MCPClientError",message:t,cause:n}){super({name:e,message:t,cause:n}),this[wu]=!0}static isInstance(e){return G.hasMarker(e,_u)}};wu=X_;var bu="AI_NoObjectGeneratedError",xu=`vercel.ai.error.${bu}`,Q_=Symbol.for(xu),ku,Tu=class extends G{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:o,finishReason:s}){super({name:bu,message:e,cause:t}),this[ku]=!0,this.text=n,this.response=r,this.usage=o,this.finishReason=s}static isInstance(e){return G.hasMarker(e,xu)}};ku=Q_;var Su="AI_NoOutputGeneratedError",Iu=`vercel.ai.error.${Su}`,ew=Symbol.for(Iu),Cu,tw=class extends G{constructor({message:e="No output generated.",cause:t}={}){super({name:Su,message:e,cause:t}),this[Cu]=!0}static isInstance(e){return G.hasMarker(e,Iu)}};Cu=ew;var Eu="AI_NoSuchToolError",Ru=`vercel.ai.error.${Eu}`,nw=Symbol.for(Ru),Au,hs=class extends G{constructor({toolName:e,availableTools:t=void 0,message:n=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:Eu,message:n}),this[Au]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return G.hasMarker(e,Ru)}};Au=nw;var Ou="AI_ToolCallRepairError",Nu=`vercel.ai.error.${Ou}`,rw=Symbol.for(Nu),Mu,ow=class extends G{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${ln(e)}`}){super({name:Ou,message:n,cause:e}),this[Mu]=!0,this.originalError=t}static isInstance(e){return G.hasMarker(e,Nu)}};Mu=rw;var sw=class extends G{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},Pu="AI_InvalidMessageRoleError",$u=`vercel.ai.error.${Pu}`,aw=Symbol.for($u),zu,iw=class extends G{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Pu,message:t}),this[zu]=!0,this.role=e}static isInstance(e){return G.hasMarker(e,$u)}};zu=aw;var ju="AI_DownloadError",Du=`vercel.ai.error.${ju}`,lw=Symbol.for(Du),Zu,fs=class extends G{constructor({url:e,statusCode:t,statusText:n,cause:r,message:o=r==null?`Failed to download ${e}: ${t} ${n}`:`Failed to download ${e}: ${r}`}){super({name:ju,message:o,cause:r}),this[Zu]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return G.hasMarker(e,Du)}};Zu=lw;var Uu="AI_RetryError",Lu=`vercel.ai.error.${Uu}`,uw=Symbol.for(Lu),qu,Bu=class extends G{constructor({message:e,reason:t,errors:n}){super({name:Uu,message:e}),this[qu]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return G.hasMarker(e,Lu)}};qu=uw;function Jr(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new sw({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return cw().languageModel(e)}function cw(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:Nv}var dw=[{mediaType:"image/gif",bytesPrefix:[71,73,70],base64Prefix:"R0lG"},{mediaType:"image/png",bytesPrefix:[137,80,78,71],base64Prefix:"iVBORw"},{mediaType:"image/jpeg",bytesPrefix:[255,216],base64Prefix:"/9j/"},{mediaType:"image/webp",bytesPrefix:[82,73,70,70],base64Prefix:"UklGRg"},{mediaType:"image/bmp",bytesPrefix:[66,77],base64Prefix:"Qk"},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0],base64Prefix:"SUkqAA"},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42],base64Prefix:"TU0AKg"},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102],base64Prefix:"AAAAIGZ0eXBhdmlm"},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99],base64Prefix:"AAAAIGZ0eXBoZWlj"}],pw=e=>{const t=typeof e=="string"?wl(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function hw(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?pw(e):e}function fw({data:e,signatures:t}){const n=hw(e);for(const r of t)if(typeof n=="string"?n.startsWith(r.base64Prefix):n.length>=r.bytesPrefix.length&&r.bytesPrefix.every((o,s)=>n[s]===o))return r.mediaType}async function mw({url:e}){var t;const n=e.toString();try{const r=await fetch(n);if(!r.ok)throw new fs({url:n,statusCode:r.status,statusText:r.statusText});return{data:new Uint8Array(await r.arrayBuffer()),mediaType:(t=r.headers.get("content-type"))!=null?t:void 0}}catch(r){throw fs.isInstance(r)?r:new fs({url:n,cause:r})}}function gw(e){try{const[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}var Vu=ee([h(),Ir(Uint8Array),Ir(ArrayBuffer),gg(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function Fu(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}=gw(e.toString());if(t==null||n==null)throw new G({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}function yw(e){return typeof e=="string"?e:e instanceof ArrayBuffer?es(new Uint8Array(e)):es(e)}async function Hu({prompt:e,supportedUrls:t,downloadImplementation:n=mw}){const r=await _w(e.messages,n,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(o=>vw({message:o,downloadedAssets:r}))]}function vw({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=>ww(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!=="").map(r=>{const o=r.providerOptions;switch(r.type){case"file":{const{data:s,mediaType:a}=Fu(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:r.output,providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.map(r=>({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:r.output,providerOptions:r.providerOptions})),providerOptions:e.providerOptions};default:{const r=n;throw new iw({role:r})}}}async function _w(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 i=(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:i,data:l}}).filter(s=>s.data instanceof URL&&s.mediaType!=null&&!zy({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:n})).map(s=>s.data),o=await Promise.all(r.map(async s=>({url:s,data:await t({url:s})})));return Object.fromEntries(o.map(({url:s,data:a})=>[s.toString(),a]))}function ww(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}=Fu(r);let i=a??e.mediaType,l=s;if(l instanceof URL){const u=t[l.toString()];u&&(l=u.data,i??(i=u.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(n=fw({data:l,signatures:dw}))!=null?n:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function ms({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,seed:a,stopSequences:i}){if(e!=null){if(!Number.isInteger(e))throw new bt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new bt({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new bt({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new bt({parameter:"topP",value:n,message:"topP must be a number"});if(r!=null&&typeof r!="number")throw new bt({parameter:"topK",value:r,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new bt({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new bt({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new bt({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:s,stopSequences:i,seed:a}}function bw(e){return e!=null&&Object.keys(e).length>0}function Ju({tools:e,toolChoice:t,activeTools:n}){return bw(e)?{tools:(n!=null?Object.entries(e).filter(([o])=>n.includes(o)):Object.entries(e)).map(([o,s])=>{const a=s.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:o,description:s.description,inputSchema:Lr(s.inputSchema).jsonSchema,providerOptions:s.providerOptions};case"provider-defined":return{type:"provider-defined",name:o,id:s.id,args:s.args};default:{const i=a;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var Yn=Ji(()=>ee([Fm(),h(),R(),re(),We(h(),Yn),Z(Yn)])),xe=We(h(),We(h(),Yn)),Gu=x({type:A("text"),text:h(),providerOptions:xe.optional()}),xw=x({type:A("image"),image:ee([Vu,Ir(URL)]),mediaType:h().optional(),providerOptions:xe.optional()}),Wu=x({type:A("file"),data:ee([Vu,Ir(URL)]),filename:h().optional(),mediaType:h(),providerOptions:xe.optional()}),kw=x({type:A("reasoning"),text:h(),providerOptions:xe.optional()}),Tw=x({type:A("tool-call"),toolCallId:h(),toolName:h(),input:Le(),providerOptions:xe.optional(),providerExecuted:re().optional()}),Sw=cn("type",[x({type:A("text"),value:h()}),x({type:A("json"),value:Yn}),x({type:A("error-text"),value:h()}),x({type:A("error-json"),value:Yn}),x({type:A("content"),value:Z(ee([x({type:A("text"),text:h()}),x({type:A("media"),data:h(),mediaType:h()})]))})]),Ku=x({type:A("tool-result"),toolCallId:h(),toolName:h(),output:Sw,providerOptions:xe.optional()}),Iw=x({role:A("system"),content:h(),providerOptions:xe.optional()}),Cw=x({role:A("user"),content:ee([h(),Z(ee([Gu,xw,Wu]))]),providerOptions:xe.optional()}),Ew=x({role:A("assistant"),content:ee([h(),Z(ee([Gu,Wu,kw,Tw,Ku]))]),providerOptions:xe.optional()}),Rw=x({role:A("tool"),content:Z(Ku),providerOptions:xe.optional()}),Aw=ee([Iw,Cw,Ew,Rw]);async function Yu(e){if(e.prompt==null&&e.messages==null)throw new Ht({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new Ht({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string")throw new Ht({prompt:e,message:"system must be a string"});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 Ht({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new Ht({prompt:e,message:"messages must not be empty"});const n=await qn({value:t,schema:Z(Aw)});if(!n.success)throw new Ht({prompt:e,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:n.error});return{messages:t,system:e.system}}function Xu(e){return qr.isInstance(e)||Ul.isInstance(e)?new G({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:e}):e}function mn({operationId:e,telemetry:t}){return{"operation.name":`${e}${(t==null?void 0:t.functionId)!=null?` ${t.functionId}`:""}`,"resource.name":t==null?void 0:t.functionId,"ai.operationId":e,"ai.telemetry.functionId":t==null?void 0:t.functionId}}function Qu({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,i])=>(s[`ai.settings.${a}`]=i,s),{}),...Object.entries((o=n==null?void 0:n.metadata)!=null?o:{}).reduce((s,[a,i])=>(s[`ai.telemetry.metadata.${a}`]=i,s),{}),...Object.entries(r??{}).reduce((s,[a,i])=>(i!==void 0&&(s[`ai.request.headers.${a}`]=i),s),{})}}var Ow={startSpan(){return Gr},startActiveSpan(e,t,n,r){if(typeof t=="function")return t(Gr);if(typeof n=="function")return n(Gr);if(typeof r=="function")return r(Gr)}},Gr={spanContext(){return Nw},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}},Nw={traceId:"",spanId:"",traceFlags:0};function ec({isEnabled:e=!1,tracer:t}={}){return e?t||F_.getTracer("ai"):Ow}function gn({name:e,tracer:t,attributes:n,fn:r,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:n},async s=>{try{const a=await r(s);return o&&s.end(),a}catch(a){try{gs(s,a)}finally{s.end()}throw a}})}function gs(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Hr.ERROR,message:t.message})):e.setStatus({code:Hr.ERROR})}function lt({telemetry:e,attributes:t}){return(e==null?void 0:e.isEnabled)!==!0?{}:Object.entries(t).reduce((n,[r,o])=>{if(o==null)return n;if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if((e==null?void 0:e.recordInputs)===!1)return n;const s=o.input();return s==null?n:{...n,[r]:s}}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if((e==null?void 0:e.recordOutputs)===!1)return n;const s=o.output();return s==null?n:{...n,[r]:s}}return{...n,[r]:o}},{})}function tc(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?yw(n.data):n.data}:n)})))}function nc(e,t){return{inputTokens:Xn(e.inputTokens,t.inputTokens),outputTokens:Xn(e.outputTokens,t.outputTokens),totalTokens:Xn(e.totalTokens,t.totalTokens),reasoningTokens:Xn(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:Xn(e.cachedInputTokens,t.cachedInputTokens)}}function Xn(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function ys(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function Mw({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}var Pw=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async o=>rc(o,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r});async function rc(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:o},s=[]){try{return await e()}catch(a){if(Qt(a)||t===0)throw a;const i=Wo(a),l=[...s,a],u=l.length;if(u>t)throw new Bu({message:`Failed after ${u} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&pe.isInstance(a)&&a.isRetryable===!0&&u<=t)return await Oy(Mw({error:a,exponentialBackoffDelay:n}),{abortSignal:o}),rc(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:o},l);throw u===1?a:new Bu({message:`Failed after ${u} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function oc({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new bt({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new bt({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const n=e??2;return{maxRetries:n,retry:Pw({maxRetries:n,abortSignal:t})}}function sc(e){const t=e.filter(n=>n.type==="text");if(t.length!==0)return t.map(n=>n.text).join("")}var ac=class{constructor({data:e,mediaType:t}){const n=e instanceof Uint8Array;this.base64Data=n?void 0:e,this.uint8ArrayData=n?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=es(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=wl(this.base64Data)),this.uint8ArrayData}},$w=class extends ac{constructor(e){super(e),this.type="file"}};async function ic({toolCall:e,tools:t,repairToolCall:n,system:r,messages:o}){try{if(t==null)throw new hs({toolName:e.toolName});try{return await lc({toolCall:e,tools:t})}catch(s){if(n==null||!(hs.isInstance(s)||vu.isInstance(s)))throw s;let a=null;try{a=await n({toolCall:e,tools:t,inputSchema:({toolName:i})=>{const{inputSchema:l}=t[i];return Lr(l).jsonSchema},system:r,messages:o,error:s})}catch(i){throw new ow({cause:i,originalError:s})}if(a==null)throw s;return await lc({toolCall:a,tools:t})}}catch(s){return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,dynamic:!0,invalid:!0,error:s}}}async function lc({toolCall:e,tools:t}){const n=e.toolName,r=t[n];if(r==null)throw new hs({toolName:e.toolName,availableTools:Object.keys(t)});const o=Lr(r.inputSchema),s=e.input.trim()===""?await qn({value:{},schema:o}):await fn({text:e.input,schema:o});if(s.success===!1)throw new vu({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}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var uc=class{constructor({content:e,finishReason:t,usage:n,warnings:r,request:o,response:s,providerMetadata:a}){this.content=e,this.finishReason=t,this.usage=n,this.warnings=r,this.request=o,this.response=s,this.providerMetadata=a}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!1)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic===!1)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function vs(e){return({steps:t})=>t.length===e}async function cc({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}function _s({output:e,tool:t,errorMode:n}){return n==="text"?{type:"error-text",value:ln(e)}:n==="json"?{type:"error-json",value:dc(e)}:t!=null&&t.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:dc(e)}}function dc(e){return e===void 0?null:e}function ws({content:e,tools:t}){const n=[],r=e.filter(s=>s.type!=="source").filter(s=>(s.type!=="tool-result"||s.providerExecuted)&&(s.type!=="tool-error"||s.providerExecuted)).filter(s=>s.type!=="text"||s.text.length>0).map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,providerOptions:s.providerMetadata};case"reasoning":return{type:"reasoning",text:s.text,providerOptions:s.providerMetadata};case"file":return{type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:_s({tool:t==null?void 0:t[s.toolName],output:s.output,errorMode:"none"}),providerExecuted:!0,providerOptions:s.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:_s({tool:t==null?void 0:t[s.toolName],output:s.error,errorMode:"json"}),providerOptions:s.providerMetadata}}});r.length>0&&n.push({role:"assistant",content:r});const o=e.filter(s=>s.type==="tool-result"||s.type==="tool-error").filter(s=>!s.providerExecuted).map(s=>({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:_s({tool:t==null?void 0:t[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"})}));return o.length>0&&n.push({role:"tool",content:o}),n}var zw=Ln({prefix:"aitxt",size:24});async function jw({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:s,maxRetries:a,abortSignal:i,headers:l,stopWhen:u=vs(1),experimental_output:c,experimental_telemetry:w,providerOptions:_,experimental_activeTools:d,activeTools:f=d,experimental_prepareStep:y,prepareStep:v=y,experimental_repairToolCall:p,experimental_context:b,_internal:{generateId:g=zw,currentDate:m=()=>new Date}={},onStepFinish:E,...S}){const T=Jr(e),P=ys(u),{maxRetries:V,retry:H}=oc({maxRetries:a,abortSignal:i}),B=ms(S),oe=Qu({model:T,telemetry:w,headers:l,settings:{...B,maxRetries:V}}),F=await Yu({system:r,prompt:o,messages:s}),be=ec(w);try{return await gn({name:"ai.generateText",attributes:lt({telemetry:w,attributes:{...mn({operationId:"ai.generateText",telemetry:w}),...oe,"ai.model.provider":T.provider,"ai.model.id":T.modelId,"ai.prompt":{input:()=>JSON.stringify({system:r,prompt:o,messages:s})}}}),tracer:be,fn:async Ee=>{var Ne,Xe,I,ie,me,de;const Q=ms(S);let fe,Ze=[],se=[];const It=[],Se=[];do{const ze=[...F.messages,...It],rt=await(v==null?void 0:v({model:T,steps:Se,stepNumber:Se.length,messages:ze})),He=await Hu({prompt:{system:(Ne=rt==null?void 0:rt.system)!=null?Ne:F.system,messages:(Xe=rt==null?void 0:rt.messages)!=null?Xe:ze},supportedUrls:await T.supportedUrls}),ke=Jr((I=rt==null?void 0:rt.model)!=null?I:T),{toolChoice:_e,tools:Ue}=Ju({tools:t,toolChoice:(ie=rt==null?void 0:rt.toolChoice)!=null?ie:n,activeTools:(me=rt==null?void 0:rt.activeTools)!=null?me:f});fe=await H(()=>{var ce;return gn({name:"ai.generateText.doGenerate",attributes:lt({telemetry:w,attributes:{...mn({operationId:"ai.generateText.doGenerate",telemetry:w}),...oe,"ai.model.provider":ke.provider,"ai.model.id":ke.modelId,"ai.prompt.messages":{input:()=>tc(He)},"ai.prompt.tools":{input:()=>Ue==null?void 0:Ue.map(Ct=>JSON.stringify(Ct))},"ai.prompt.toolChoice":{input:()=>_e!=null?JSON.stringify(_e):void 0},"gen_ai.system":ke.provider,"gen_ai.request.model":ke.modelId,"gen_ai.request.frequency_penalty":S.frequencyPenalty,"gen_ai.request.max_tokens":S.maxOutputTokens,"gen_ai.request.presence_penalty":S.presencePenalty,"gen_ai.request.stop_sequences":S.stopSequences,"gen_ai.request.temperature":(ce=S.temperature)!=null?ce:void 0,"gen_ai.request.top_k":S.topK,"gen_ai.request.top_p":S.topP}}),tracer:be,fn:async Ct=>{var ur,cr,dr,Bt,st,pr,Vt,kn;const Me=await ke.doGenerate({...Q,tools:Ue,toolChoice:_e,responseFormat:c==null?void 0:c.responseFormat,prompt:He,providerOptions:_,abortSignal:i,headers:l}),Ft={id:(cr=(ur=Me.response)==null?void 0:ur.id)!=null?cr:g(),timestamp:(Bt=(dr=Me.response)==null?void 0:dr.timestamp)!=null?Bt:m(),modelId:(pr=(st=Me.response)==null?void 0:st.modelId)!=null?pr:ke.modelId,headers:(Vt=Me.response)==null?void 0:Vt.headers,body:(kn=Me.response)==null?void 0:kn.body};return Ct.setAttributes(lt({telemetry:w,attributes:{"ai.response.finishReason":Me.finishReason,"ai.response.text":{output:()=>sc(Me.content)},"ai.response.toolCalls":{output:()=>{const hr=pc(Me.content);return hr==null?void 0:JSON.stringify(hr)}},"ai.response.id":Ft.id,"ai.response.model":Ft.modelId,"ai.response.timestamp":Ft.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Me.providerMetadata),"ai.usage.promptTokens":Me.usage.inputTokens,"ai.usage.completionTokens":Me.usage.outputTokens,"gen_ai.response.finish_reasons":[Me.finishReason],"gen_ai.response.id":Ft.id,"gen_ai.response.model":Ft.modelId,"gen_ai.usage.input_tokens":Me.usage.inputTokens,"gen_ai.usage.output_tokens":Me.usage.outputTokens}})),{...Me,response:Ft}}})});const ne=await Promise.all(fe.content.filter(ce=>ce.type==="tool-call").map(ce=>ic({toolCall:ce,tools:t,repairToolCall:p,system:r,messages:ze})));for(const ce of ne){if(ce.invalid)continue;const Ct=t[ce.toolName];(Ct==null?void 0:Ct.onInputAvailable)!=null&&await Ct.onInputAvailable({input:ce.input,toolCallId:ce.toolCallId,messages:ze,abortSignal:i,experimental_context:b})}const ot=ne.filter(ce=>ce.invalid&&ce.dynamic);se=[];for(const ce of ot)se.push({type:"tool-error",toolCallId:ce.toolCallId,toolName:ce.toolName,input:ce.input,error:Wo(ce.error),dynamic:!0});Ze=ne.filter(ce=>!ce.providerExecuted),t!=null&&se.push(...await Dw({toolCalls:Ze.filter(ce=>!ce.invalid),tools:t,tracer:be,telemetry:w,messages:ze,abortSignal:i,experimental_context:b}));const D=Uw({content:fe.content,toolCalls:ne,toolOutputs:se});It.push(...ws({content:D,tools:t}));const Te=new uc({content:D,finishReason:fe.finishReason,usage:fe.usage,warnings:fe.warnings,providerMetadata:fe.providerMetadata,request:(de=fe.request)!=null?de:{},response:{...fe.response,messages:structuredClone(It)}});Se.push(Te),await(E==null?void 0:E(Te))}while(Ze.length>0&&se.length===Ze.length&&!await cc({stopConditions:P,steps:Se}));Ee.setAttributes(lt({telemetry:w,attributes:{"ai.response.finishReason":fe.finishReason,"ai.response.text":{output:()=>sc(fe.content)},"ai.response.toolCalls":{output:()=>{const ze=pc(fe.content);return ze==null?void 0:JSON.stringify(ze)}},"ai.response.providerMetadata":JSON.stringify(fe.providerMetadata),"ai.usage.promptTokens":fe.usage.inputTokens,"ai.usage.completionTokens":fe.usage.outputTokens}}));const Re=Se[Se.length-1];return new Zw({steps:Se,resolvedOutput:await(c==null?void 0:c.parseOutput({text:Re.text},{response:Re.response,usage:Re.usage,finishReason:Re.finishReason}))})}})}catch(Ee){throw Xu(Ee)}}async function Dw({toolCalls:e,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:s,experimental_context:a}){return(await Promise.all(e.map(async({toolCallId:l,toolName:u,input:c})=>{const w=t[u];if((w==null?void 0:w.execute)!=null)return gn({name:"ai.toolCall",attributes:lt({telemetry:r,attributes:{...mn({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":u,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(c)}}}),tracer:n,fn:async _=>{try{const d=bl({execute:w.execute.bind(w),input:c,options:{toolCallId:l,messages:o,abortSignal:s,experimental_context:a}});let f;for await(const y of d)y.type==="final"&&(f=y.output);try{_.setAttributes(lt({telemetry:r,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(f)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:u,input:c,output:f,dynamic:w.type==="dynamic"}}catch(d){return gs(_,d),{type:"tool-error",toolCallId:l,toolName:u,input:c,error:d,dynamic:w.type==="dynamic"}}}})}))).filter(l=>l!=null)}var Zw=class{constructor(e){this.steps=e.steps,this.resolvedOutput=e.resolvedOutput}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 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 totalUsage(){return this.steps.reduce((e,t)=>nc(e,t.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new du;return this.resolvedOutput}};function pc(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}))}function Uw({content:e,toolCalls:t,toolOutputs:n}){return[...e.map(r=>{switch(r.type){case"text":case"reasoning":case"source":return r;case"file":return{type:"file",file:new ac(r)};case"tool-call":return t.find(o=>o.toolCallId===r.toolCallId);case"tool-result":{const o=t.find(s=>s.toolCallId===r.toolCallId);if(o==null)throw new Error(`Tool call ${r.toolCallId} not found.`);return r.isError?{type:"tool-error",toolCallId:r.toolCallId,toolName:r.toolName,input:o.input,error:r.result,providerExecuted:!0,dynamic:o.dynamic}:{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,input:o.input,output:r.result,providerExecuted:!0,dynamic:o.dynamic}}}}),...n]}function Wr(e,t){const n=new Headers(e??{});for(const[r,o]of Object.entries(t))n.has(r)||n.set(r,o);return n}function Lw({status:e,statusText:t,headers:n,textStream:r}){return new Response(r.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:Wr(n,{"content-type":"text/plain; charset=utf-8"})})}function hc({response:e,status:t,statusText:n,headers:r,stream:o}){e.writeHead(t??200,n,r);const s=o.getReader();(async()=>{try{for(;;){const{done:i,value:l}=await s.read();if(i)break;e.write(l)}}catch(i){throw i}finally{e.end()}})()}function qw({response:e,status:t,statusText:n,headers:r,textStream:o}){hc({response:e,status:t,statusText:n,headers:Object.fromEntries(Wr(r,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var fc=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
63
63
 
64
64
  `)},flush(e){e.enqueue(`data: [DONE]
65
65
 
66
- `)}})}},mc={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Vw({status:e,statusText:t,headers:n,stream:r,consumeSseStream:o}){let s=r.pipeThrough(new fc);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Wr(n,mc)})}function Fw({originalMessages:e,responseMessageId:t}){if(e==null)return;const n=e[e.length-1];return(n==null?void 0:n.role)==="assistant"?n.id:typeof t=="function"?t():t}ee([ye({type:A("text-start"),id:h(),providerMetadata:xe.optional()}),ye({type:A("text-delta"),id:h(),delta:h(),providerMetadata:xe.optional()}),ye({type:A("text-end"),id:h(),providerMetadata:xe.optional()}),ye({type:A("error"),errorText:h()}),ye({type:A("tool-input-start"),toolCallId:h(),toolName:h(),providerExecuted:re().optional(),dynamic:re().optional()}),ye({type:A("tool-input-delta"),toolCallId:h(),inputTextDelta:h()}),ye({type:A("tool-input-available"),toolCallId:h(),toolName:h(),input:Le(),providerExecuted:re().optional(),providerMetadata:xe.optional(),dynamic:re().optional()}),ye({type:A("tool-input-error"),toolCallId:h(),toolName:h(),input:Le(),providerExecuted:re().optional(),providerMetadata:xe.optional(),dynamic:re().optional(),errorText:h()}),ye({type:A("tool-output-available"),toolCallId:h(),output:Le(),providerExecuted:re().optional(),dynamic:re().optional(),preliminary:re().optional()}),ye({type:A("tool-output-error"),toolCallId:h(),errorText:h(),providerExecuted:re().optional(),dynamic:re().optional()}),ye({type:A("reasoning"),text:h(),providerMetadata:xe.optional()}),ye({type:A("reasoning-start"),id:h(),providerMetadata:xe.optional()}),ye({type:A("reasoning-delta"),id:h(),delta:h(),providerMetadata:xe.optional()}),ye({type:A("reasoning-end"),id:h(),providerMetadata:xe.optional()}),ye({type:A("reasoning-part-finish")}),ye({type:A("source-url"),sourceId:h(),url:h(),title:h().optional(),providerMetadata:xe.optional()}),ye({type:A("source-document"),sourceId:h(),mediaType:h(),title:h(),filename:h().optional(),providerMetadata:xe.optional()}),ye({type:A("file"),url:h(),mediaType:h(),providerMetadata:xe.optional()}),ye({type:h().startsWith("data-"),id:h().optional(),data:Le(),transient:re().optional()}),ye({type:A("start-step")}),ye({type:A("finish-step")}),ye({type:A("start"),messageId:h().optional(),messageMetadata:Le().optional()}),ye({type:A("finish"),messageMetadata:Le().optional()}),ye({type:A("abort")}),ye({type:A("message-metadata"),messageMetadata:Le()})]);function Hw(e){return e.type.startsWith("data-")}function gc(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),i=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);a&&i?n[r]=gc(s,o):n[r]=o}return n}function Jw(e){const t=["ROOT"];let n=-1,r=null;function o(l,u,c){switch(l){case'"':{n=u,t.pop(),t.push(c),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(c),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(c),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=u,t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(c),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(c),t.push("INSIDE_ARRAY_START");break}}}function s(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function a(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":o(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,o(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){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(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){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(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const w=e.substring(r,l+1);!"false".startsWith(w)&&!"true".startsWith(w)&&!"null".startsWith(w)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l)):n=l;break}}}let i=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{i+='"';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":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const c=e.substring(r,e.length);"true".startsWith(c)?i+="true".slice(c.length):"false".startsWith(c)?i+="false".slice(c.length):"null".startsWith(c)&&(i+="null".slice(c.length))}}return i}async function yc(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await fn({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await fn({text:Jw(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function bs(e){return e.type.startsWith("tool-")}function vc(e){return e.type.split("-").slice(1).join("-")}function Gw({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Ww({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:o,onToolCall:s,onData:a}){return e.pipeThrough(new TransformStream({async transform(i,l){await r(async({state:u,write:c})=>{var w,_,d,f;function y(m){const S=u.message.parts.filter(bs).find(T=>T.toolCallId===m);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function v(m){const S=u.message.parts.filter(T=>T.type==="dynamic-tool").find(T=>T.toolCallId===m);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function p(m){var E;const S=u.message.parts.find(V=>bs(V)&&V.toolCallId===m.toolCallId),T=m,P=S;S!=null?(S.state=m.state,P.input=T.input,P.output=T.output,P.errorText=T.errorText,P.rawInput=T.rawInput,P.preliminary=T.preliminary,P.providerExecuted=(E=T.providerExecuted)!=null?E:S.providerExecuted,T.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=T.providerMetadata)):u.message.parts.push({type:`tool-${m.toolName}`,toolCallId:m.toolCallId,state:m.state,input:T.input,output:T.output,rawInput:T.rawInput,errorText:T.errorText,providerExecuted:T.providerExecuted,preliminary:T.preliminary,...T.providerMetadata!=null?{callProviderMetadata:T.providerMetadata}:{}})}function b(m){var E;const S=u.message.parts.find(V=>V.type==="dynamic-tool"&&V.toolCallId===m.toolCallId),T=m,P=S;S!=null?(S.state=m.state,P.toolName=m.toolName,P.input=T.input,P.output=T.output,P.errorText=T.errorText,P.rawInput=(E=T.rawInput)!=null?E:P.rawInput,P.preliminary=T.preliminary,T.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=T.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:m.toolName,toolCallId:m.toolCallId,state:m.state,input:T.input,output:T.output,errorText:T.errorText,preliminary:T.preliminary,...T.providerMetadata!=null?{callProviderMetadata:T.providerMetadata}:{}})}async function g(m){if(m!=null){const E=u.message.metadata!=null?gc(u.message.metadata,m):m;t!=null&&await Ko({value:E,schema:t}),u.message.metadata=E}}switch(i.type){case"text-start":{const m={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeTextParts[i.id]=m,u.message.parts.push(m),c();break}case"text-delta":{const m=u.activeTextParts[i.id];m.text+=i.delta,m.providerMetadata=(w=i.providerMetadata)!=null?w:m.providerMetadata,c();break}case"text-end":{const m=u.activeTextParts[i.id];m.state="done",m.providerMetadata=(_=i.providerMetadata)!=null?_:m.providerMetadata,delete u.activeTextParts[i.id],c();break}case"reasoning-start":{const m={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeReasoningParts[i.id]=m,u.message.parts.push(m),c();break}case"reasoning-delta":{const m=u.activeReasoningParts[i.id];m.text+=i.delta,m.providerMetadata=(d=i.providerMetadata)!=null?d:m.providerMetadata,c();break}case"reasoning-end":{const m=u.activeReasoningParts[i.id];m.providerMetadata=(f=i.providerMetadata)!=null?f:m.providerMetadata,m.state="done",delete u.activeReasoningParts[i.id],c();break}case"file":{u.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),c();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),c();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),c();break}case"tool-input-start":{const m=u.message.parts.filter(bs);u.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:m.length,dynamic:i.dynamic},i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),c();break}case"tool-input-delta":{const m=u.partialToolCalls[i.toolCallId];m.text+=i.inputTextDelta;const{value:E}=await yc(m.text);m.dynamic?b({toolCallId:i.toolCallId,toolName:m.toolName,state:"input-streaming",input:E}):p({toolCallId:i.toolCallId,toolName:m.toolName,state:"input-streaming",input:E}),c();break}case"tool-input-available":{i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerMetadata:i.providerMetadata}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),c(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerMetadata:i.providerMetadata}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),c();break}case"tool-output-available":{if(i.dynamic){const m=v(i.toolCallId);b({toolCallId:i.toolCallId,toolName:m.toolName,state:"output-available",input:m.input,output:i.output,preliminary:i.preliminary})}else{const m=y(i.toolCallId);p({toolCallId:i.toolCallId,toolName:vc(m),state:"output-available",input:m.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}c();break}case"tool-output-error":{if(i.dynamic){const m=v(i.toolCallId);b({toolCallId:i.toolCallId,toolName:m.toolName,state:"output-error",input:m.input,errorText:i.errorText})}else{const m=y(i.toolCallId);p({toolCallId:i.toolCallId,toolName:vc(m),state:"output-error",input:m.input,rawInput:m.rawInput,errorText:i.errorText})}c();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{i.messageId!=null&&(u.message.id=i.messageId),await g(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&c();break}case"finish":{await g(i.messageMetadata),i.messageMetadata!=null&&c();break}case"message-metadata":{await g(i.messageMetadata),i.messageMetadata!=null&&c();break}case"error":{o==null||o(new Error(i.errorText));break}default:if(Hw(i)){(n==null?void 0:n[i.type])!=null&&await Ko({value:i.data,schema:n[i.type]});const m=i;if(m.transient){a==null||a(m);break}const E=m.id!=null?u.message.parts.find(S=>m.type===S.type&&m.id===S.id):void 0;E!=null?E.data=m.data:u.message.parts.push(m),a==null||a(m),c()}}l.enqueue(i)})}}))}function Kw({messageId:e,originalMessages:t=[],onFinish:n,onError:r,stream:o}){let s=t==null?void 0:t[t.length-1];(s==null?void 0:s.role)!=="assistant"?s=void 0:e=s.id;let a=!1;const i=o.pipeThrough(new TransformStream({transform(c,w){if(c.type==="start"){const _=c;_.messageId==null&&e!=null&&(_.messageId=e)}c.type==="abort"&&(a=!0),w.enqueue(c)}}));if(n==null)return i;const l=Gw({lastMessage:s?structuredClone(s):void 0,messageId:e??""});return Ww({stream:i,runUpdateMessageJob:async c=>{await c({state:l,write:()=>{}})},onError:r}).pipeThrough(new TransformStream({transform(c,w){w.enqueue(c)},async flush(){const c=l.message.id===(s==null?void 0:s.id);await n({isAborted:a,isContinuation:c,responseMessage:l.message,messages:[...c?t.slice(0,-1):t,l.message]})}}))}function Yw({response:e,status:t,statusText:n,headers:r,stream:o,consumeSseStream:s}){let a=o.pipeThrough(new fc);if(s){const[i,l]=a.tee();a=i,s({stream:l})}hc({response:e,status:t,statusText:n,headers:Object.fromEntries(Wr(r,mc).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Kr(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=()=>{const n=t.getReader();return{async next(){const{done:r,value:o}=await n.read();return r?{done:!0,value:void 0}:{done:!1,value:o}}}},t}async function Xw({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}function _c(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}function Qw(){let e=[],t=null,n=!1,r=_c();const o=()=>{n=!0,r.resolve(),e.forEach(a=>a.cancel()),e=[],t==null||t.close()},s=async()=>{if(n&&e.length===0){t==null||t.close();return}if(e.length===0)return r=_c(),await r.promise,s();try{const{value:a,done:i}=await e[0].read();i?(e.shift(),e.length>0?await s():n&&(t==null||t.close())):t==null||t.enqueue(a)}catch(a){t==null||t.error(a),e.shift(),o()}};return{stream:new ReadableStream({start(a){t=a},pull:s,async cancel(){for(const a of e)await a.cancel();e=[],n=!0}}),addStream:a=>{if(n)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),r.resolve()},close:()=>{n=!0,r.resolve(),e.length===0&&(t==null||t.close())},terminate:o}}var Yr=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}};function e0(e,t){return new ReadableStream({async start(n){const r=e.getReader();try{for(;;){const{done:o,value:s}=await r.read();if(o){n.close();break}n.enqueue(s)}}catch(o){await t({error:o,controller:n})}},cancel(n){return e.cancel(n)}})}function t0(){var e,t;return(t=(e=globalThis==null?void 0:globalThis.performance)==null?void 0:e.now())!=null?t:Date.now()}function n0({tools:e,generatorStream:t,tracer:n,telemetry:r,system:o,messages:s,abortSignal:a,repairToolCall:i,experimental_context:l}){let u=null;const c=new ReadableStream({start(p){u=p}}),w=new Set,_=new Map;let d=!1,f;function y(){d&&w.size===0&&(f!=null&&u.enqueue(f),u.close())}const v=new TransformStream({async transform(p,b){const g=p.type;switch(g){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{b.enqueue(p);break}case"file":{b.enqueue({type:"file",file:new zw({data:p.data,mediaType:p.mediaType})});break}case"finish":{f={type:"finish",finishReason:p.finishReason,usage:p.usage,providerMetadata:p.providerMetadata};break}case"tool-call":{try{const m=await ic({toolCall:p,tools:e,repairToolCall:i,system:o,messages:s});if(b.enqueue(m),m.invalid){u.enqueue({type:"tool-error",toolCallId:m.toolCallId,toolName:m.toolName,input:m.input,error:Wo(m.error),dynamic:!0});break}const E=e[m.toolName];if(_.set(m.toolCallId,m.input),E.onInputAvailable!=null&&await E.onInputAvailable({input:m.input,toolCallId:m.toolCallId,messages:s,abortSignal:a,experimental_context:l}),E.execute!=null&&m.providerExecuted!==!0){const S=My();w.add(S),gn({name:"ai.toolCall",attributes:lt({telemetry:r,attributes:{...mn({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":m.toolName,"ai.toolCall.id":m.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(m.input)}}}),tracer:n,fn:async T=>{let P;try{const V=bl({execute:E.execute.bind(E),input:m.input,options:{toolCallId:m.toolCallId,messages:s,abortSignal:a,experimental_context:l}});for await(const H of V)u.enqueue({...m,type:"tool-result",output:H.output,...H.type==="preliminary"&&{preliminary:!0}}),H.type==="final"&&(P=H.output)}catch(V){gs(T,V),u.enqueue({...m,type:"tool-error",error:V}),w.delete(S),y();return}w.delete(S),y();try{T.setAttributes(lt({telemetry:r,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(P)}}}))}catch{}}})}}catch(m){u.enqueue({type:"error",error:m})}break}case"tool-result":{const m=p.toolName;p.isError?u.enqueue({type:"tool-error",toolCallId:p.toolCallId,toolName:m,input:_.get(p.toolCallId),providerExecuted:p.providerExecuted,error:p.result}):b.enqueue({type:"tool-result",toolCallId:p.toolCallId,toolName:m,input:_.get(p.toolCallId),output:p.result,providerExecuted:p.providerExecuted});break}default:{const m=g;throw new Error(`Unhandled chunk type: ${m}`)}}},flush(){d=!0,y()}});return new ReadableStream({async start(p){return Promise.all([t.pipeThrough(v).pipeTo(new WritableStream({write(b){p.enqueue(b)},close(){}})),c.pipeTo(new WritableStream({write(b){p.enqueue(b)},close(){p.close()}}))])}})}var r0=Ln({prefix:"aitxt",size:24});function o0({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:s,maxRetries:a,abortSignal:i,headers:l,stopWhen:u=vs(1),experimental_output:c,experimental_telemetry:w,prepareStep:_,providerOptions:d,experimental_activeTools:f,activeTools:y=f,experimental_repairToolCall:v,experimental_transform:p,includeRawChunks:b=!1,onChunk:g,onError:m=({error:F})=>{console.error(F)},onFinish:E,onAbort:S,onStepFinish:T,experimental_context:P,_internal:{now:V=t0,generateId:H=r0,currentDate:B=()=>new Date}={},...oe}){return new a0({model:Jr(e),telemetry:w,headers:l,settings:oe,maxRetries:a,abortSignal:i,system:r,prompt:o,messages:s,tools:t,toolChoice:n,transforms:ys(p),activeTools:y,repairToolCall:v,stopConditions:ys(u),output:c,providerOptions:d,prepareStep:_,includeRawChunks:b,onChunk:g,onError:m,onFinish:E,onAbort:S,onStepFinish:T,now:V,currentDate:B,generateId:H,experimental_context:P})}function s0(e){if(!e)return new TransformStream({transform(a,i){i.enqueue({part:a,partialOutput:void 0})}});let t,n="",r="",o="";function s({controller:a,partialOutput:i=void 0}){a.enqueue({part:{type:"text-delta",id:t,text:r},partialOutput:i}),r=""}return new TransformStream({async transform(a,i){if(a.type==="finish-step"&&r.length>0&&s({controller:i}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){i.enqueue({part:a,partialOutput:void 0});return}if(t==null)t=a.id;else if(a.id!==t){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){r.length>0&&s({controller:i}),i.enqueue({part:a,partialOutput:void 0});return}n+=a.text,r+=a.text;const l=await e.parsePartial({text:n});if(l!=null){const u=JSON.stringify(l.partial);u!==o&&(s({controller:i,partialOutput:l.partial}),o=u)}}})}var a0=class{constructor({model:e,telemetry:t,headers:n,settings:r,maxRetries:o,abortSignal:s,system:a,prompt:i,messages:l,tools:u,toolChoice:c,transforms:w,activeTools:_,repairToolCall:d,stopConditions:f,output:y,providerOptions:v,prepareStep:p,includeRawChunks:b,now:g,currentDate:m,generateId:E,onChunk:S,onError:T,onFinish:P,onAbort:V,onStepFinish:H,experimental_context:B}){this._totalUsage=new Yr,this._finishReason=new Yr,this._steps=new Yr,this.output=y,this.includeRawChunks=b,this.tools=u;let oe,F=[];const be=[];let Ee,Ne,Xe={},I=[];const ie=[];let me,de={},Q={};const fe=new TransformStream({async transform(ke,_e){var Ue,ne,ot;_e.enqueue(ke);const{part:D}=ke;if((D.type==="text-delta"||D.type==="reasoning-delta"||D.type==="source"||D.type==="tool-call"||D.type==="tool-result"||D.type==="tool-input-start"||D.type==="tool-input-delta"||D.type==="raw")&&await(S==null?void 0:S({chunk:D})),D.type==="error"&&await T({error:Xu(D.error)}),D.type==="text-start"&&(de[D.id]={type:"text",text:"",providerMetadata:D.providerMetadata},F.push(de[D.id])),D.type==="text-delta"){const Te=de[D.id];if(Te==null){_e.enqueue({part:{type:"error",error:`text part ${D.id} not found`},partialOutput:void 0});return}Te.text+=D.text,Te.providerMetadata=(Ue=D.providerMetadata)!=null?Ue:Te.providerMetadata}if(D.type==="text-end"&&delete de[D.id],D.type==="reasoning-start"&&(Q[D.id]={type:"reasoning",text:"",providerMetadata:D.providerMetadata},F.push(Q[D.id])),D.type==="reasoning-delta"){const Te=Q[D.id];if(Te==null){_e.enqueue({part:{type:"error",error:`reasoning part ${D.id} not found`},partialOutput:void 0});return}Te.text+=D.text,Te.providerMetadata=(ne=D.providerMetadata)!=null?ne:Te.providerMetadata}if(D.type==="reasoning-end"){const Te=Q[D.id];if(Te==null){_e.enqueue({part:{type:"error",error:`reasoning part ${D.id} not found`},partialOutput:void 0});return}Te.providerMetadata=(ot=D.providerMetadata)!=null?ot:Te.providerMetadata,delete Q[D.id]}if(D.type==="file"&&F.push({type:"file",file:D.file}),D.type==="source"&&F.push(D),D.type==="tool-call"&&F.push(D),D.type==="tool-result"&&!D.preliminary&&F.push(D),D.type==="tool-error"&&F.push(D),D.type==="start-step"&&(Xe=D.request,I=D.warnings),D.type==="finish-step"){const Te=ws({content:F,tools:u}),ce=new uc({content:F,finishReason:D.finishReason,usage:D.usage,warnings:I,request:Xe,response:{...D.response,messages:[...be,...Te]},providerMetadata:D.providerMetadata});await(H==null?void 0:H(ce)),ie.push(ce),F=[],Q={},de={},be.push(...Te),oe.resolve()}D.type==="finish"&&(Ne=D.totalUsage,Ee=D.finishReason)},async flush(ke){try{if(ie.length===0){const ot=new nw({message:"No output generated. Check the stream for errors."});He._finishReason.reject(ot),He._totalUsage.reject(ot),He._steps.reject(ot);return}const _e=Ee??"unknown",Ue=Ne??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};He._finishReason.resolve(_e),He._totalUsage.resolve(Ue),He._steps.resolve(ie);const ne=ie[ie.length-1];await(P==null?void 0:P({finishReason:_e,totalUsage:Ue,usage:ne.usage,content:ne.content,text:ne.text,reasoningText:ne.reasoningText,reasoning:ne.reasoning,files:ne.files,sources:ne.sources,toolCalls:ne.toolCalls,staticToolCalls:ne.staticToolCalls,dynamicToolCalls:ne.dynamicToolCalls,toolResults:ne.toolResults,staticToolResults:ne.staticToolResults,dynamicToolResults:ne.dynamicToolResults,request:ne.request,response:ne.response,warnings:ne.warnings,providerMetadata:ne.providerMetadata,steps:ie})),me.setAttributes(lt({telemetry:t,attributes:{"ai.response.finishReason":_e,"ai.response.text":{output:()=>ne.text},"ai.response.toolCalls":{output:()=>{var ot;return(ot=ne.toolCalls)!=null&&ot.length?JSON.stringify(ne.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(ne.providerMetadata),"ai.usage.inputTokens":Ue.inputTokens,"ai.usage.outputTokens":Ue.outputTokens,"ai.usage.totalTokens":Ue.totalTokens,"ai.usage.reasoningTokens":Ue.reasoningTokens,"ai.usage.cachedInputTokens":Ue.cachedInputTokens}}))}catch(_e){ke.error(_e)}finally{me.end()}}}),Ze=Qw();this.addStream=Ze.addStream,this.closeStream=Ze.close;let se=Ze.stream;se=e0(se,({error:ke,controller:_e})=>{Qt(ke)&&(s!=null&&s.aborted)?(V==null||V({steps:ie}),_e.enqueue({type:"abort"}),_e.close()):_e.error(ke)}),se=se.pipeThrough(new TransformStream({start(ke){ke.enqueue({type:"start"})}}));for(const ke of w)se=se.pipeThrough(ke({tools:u,stopStream(){Ze.terminate()}}));this.baseStream=se.pipeThrough(s0(y)).pipeThrough(fe);const{maxRetries:It,retry:Se}=oc({maxRetries:o,abortSignal:s}),Re=ec(t),ze=ms(r),rt=Qu({model:e,telemetry:t,headers:n,settings:{...ze,maxRetries:It}}),He=this;gn({name:"ai.streamText",attributes:lt({telemetry:t,attributes:{...mn({operationId:"ai.streamText",telemetry:t}),...rt,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:i,messages:l})}}}),tracer:Re,endWhenDone:!1,fn:async ke=>{me=ke;async function _e({currentStep:Ue,responseMessages:ne,usage:ot}){var D,Te,ce,Ct,ur;const cr=He.includeRawChunks;oe=new Yr;const dr=await Yu({system:a,prompt:i,messages:l}),Bt=[...dr.messages,...ne],st=await(p==null?void 0:p({model:e,steps:ie,stepNumber:ie.length,messages:Bt})),pr=await Hu({prompt:{system:(D=st==null?void 0:st.system)!=null?D:dr.system,messages:(Te=st==null?void 0:st.messages)!=null?Te:Bt},supportedUrls:await e.supportedUrls}),Vt=Jr((ce=st==null?void 0:st.model)!=null?ce:e),{toolChoice:kn,tools:Me}=Ju({tools:u,toolChoice:(Ct=st==null?void 0:st.toolChoice)!=null?Ct:c,activeTools:(ur=st==null?void 0:st.activeTools)!=null?ur:_}),{result:{stream:Ft,response:hr,request:Gd},doStreamSpan:Tn,startTimestampMs:Wd}=await Se(()=>gn({name:"ai.streamText.doStream",attributes:lt({telemetry:t,attributes:{...mn({operationId:"ai.streamText.doStream",telemetry:t}),...rt,"ai.model.provider":Vt.provider,"ai.model.id":Vt.modelId,"ai.prompt.messages":{input:()=>tc(pr)},"ai.prompt.tools":{input:()=>Me==null?void 0:Me.map(J=>JSON.stringify(J))},"ai.prompt.toolChoice":{input:()=>kn!=null?JSON.stringify(kn):void 0},"gen_ai.system":Vt.provider,"gen_ai.request.model":Vt.modelId,"gen_ai.request.frequency_penalty":ze.frequencyPenalty,"gen_ai.request.max_tokens":ze.maxOutputTokens,"gen_ai.request.presence_penalty":ze.presencePenalty,"gen_ai.request.stop_sequences":ze.stopSequences,"gen_ai.request.temperature":ze.temperature,"gen_ai.request.top_k":ze.topK,"gen_ai.request.top_p":ze.topP}}),tracer:Re,endWhenDone:!1,fn:async J=>({startTimestampMs:g(),doStreamSpan:J,result:await Vt.doStream({...ze,tools:Me,toolChoice:kn,responseFormat:y==null?void 0:y.responseFormat,prompt:pr,providerOptions:v,abortSignal:s,headers:n,includeRawChunks:cr})})})),GT=n0({tools:u,generatorStream:Ft,tracer:Re,telemetry:t,system:a,messages:Bt,repairToolCall:d,abortSignal:s,experimental_context:B}),WT=Gd??{},yo=[],da=[];let pa;const ha={};let Sn="unknown",gt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},fa,Kd=!0,Et={id:E(),timestamp:m(),modelId:e.modelId},Yd="";He.addStream(GT.pipeThrough(new TransformStream({async transform(J,De){var fr,mr,vo,$t;if(J.type==="stream-start"){pa=J.warnings;return}if(Kd){const Je=g()-Wd;Kd=!1,Tn.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":Je}),Tn.setAttributes({"ai.response.msToFirstChunk":Je}),De.enqueue({type:"start-step",request:WT,warnings:pa??[]})}const Xd=J.type;switch(Xd){case"text-start":case"text-end":{De.enqueue(J);break}case"text-delta":{J.delta.length>0&&(De.enqueue({type:"text-delta",id:J.id,text:J.delta,providerMetadata:J.providerMetadata}),Yd+=J.delta);break}case"reasoning-start":case"reasoning-end":{De.enqueue(J);break}case"reasoning-delta":{De.enqueue({type:"reasoning-delta",id:J.id,text:J.delta,providerMetadata:J.providerMetadata});break}case"tool-call":{De.enqueue(J),yo.push(J);break}case"tool-result":{De.enqueue(J),J.preliminary||da.push(J);break}case"tool-error":{De.enqueue(J),da.push(J);break}case"response-metadata":{Et={id:(fr=J.id)!=null?fr:Et.id,timestamp:(mr=J.timestamp)!=null?mr:Et.timestamp,modelId:(vo=J.modelId)!=null?vo:Et.modelId};break}case"finish":{gt=J.usage,Sn=J.finishReason,fa=J.providerMetadata;const Je=g()-Wd;Tn.addEvent("ai.stream.finish"),Tn.setAttributes({"ai.response.msToFinish":Je,"ai.response.avgOutputTokensPerSecond":1e3*(($t=gt.outputTokens)!=null?$t:0)/Je});break}case"file":{De.enqueue(J);break}case"source":{De.enqueue(J);break}case"tool-input-start":{ha[J.id]=J.toolName;const Je=u==null?void 0:u[J.toolName];(Je==null?void 0:Je.onInputStart)!=null&&await Je.onInputStart({toolCallId:J.id,messages:Bt,abortSignal:s,experimental_context:B}),De.enqueue({...J,dynamic:(Je==null?void 0:Je.type)==="dynamic"});break}case"tool-input-end":{delete ha[J.id],De.enqueue(J);break}case"tool-input-delta":{const Je=ha[J.id],ma=u==null?void 0:u[Je];(ma==null?void 0:ma.onInputDelta)!=null&&await ma.onInputDelta({inputTextDelta:J.delta,toolCallId:J.id,messages:Bt,abortSignal:s,experimental_context:B}),De.enqueue(J);break}case"error":{De.enqueue(J),Sn="error";break}case"raw":{cr&&De.enqueue(J);break}default:{const Je=Xd;throw new Error(`Unknown chunk type: ${Je}`)}}},async flush(J){const De=yo.length>0?JSON.stringify(yo):void 0;try{Tn.setAttributes(lt({telemetry:t,attributes:{"ai.response.finishReason":Sn,"ai.response.text":{output:()=>Yd},"ai.response.toolCalls":{output:()=>De},"ai.response.id":Et.id,"ai.response.model":Et.modelId,"ai.response.timestamp":Et.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(fa),"ai.usage.inputTokens":gt.inputTokens,"ai.usage.outputTokens":gt.outputTokens,"ai.usage.totalTokens":gt.totalTokens,"ai.usage.reasoningTokens":gt.reasoningTokens,"ai.usage.cachedInputTokens":gt.cachedInputTokens,"gen_ai.response.finish_reasons":[Sn],"gen_ai.response.id":Et.id,"gen_ai.response.model":Et.modelId,"gen_ai.usage.input_tokens":gt.inputTokens,"gen_ai.usage.output_tokens":gt.outputTokens}}))}catch{}finally{Tn.end()}J.enqueue({type:"finish-step",finishReason:Sn,usage:gt,providerMetadata:fa,response:{...Et,headers:hr==null?void 0:hr.headers}});const fr=nc(ot,gt);await oe.promise;const mr=yo.filter($t=>$t.providerExecuted!==!0),vo=da.filter($t=>$t.providerExecuted!==!0);if(mr.length>0&&vo.length===mr.length&&!await cc({stopConditions:f,steps:ie})){ne.push(...ws({content:ie[ie.length-1].content,tools:u}));try{await _e({currentStep:Ue+1,responseMessages:ne,usage:fr})}catch($t){J.enqueue({type:"error",error:$t}),He.closeStream()}}else J.enqueue({type:"finish",finishReason:Sn,totalUsage:fr}),He.closeStream()}})))}await _e({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(ke=>{He.addStream(new ReadableStream({start(_e){_e.enqueue({type:"error",error:ke}),_e.close()}})),He.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Kr(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Kr(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await Xw({stream:this.fullStream,onError:e==null?void 0:e.onError})}catch(n){(t=e==null?void 0:e.onError)==null||t.call(e,n)}}get experimental_partialOutputStream(){if(this.output==null)throw new du;return Kr(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:o=!0,sendSources:s=!1,sendStart:a=!0,sendFinish:i=!0,onError:l=ln}={}){const u=t!=null?Fw({originalMessages:e,responseMessageId:t}):void 0,c={},w=d=>{var f,y;const v=c[d];return((y=(f=this.tools)==null?void 0:f[v])==null?void 0:y.type)==="dynamic"?!0:void 0},_=this.fullStream.pipeThrough(new TransformStream({transform:async(d,f)=>{const y=r==null?void 0:r({part:d}),v=d.type;switch(v){case"text-start":{f.enqueue({type:"text-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-delta":{f.enqueue({type:"text-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-end":{f.enqueue({type:"text-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-start":{f.enqueue({type:"reasoning-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-delta":{o&&f.enqueue({type:"reasoning-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-end":{f.enqueue({type:"reasoning-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"file":{f.enqueue({type:"file",mediaType:d.file.mediaType,url:`data:${d.file.mediaType};base64,${d.file.base64}`});break}case"source":{s&&d.sourceType==="url"&&f.enqueue({type:"source-url",sourceId:d.id,url:d.url,title:d.title,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}}),s&&d.sourceType==="document"&&f.enqueue({type:"source-document",sourceId:d.id,mediaType:d.mediaType,title:d.title,filename:d.filename,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"tool-input-start":{c[d.id]=d.toolName;const p=w(d.id);f.enqueue({type:"tool-input-start",toolCallId:d.id,toolName:d.toolName,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...p!=null?{dynamic:p}:{}});break}case"tool-input-delta":{f.enqueue({type:"tool-input-delta",toolCallId:d.id,inputTextDelta:d.delta});break}case"tool-call":{c[d.toolCallId]=d.toolName;const p=w(d.toolCallId);d.invalid?f.enqueue({type:"tool-input-error",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...p!=null?{dynamic:p}:{},errorText:l(d.error)}):f.enqueue({type:"tool-input-available",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...p!=null?{dynamic:p}:{}});break}case"tool-result":{const p=w(d.toolCallId);f.enqueue({type:"tool-output-available",toolCallId:d.toolCallId,output:d.output,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.preliminary!=null?{preliminary:d.preliminary}:{},...p!=null?{dynamic:p}:{}});break}case"tool-error":{const p=w(d.toolCallId);f.enqueue({type:"tool-output-error",toolCallId:d.toolCallId,errorText:l(d.error),...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...p!=null?{dynamic:p}:{}});break}case"error":{f.enqueue({type:"error",errorText:l(d.error)});break}case"start-step":{f.enqueue({type:"start-step"});break}case"finish-step":{f.enqueue({type:"finish-step"});break}case"start":{a&&f.enqueue({type:"start",...y!=null?{messageMetadata:y}:{},...u!=null?{messageId:u}:{}});break}case"finish":{i&&f.enqueue({type:"finish",...y!=null?{messageMetadata:y}:{}});break}case"abort":{f.enqueue(d);break}case"tool-input-end":break;case"raw":break;default:{const p=v;throw new Error(`Unknown chunk type: ${p}`)}}y!=null&&v!=="start"&&v!=="finish"&&f.enqueue({type:"message-metadata",messageMetadata:y})}}));return Kr(Kw({stream:_,messageId:u??(t==null?void 0:t()),originalMessages:e,onFinish:n,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:n,onFinish:r,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:u,...c}={}){Yw({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:n,onFinish:r,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:u}),...c})}pipeTextStreamToResponse(e,t){Bw({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l,...u}={}){return Vw({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l}),...u})}toTextStreamResponse(e){return qw({textStream:this.textStream,...e})}};Ln({prefix:"aiobj",size:24}),Ln({prefix:"aiobj",size:24});var i0={};G_(i0,{object:()=>u0,text:()=>l0});var l0=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),u0=({schema:e})=>{const t=Lr(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await yc(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const o=r.state;throw new Error(`Unsupported parse state: ${o}`)}}},async parseOutput({text:n},r){const o=await fn({text:n});if(!o.success)throw new Tu({message:"No object generated: could not parse the response.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const s=await qn({value:o.value,schema:t});if(!s.success)throw new Tu({message:"No object generated: response did not match schema.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return s.value}}},wc="2025-06-18",c0=[wc,"2025-03-26","2024-11-05"],d0=un({name:h(),version:h()}),xs=un({_meta:Ie(x({}).loose())}),Qn=xs,p0=x({method:h(),params:Ie(xs)}),h0=un({experimental:Ie(x({}).loose()),logging:Ie(x({}).loose()),prompts:Ie(un({listChanged:Ie(re())})),resources:Ie(un({subscribe:Ie(re()),listChanged:Ie(re())})),tools:Ie(un({listChanged:Ie(re())}))}),f0=Qn.extend({protocolVersion:h(),capabilities:h0,serverInfo:d0,instructions:Ie(h())}),m0=Qn.extend({nextCursor:Ie(h())}),g0=x({name:h(),description:Ie(h()),inputSchema:x({type:A("object"),properties:Ie(x({}).loose())}).loose()}).loose(),y0=m0.extend({tools:Z(g0)}),v0=x({type:A("text"),text:h()}).loose(),_0=x({type:A("image"),data:Zi(),mimeType:h()}).loose(),bc=x({uri:h(),mimeType:Ie(h())}).loose(),w0=bc.extend({text:h()}),b0=bc.extend({blob:Zi()}),x0=x({type:A("resource"),resource:ee([w0,b0])}).loose(),k0=Qn.extend({content:Z(ee([v0,_0,x0])),isError:re().default(!1).optional()}).or(Qn.extend({toolResult:Le()})),Xr="2.0",T0=x({jsonrpc:A(Xr),id:ee([h(),R().int()])}).merge(p0).strict(),S0=x({jsonrpc:A(Xr),id:ee([h(),R().int()]),result:Qn}).strict(),I0=x({jsonrpc:A(Xr),id:ee([h(),R().int()]),error:x({code:R().int(),message:h(),data:Ie(Le())})}).strict(),C0=x({jsonrpc:A(Xr)}).merge(x({method:h(),params:Ie(xs)})).strict(),E0=ee([T0,C0,S0,I0]),R0=class{constructor({url:e,headers:t}){this.connected=!1,this.url=new URL(e),this.headers=t}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController,(async()=>{var r,o,s;try{const a=new Headers(this.headers);a.set("Accept","text/event-stream");const i=await fetch(this.url.href,{headers:a,signal:(r=this.abortController)==null?void 0:r.signal});if(!i.ok||!i.body){const w=new $e({message:`MCP SSE Transport Error: ${i.status} ${i.statusText}`});return(o=this.onerror)==null||o.call(this,w),t(w)}const u=i.body.pipeThrough(new TextDecoderStream).pipeThrough(new yr).getReader(),c=async()=>{var w,_,d;try{for(;;){const{done:f,value:y}=await u.read();if(f){if(this.connected)throw this.connected=!1,new $e({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:v,data:p}=y;if(v==="endpoint"){if(this.endpoint=new URL(p,this.url),this.endpoint.origin!==this.url.origin)throw new $e({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(v==="message")try{const b=E0.parse(JSON.parse(p));(w=this.onmessage)==null||w.call(this,b)}catch(b){const g=new $e({message:"MCP SSE Transport Error: Failed to parse message",cause:b});(_=this.onerror)==null||_.call(this,g)}}}catch(f){if(f instanceof Error&&f.name==="AbortError")return;(d=this.onerror)==null||d.call(this,f),t(f)}};this.sseConnection={close:()=>u.cancel()},c()}catch(a){if(a instanceof Error&&a.name==="AbortError")return;(s=this.onerror)==null||s.call(this,a),t(a)}})()})}async close(){var e,t,n;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){var t,n,r;if(!this.endpoint||!this.connected)throw new $e({message:"MCP SSE Transport Error: Not connected"});try{const o=new Headers(this.headers);o.set("Content-Type","application/json");const s={method:"POST",headers:o,body:JSON.stringify(e),signal:(t=this.abortController)==null?void 0:t.signal},a=await fetch(this.endpoint,s);if(!a.ok){const i=await a.text().catch(()=>null),l=new $e({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${a.status}): ${i}`});(n=this.onerror)==null||n.call(this,l);return}}catch(o){(r=this.onerror)==null||r.call(this,o);return}}};function A0(e){if(e.type!=="sse")throw new $e({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."});return new R0(e)}function O0(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var N0="1.0.0";async function M0(e){const t=new P0(e);return await t.init(),t}var P0=class{constructor({transport:e,name:t="ai-sdk-mcp-client",onUncaughtError:n}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,O0(e)?this.transport=e:this.transport=A0(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=r=>this.onError(r),this.transport.onmessage=r=>{if("method"in r){this.onError(new $e({message:"Unsupported message type"}));return}this.onResponse(r)},this.clientInfo={name:t,version:N0}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:wc,capabilities:{},clientInfo:this.clientInfo}},resultSchema:f0});if(e===void 0)throw new $e({message:"Server sent invalid initialize result"});if(!c0.includes(e.protocolVersion))throw new $e({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new $e({message:"Server does not support tools"});break;default:throw new $e({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,o)=>{if(this.isClosed)return o(new $e({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const s=n==null?void 0:n.signal;s==null||s.throwIfAborted();const a=this.requestMessageId++,i={...e,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,u=>{if(s!=null&&s.aborted)return o(new $e({message:"Request was aborted",cause:s.reason}));if(u instanceof Error)return o(u);try{const c=t.parse(u.result);r(c)}catch(c){const w=new $e({message:"Failed to parse server response",cause:c});o(w)}}),this.transport.send(i).catch(u=>{l(),o(u)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:y0,options:t})}catch(n){throw n}}async callTool({name:e,args:t,options:n}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:k0,options:{signal:n==null?void 0:n.abortSignal}})}catch(r){throw r}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){var t;const n={};try{const r=await this.listTools();for(const{name:o,description:s,inputSchema:a}of r.tools){if(e!=="automatic"&&!(o in e))continue;const i=this,l=async(c,w)=>{var _;return(_=w==null?void 0:w.abortSignal)==null||_.throwIfAborted(),i.callTool({name:o,args:c,options:w})},u=e==="automatic"?_l({description:s,inputSchema:Bn({...a,properties:(t=a.properties)!=null?t:{},additionalProperties:!1}),execute:l}):{description:s,inputSchema:e[o].inputSchema,execute:l};n[o]=u}return n}catch(r){throw r}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new $e({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new $e({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n("result"in e?e:new $e({message:e.error.message,cause:e.error}))}};const xc="2025-06-18",Qr="2.0",kc=Ve([k(),Pe().int()]),Tc=k(),$0=$({progressToken:O(kc)}).passthrough(),ut=$({_meta:O($0)}).passthrough(),Ye=$({method:k(),params:O(ut)}),er=$({_meta:O($({}).passthrough())}).passthrough(),xt=$({method:k(),params:O(er)}),ct=$({_meta:O($({}).passthrough())}).passthrough(),eo=Ve([k(),Pe().int()]),Sc=$({jsonrpc:K(Qr),id:eo}).merge(Ye).strict(),z0=e=>Sc.safeParse(e).success,j0=$({jsonrpc:K(Qr)}).merge(xt).strict(),Ic=$({jsonrpc:K(Qr),id:eo,result:ct}).strict(),D0=e=>Ic.safeParse(e).success;var Cc;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"})(Cc||(Cc={}));const Z0=$({jsonrpc:K(Qr),id:eo,error:$({code:Pe().int(),message:k(),data:O(Dn())})}).strict(),ks=Ve([Sc,j0,Ic,Z0]),Ec=ct.strict(),Rc=xt.extend({method:K("notifications/cancelled"),params:er.extend({requestId:eo,reason:k().optional()})}),tr=$({name:k(),title:O(k())}).passthrough(),Ac=tr.extend({version:k()}),U0=$({experimental:O($({}).passthrough()),sampling:O($({}).passthrough()),elicitation:O($({}).passthrough()),roots:O($({listChanged:O(Oe())}).passthrough())}).passthrough(),L0=Ye.extend({method:K("initialize"),params:ut.extend({protocolVersion:k(),capabilities:U0,clientInfo:Ac})}),q0=$({experimental:O($({}).passthrough()),logging:O($({}).passthrough()),completions:O($({}).passthrough()),prompts:O($({listChanged:O(Oe())}).passthrough()),resources:O($({subscribe:O(Oe()),listChanged:O(Oe())}).passthrough()),tools:O($({listChanged:O(Oe())}).passthrough())}).passthrough(),B0=ct.extend({protocolVersion:k(),capabilities:q0,serverInfo:Ac,instructions:O(k())}),Oc=xt.extend({method:K("notifications/initialized")}),V0=e=>Oc.safeParse(e).success,Nc=Ye.extend({method:K("ping")}),F0=$({progress:Pe(),total:O(Pe()),message:O(k())}).passthrough(),Mc=xt.extend({method:K("notifications/progress"),params:er.merge(F0).extend({progressToken:kc})}),to=Ye.extend({params:ut.extend({cursor:O(Tc)}).optional()}),no=ct.extend({nextCursor:O(Tc)}),Pc=$({uri:k(),mimeType:O(k()),_meta:O($({}).passthrough())}).passthrough(),$c=Pc.extend({text:k()}),Ts=k().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),zc=Pc.extend({blob:Ts}),jc=tr.extend({uri:k(),description:O(k()),mimeType:O(k()),_meta:O($({}).passthrough())}),H0=tr.extend({uriTemplate:k(),description:O(k()),mimeType:O(k()),_meta:O($({}).passthrough())}),J0=to.extend({method:K("resources/list")}),G0=no.extend({resources:L(jc)}),W0=to.extend({method:K("resources/templates/list")}),K0=no.extend({resourceTemplates:L(H0)}),Y0=Ye.extend({method:K("resources/read"),params:ut.extend({uri:k()})}),X0=ct.extend({contents:L(Ve([$c,zc]))}),Q0=xt.extend({method:K("notifications/resources/list_changed")}),eb=Ye.extend({method:K("resources/subscribe"),params:ut.extend({uri:k()})}),tb=Ye.extend({method:K("resources/unsubscribe"),params:ut.extend({uri:k()})}),nb=xt.extend({method:K("notifications/resources/updated"),params:er.extend({uri:k()})}),rb=$({name:k(),description:O(k()),required:O(Oe())}).passthrough(),ob=tr.extend({description:O(k()),arguments:O(L(rb)),_meta:O($({}).passthrough())}),sb=to.extend({method:K("prompts/list")}),ab=no.extend({prompts:L(ob)}),ib=Ye.extend({method:K("prompts/get"),params:ut.extend({name:k(),arguments:O(Zn(k()))})}),Ss=$({type:K("text"),text:k(),_meta:O($({}).passthrough())}).passthrough(),Is=$({type:K("image"),data:Ts,mimeType:k(),_meta:O($({}).passthrough())}).passthrough(),Cs=$({type:K("audio"),data:Ts,mimeType:k(),_meta:O($({}).passthrough())}).passthrough(),lb=$({type:K("resource"),resource:Ve([$c,zc]),_meta:O($({}).passthrough())}).passthrough(),ub=jc.extend({type:K("resource_link")}),Dc=Ve([Ss,Is,Cs,ub,lb]),cb=$({role:Pt(["user","assistant"]),content:Dc}).passthrough(),db=ct.extend({description:O(k()),messages:L(cb)}),pb=xt.extend({method:K("notifications/prompts/list_changed")}),hb=$({title:O(k()),readOnlyHint:O(Oe()),destructiveHint:O(Oe()),idempotentHint:O(Oe()),openWorldHint:O(Oe())}).passthrough(),fb=tr.extend({description:O(k()),inputSchema:$({type:K("object"),properties:O($({}).passthrough()),required:O(L(k()))}).passthrough(),outputSchema:O($({type:K("object"),properties:O($({}).passthrough()),required:O(L(k()))}).passthrough()),annotations:O(hb),_meta:O($({}).passthrough())}),mb=to.extend({method:K("tools/list")}),gb=no.extend({tools:L(fb)}),Zc=ct.extend({content:L(Dc).default([]),structuredContent:$({}).passthrough().optional(),isError:O(Oe())});Zc.or(ct.extend({toolResult:Dn()}));const yb=Ye.extend({method:K("tools/call"),params:ut.extend({name:k(),arguments:O(Zn(Dn()))})}),vb=xt.extend({method:K("notifications/tools/list_changed")}),Uc=Pt(["debug","info","notice","warning","error","critical","alert","emergency"]),_b=Ye.extend({method:K("logging/setLevel"),params:ut.extend({level:Uc})}),wb=xt.extend({method:K("notifications/message"),params:er.extend({level:Uc,logger:O(k()),data:Dn()})}),bb=$({name:k().optional()}).passthrough(),xb=$({hints:O(L(bb)),costPriority:O(Pe().min(0).max(1)),speedPriority:O(Pe().min(0).max(1)),intelligencePriority:O(Pe().min(0).max(1))}).passthrough(),kb=$({role:Pt(["user","assistant"]),content:Ve([Ss,Is,Cs])}).passthrough(),Tb=Ye.extend({method:K("sampling/createMessage"),params:ut.extend({messages:L(kb),systemPrompt:O(k()),includeContext:O(Pt(["none","thisServer","allServers"])),temperature:O(Pe()),maxTokens:Pe().int(),stopSequences:O(L(k())),metadata:O($({}).passthrough()),modelPreferences:O(xb)})}),Sb=ct.extend({model:k(),stopReason:O(Pt(["endTurn","stopSequence","maxTokens"]).or(k())),role:Pt(["user","assistant"]),content:Kg("type",[Ss,Is,Cs])}),Ib=$({type:K("boolean"),title:O(k()),description:O(k()),default:O(Oe())}).passthrough(),Cb=$({type:K("string"),title:O(k()),description:O(k()),minLength:O(Pe()),maxLength:O(Pe()),format:O(Pt(["email","uri","date","date-time"]))}).passthrough(),Eb=$({type:Pt(["number","integer"]),title:O(k()),description:O(k()),minimum:O(Pe()),maximum:O(Pe())}).passthrough(),Rb=$({type:K("string"),title:O(k()),description:O(k()),enum:L(k()),enumNames:O(L(k()))}).passthrough(),Ab=Ve([Ib,Cb,Eb,Rb]),Ob=Ye.extend({method:K("elicitation/create"),params:ut.extend({message:k(),requestedSchema:$({type:K("object"),properties:Zn(k(),Ab),required:O(L(k()))}).passthrough()})}),Nb=ct.extend({action:Pt(["accept","decline","cancel"]),content:O(Zn(k(),Dn()))}),Mb=$({type:K("ref/resource"),uri:k()}).passthrough(),Pb=$({type:K("ref/prompt"),name:k()}).passthrough(),$b=Ye.extend({method:K("completion/complete"),params:ut.extend({ref:Ve([Pb,Mb]),argument:$({name:k(),value:k()}).passthrough(),context:O($({arguments:O(Zn(k(),k()))}))})}),zb=ct.extend({completion:$({values:L(k()).max(100),total:O(Pe().int()),hasMore:O(Oe())}).passthrough()}),jb=$({uri:k().startsWith("file://"),name:O(k()),_meta:O($({}).passthrough())}).passthrough(),Db=Ye.extend({method:K("roots/list")}),Zb=ct.extend({roots:L(jb)}),Ub=xt.extend({method:K("notifications/roots/list_changed")});Ve([Nc,L0,$b,_b,ib,sb,J0,W0,Y0,eb,tb,yb,mb]),Ve([Rc,Mc,Oc,Ub]),Ve([Ec,Sb,Nb,Zb]),Ve([Nc,Tb,Ob,Db]),Ve([Rc,Mc,wb,nb,Q0,vb,pb]),Ve([Ec,B0,zb,db,ab,G0,K0,X0,Zc,gb]);let Es;Es=globalThis.crypto;async function Lb(e){return(await Es).getRandomValues(new Uint8Array(e))}async function qb(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let n="";const r=await Lb(e);for(let o=0;o<e;o++){const s=r[o]%t.length;n+=t[s]}return n}async function Bb(e){return await qb(e)}async function Vb(e){const t=await(await Es).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Fb(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await Bb(e),n=await Vb(t);return{code_verifier:t,code_challenge:n}}const Hb=$({resource:k().url(),authorization_servers:L(k().url()).optional(),jwks_uri:k().url().optional(),scopes_supported:L(k()).optional(),bearer_methods_supported:L(k()).optional(),resource_signing_alg_values_supported:L(k()).optional(),resource_name:k().optional(),resource_documentation:k().optional(),resource_policy_uri:k().url().optional(),resource_tos_uri:k().url().optional(),tls_client_certificate_bound_access_tokens:Oe().optional(),authorization_details_types_supported:L(k()).optional(),dpop_signing_alg_values_supported:L(k()).optional(),dpop_bound_access_tokens_required:Oe().optional()}).passthrough(),Lc=$({issuer:k(),authorization_endpoint:k(),token_endpoint:k(),registration_endpoint:k().optional(),scopes_supported:L(k()).optional(),response_types_supported:L(k()),response_modes_supported:L(k()).optional(),grant_types_supported:L(k()).optional(),token_endpoint_auth_methods_supported:L(k()).optional(),token_endpoint_auth_signing_alg_values_supported:L(k()).optional(),service_documentation:k().optional(),revocation_endpoint:k().optional(),revocation_endpoint_auth_methods_supported:L(k()).optional(),revocation_endpoint_auth_signing_alg_values_supported:L(k()).optional(),introspection_endpoint:k().optional(),introspection_endpoint_auth_methods_supported:L(k()).optional(),introspection_endpoint_auth_signing_alg_values_supported:L(k()).optional(),code_challenge_methods_supported:L(k()).optional()}).passthrough(),Jb=$({issuer:k(),authorization_endpoint:k(),token_endpoint:k(),userinfo_endpoint:k().optional(),jwks_uri:k(),registration_endpoint:k().optional(),scopes_supported:L(k()).optional(),response_types_supported:L(k()),response_modes_supported:L(k()).optional(),grant_types_supported:L(k()).optional(),acr_values_supported:L(k()).optional(),subject_types_supported:L(k()),id_token_signing_alg_values_supported:L(k()),id_token_encryption_alg_values_supported:L(k()).optional(),id_token_encryption_enc_values_supported:L(k()).optional(),userinfo_signing_alg_values_supported:L(k()).optional(),userinfo_encryption_alg_values_supported:L(k()).optional(),userinfo_encryption_enc_values_supported:L(k()).optional(),request_object_signing_alg_values_supported:L(k()).optional(),request_object_encryption_alg_values_supported:L(k()).optional(),request_object_encryption_enc_values_supported:L(k()).optional(),token_endpoint_auth_methods_supported:L(k()).optional(),token_endpoint_auth_signing_alg_values_supported:L(k()).optional(),display_values_supported:L(k()).optional(),claim_types_supported:L(k()).optional(),claims_supported:L(k()).optional(),service_documentation:k().optional(),claims_locales_supported:L(k()).optional(),ui_locales_supported:L(k()).optional(),claims_parameter_supported:Oe().optional(),request_parameter_supported:Oe().optional(),request_uri_parameter_supported:Oe().optional(),require_request_uri_registration:Oe().optional(),op_policy_uri:k().optional(),op_tos_uri:k().optional()}).passthrough().merge(Lc.pick({code_challenge_methods_supported:!0})),qc=$({access_token:k(),id_token:k().optional(),token_type:k(),expires_in:Pe().optional(),scope:k().optional(),refresh_token:k().optional()}).strip(),Gb=$({error:k(),error_description:k().optional(),error_uri:k().optional()}),Wb=$({redirect_uris:L(k()).refine(e=>e.every(t=>URL.canParse(t)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:k().optional(),grant_types:L(k()).optional(),response_types:L(k()).optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),scope:k().optional(),contacts:L(k()).optional(),tos_uri:k().optional(),policy_uri:k().optional(),jwks_uri:k().optional(),jwks:Wg().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional()}).strip(),Kb=$({client_id:k(),client_secret:k().optional(),client_id_issued_at:Pe().optional(),client_secret_expires_at:Pe().optional()}).strip(),Yb=Wb.merge(Kb);$({error:k(),error_description:k().optional()}).strip(),$({token:k(),token_type_hint:k().optional()}).strip();function Xb(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Qb({requestedResource:e,configuredResource:t}){const n=typeof e=="string"?new URL(e):new URL(e.href),r=typeof t=="string"?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;const o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/";return o.startsWith(s)}class je extends Error{constructor(t,n){super(t),this.errorUri=n,this.name=this.constructor.name}toResponseObject(){const t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}}class Rs extends je{}Rs.errorCode="invalid_request";class ro extends je{}ro.errorCode="invalid_client";class oo extends je{}oo.errorCode="invalid_grant";class so extends je{}so.errorCode="unauthorized_client";class As extends je{}As.errorCode="unsupported_grant_type";class Os extends je{}Os.errorCode="invalid_scope";class Ns extends je{}Ns.errorCode="access_denied";class yn extends je{}yn.errorCode="server_error";class Ms extends je{}Ms.errorCode="temporarily_unavailable";class Ps extends je{}Ps.errorCode="unsupported_response_type";class $s extends je{}$s.errorCode="unsupported_token_type";class zs extends je{}zs.errorCode="invalid_token";class js extends je{}js.errorCode="method_not_allowed";class Ds extends je{}Ds.errorCode="too_many_requests";class Zs extends je{}Zs.errorCode="invalid_client_metadata";class Us extends je{}Us.errorCode="insufficient_scope";const ex={[Rs.errorCode]:Rs,[ro.errorCode]:ro,[oo.errorCode]:oo,[so.errorCode]:so,[As.errorCode]:As,[Os.errorCode]:Os,[Ns.errorCode]:Ns,[yn.errorCode]:yn,[Ms.errorCode]:Ms,[Ps.errorCode]:Ps,[$s.errorCode]:$s,[zs.errorCode]:zs,[js.errorCode]:js,[Ds.errorCode]:Ds,[Zs.errorCode]:Zs,[Us.errorCode]:Us};class nr extends Error{constructor(t){super(t??"Unauthorized")}}function Bc(e,t){const n=e.client_secret!==void 0;return t.length===0?n?"client_secret_post":"none":n&&t.includes("client_secret_basic")?"client_secret_basic":n&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":n?"client_secret_post":"none"}function Vc(e,t,n,r){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":tx(o,s,n);return;case"client_secret_post":nx(o,s,r);return;case"none":rx(o,r);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function tx(e,t,n){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const r=btoa(`${e}:${t}`);n.set("Authorization",`Basic ${r}`)}function nx(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}function rx(e,t){t.set("client_id",e)}async function Ls(e){const t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{const r=Gb.parse(JSON.parse(n)),{error:o,error_description:s,error_uri:a}=r,i=ex[o]||yn;return new i(s||"",a)}catch(r){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${r}. Raw body: ${n}`;return new yn(o)}}async function qs(e,t){var n,r;try{return await Bs(e,t)}catch(o){if(o instanceof ro||o instanceof so)return await((n=e.invalidateCredentials)===null||n===void 0?void 0:n.call(e,"all")),await Bs(e,t);if(o instanceof oo)return await((r=e.invalidateCredentials)===null||r===void 0?void 0:r.call(e,"tokens")),await Bs(e,t);throw o}}async function Bs(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await ax(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=t);const l=await ox(t,e,a),u=await dx(i,{fetchFn:s});let c=await Promise.resolve(e.clientInformation());if(!c){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const y=await mx(i,{metadata:u,clientMetadata:e.clientMetadata});await e.saveClientInformation(y),c=y}if(n!==void 0){const y=await e.codeVerifier(),v=await hx(i,{metadata:u,clientInformation:c,authorizationCode:n,codeVerifier:y,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(v),"AUTHORIZED"}const w=await e.tokens();if(w!=null&&w.refresh_token)try{const y=await fx(i,{metadata:u,clientInformation:c,refreshToken:w.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication});return await e.saveTokens(y),"AUTHORIZED"}catch(y){if(!(!(y instanceof je)||y instanceof yn))throw y}const _=e.state?await e.state():void 0,{authorizationUrl:d,codeVerifier:f}=await px(i,{metadata:u,clientInformation:c,state:_,redirectUrl:e.redirectUrl,scope:r||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(f),await e.redirectToAuthorization(d),"REDIRECT"}async function ox(e,t,n){const r=Xb(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n==null?void 0:n.resource);if(n){if(!Qb({requestedResource:r,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function sx(e){const t=e.headers.get("WWW-Authenticate");if(!t)return;const[n,r]=t.split(" ");if(n.toLowerCase()!=="bearer"||!r)return;const s=/resource_metadata="([^"]*)"/.exec(t);if(s)try{return new URL(s[1])}catch{return}}async function ax(e,t,n=fetch){const r=await ux(e,"oauth-protected-resource",n,{protocolVersion:t==null?void 0:t.protocolVersion,metadataUrl:t==null?void 0:t.resourceMetadataUrl});if(!r||r.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!r.ok)throw new Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return Hb.parse(await r.json())}async function Vs(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Vs(e,void 0,n):void 0;throw r}}function ix(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Fc(e,t,n=fetch){return await Vs(e,{"MCP-Protocol-Version":t},n)}function lx(e,t){return!e||e.status===404&&t!=="/"}async function ux(e,t,n,r){var o,s;const a=new URL(e),i=(o=r==null?void 0:r.protocolVersion)!==null&&o!==void 0?o:xc;let l;if(r!=null&&r.metadataUrl)l=new URL(r.metadataUrl);else{const c=ix(t,a.pathname);l=new URL(c,(s=r==null?void 0:r.metadataServerUrl)!==null&&s!==void 0?s:a),l.search=a.search}let u=await Fc(l,i,n);if(!(r!=null&&r.metadataUrl)&&lx(u,a.pathname)){const c=new URL(`/.well-known/${t}`,a);u=await Fc(c,i,n)}return u}function cx(e){const t=typeof e=="string"?new URL(e):e,n=t.pathname!=="/",r=[];if(!n)return r.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),r.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),r;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),r.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),r.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),r.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),r}async function dx(e,{fetchFn:t=fetch,protocolVersion:n=xc}={}){var r;const o={"MCP-Protocol-Version":n},s=cx(e);for(const{url:a,type:i}of s){const l=await Vs(a,o,t);if(!l)throw new Error(`CORS error trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`);if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(i==="oauth")return Lc.parse(await l.json());{const u=Jb.parse(await l.json());if(!(!((r=u.code_challenge_methods_supported)===null||r===void 0)&&r.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return u}}}async function px(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:o,state:s,resource:a}){const i="code",l="S256";let u;if(t){if(u=new URL(t.authorization_endpoint),!t.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else u=new URL("/authorize",e);const c=await Fb(),w=c.code_verifier,_=c.code_challenge;return u.searchParams.set("response_type",i),u.searchParams.set("client_id",n.client_id),u.searchParams.set("code_challenge",_),u.searchParams.set("code_challenge_method",l),u.searchParams.set("redirect_uri",String(r)),s&&u.searchParams.set("state",s),o&&u.searchParams.set("scope",o),o!=null&&o.includes("offline_access")&&u.searchParams.append("prompt","consent"),a&&u.searchParams.set("resource",a.href),{authorizationUrl:u,codeVerifier:w}}async function hx(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:o,redirectUri:s,resource:a,addClientAuthentication:i,fetchFn:l}){var u;const c="authorization_code",w=t!=null&&t.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t!=null&&t.grant_types_supported&&!t.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`);const _=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),d=new URLSearchParams({grant_type:c,code:r,code_verifier:o,redirect_uri:String(s)});if(i)i(_,d,e,t);else{const y=(u=t==null?void 0:t.token_endpoint_auth_methods_supported)!==null&&u!==void 0?u:[],v=Bc(n,y);Vc(v,n,_,d)}a&&d.set("resource",a.href);const f=await(l??fetch)(w,{method:"POST",headers:_,body:d});if(!f.ok)throw await Ls(f);return qc.parse(await f.json())}async function fx(e,{metadata:t,clientInformation:n,refreshToken:r,resource:o,addClientAuthentication:s,fetchFn:a}){var i;const l="refresh_token";let u;if(t){if(u=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else u=new URL("/token",e);const c=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),w=new URLSearchParams({grant_type:l,refresh_token:r});if(s)s(c,w,e,t);else{const d=(i=t==null?void 0:t.token_endpoint_auth_methods_supported)!==null&&i!==void 0?i:[],f=Bc(n,d);Vc(f,n,c,w)}o&&w.set("resource",o.href);const _=await(a??fetch)(u,{method:"POST",headers:c,body:w});if(!_.ok)throw await Ls(_);return qc.parse({refresh_token:r,...await _.json()})}async function mx(e,{metadata:t,clientMetadata:n,fetchFn:r}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await(r??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw await Ls(s);return Yb.parse(await s.json())}const gx={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Fs extends Error{constructor(t,n){super(`Streamable HTTP error: ${n}`),this.code=t}}class yx{constructor(t,n){var r;this._url=t,this._resourceMetadataUrl=void 0,this._requestInit=n==null?void 0:n.requestInit,this._authProvider=n==null?void 0:n.authProvider,this._fetch=n==null?void 0:n.fetch,this._sessionId=n==null?void 0:n.sessionId,this._reconnectionOptions=(r=n==null?void 0:n.reconnectionOptions)!==null&&r!==void 0?r:gx}async _authThenStart(){var t;if(!this._authProvider)throw new nr("No auth provider");let n;try{n=await qs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(r){throw(t=this.onerror)===null||t===void 0||t.call(this,r),r}if(n!=="AUTHORIZED")throw new nr;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var t;const n={};if(this._authProvider){const o=await this._authProvider.tokens();o&&(n.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(n["mcp-session-id"]=this._sessionId),this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const r=this._normalizeHeaders((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...r})}async _startOrAuthSse(t){var n,r,o;const{resumptionToken:s}=t;try{const a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);const i=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,{method:"GET",headers:a,signal:(r=this._abortController)===null||r===void 0?void 0:r.signal});if(!i.ok){if(i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Fs(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,t,!0)}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}_getNextReconnectionDelay(t){const n=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(n*Math.pow(r,t),o)}_normalizeHeaders(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}_scheduleReconnection(t,n=0){var r;const o=this._reconnectionOptions.maxRetries;if(o>0&&n>=o){(r=this.onerror)===null||r===void 0||r.call(this,new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}const s=this._getNextReconnectionDelay(n);setTimeout(()=>{this._startOrAuthSse(t).catch(a=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(t,n+1)})},s)}_handleSseStream(t,n,r){if(!t)return;const{onresumptiontoken:o,replayMessageId:s}=n;let a;(async()=>{var l,u,c,w;try{const _=t.pipeThrough(new TextDecoderStream).pipeThrough(new yr).getReader();for(;;){const{value:d,done:f}=await _.read();if(f)break;if(d.id&&(a=d.id,o==null||o(d.id)),!d.event||d.event==="message")try{const y=ks.parse(JSON.parse(d.data));s!==void 0&&D0(y)&&(y.id=s),(l=this.onmessage)===null||l===void 0||l.call(this,y)}catch(y){(u=this.onerror)===null||u===void 0||u.call(this,y)}}}catch(_){if((c=this.onerror)===null||c===void 0||c.call(this,new Error(`SSE stream disconnected: ${_}`)),r&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(d){(w=this.onerror)===null||w===void 0||w.call(this,new Error(`Failed to reconnect: ${d instanceof Error?d.message:String(d)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new nr("No auth provider");if(await qs(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new nr("Failed to authorize")}async close(){var t,n;(t=this._abortController)===null||t===void 0||t.abort(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(t,n){var r,o,s,a;try{const{resumptionToken:i,onresumptiontoken:l}=n||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:z0(t)?t.id:void 0}).catch(v=>{var p;return(p=this.onerror)===null||p===void 0?void 0:p.call(this,v)});return}const u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");const c={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(t),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},w=await((o=this._fetch)!==null&&o!==void 0?o:fetch)(this._url,c),_=w.headers.get("mcp-session-id");if(_&&(this._sessionId=_),!w.ok){if(w.status===401&&this._authProvider){if(this._resourceMetadataUrl=sx(w),await qs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new nr;return this.send(t)}const v=await w.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${w.status}): ${v}`)}if(w.status===202){V0(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(v=>{var p;return(p=this.onerror)===null||p===void 0?void 0:p.call(this,v)});return}const f=(Array.isArray(t)?t:[t]).filter(v=>"method"in v&&"id"in v&&v.id!==void 0).length>0,y=w.headers.get("content-type");if(f)if(y!=null&&y.includes("text/event-stream"))this._handleSseStream(w.body,{onresumptiontoken:l},!1);else if(y!=null&&y.includes("application/json")){const v=await w.json(),p=Array.isArray(v)?v.map(b=>ks.parse(b)):[ks.parse(v)];for(const b of p)(s=this.onmessage)===null||s===void 0||s.call(this,b)}else throw new Fs(-1,`Unexpected content type: ${y}`)}catch(i){throw(a=this.onerror)===null||a===void 0||a.call(this,i),i}}get sessionId(){return this._sessionId}async terminateSession(){var t,n,r;if(this._sessionId)try{const o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal},a=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,s);if(!a.ok&&a.status!==405)throw new Fs(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(o){throw(r=this.onerror)===null||r===void 0||r.call(this,o),o}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}}function dt(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}function rr(e){return Object.fromEntries([...e.headers])}var vx=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const s=n.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=n[Math.random()*s|0];return a.join("")};if(e==null)return o;if(n.includes(r))throw new _o({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},tt=vx();function Hs(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var _x=["fetch failed","failed to fetch"];function wx({error:e,url:t,requestBodyValues:n}){if(Hs(e))return e;if(e instanceof TypeError&&_x.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new pe({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}function bx(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!=null))}function Hc({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if(typeof e=="string")return e;if(e!=null)throw new gr({message:`${r} API key must be a string.`});if(typeof process>"u")throw new gr({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 gr({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new gr({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var xx=/"__proto__"\s*:/,kx=/"constructor"\s*:/;function Tx(e){const t=JSON.parse(e);return t===null||typeof t!="object"||xx.test(e)===!1&&kx.test(e)===!1?t:Sx(t)}function Sx(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}function Js(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Tx(e)}finally{Error.stackTraceLimit=t}}var Gs=Symbol.for("vercel.ai.validator");function Ix(e){return{[Gs]:!0,validate:e}}function Cx(e){return typeof e=="object"&&e!==null&&Gs in e&&e[Gs]===!0&&"validate"in e}function Ex(e){return Cx(e)?e:Rx(e)}function Rx(e){return Ix(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new yt({value:t,cause:n.issues})}})}async function Ax({value:e,schema:t}){const n=await or({value:e,schema:t});if(!n.success)throw yt.wrap({value:e,cause:n.error});return n.value}async function or({value:e,schema:t}){const n=Ex(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const r=await n.validate(e);return r.success?{success:!0,value:r.value,rawValue:e}:{success:!1,error:yt.wrap({value:e,cause:r.error}),rawValue:e}}catch(r){return{success:!1,error:yt.wrap({value:e,cause:r}),rawValue:e}}}async function Ox({text:e,schema:t}){try{const n=Js(e);return t==null?n:Ax({value:n,schema:t})}catch(n){throw zt.isInstance(n)||yt.isInstance(n)?n:new zt({text:e,cause:n})}}async function Jc({text:e,schema:t}){try{const n=Js(e);return t==null?{success:!0,value:n,rawValue:n}:await or({value:n,schema:t})}catch(n){return{success:!1,error:zt.isInstance(n)?n:new zt({text:e,cause:n}),rawValue:void 0}}}function ao(e){try{return Js(e),!0}catch{return!1}}function Nx({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new yr).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await Jc({text:n,schema:t}))}}))}async function kt({provider:e,providerOptions:t,schema:n}){if((t==null?void 0:t[e])==null)return;const r=await or({value:t[e],schema:n});if(!r.success)throw new _o({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}var Mx=()=>globalThis.fetch,mt=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Gc({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),Px=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Gc({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),Gc=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:s,fetch:a=Mx()})=>{try{const i=await a(e,{method:"POST",headers:bx(t),body:n.content,signal:s}),l=rr(i);if(!i.ok){let u;try{u=await o({response:i,url:e,requestBodyValues:n.values})}catch(c){throw Hs(c)||pe.isInstance(c)?c:new pe({message:"Failed to process error response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw u.value}try{return await r({response:i,url:e,requestBodyValues:n.values})}catch(u){throw u instanceof Error&&(Hs(u)||pe.isInstance(u))?u:new pe({message:"Failed to process successful response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(i){throw wx({error:i,url:e,requestBodyValues:n.values})}};function QT(e){return e}function Ws({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l,...u})=>({type:"provider-defined",id:e,name:t,args:u,inputSchema:n,outputSchema:o,execute:r,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l})}var Wc=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:s})=>{const a=await r.text(),i=rr(r);if(a.trim()==="")return{responseHeaders:i,value:new pe({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,isRetryable:n==null?void 0:n(r)})};try{const l=await Ox({text:a,schema:e});return{responseHeaders:i,value:new pe({message:t(l),url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,data:l,isRetryable:n==null?void 0:n(r,l)})}}catch{return{responseHeaders:i,value:new pe({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,isRetryable:n==null?void 0:n(r)})}}},io=e=>async({response:t})=>{const n=rr(t);if(t.body==null)throw new Ta({});return{responseHeaders:n,value:Nx({stream:t.body,schema:e})}},on=e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),s=await Jc({text:o,schema:e}),a=rr(t);if(!s.success)throw new pe({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}},$x=()=>async({response:e,url:t,requestBodyValues:n})=>{const r=rr(e);if(!e.body)throw new pe({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 pe({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:o})}},{btoa:zx,atob:jx}=globalThis;function Dx(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=jx(t);return Uint8Array.from(n,r=>r.codePointAt(0))}function Zx(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return zx(t)}function sn(e){return e instanceof Uint8Array?Zx(e):e}function Kc(e){return e==null?void 0:e.replace(/\/$/,"")}var Ks=x({error:x({message:h(),type:h().nullish(),param:pt().nullish(),code:ee([h(),R()]).nullish()})}),Tt=Wc({errorSchema:Ks,errorToMessage:e=>e.error.message});function Ux({prompt:e,systemMessageMode:t="system"}){const n=[],r=[];for(const{role:o,content:s}of e)switch(o){case"system":{switch(t){case"system":{n.push({role:"system",content:s});break}case"developer":{n.push({role:"developer",content:s});break}case"remove":{r.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=t;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(s.length===1&&s[0].type==="text"){n.push({role:"user",content:s[0].text});break}n.push({role:"user",content:s.map((a,i)=>{var l,u,c;switch(a.type){case"text":return{type:"text",text:a.text};case"file":if(a.mediaType.startsWith("image/")){const w=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${w};base64,${sn(a.data)}`,detail:(u=(l=a.providerOptions)==null?void 0:l.openai)==null?void 0:u.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new at({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:sn(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:sn(a.data),format:"mp3"}};default:throw new at({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new at({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof a.data=="string"&&a.data.startsWith("file-")?{file_id:a.data}:{filename:(c=a.filename)!=null?c:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${sn(a.data)}`}}}else throw new at({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const i=[];for(const l of s)switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}n.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const a of s){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}n.push({role:"tool",tool_call_id:a.toolCallId,content:l})}break}default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return{messages:n,warnings:r}}function Yc({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function Xc(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"unknown"}}var Lx=x({logitBias:We(wg(),R()).optional(),logprobs:ee([re(),R()]).optional(),parallelToolCalls:re().optional(),user:h().optional(),reasoningEffort:qe(["minimal","low","medium","high"]).optional(),maxCompletionTokens:R().optional(),store:re().optional(),metadata:We(h().max(64),h().max(512)).optional(),prediction:We(h(),pt()).optional(),structuredOutputs:re().optional(),serviceTier:qe(["auto","flex","priority"]).optional(),strictJsonSchema:re().optional(),textVerbosity:qe(["low","medium","high"]).optional(),promptCacheKey:h().optional(),safetyIdentifier:h().optional()}),Qc=x({key:h(),type:qe(["eq","ne","gt","gte","lt","lte"]),value:ee([h(),R(),re()])}),ed=x({type:qe(["and","or"]),filters:Z(ee([Qc,Ji(()=>ed)]))}),qx=ee([Qc,ed]),td=x({vectorStoreIds:Z(h()).optional(),maxNumResults:R().optional(),ranking:x({ranker:qe(["auto","default-2024-08-21"]).optional()}).optional(),filters:qx.optional()}),Bx=Ws({id:"openai.file_search",name:"file_search",inputSchema:x({query:h()})}),nd=x({searchContextSize:qe(["low","medium","high"]).optional(),userLocation:x({type:A("approximate"),country:h().optional(),city:h().optional(),region:h().optional(),timezone:h().optional()}).optional()}),Vx=Ws({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:x({})});function Fx({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){e=e!=null&&e.length?e:void 0;const o=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const s=[];for(const i of e)switch(i.type){case"function":s.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:n?r:void 0}});break;case"provider-defined":switch(i.id){case"openai.file_search":{const l=td.parse(i.args);s.push({type:"file_search",vector_store_ids:l.vectorStoreIds,max_num_results:l.maxNumResults,ranking_options:l.ranking?{ranker:l.ranking.ranker}:void 0,filters:l.filters});break}case"openai.web_search_preview":{const l=nd.parse(i.args);s.push({type:"web_search_preview",search_context_size:l.searchContextSize,user_location:l.userLocation});break}default:o.push({type:"unsupported-tool",tool:i});break}break;default:o.push({type:"unsupported-tool",tool:i});break}if(t==null)return{tools:s,toolChoice:void 0,toolWarnings:o};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:s,toolChoice:a,toolWarnings:o};case"tool":return{tools:s,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:o};default:{const i=a;throw new at({functionality:`tool choice type: ${i}`})}}}var Hx=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,seed:u,tools:c,toolChoice:w,providerOptions:_}){var d,f,y,v;const p=[],b=(d=await kt({provider:"openai",providerOptions:_,schema:Lx}))!=null?d:{},g=(f=b.structuredOutputs)!=null?f:!0;o!=null&&p.push({type:"unsupported-setting",setting:"topK"}),(l==null?void 0:l.type)==="json"&&l.schema!=null&&!g&&p.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:m,warnings:E}=Ux({prompt:e,systemMessageMode:Yx(this.modelId)});p.push(...E);const S=(y=b.strictJsonSchema)!=null?y:!1,T={model:this.modelId,logit_bias:b.logitBias,logprobs:b.logprobs===!0||typeof b.logprobs=="number"?!0:void 0,top_logprobs:typeof b.logprobs=="number"?b.logprobs:typeof b.logprobs=="boolean"&&b.logprobs?0:void 0,user:b.user,parallel_tool_calls:b.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,response_format:(l==null?void 0:l.type)==="json"?g&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:S,name:(v=l.name)!=null?v:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:u,verbosity:b.textVerbosity,max_completion_tokens:b.maxCompletionTokens,store:b.store,metadata:b.metadata,prediction:b.prediction,reasoning_effort:b.reasoningEffort,service_tier:b.serviceTier,prompt_cache_key:b.promptCacheKey,safety_identifier:b.safetyIdentifier,messages:m};od(this.modelId)?(T.temperature!=null&&(T.temperature=void 0,p.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),T.top_p!=null&&(T.top_p=void 0,p.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),T.frequency_penalty!=null&&(T.frequency_penalty=void 0,p.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),T.presence_penalty!=null&&(T.presence_penalty=void 0,p.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),T.logit_bias!=null&&(T.logit_bias=void 0,p.push({type:"other",message:"logitBias is not supported for reasoning models"})),T.logprobs!=null&&(T.logprobs=void 0,p.push({type:"other",message:"logprobs is not supported for reasoning models"})),T.top_logprobs!=null&&(T.top_logprobs=void 0,p.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),T.max_tokens!=null&&(T.max_completion_tokens==null&&(T.max_completion_tokens=T.max_tokens),T.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&T.temperature!=null&&(T.temperature=void 0,p.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),b.serviceTier==="flex"&&!Wx(this.modelId)&&(p.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),T.service_tier=void 0),b.serviceTier==="priority"&&!Kx(this.modelId)&&(p.push({type:"unsupported-setting",setting:"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"}),T.service_tier=void 0);const{tools:P,toolChoice:V,toolWarnings:H}=Fx({tools:c,toolChoice:w,structuredOutputs:g,strictJsonSchema:S});return{args:{...T,tools:P,tool_choice:V},warnings:[...p,...H]}}async doGenerate(e){var t,n,r,o,s,a,i,l,u,c,w,_,d,f;const{args:y,warnings:v}=await this.getArgs(e),{responseHeaders:p,value:b,rawValue:g}=await mt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:y,failedResponseHandler:Tt,successfulResponseHandler:on(Jx),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=b.choices[0],E=[],S=m.message.content;S!=null&&S.length>0&&E.push({type:"text",text:S});for(const H of(t=m.message.tool_calls)!=null?t:[])E.push({type:"tool-call",toolCallId:(n=H.id)!=null?n:tt(),toolName:H.function.name,input:H.function.arguments});for(const H of(r=m.message.annotations)!=null?r:[])E.push({type:"source",sourceType:"url",id:tt(),url:H.url,title:H.title});const T=(o=b.usage)==null?void 0:o.completion_tokens_details,P=(s=b.usage)==null?void 0:s.prompt_tokens_details,V={openai:{}};return(T==null?void 0:T.accepted_prediction_tokens)!=null&&(V.openai.acceptedPredictionTokens=T==null?void 0:T.accepted_prediction_tokens),(T==null?void 0:T.rejected_prediction_tokens)!=null&&(V.openai.rejectedPredictionTokens=T==null?void 0:T.rejected_prediction_tokens),((a=m.logprobs)==null?void 0:a.content)!=null&&(V.openai.logprobs=m.logprobs.content),{content:E,finishReason:Xc(m.finish_reason),usage:{inputTokens:(l=(i=b.usage)==null?void 0:i.prompt_tokens)!=null?l:void 0,outputTokens:(c=(u=b.usage)==null?void 0:u.completion_tokens)!=null?c:void 0,totalTokens:(_=(w=b.usage)==null?void 0:w.total_tokens)!=null?_:void 0,reasoningTokens:(d=T==null?void 0:T.reasoning_tokens)!=null?d:void 0,cachedInputTokens:(f=P==null?void 0:P.cached_tokens)!=null?f:void 0},request:{body:y},response:{...Yc(b),headers:p,body:g},warnings:v,providerMetadata:V}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await mt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:r,failedResponseHandler:Tt,successfulResponseHandler:io(Gx),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let i="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0,c=!1;const w={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:n})},transform(_,d){var f,y,v,p,b,g,m,E,S,T,P,V,H,B,oe,F,be,Ee,Ne,Xe,I,ie,me,de;if(e.includeRawChunks&&d.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){i="error",d.enqueue({type:"error",error:_.error});return}const Q=_.value;if("error"in Q){i="error",d.enqueue({type:"error",error:Q.error});return}u&&(u=!1,d.enqueue({type:"response-metadata",...Yc(Q)})),Q.usage!=null&&(l.inputTokens=(f=Q.usage.prompt_tokens)!=null?f:void 0,l.outputTokens=(y=Q.usage.completion_tokens)!=null?y:void 0,l.totalTokens=(v=Q.usage.total_tokens)!=null?v:void 0,l.reasoningTokens=(b=(p=Q.usage.completion_tokens_details)==null?void 0:p.reasoning_tokens)!=null?b:void 0,l.cachedInputTokens=(m=(g=Q.usage.prompt_tokens_details)==null?void 0:g.cached_tokens)!=null?m:void 0,((E=Q.usage.completion_tokens_details)==null?void 0:E.accepted_prediction_tokens)!=null&&(w.openai.acceptedPredictionTokens=(S=Q.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens),((T=Q.usage.completion_tokens_details)==null?void 0:T.rejected_prediction_tokens)!=null&&(w.openai.rejectedPredictionTokens=(P=Q.usage.completion_tokens_details)==null?void 0:P.rejected_prediction_tokens));const fe=Q.choices[0];if((fe==null?void 0:fe.finish_reason)!=null&&(i=Xc(fe.finish_reason)),((V=fe==null?void 0:fe.logprobs)==null?void 0:V.content)!=null&&(w.openai.logprobs=fe.logprobs.content),(fe==null?void 0:fe.delta)==null)return;const Ze=fe.delta;if(Ze.content!=null&&(c||(d.enqueue({type:"text-start",id:"0"}),c=!0),d.enqueue({type:"text-delta",id:"0",delta:Ze.content})),Ze.tool_calls!=null)for(const se of Ze.tool_calls){const It=se.index;if(a[It]==null){if(se.type!=="function")throw new In({data:se,message:"Expected 'function' type."});if(se.id==null)throw new In({data:se,message:"Expected 'id' to be a string."});if(((H=se.function)==null?void 0:H.name)==null)throw new In({data:se,message:"Expected 'function.name' to be a string."});d.enqueue({type:"tool-input-start",id:se.id,toolName:se.function.name}),a[It]={id:se.id,type:"function",function:{name:se.function.name,arguments:(B=se.function.arguments)!=null?B:""},hasFinished:!1};const Re=a[It];((oe=Re.function)==null?void 0:oe.name)!=null&&((F=Re.function)==null?void 0:F.arguments)!=null&&(Re.function.arguments.length>0&&d.enqueue({type:"tool-input-delta",id:Re.id,delta:Re.function.arguments}),ao(Re.function.arguments)&&(d.enqueue({type:"tool-input-end",id:Re.id}),d.enqueue({type:"tool-call",toolCallId:(be=Re.id)!=null?be:tt(),toolName:Re.function.name,input:Re.function.arguments}),Re.hasFinished=!0));continue}const Se=a[It];Se.hasFinished||(((Ee=se.function)==null?void 0:Ee.arguments)!=null&&(Se.function.arguments+=(Xe=(Ne=se.function)==null?void 0:Ne.arguments)!=null?Xe:""),d.enqueue({type:"tool-input-delta",id:Se.id,delta:(I=se.function.arguments)!=null?I:""}),((ie=Se.function)==null?void 0:ie.name)!=null&&((me=Se.function)==null?void 0:me.arguments)!=null&&ao(Se.function.arguments)&&(d.enqueue({type:"tool-input-end",id:Se.id}),d.enqueue({type:"tool-call",toolCallId:(de=Se.id)!=null?de:tt(),toolName:Se.function.name,input:Se.function.arguments}),Se.hasFinished=!0))}if(Ze.annotations!=null)for(const se of Ze.annotations)d.enqueue({type:"source",sourceType:"url",id:tt(),url:se.url,title:se.title})},flush(_){c&&_.enqueue({type:"text-end",id:"0"}),_.enqueue({type:"finish",finishReason:i,usage:l,...w!=null?{providerMetadata:w}:{}})}})),request:{body:r},response:{headers:o}}}},rd=x({prompt_tokens:R().nullish(),completion_tokens:R().nullish(),total_tokens:R().nullish(),prompt_tokens_details:x({cached_tokens:R().nullish()}).nullish(),completion_tokens_details:x({reasoning_tokens:R().nullish(),accepted_prediction_tokens:R().nullish(),rejected_prediction_tokens:R().nullish()}).nullish()}).nullish(),Jx=x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({message:x({role:A("assistant").nullish(),content:h().nullish(),tool_calls:Z(x({id:h().nullish(),type:A("function"),function:x({name:h(),arguments:h()})})).nullish(),annotations:Z(x({type:A("url_citation"),start_index:R(),end_index:R(),url:h(),title:h()})).nullish()}),index:R(),logprobs:x({content:Z(x({token:h(),logprob:R(),top_logprobs:Z(x({token:h(),logprob:R()}))})).nullish()}).nullish(),finish_reason:h().nullish()})),usage:rd}),Gx=ee([x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({delta:x({role:qe(["assistant"]).nullish(),content:h().nullish(),tool_calls:Z(x({index:R(),id:h().nullish(),type:A("function").nullish(),function:x({name:h().nullish(),arguments:h().nullish()})})).nullish(),annotations:Z(x({type:A("url_citation"),start_index:R(),end_index:R(),url:h(),title:h()})).nullish()}).nullish(),logprobs:x({content:Z(x({token:h(),logprob:R(),top_logprobs:Z(x({token:h(),logprob:R()}))})).nullish()}).nullish(),finish_reason:h().nullish(),index:R()})),usage:rd}),Ks]);function od(e){return(e.startsWith("o")||e.startsWith("gpt-5"))&&!e.startsWith("gpt-5-chat")}function Wx(e){return e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat")}function Kx(e){return 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")}function Yx(e){var t,n;return od(e)?(n=(t=Xx[e])==null?void 0:t.systemMessageMode)!=null?n:"developer":"system"}var Xx={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function Qx({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
66
+ `)}})}},mc={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Bw({status:e,statusText:t,headers:n,stream:r,consumeSseStream:o}){let s=r.pipeThrough(new fc);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Wr(n,mc)})}function Vw({originalMessages:e,responseMessageId:t}){if(e==null)return;const n=e[e.length-1];return(n==null?void 0:n.role)==="assistant"?n.id:typeof t=="function"?t():t}ee([ye({type:A("text-start"),id:h(),providerMetadata:xe.optional()}),ye({type:A("text-delta"),id:h(),delta:h(),providerMetadata:xe.optional()}),ye({type:A("text-end"),id:h(),providerMetadata:xe.optional()}),ye({type:A("error"),errorText:h()}),ye({type:A("tool-input-start"),toolCallId:h(),toolName:h(),providerExecuted:re().optional(),dynamic:re().optional()}),ye({type:A("tool-input-delta"),toolCallId:h(),inputTextDelta:h()}),ye({type:A("tool-input-available"),toolCallId:h(),toolName:h(),input:Le(),providerExecuted:re().optional(),providerMetadata:xe.optional(),dynamic:re().optional()}),ye({type:A("tool-input-error"),toolCallId:h(),toolName:h(),input:Le(),providerExecuted:re().optional(),providerMetadata:xe.optional(),dynamic:re().optional(),errorText:h()}),ye({type:A("tool-output-available"),toolCallId:h(),output:Le(),providerExecuted:re().optional(),dynamic:re().optional(),preliminary:re().optional()}),ye({type:A("tool-output-error"),toolCallId:h(),errorText:h(),providerExecuted:re().optional(),dynamic:re().optional()}),ye({type:A("reasoning"),text:h(),providerMetadata:xe.optional()}),ye({type:A("reasoning-start"),id:h(),providerMetadata:xe.optional()}),ye({type:A("reasoning-delta"),id:h(),delta:h(),providerMetadata:xe.optional()}),ye({type:A("reasoning-end"),id:h(),providerMetadata:xe.optional()}),ye({type:A("reasoning-part-finish")}),ye({type:A("source-url"),sourceId:h(),url:h(),title:h().optional(),providerMetadata:xe.optional()}),ye({type:A("source-document"),sourceId:h(),mediaType:h(),title:h(),filename:h().optional(),providerMetadata:xe.optional()}),ye({type:A("file"),url:h(),mediaType:h(),providerMetadata:xe.optional()}),ye({type:h().startsWith("data-"),id:h().optional(),data:Le(),transient:re().optional()}),ye({type:A("start-step")}),ye({type:A("finish-step")}),ye({type:A("start"),messageId:h().optional(),messageMetadata:Le().optional()}),ye({type:A("finish"),messageMetadata:Le().optional()}),ye({type:A("abort")}),ye({type:A("message-metadata"),messageMetadata:Le()})]);function Fw(e){return e.type.startsWith("data-")}function gc(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),i=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);a&&i?n[r]=gc(s,o):n[r]=o}return n}function Hw(e){const t=["ROOT"];let n=-1,r=null;function o(l,u,c){switch(l){case'"':{n=u,t.pop(),t.push(c),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(c),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(c),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=u,t.pop(),t.push(c),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(c),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(c),t.push("INSIDE_ARRAY_START");break}}}function s(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function a(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":o(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,o(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){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(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){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(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const w=e.substring(r,l+1);!"false".startsWith(w)&&!"true".startsWith(w)&&!"null".startsWith(w)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,l)):n=l;break}}}let i=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{i+='"';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":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const c=e.substring(r,e.length);"true".startsWith(c)?i+="true".slice(c.length):"false".startsWith(c)?i+="false".slice(c.length):"null".startsWith(c)&&(i+="null".slice(c.length))}}return i}async function yc(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await fn({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await fn({text:Hw(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function bs(e){return e.type.startsWith("tool-")}function vc(e){return e.type.split("-").slice(1).join("-")}function Jw({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Gw({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:o,onToolCall:s,onData:a}){return e.pipeThrough(new TransformStream({async transform(i,l){await r(async({state:u,write:c})=>{var w,_,d,f;function y(m){const S=u.message.parts.filter(bs).find(T=>T.toolCallId===m);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function v(m){const S=u.message.parts.filter(T=>T.type==="dynamic-tool").find(T=>T.toolCallId===m);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function p(m){var E;const S=u.message.parts.find(V=>bs(V)&&V.toolCallId===m.toolCallId),T=m,P=S;S!=null?(S.state=m.state,P.input=T.input,P.output=T.output,P.errorText=T.errorText,P.rawInput=T.rawInput,P.preliminary=T.preliminary,P.providerExecuted=(E=T.providerExecuted)!=null?E:S.providerExecuted,T.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=T.providerMetadata)):u.message.parts.push({type:`tool-${m.toolName}`,toolCallId:m.toolCallId,state:m.state,input:T.input,output:T.output,rawInput:T.rawInput,errorText:T.errorText,providerExecuted:T.providerExecuted,preliminary:T.preliminary,...T.providerMetadata!=null?{callProviderMetadata:T.providerMetadata}:{}})}function b(m){var E;const S=u.message.parts.find(V=>V.type==="dynamic-tool"&&V.toolCallId===m.toolCallId),T=m,P=S;S!=null?(S.state=m.state,P.toolName=m.toolName,P.input=T.input,P.output=T.output,P.errorText=T.errorText,P.rawInput=(E=T.rawInput)!=null?E:P.rawInput,P.preliminary=T.preliminary,T.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=T.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:m.toolName,toolCallId:m.toolCallId,state:m.state,input:T.input,output:T.output,errorText:T.errorText,preliminary:T.preliminary,...T.providerMetadata!=null?{callProviderMetadata:T.providerMetadata}:{}})}async function g(m){if(m!=null){const E=u.message.metadata!=null?gc(u.message.metadata,m):m;t!=null&&await Ko({value:E,schema:t}),u.message.metadata=E}}switch(i.type){case"text-start":{const m={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeTextParts[i.id]=m,u.message.parts.push(m),c();break}case"text-delta":{const m=u.activeTextParts[i.id];m.text+=i.delta,m.providerMetadata=(w=i.providerMetadata)!=null?w:m.providerMetadata,c();break}case"text-end":{const m=u.activeTextParts[i.id];m.state="done",m.providerMetadata=(_=i.providerMetadata)!=null?_:m.providerMetadata,delete u.activeTextParts[i.id],c();break}case"reasoning-start":{const m={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};u.activeReasoningParts[i.id]=m,u.message.parts.push(m),c();break}case"reasoning-delta":{const m=u.activeReasoningParts[i.id];m.text+=i.delta,m.providerMetadata=(d=i.providerMetadata)!=null?d:m.providerMetadata,c();break}case"reasoning-end":{const m=u.activeReasoningParts[i.id];m.providerMetadata=(f=i.providerMetadata)!=null?f:m.providerMetadata,m.state="done",delete u.activeReasoningParts[i.id],c();break}case"file":{u.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),c();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),c();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),c();break}case"tool-input-start":{const m=u.message.parts.filter(bs);u.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:m.length,dynamic:i.dynamic},i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),c();break}case"tool-input-delta":{const m=u.partialToolCalls[i.toolCallId];m.text+=i.inputTextDelta;const{value:E}=await yc(m.text);m.dynamic?b({toolCallId:i.toolCallId,toolName:m.toolName,state:"input-streaming",input:E}):p({toolCallId:i.toolCallId,toolName:m.toolName,state:"input-streaming",input:E}),c();break}case"tool-input-available":{i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerMetadata:i.providerMetadata}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),c(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{i.dynamic?b({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerMetadata:i.providerMetadata}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),c();break}case"tool-output-available":{if(i.dynamic){const m=v(i.toolCallId);b({toolCallId:i.toolCallId,toolName:m.toolName,state:"output-available",input:m.input,output:i.output,preliminary:i.preliminary})}else{const m=y(i.toolCallId);p({toolCallId:i.toolCallId,toolName:vc(m),state:"output-available",input:m.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}c();break}case"tool-output-error":{if(i.dynamic){const m=v(i.toolCallId);b({toolCallId:i.toolCallId,toolName:m.toolName,state:"output-error",input:m.input,errorText:i.errorText})}else{const m=y(i.toolCallId);p({toolCallId:i.toolCallId,toolName:vc(m),state:"output-error",input:m.input,rawInput:m.rawInput,errorText:i.errorText})}c();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{i.messageId!=null&&(u.message.id=i.messageId),await g(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&c();break}case"finish":{await g(i.messageMetadata),i.messageMetadata!=null&&c();break}case"message-metadata":{await g(i.messageMetadata),i.messageMetadata!=null&&c();break}case"error":{o==null||o(new Error(i.errorText));break}default:if(Fw(i)){(n==null?void 0:n[i.type])!=null&&await Ko({value:i.data,schema:n[i.type]});const m=i;if(m.transient){a==null||a(m);break}const E=m.id!=null?u.message.parts.find(S=>m.type===S.type&&m.id===S.id):void 0;E!=null?E.data=m.data:u.message.parts.push(m),a==null||a(m),c()}}l.enqueue(i)})}}))}function Ww({messageId:e,originalMessages:t=[],onFinish:n,onError:r,stream:o}){let s=t==null?void 0:t[t.length-1];(s==null?void 0:s.role)!=="assistant"?s=void 0:e=s.id;let a=!1;const i=o.pipeThrough(new TransformStream({transform(c,w){if(c.type==="start"){const _=c;_.messageId==null&&e!=null&&(_.messageId=e)}c.type==="abort"&&(a=!0),w.enqueue(c)}}));if(n==null)return i;const l=Jw({lastMessage:s?structuredClone(s):void 0,messageId:e??""});return Gw({stream:i,runUpdateMessageJob:async c=>{await c({state:l,write:()=>{}})},onError:r}).pipeThrough(new TransformStream({transform(c,w){w.enqueue(c)},async flush(){const c=l.message.id===(s==null?void 0:s.id);await n({isAborted:a,isContinuation:c,responseMessage:l.message,messages:[...c?t.slice(0,-1):t,l.message]})}}))}function Kw({response:e,status:t,statusText:n,headers:r,stream:o,consumeSseStream:s}){let a=o.pipeThrough(new fc);if(s){const[i,l]=a.tee();a=i,s({stream:l})}hc({response:e,status:t,statusText:n,headers:Object.fromEntries(Wr(r,mc).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Kr(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=()=>{const n=t.getReader();return{async next(){const{done:r,value:o}=await n.read();return r?{done:!0,value:void 0}:{done:!1,value:o}}}},t}async function Yw({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}function _c(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}function Xw(){let e=[],t=null,n=!1,r=_c();const o=()=>{n=!0,r.resolve(),e.forEach(a=>a.cancel()),e=[],t==null||t.close()},s=async()=>{if(n&&e.length===0){t==null||t.close();return}if(e.length===0)return r=_c(),await r.promise,s();try{const{value:a,done:i}=await e[0].read();i?(e.shift(),e.length>0?await s():n&&(t==null||t.close())):t==null||t.enqueue(a)}catch(a){t==null||t.error(a),e.shift(),o()}};return{stream:new ReadableStream({start(a){t=a},pull:s,async cancel(){for(const a of e)await a.cancel();e=[],n=!0}}),addStream:a=>{if(n)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),r.resolve()},close:()=>{n=!0,r.resolve(),e.length===0&&(t==null||t.close())},terminate:o}}var Yr=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}};function Qw(e,t){return new ReadableStream({async start(n){const r=e.getReader();try{for(;;){const{done:o,value:s}=await r.read();if(o){n.close();break}n.enqueue(s)}}catch(o){await t({error:o,controller:n})}},cancel(n){return e.cancel(n)}})}function e0(){var e,t;return(t=(e=globalThis==null?void 0:globalThis.performance)==null?void 0:e.now())!=null?t:Date.now()}function t0({tools:e,generatorStream:t,tracer:n,telemetry:r,system:o,messages:s,abortSignal:a,repairToolCall:i,experimental_context:l}){let u=null;const c=new ReadableStream({start(p){u=p}}),w=new Set,_=new Map;let d=!1,f;function y(){d&&w.size===0&&(f!=null&&u.enqueue(f),u.close())}const v=new TransformStream({async transform(p,b){const g=p.type;switch(g){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{b.enqueue(p);break}case"file":{b.enqueue({type:"file",file:new $w({data:p.data,mediaType:p.mediaType})});break}case"finish":{f={type:"finish",finishReason:p.finishReason,usage:p.usage,providerMetadata:p.providerMetadata};break}case"tool-call":{try{const m=await ic({toolCall:p,tools:e,repairToolCall:i,system:o,messages:s});if(b.enqueue(m),m.invalid){u.enqueue({type:"tool-error",toolCallId:m.toolCallId,toolName:m.toolName,input:m.input,error:Wo(m.error),dynamic:!0});break}const E=e[m.toolName];if(_.set(m.toolCallId,m.input),E.onInputAvailable!=null&&await E.onInputAvailable({input:m.input,toolCallId:m.toolCallId,messages:s,abortSignal:a,experimental_context:l}),E.execute!=null&&m.providerExecuted!==!0){const S=Ny();w.add(S),gn({name:"ai.toolCall",attributes:lt({telemetry:r,attributes:{...mn({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":m.toolName,"ai.toolCall.id":m.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(m.input)}}}),tracer:n,fn:async T=>{let P;try{const V=bl({execute:E.execute.bind(E),input:m.input,options:{toolCallId:m.toolCallId,messages:s,abortSignal:a,experimental_context:l}});for await(const H of V)u.enqueue({...m,type:"tool-result",output:H.output,...H.type==="preliminary"&&{preliminary:!0}}),H.type==="final"&&(P=H.output)}catch(V){gs(T,V),u.enqueue({...m,type:"tool-error",error:V}),w.delete(S),y();return}w.delete(S),y();try{T.setAttributes(lt({telemetry:r,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(P)}}}))}catch{}}})}}catch(m){u.enqueue({type:"error",error:m})}break}case"tool-result":{const m=p.toolName;p.isError?u.enqueue({type:"tool-error",toolCallId:p.toolCallId,toolName:m,input:_.get(p.toolCallId),providerExecuted:p.providerExecuted,error:p.result}):b.enqueue({type:"tool-result",toolCallId:p.toolCallId,toolName:m,input:_.get(p.toolCallId),output:p.result,providerExecuted:p.providerExecuted});break}default:{const m=g;throw new Error(`Unhandled chunk type: ${m}`)}}},flush(){d=!0,y()}});return new ReadableStream({async start(p){return Promise.all([t.pipeThrough(v).pipeTo(new WritableStream({write(b){p.enqueue(b)},close(){}})),c.pipeTo(new WritableStream({write(b){p.enqueue(b)},close(){p.close()}}))])}})}var n0=Ln({prefix:"aitxt",size:24});function r0({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:s,maxRetries:a,abortSignal:i,headers:l,stopWhen:u=vs(1),experimental_output:c,experimental_telemetry:w,prepareStep:_,providerOptions:d,experimental_activeTools:f,activeTools:y=f,experimental_repairToolCall:v,experimental_transform:p,includeRawChunks:b=!1,onChunk:g,onError:m=({error:F})=>{console.error(F)},onFinish:E,onAbort:S,onStepFinish:T,experimental_context:P,_internal:{now:V=e0,generateId:H=n0,currentDate:B=()=>new Date}={},...oe}){return new s0({model:Jr(e),telemetry:w,headers:l,settings:oe,maxRetries:a,abortSignal:i,system:r,prompt:o,messages:s,tools:t,toolChoice:n,transforms:ys(p),activeTools:y,repairToolCall:v,stopConditions:ys(u),output:c,providerOptions:d,prepareStep:_,includeRawChunks:b,onChunk:g,onError:m,onFinish:E,onAbort:S,onStepFinish:T,now:V,currentDate:B,generateId:H,experimental_context:P})}function o0(e){if(!e)return new TransformStream({transform(a,i){i.enqueue({part:a,partialOutput:void 0})}});let t,n="",r="",o="";function s({controller:a,partialOutput:i=void 0}){a.enqueue({part:{type:"text-delta",id:t,text:r},partialOutput:i}),r=""}return new TransformStream({async transform(a,i){if(a.type==="finish-step"&&r.length>0&&s({controller:i}),a.type!=="text-delta"&&a.type!=="text-start"&&a.type!=="text-end"){i.enqueue({part:a,partialOutput:void 0});return}if(t==null)t=a.id;else if(a.id!==t){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-start"){i.enqueue({part:a,partialOutput:void 0});return}if(a.type==="text-end"){r.length>0&&s({controller:i}),i.enqueue({part:a,partialOutput:void 0});return}n+=a.text,r+=a.text;const l=await e.parsePartial({text:n});if(l!=null){const u=JSON.stringify(l.partial);u!==o&&(s({controller:i,partialOutput:l.partial}),o=u)}}})}var s0=class{constructor({model:e,telemetry:t,headers:n,settings:r,maxRetries:o,abortSignal:s,system:a,prompt:i,messages:l,tools:u,toolChoice:c,transforms:w,activeTools:_,repairToolCall:d,stopConditions:f,output:y,providerOptions:v,prepareStep:p,includeRawChunks:b,now:g,currentDate:m,generateId:E,onChunk:S,onError:T,onFinish:P,onAbort:V,onStepFinish:H,experimental_context:B}){this._totalUsage=new Yr,this._finishReason=new Yr,this._steps=new Yr,this.output=y,this.includeRawChunks=b,this.tools=u;let oe,F=[];const be=[];let Ee,Ne,Xe={},I=[];const ie=[];let me,de={},Q={};const fe=new TransformStream({async transform(ke,_e){var Ue,ne,ot;_e.enqueue(ke);const{part:D}=ke;if((D.type==="text-delta"||D.type==="reasoning-delta"||D.type==="source"||D.type==="tool-call"||D.type==="tool-result"||D.type==="tool-input-start"||D.type==="tool-input-delta"||D.type==="raw")&&await(S==null?void 0:S({chunk:D})),D.type==="error"&&await T({error:Xu(D.error)}),D.type==="text-start"&&(de[D.id]={type:"text",text:"",providerMetadata:D.providerMetadata},F.push(de[D.id])),D.type==="text-delta"){const Te=de[D.id];if(Te==null){_e.enqueue({part:{type:"error",error:`text part ${D.id} not found`},partialOutput:void 0});return}Te.text+=D.text,Te.providerMetadata=(Ue=D.providerMetadata)!=null?Ue:Te.providerMetadata}if(D.type==="text-end"&&delete de[D.id],D.type==="reasoning-start"&&(Q[D.id]={type:"reasoning",text:"",providerMetadata:D.providerMetadata},F.push(Q[D.id])),D.type==="reasoning-delta"){const Te=Q[D.id];if(Te==null){_e.enqueue({part:{type:"error",error:`reasoning part ${D.id} not found`},partialOutput:void 0});return}Te.text+=D.text,Te.providerMetadata=(ne=D.providerMetadata)!=null?ne:Te.providerMetadata}if(D.type==="reasoning-end"){const Te=Q[D.id];if(Te==null){_e.enqueue({part:{type:"error",error:`reasoning part ${D.id} not found`},partialOutput:void 0});return}Te.providerMetadata=(ot=D.providerMetadata)!=null?ot:Te.providerMetadata,delete Q[D.id]}if(D.type==="file"&&F.push({type:"file",file:D.file}),D.type==="source"&&F.push(D),D.type==="tool-call"&&F.push(D),D.type==="tool-result"&&!D.preliminary&&F.push(D),D.type==="tool-error"&&F.push(D),D.type==="start-step"&&(Xe=D.request,I=D.warnings),D.type==="finish-step"){const Te=ws({content:F,tools:u}),ce=new uc({content:F,finishReason:D.finishReason,usage:D.usage,warnings:I,request:Xe,response:{...D.response,messages:[...be,...Te]},providerMetadata:D.providerMetadata});await(H==null?void 0:H(ce)),ie.push(ce),F=[],Q={},de={},be.push(...Te),oe.resolve()}D.type==="finish"&&(Ne=D.totalUsage,Ee=D.finishReason)},async flush(ke){try{if(ie.length===0){const ot=new tw({message:"No output generated. Check the stream for errors."});He._finishReason.reject(ot),He._totalUsage.reject(ot),He._steps.reject(ot);return}const _e=Ee??"unknown",Ue=Ne??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};He._finishReason.resolve(_e),He._totalUsage.resolve(Ue),He._steps.resolve(ie);const ne=ie[ie.length-1];await(P==null?void 0:P({finishReason:_e,totalUsage:Ue,usage:ne.usage,content:ne.content,text:ne.text,reasoningText:ne.reasoningText,reasoning:ne.reasoning,files:ne.files,sources:ne.sources,toolCalls:ne.toolCalls,staticToolCalls:ne.staticToolCalls,dynamicToolCalls:ne.dynamicToolCalls,toolResults:ne.toolResults,staticToolResults:ne.staticToolResults,dynamicToolResults:ne.dynamicToolResults,request:ne.request,response:ne.response,warnings:ne.warnings,providerMetadata:ne.providerMetadata,steps:ie})),me.setAttributes(lt({telemetry:t,attributes:{"ai.response.finishReason":_e,"ai.response.text":{output:()=>ne.text},"ai.response.toolCalls":{output:()=>{var ot;return(ot=ne.toolCalls)!=null&&ot.length?JSON.stringify(ne.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(ne.providerMetadata),"ai.usage.inputTokens":Ue.inputTokens,"ai.usage.outputTokens":Ue.outputTokens,"ai.usage.totalTokens":Ue.totalTokens,"ai.usage.reasoningTokens":Ue.reasoningTokens,"ai.usage.cachedInputTokens":Ue.cachedInputTokens}}))}catch(_e){ke.error(_e)}finally{me.end()}}}),Ze=Xw();this.addStream=Ze.addStream,this.closeStream=Ze.close;let se=Ze.stream;se=Qw(se,({error:ke,controller:_e})=>{Qt(ke)&&(s!=null&&s.aborted)?(V==null||V({steps:ie}),_e.enqueue({type:"abort"}),_e.close()):_e.error(ke)}),se=se.pipeThrough(new TransformStream({start(ke){ke.enqueue({type:"start"})}}));for(const ke of w)se=se.pipeThrough(ke({tools:u,stopStream(){Ze.terminate()}}));this.baseStream=se.pipeThrough(o0(y)).pipeThrough(fe);const{maxRetries:It,retry:Se}=oc({maxRetries:o,abortSignal:s}),Re=ec(t),ze=ms(r),rt=Qu({model:e,telemetry:t,headers:n,settings:{...ze,maxRetries:It}}),He=this;gn({name:"ai.streamText",attributes:lt({telemetry:t,attributes:{...mn({operationId:"ai.streamText",telemetry:t}),...rt,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:i,messages:l})}}}),tracer:Re,endWhenDone:!1,fn:async ke=>{me=ke;async function _e({currentStep:Ue,responseMessages:ne,usage:ot}){var D,Te,ce,Ct,ur;const cr=He.includeRawChunks;oe=new Yr;const dr=await Yu({system:a,prompt:i,messages:l}),Bt=[...dr.messages,...ne],st=await(p==null?void 0:p({model:e,steps:ie,stepNumber:ie.length,messages:Bt})),pr=await Hu({prompt:{system:(D=st==null?void 0:st.system)!=null?D:dr.system,messages:(Te=st==null?void 0:st.messages)!=null?Te:Bt},supportedUrls:await e.supportedUrls}),Vt=Jr((ce=st==null?void 0:st.model)!=null?ce:e),{toolChoice:kn,tools:Me}=Ju({tools:u,toolChoice:(Ct=st==null?void 0:st.toolChoice)!=null?Ct:c,activeTools:(ur=st==null?void 0:st.activeTools)!=null?ur:_}),{result:{stream:Ft,response:hr,request:Jd},doStreamSpan:Tn,startTimestampMs:Gd}=await Se(()=>gn({name:"ai.streamText.doStream",attributes:lt({telemetry:t,attributes:{...mn({operationId:"ai.streamText.doStream",telemetry:t}),...rt,"ai.model.provider":Vt.provider,"ai.model.id":Vt.modelId,"ai.prompt.messages":{input:()=>tc(pr)},"ai.prompt.tools":{input:()=>Me==null?void 0:Me.map(J=>JSON.stringify(J))},"ai.prompt.toolChoice":{input:()=>kn!=null?JSON.stringify(kn):void 0},"gen_ai.system":Vt.provider,"gen_ai.request.model":Vt.modelId,"gen_ai.request.frequency_penalty":ze.frequencyPenalty,"gen_ai.request.max_tokens":ze.maxOutputTokens,"gen_ai.request.presence_penalty":ze.presencePenalty,"gen_ai.request.stop_sequences":ze.stopSequences,"gen_ai.request.temperature":ze.temperature,"gen_ai.request.top_k":ze.topK,"gen_ai.request.top_p":ze.topP}}),tracer:Re,endWhenDone:!1,fn:async J=>({startTimestampMs:g(),doStreamSpan:J,result:await Vt.doStream({...ze,tools:Me,toolChoice:kn,responseFormat:y==null?void 0:y.responseFormat,prompt:pr,providerOptions:v,abortSignal:s,headers:n,includeRawChunks:cr})})})),GT=t0({tools:u,generatorStream:Ft,tracer:Re,telemetry:t,system:a,messages:Bt,repairToolCall:d,abortSignal:s,experimental_context:B}),WT=Jd??{},yo=[],da=[];let pa;const ha={};let Sn="unknown",gt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},fa,Wd=!0,Et={id:E(),timestamp:m(),modelId:e.modelId},Kd="";He.addStream(GT.pipeThrough(new TransformStream({async transform(J,De){var fr,mr,vo,$t;if(J.type==="stream-start"){pa=J.warnings;return}if(Wd){const Je=g()-Gd;Wd=!1,Tn.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":Je}),Tn.setAttributes({"ai.response.msToFirstChunk":Je}),De.enqueue({type:"start-step",request:WT,warnings:pa??[]})}const Yd=J.type;switch(Yd){case"text-start":case"text-end":{De.enqueue(J);break}case"text-delta":{J.delta.length>0&&(De.enqueue({type:"text-delta",id:J.id,text:J.delta,providerMetadata:J.providerMetadata}),Kd+=J.delta);break}case"reasoning-start":case"reasoning-end":{De.enqueue(J);break}case"reasoning-delta":{De.enqueue({type:"reasoning-delta",id:J.id,text:J.delta,providerMetadata:J.providerMetadata});break}case"tool-call":{De.enqueue(J),yo.push(J);break}case"tool-result":{De.enqueue(J),J.preliminary||da.push(J);break}case"tool-error":{De.enqueue(J),da.push(J);break}case"response-metadata":{Et={id:(fr=J.id)!=null?fr:Et.id,timestamp:(mr=J.timestamp)!=null?mr:Et.timestamp,modelId:(vo=J.modelId)!=null?vo:Et.modelId};break}case"finish":{gt=J.usage,Sn=J.finishReason,fa=J.providerMetadata;const Je=g()-Gd;Tn.addEvent("ai.stream.finish"),Tn.setAttributes({"ai.response.msToFinish":Je,"ai.response.avgOutputTokensPerSecond":1e3*(($t=gt.outputTokens)!=null?$t:0)/Je});break}case"file":{De.enqueue(J);break}case"source":{De.enqueue(J);break}case"tool-input-start":{ha[J.id]=J.toolName;const Je=u==null?void 0:u[J.toolName];(Je==null?void 0:Je.onInputStart)!=null&&await Je.onInputStart({toolCallId:J.id,messages:Bt,abortSignal:s,experimental_context:B}),De.enqueue({...J,dynamic:(Je==null?void 0:Je.type)==="dynamic"});break}case"tool-input-end":{delete ha[J.id],De.enqueue(J);break}case"tool-input-delta":{const Je=ha[J.id],ma=u==null?void 0:u[Je];(ma==null?void 0:ma.onInputDelta)!=null&&await ma.onInputDelta({inputTextDelta:J.delta,toolCallId:J.id,messages:Bt,abortSignal:s,experimental_context:B}),De.enqueue(J);break}case"error":{De.enqueue(J),Sn="error";break}case"raw":{cr&&De.enqueue(J);break}default:{const Je=Yd;throw new Error(`Unknown chunk type: ${Je}`)}}},async flush(J){const De=yo.length>0?JSON.stringify(yo):void 0;try{Tn.setAttributes(lt({telemetry:t,attributes:{"ai.response.finishReason":Sn,"ai.response.text":{output:()=>Kd},"ai.response.toolCalls":{output:()=>De},"ai.response.id":Et.id,"ai.response.model":Et.modelId,"ai.response.timestamp":Et.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(fa),"ai.usage.inputTokens":gt.inputTokens,"ai.usage.outputTokens":gt.outputTokens,"ai.usage.totalTokens":gt.totalTokens,"ai.usage.reasoningTokens":gt.reasoningTokens,"ai.usage.cachedInputTokens":gt.cachedInputTokens,"gen_ai.response.finish_reasons":[Sn],"gen_ai.response.id":Et.id,"gen_ai.response.model":Et.modelId,"gen_ai.usage.input_tokens":gt.inputTokens,"gen_ai.usage.output_tokens":gt.outputTokens}}))}catch{}finally{Tn.end()}J.enqueue({type:"finish-step",finishReason:Sn,usage:gt,providerMetadata:fa,response:{...Et,headers:hr==null?void 0:hr.headers}});const fr=nc(ot,gt);await oe.promise;const mr=yo.filter($t=>$t.providerExecuted!==!0),vo=da.filter($t=>$t.providerExecuted!==!0);if(mr.length>0&&vo.length===mr.length&&!await cc({stopConditions:f,steps:ie})){ne.push(...ws({content:ie[ie.length-1].content,tools:u}));try{await _e({currentStep:Ue+1,responseMessages:ne,usage:fr})}catch($t){J.enqueue({type:"error",error:$t}),He.closeStream()}}else J.enqueue({type:"finish",finishReason:Sn,totalUsage:fr}),He.closeStream()}})))}await _e({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(ke=>{He.addStream(new ReadableStream({start(_e){_e.enqueue({type:"error",error:ke}),_e.close()}})),He.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Kr(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Kr(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await Yw({stream:this.fullStream,onError:e==null?void 0:e.onError})}catch(n){(t=e==null?void 0:e.onError)==null||t.call(e,n)}}get experimental_partialOutputStream(){if(this.output==null)throw new du;return Kr(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:o=!0,sendSources:s=!1,sendStart:a=!0,sendFinish:i=!0,onError:l=ln}={}){const u=t!=null?Vw({originalMessages:e,responseMessageId:t}):void 0,c={},w=d=>{var f,y;const v=c[d];return((y=(f=this.tools)==null?void 0:f[v])==null?void 0:y.type)==="dynamic"?!0:void 0},_=this.fullStream.pipeThrough(new TransformStream({transform:async(d,f)=>{const y=r==null?void 0:r({part:d}),v=d.type;switch(v){case"text-start":{f.enqueue({type:"text-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-delta":{f.enqueue({type:"text-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-end":{f.enqueue({type:"text-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-start":{f.enqueue({type:"reasoning-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-delta":{o&&f.enqueue({type:"reasoning-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-end":{f.enqueue({type:"reasoning-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"file":{f.enqueue({type:"file",mediaType:d.file.mediaType,url:`data:${d.file.mediaType};base64,${d.file.base64}`});break}case"source":{s&&d.sourceType==="url"&&f.enqueue({type:"source-url",sourceId:d.id,url:d.url,title:d.title,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}}),s&&d.sourceType==="document"&&f.enqueue({type:"source-document",sourceId:d.id,mediaType:d.mediaType,title:d.title,filename:d.filename,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"tool-input-start":{c[d.id]=d.toolName;const p=w(d.id);f.enqueue({type:"tool-input-start",toolCallId:d.id,toolName:d.toolName,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...p!=null?{dynamic:p}:{}});break}case"tool-input-delta":{f.enqueue({type:"tool-input-delta",toolCallId:d.id,inputTextDelta:d.delta});break}case"tool-call":{c[d.toolCallId]=d.toolName;const p=w(d.toolCallId);d.invalid?f.enqueue({type:"tool-input-error",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...p!=null?{dynamic:p}:{},errorText:l(d.error)}):f.enqueue({type:"tool-input-available",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...p!=null?{dynamic:p}:{}});break}case"tool-result":{const p=w(d.toolCallId);f.enqueue({type:"tool-output-available",toolCallId:d.toolCallId,output:d.output,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.preliminary!=null?{preliminary:d.preliminary}:{},...p!=null?{dynamic:p}:{}});break}case"tool-error":{const p=w(d.toolCallId);f.enqueue({type:"tool-output-error",toolCallId:d.toolCallId,errorText:l(d.error),...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...p!=null?{dynamic:p}:{}});break}case"error":{f.enqueue({type:"error",errorText:l(d.error)});break}case"start-step":{f.enqueue({type:"start-step"});break}case"finish-step":{f.enqueue({type:"finish-step"});break}case"start":{a&&f.enqueue({type:"start",...y!=null?{messageMetadata:y}:{},...u!=null?{messageId:u}:{}});break}case"finish":{i&&f.enqueue({type:"finish",...y!=null?{messageMetadata:y}:{}});break}case"abort":{f.enqueue(d);break}case"tool-input-end":break;case"raw":break;default:{const p=v;throw new Error(`Unknown chunk type: ${p}`)}}y!=null&&v!=="start"&&v!=="finish"&&f.enqueue({type:"message-metadata",messageMetadata:y})}}));return Kr(Ww({stream:_,messageId:u??(t==null?void 0:t()),originalMessages:e,onFinish:n,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:n,onFinish:r,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:u,...c}={}){Kw({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:n,onFinish:r,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:u}),...c})}pipeTextStreamToResponse(e,t){qw({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l,...u}={}){return Bw({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l}),...u})}toTextStreamResponse(e){return Lw({textStream:this.textStream,...e})}};Ln({prefix:"aiobj",size:24}),Ln({prefix:"aiobj",size:24});var a0={};J_(a0,{object:()=>l0,text:()=>i0});var i0=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),l0=({schema:e})=>{const t=Lr(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await yc(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const o=r.state;throw new Error(`Unsupported parse state: ${o}`)}}},async parseOutput({text:n},r){const o=await fn({text:n});if(!o.success)throw new Tu({message:"No object generated: could not parse the response.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const s=await qn({value:o.value,schema:t});if(!s.success)throw new Tu({message:"No object generated: response did not match schema.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return s.value}}},wc="2025-06-18",u0=[wc,"2025-03-26","2024-11-05"],c0=un({name:h(),version:h()}),xs=un({_meta:Ie(x({}).loose())}),Qn=xs,d0=x({method:h(),params:Ie(xs)}),p0=un({experimental:Ie(x({}).loose()),logging:Ie(x({}).loose()),prompts:Ie(un({listChanged:Ie(re())})),resources:Ie(un({subscribe:Ie(re()),listChanged:Ie(re())})),tools:Ie(un({listChanged:Ie(re())}))}),h0=Qn.extend({protocolVersion:h(),capabilities:p0,serverInfo:c0,instructions:Ie(h())}),f0=Qn.extend({nextCursor:Ie(h())}),m0=x({name:h(),description:Ie(h()),inputSchema:x({type:A("object"),properties:Ie(x({}).loose())}).loose()}).loose(),g0=f0.extend({tools:Z(m0)}),y0=x({type:A("text"),text:h()}).loose(),v0=x({type:A("image"),data:Zi(),mimeType:h()}).loose(),bc=x({uri:h(),mimeType:Ie(h())}).loose(),_0=bc.extend({text:h()}),w0=bc.extend({blob:Zi()}),b0=x({type:A("resource"),resource:ee([_0,w0])}).loose(),x0=Qn.extend({content:Z(ee([y0,v0,b0])),isError:re().default(!1).optional()}).or(Qn.extend({toolResult:Le()})),Xr="2.0",k0=x({jsonrpc:A(Xr),id:ee([h(),R().int()])}).merge(d0).strict(),T0=x({jsonrpc:A(Xr),id:ee([h(),R().int()]),result:Qn}).strict(),S0=x({jsonrpc:A(Xr),id:ee([h(),R().int()]),error:x({code:R().int(),message:h(),data:Ie(Le())})}).strict(),I0=x({jsonrpc:A(Xr)}).merge(x({method:h(),params:Ie(xs)})).strict(),C0=ee([k0,I0,T0,S0]),E0=class{constructor({url:e,headers:t}){this.connected=!1,this.url=new URL(e),this.headers=t}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController,(async()=>{var r,o,s;try{const a=new Headers(this.headers);a.set("Accept","text/event-stream");const i=await fetch(this.url.href,{headers:a,signal:(r=this.abortController)==null?void 0:r.signal});if(!i.ok||!i.body){const w=new $e({message:`MCP SSE Transport Error: ${i.status} ${i.statusText}`});return(o=this.onerror)==null||o.call(this,w),t(w)}const u=i.body.pipeThrough(new TextDecoderStream).pipeThrough(new yr).getReader(),c=async()=>{var w,_,d;try{for(;;){const{done:f,value:y}=await u.read();if(f){if(this.connected)throw this.connected=!1,new $e({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:v,data:p}=y;if(v==="endpoint"){if(this.endpoint=new URL(p,this.url),this.endpoint.origin!==this.url.origin)throw new $e({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(v==="message")try{const b=C0.parse(JSON.parse(p));(w=this.onmessage)==null||w.call(this,b)}catch(b){const g=new $e({message:"MCP SSE Transport Error: Failed to parse message",cause:b});(_=this.onerror)==null||_.call(this,g)}}}catch(f){if(f instanceof Error&&f.name==="AbortError")return;(d=this.onerror)==null||d.call(this,f),t(f)}};this.sseConnection={close:()=>u.cancel()},c()}catch(a){if(a instanceof Error&&a.name==="AbortError")return;(s=this.onerror)==null||s.call(this,a),t(a)}})()})}async close(){var e,t,n;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(n=this.onclose)==null||n.call(this)}async send(e){var t,n,r;if(!this.endpoint||!this.connected)throw new $e({message:"MCP SSE Transport Error: Not connected"});try{const o=new Headers(this.headers);o.set("Content-Type","application/json");const s={method:"POST",headers:o,body:JSON.stringify(e),signal:(t=this.abortController)==null?void 0:t.signal},a=await fetch(this.endpoint,s);if(!a.ok){const i=await a.text().catch(()=>null),l=new $e({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${a.status}): ${i}`});(n=this.onerror)==null||n.call(this,l);return}}catch(o){(r=this.onerror)==null||r.call(this,o);return}}};function R0(e){if(e.type!=="sse")throw new $e({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."});return new E0(e)}function A0(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var O0="1.0.0";async function N0(e){const t=new M0(e);return await t.init(),t}var M0=class{constructor({transport:e,name:t="ai-sdk-mcp-client",onUncaughtError:n}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,A0(e)?this.transport=e:this.transport=R0(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=r=>this.onError(r),this.transport.onmessage=r=>{if("method"in r){this.onError(new $e({message:"Unsupported message type"}));return}this.onResponse(r)},this.clientInfo={name:t,version:O0}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:wc,capabilities:{},clientInfo:this.clientInfo}},resultSchema:h0});if(e===void 0)throw new $e({message:"Server sent invalid initialize result"});if(!u0.includes(e.protocolVersion))throw new $e({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new $e({message:"Server does not support tools"});break;default:throw new $e({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:n}){return new Promise((r,o)=>{if(this.isClosed)return o(new $e({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const s=n==null?void 0:n.signal;s==null||s.throwIfAborted();const a=this.requestMessageId++,i={...e,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,u=>{if(s!=null&&s.aborted)return o(new $e({message:"Request was aborted",cause:s.reason}));if(u instanceof Error)return o(u);try{const c=t.parse(u.result);r(c)}catch(c){const w=new $e({message:"Failed to parse server response",cause:c});o(w)}}),this.transport.send(i).catch(u=>{l(),o(u)})})}async listTools({params:e,options:t}={}){try{return this.request({request:{method:"tools/list",params:e},resultSchema:g0,options:t})}catch(n){throw n}}async callTool({name:e,args:t,options:n}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:x0,options:{signal:n==null?void 0:n.abortSignal}})}catch(r){throw r}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){var t;const n={};try{const r=await this.listTools();for(const{name:o,description:s,inputSchema:a}of r.tools){if(e!=="automatic"&&!(o in e))continue;const i=this,l=async(c,w)=>{var _;return(_=w==null?void 0:w.abortSignal)==null||_.throwIfAborted(),i.callTool({name:o,args:c,options:w})},u=e==="automatic"?_l({description:s,inputSchema:Bn({...a,properties:(t=a.properties)!=null?t:{},additionalProperties:!1}),execute:l}):{description:s,inputSchema:e[o].inputSchema,execute:l};n[o]=u}return n}catch(r){throw r}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new $e({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),n=this.responseHandlers.get(t);if(n===void 0)throw new $e({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),n("result"in e?e:new $e({message:e.error.message,cause:e.error}))}};const xc="2025-06-18",Qr="2.0",kc=Ve([k(),Pe().int()]),Tc=k(),P0=$({progressToken:O(kc)}).passthrough(),ut=$({_meta:O(P0)}).passthrough(),Ye=$({method:k(),params:O(ut)}),er=$({_meta:O($({}).passthrough())}).passthrough(),xt=$({method:k(),params:O(er)}),ct=$({_meta:O($({}).passthrough())}).passthrough(),eo=Ve([k(),Pe().int()]),Sc=$({jsonrpc:K(Qr),id:eo}).merge(Ye).strict(),$0=e=>Sc.safeParse(e).success,z0=$({jsonrpc:K(Qr)}).merge(xt).strict(),Ic=$({jsonrpc:K(Qr),id:eo,result:ct}).strict(),j0=e=>Ic.safeParse(e).success;var Cc;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"})(Cc||(Cc={}));const D0=$({jsonrpc:K(Qr),id:eo,error:$({code:Pe().int(),message:k(),data:O(Dn())})}).strict(),ks=Ve([Sc,z0,Ic,D0]),Ec=ct.strict(),Rc=xt.extend({method:K("notifications/cancelled"),params:er.extend({requestId:eo,reason:k().optional()})}),tr=$({name:k(),title:O(k())}).passthrough(),Ac=tr.extend({version:k()}),Z0=$({experimental:O($({}).passthrough()),sampling:O($({}).passthrough()),elicitation:O($({}).passthrough()),roots:O($({listChanged:O(Oe())}).passthrough())}).passthrough(),U0=Ye.extend({method:K("initialize"),params:ut.extend({protocolVersion:k(),capabilities:Z0,clientInfo:Ac})}),L0=$({experimental:O($({}).passthrough()),logging:O($({}).passthrough()),completions:O($({}).passthrough()),prompts:O($({listChanged:O(Oe())}).passthrough()),resources:O($({subscribe:O(Oe()),listChanged:O(Oe())}).passthrough()),tools:O($({listChanged:O(Oe())}).passthrough())}).passthrough(),q0=ct.extend({protocolVersion:k(),capabilities:L0,serverInfo:Ac,instructions:O(k())}),Oc=xt.extend({method:K("notifications/initialized")}),B0=e=>Oc.safeParse(e).success,Nc=Ye.extend({method:K("ping")}),V0=$({progress:Pe(),total:O(Pe()),message:O(k())}).passthrough(),Mc=xt.extend({method:K("notifications/progress"),params:er.merge(V0).extend({progressToken:kc})}),to=Ye.extend({params:ut.extend({cursor:O(Tc)}).optional()}),no=ct.extend({nextCursor:O(Tc)}),Pc=$({uri:k(),mimeType:O(k()),_meta:O($({}).passthrough())}).passthrough(),$c=Pc.extend({text:k()}),Ts=k().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),zc=Pc.extend({blob:Ts}),jc=tr.extend({uri:k(),description:O(k()),mimeType:O(k()),_meta:O($({}).passthrough())}),F0=tr.extend({uriTemplate:k(),description:O(k()),mimeType:O(k()),_meta:O($({}).passthrough())}),H0=to.extend({method:K("resources/list")}),J0=no.extend({resources:L(jc)}),G0=to.extend({method:K("resources/templates/list")}),W0=no.extend({resourceTemplates:L(F0)}),K0=Ye.extend({method:K("resources/read"),params:ut.extend({uri:k()})}),Y0=ct.extend({contents:L(Ve([$c,zc]))}),X0=xt.extend({method:K("notifications/resources/list_changed")}),Q0=Ye.extend({method:K("resources/subscribe"),params:ut.extend({uri:k()})}),eb=Ye.extend({method:K("resources/unsubscribe"),params:ut.extend({uri:k()})}),tb=xt.extend({method:K("notifications/resources/updated"),params:er.extend({uri:k()})}),nb=$({name:k(),description:O(k()),required:O(Oe())}).passthrough(),rb=tr.extend({description:O(k()),arguments:O(L(nb)),_meta:O($({}).passthrough())}),ob=to.extend({method:K("prompts/list")}),sb=no.extend({prompts:L(rb)}),ab=Ye.extend({method:K("prompts/get"),params:ut.extend({name:k(),arguments:O(Zn(k()))})}),Ss=$({type:K("text"),text:k(),_meta:O($({}).passthrough())}).passthrough(),Is=$({type:K("image"),data:Ts,mimeType:k(),_meta:O($({}).passthrough())}).passthrough(),Cs=$({type:K("audio"),data:Ts,mimeType:k(),_meta:O($({}).passthrough())}).passthrough(),ib=$({type:K("resource"),resource:Ve([$c,zc]),_meta:O($({}).passthrough())}).passthrough(),lb=jc.extend({type:K("resource_link")}),Dc=Ve([Ss,Is,Cs,lb,ib]),ub=$({role:Pt(["user","assistant"]),content:Dc}).passthrough(),cb=ct.extend({description:O(k()),messages:L(ub)}),db=xt.extend({method:K("notifications/prompts/list_changed")}),pb=$({title:O(k()),readOnlyHint:O(Oe()),destructiveHint:O(Oe()),idempotentHint:O(Oe()),openWorldHint:O(Oe())}).passthrough(),hb=tr.extend({description:O(k()),inputSchema:$({type:K("object"),properties:O($({}).passthrough()),required:O(L(k()))}).passthrough(),outputSchema:O($({type:K("object"),properties:O($({}).passthrough()),required:O(L(k()))}).passthrough()),annotations:O(pb),_meta:O($({}).passthrough())}),fb=to.extend({method:K("tools/list")}),mb=no.extend({tools:L(hb)}),Zc=ct.extend({content:L(Dc).default([]),structuredContent:$({}).passthrough().optional(),isError:O(Oe())});Zc.or(ct.extend({toolResult:Dn()}));const gb=Ye.extend({method:K("tools/call"),params:ut.extend({name:k(),arguments:O(Zn(Dn()))})}),yb=xt.extend({method:K("notifications/tools/list_changed")}),Uc=Pt(["debug","info","notice","warning","error","critical","alert","emergency"]),vb=Ye.extend({method:K("logging/setLevel"),params:ut.extend({level:Uc})}),_b=xt.extend({method:K("notifications/message"),params:er.extend({level:Uc,logger:O(k()),data:Dn()})}),wb=$({name:k().optional()}).passthrough(),bb=$({hints:O(L(wb)),costPriority:O(Pe().min(0).max(1)),speedPriority:O(Pe().min(0).max(1)),intelligencePriority:O(Pe().min(0).max(1))}).passthrough(),xb=$({role:Pt(["user","assistant"]),content:Ve([Ss,Is,Cs])}).passthrough(),kb=Ye.extend({method:K("sampling/createMessage"),params:ut.extend({messages:L(xb),systemPrompt:O(k()),includeContext:O(Pt(["none","thisServer","allServers"])),temperature:O(Pe()),maxTokens:Pe().int(),stopSequences:O(L(k())),metadata:O($({}).passthrough()),modelPreferences:O(bb)})}),Tb=ct.extend({model:k(),stopReason:O(Pt(["endTurn","stopSequence","maxTokens"]).or(k())),role:Pt(["user","assistant"]),content:Wg("type",[Ss,Is,Cs])}),Sb=$({type:K("boolean"),title:O(k()),description:O(k()),default:O(Oe())}).passthrough(),Ib=$({type:K("string"),title:O(k()),description:O(k()),minLength:O(Pe()),maxLength:O(Pe()),format:O(Pt(["email","uri","date","date-time"]))}).passthrough(),Cb=$({type:Pt(["number","integer"]),title:O(k()),description:O(k()),minimum:O(Pe()),maximum:O(Pe())}).passthrough(),Eb=$({type:K("string"),title:O(k()),description:O(k()),enum:L(k()),enumNames:O(L(k()))}).passthrough(),Rb=Ve([Sb,Ib,Cb,Eb]),Ab=Ye.extend({method:K("elicitation/create"),params:ut.extend({message:k(),requestedSchema:$({type:K("object"),properties:Zn(k(),Rb),required:O(L(k()))}).passthrough()})}),Ob=ct.extend({action:Pt(["accept","decline","cancel"]),content:O(Zn(k(),Dn()))}),Nb=$({type:K("ref/resource"),uri:k()}).passthrough(),Mb=$({type:K("ref/prompt"),name:k()}).passthrough(),Pb=Ye.extend({method:K("completion/complete"),params:ut.extend({ref:Ve([Mb,Nb]),argument:$({name:k(),value:k()}).passthrough(),context:O($({arguments:O(Zn(k(),k()))}))})}),$b=ct.extend({completion:$({values:L(k()).max(100),total:O(Pe().int()),hasMore:O(Oe())}).passthrough()}),zb=$({uri:k().startsWith("file://"),name:O(k()),_meta:O($({}).passthrough())}).passthrough(),jb=Ye.extend({method:K("roots/list")}),Db=ct.extend({roots:L(zb)}),Zb=xt.extend({method:K("notifications/roots/list_changed")});Ve([Nc,U0,Pb,vb,ab,ob,H0,G0,K0,Q0,eb,gb,fb]),Ve([Rc,Mc,Oc,Zb]),Ve([Ec,Tb,Ob,Db]),Ve([Nc,kb,Ab,jb]),Ve([Rc,Mc,_b,tb,X0,yb,db]),Ve([Ec,q0,$b,cb,sb,J0,W0,Y0,Zc,mb]);let Es;Es=globalThis.crypto;async function Ub(e){return(await Es).getRandomValues(new Uint8Array(e))}async function Lb(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let n="";const r=await Ub(e);for(let o=0;o<e;o++){const s=r[o]%t.length;n+=t[s]}return n}async function qb(e){return await Lb(e)}async function Bb(e){const t=await(await Es).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Vb(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await qb(e),n=await Bb(t);return{code_verifier:t,code_challenge:n}}const Fb=$({resource:k().url(),authorization_servers:L(k().url()).optional(),jwks_uri:k().url().optional(),scopes_supported:L(k()).optional(),bearer_methods_supported:L(k()).optional(),resource_signing_alg_values_supported:L(k()).optional(),resource_name:k().optional(),resource_documentation:k().optional(),resource_policy_uri:k().url().optional(),resource_tos_uri:k().url().optional(),tls_client_certificate_bound_access_tokens:Oe().optional(),authorization_details_types_supported:L(k()).optional(),dpop_signing_alg_values_supported:L(k()).optional(),dpop_bound_access_tokens_required:Oe().optional()}).passthrough(),Lc=$({issuer:k(),authorization_endpoint:k(),token_endpoint:k(),registration_endpoint:k().optional(),scopes_supported:L(k()).optional(),response_types_supported:L(k()),response_modes_supported:L(k()).optional(),grant_types_supported:L(k()).optional(),token_endpoint_auth_methods_supported:L(k()).optional(),token_endpoint_auth_signing_alg_values_supported:L(k()).optional(),service_documentation:k().optional(),revocation_endpoint:k().optional(),revocation_endpoint_auth_methods_supported:L(k()).optional(),revocation_endpoint_auth_signing_alg_values_supported:L(k()).optional(),introspection_endpoint:k().optional(),introspection_endpoint_auth_methods_supported:L(k()).optional(),introspection_endpoint_auth_signing_alg_values_supported:L(k()).optional(),code_challenge_methods_supported:L(k()).optional()}).passthrough(),Hb=$({issuer:k(),authorization_endpoint:k(),token_endpoint:k(),userinfo_endpoint:k().optional(),jwks_uri:k(),registration_endpoint:k().optional(),scopes_supported:L(k()).optional(),response_types_supported:L(k()),response_modes_supported:L(k()).optional(),grant_types_supported:L(k()).optional(),acr_values_supported:L(k()).optional(),subject_types_supported:L(k()),id_token_signing_alg_values_supported:L(k()),id_token_encryption_alg_values_supported:L(k()).optional(),id_token_encryption_enc_values_supported:L(k()).optional(),userinfo_signing_alg_values_supported:L(k()).optional(),userinfo_encryption_alg_values_supported:L(k()).optional(),userinfo_encryption_enc_values_supported:L(k()).optional(),request_object_signing_alg_values_supported:L(k()).optional(),request_object_encryption_alg_values_supported:L(k()).optional(),request_object_encryption_enc_values_supported:L(k()).optional(),token_endpoint_auth_methods_supported:L(k()).optional(),token_endpoint_auth_signing_alg_values_supported:L(k()).optional(),display_values_supported:L(k()).optional(),claim_types_supported:L(k()).optional(),claims_supported:L(k()).optional(),service_documentation:k().optional(),claims_locales_supported:L(k()).optional(),ui_locales_supported:L(k()).optional(),claims_parameter_supported:Oe().optional(),request_parameter_supported:Oe().optional(),request_uri_parameter_supported:Oe().optional(),require_request_uri_registration:Oe().optional(),op_policy_uri:k().optional(),op_tos_uri:k().optional()}).passthrough().merge(Lc.pick({code_challenge_methods_supported:!0})),qc=$({access_token:k(),id_token:k().optional(),token_type:k(),expires_in:Pe().optional(),scope:k().optional(),refresh_token:k().optional()}).strip(),Jb=$({error:k(),error_description:k().optional(),error_uri:k().optional()}),Gb=$({redirect_uris:L(k()).refine(e=>e.every(t=>URL.canParse(t)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:k().optional(),grant_types:L(k()).optional(),response_types:L(k()).optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),scope:k().optional(),contacts:L(k()).optional(),tos_uri:k().optional(),policy_uri:k().optional(),jwks_uri:k().optional(),jwks:Gg().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional()}).strip(),Wb=$({client_id:k(),client_secret:k().optional(),client_id_issued_at:Pe().optional(),client_secret_expires_at:Pe().optional()}).strip(),Kb=Gb.merge(Wb);$({error:k(),error_description:k().optional()}).strip(),$({token:k(),token_type_hint:k().optional()}).strip();function Yb(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Xb({requestedResource:e,configuredResource:t}){const n=typeof e=="string"?new URL(e):new URL(e.href),r=typeof t=="string"?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;const o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",s=r.pathname.endsWith("/")?r.pathname:r.pathname+"/";return o.startsWith(s)}class je extends Error{constructor(t,n){super(t),this.errorUri=n,this.name=this.constructor.name}toResponseObject(){const t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}}class Rs extends je{}Rs.errorCode="invalid_request";class ro extends je{}ro.errorCode="invalid_client";class oo extends je{}oo.errorCode="invalid_grant";class so extends je{}so.errorCode="unauthorized_client";class As extends je{}As.errorCode="unsupported_grant_type";class Os extends je{}Os.errorCode="invalid_scope";class Ns extends je{}Ns.errorCode="access_denied";class yn extends je{}yn.errorCode="server_error";class Ms extends je{}Ms.errorCode="temporarily_unavailable";class Ps extends je{}Ps.errorCode="unsupported_response_type";class $s extends je{}$s.errorCode="unsupported_token_type";class zs extends je{}zs.errorCode="invalid_token";class js extends je{}js.errorCode="method_not_allowed";class Ds extends je{}Ds.errorCode="too_many_requests";class Zs extends je{}Zs.errorCode="invalid_client_metadata";class Us extends je{}Us.errorCode="insufficient_scope";const Qb={[Rs.errorCode]:Rs,[ro.errorCode]:ro,[oo.errorCode]:oo,[so.errorCode]:so,[As.errorCode]:As,[Os.errorCode]:Os,[Ns.errorCode]:Ns,[yn.errorCode]:yn,[Ms.errorCode]:Ms,[Ps.errorCode]:Ps,[$s.errorCode]:$s,[zs.errorCode]:zs,[js.errorCode]:js,[Ds.errorCode]:Ds,[Zs.errorCode]:Zs,[Us.errorCode]:Us};class nr extends Error{constructor(t){super(t??"Unauthorized")}}function Bc(e,t){const n=e.client_secret!==void 0;return t.length===0?n?"client_secret_post":"none":n&&t.includes("client_secret_basic")?"client_secret_basic":n&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":n?"client_secret_post":"none"}function Vc(e,t,n,r){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":ex(o,s,n);return;case"client_secret_post":tx(o,s,r);return;case"none":nx(o,r);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function ex(e,t,n){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const r=btoa(`${e}:${t}`);n.set("Authorization",`Basic ${r}`)}function tx(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}function nx(e,t){t.set("client_id",e)}async function Ls(e){const t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{const r=Jb.parse(JSON.parse(n)),{error:o,error_description:s,error_uri:a}=r,i=Qb[o]||yn;return new i(s||"",a)}catch(r){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${r}. Raw body: ${n}`;return new yn(o)}}async function qs(e,t){var n,r;try{return await Bs(e,t)}catch(o){if(o instanceof ro||o instanceof so)return await((n=e.invalidateCredentials)===null||n===void 0?void 0:n.call(e,"all")),await Bs(e,t);if(o instanceof oo)return await((r=e.invalidateCredentials)===null||r===void 0?void 0:r.call(e,"tokens")),await Bs(e,t);throw o}}async function Bs(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await sx(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=t);const l=await rx(t,e,a),u=await cx(i,{fetchFn:s});let c=await Promise.resolve(e.clientInformation());if(!c){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const y=await fx(i,{metadata:u,clientMetadata:e.clientMetadata});await e.saveClientInformation(y),c=y}if(n!==void 0){const y=await e.codeVerifier(),v=await px(i,{metadata:u,clientInformation:c,authorizationCode:n,codeVerifier:y,redirectUri:e.redirectUrl,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(v),"AUTHORIZED"}const w=await e.tokens();if(w!=null&&w.refresh_token)try{const y=await hx(i,{metadata:u,clientInformation:c,refreshToken:w.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication});return await e.saveTokens(y),"AUTHORIZED"}catch(y){if(!(!(y instanceof je)||y instanceof yn))throw y}const _=e.state?await e.state():void 0,{authorizationUrl:d,codeVerifier:f}=await dx(i,{metadata:u,clientInformation:c,state:_,redirectUrl:e.redirectUrl,scope:r||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(f),await e.redirectToAuthorization(d),"REDIRECT"}async function rx(e,t,n){const r=Yb(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n==null?void 0:n.resource);if(n){if(!Xb({requestedResource:r,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function ox(e){const t=e.headers.get("WWW-Authenticate");if(!t)return;const[n,r]=t.split(" ");if(n.toLowerCase()!=="bearer"||!r)return;const s=/resource_metadata="([^"]*)"/.exec(t);if(s)try{return new URL(s[1])}catch{return}}async function sx(e,t,n=fetch){const r=await lx(e,"oauth-protected-resource",n,{protocolVersion:t==null?void 0:t.protocolVersion,metadataUrl:t==null?void 0:t.resourceMetadataUrl});if(!r||r.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!r.ok)throw new Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return Fb.parse(await r.json())}async function Vs(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Vs(e,void 0,n):void 0;throw r}}function ax(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Fc(e,t,n=fetch){return await Vs(e,{"MCP-Protocol-Version":t},n)}function ix(e,t){return!e||e.status===404&&t!=="/"}async function lx(e,t,n,r){var o,s;const a=new URL(e),i=(o=r==null?void 0:r.protocolVersion)!==null&&o!==void 0?o:xc;let l;if(r!=null&&r.metadataUrl)l=new URL(r.metadataUrl);else{const c=ax(t,a.pathname);l=new URL(c,(s=r==null?void 0:r.metadataServerUrl)!==null&&s!==void 0?s:a),l.search=a.search}let u=await Fc(l,i,n);if(!(r!=null&&r.metadataUrl)&&ix(u,a.pathname)){const c=new URL(`/.well-known/${t}`,a);u=await Fc(c,i,n)}return u}function ux(e){const t=typeof e=="string"?new URL(e):e,n=t.pathname!=="/",r=[];if(!n)return r.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),r.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),r;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),r.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),r.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),r.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),r}async function cx(e,{fetchFn:t=fetch,protocolVersion:n=xc}={}){var r;const o={"MCP-Protocol-Version":n},s=ux(e);for(const{url:a,type:i}of s){const l=await Vs(a,o,t);if(!l)throw new Error(`CORS error trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`);if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(i==="oauth")return Lc.parse(await l.json());{const u=Hb.parse(await l.json());if(!(!((r=u.code_challenge_methods_supported)===null||r===void 0)&&r.includes("S256")))throw new Error(`Incompatible OIDC provider at ${a}: does not support S256 code challenge method required by MCP specification`);return u}}}async function dx(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:o,state:s,resource:a}){const i="code",l="S256";let u;if(t){if(u=new URL(t.authorization_endpoint),!t.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else u=new URL("/authorize",e);const c=await Vb(),w=c.code_verifier,_=c.code_challenge;return u.searchParams.set("response_type",i),u.searchParams.set("client_id",n.client_id),u.searchParams.set("code_challenge",_),u.searchParams.set("code_challenge_method",l),u.searchParams.set("redirect_uri",String(r)),s&&u.searchParams.set("state",s),o&&u.searchParams.set("scope",o),o!=null&&o.includes("offline_access")&&u.searchParams.append("prompt","consent"),a&&u.searchParams.set("resource",a.href),{authorizationUrl:u,codeVerifier:w}}async function px(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:o,redirectUri:s,resource:a,addClientAuthentication:i,fetchFn:l}){var u;const c="authorization_code",w=t!=null&&t.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t!=null&&t.grant_types_supported&&!t.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`);const _=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),d=new URLSearchParams({grant_type:c,code:r,code_verifier:o,redirect_uri:String(s)});if(i)i(_,d,e,t);else{const y=(u=t==null?void 0:t.token_endpoint_auth_methods_supported)!==null&&u!==void 0?u:[],v=Bc(n,y);Vc(v,n,_,d)}a&&d.set("resource",a.href);const f=await(l??fetch)(w,{method:"POST",headers:_,body:d});if(!f.ok)throw await Ls(f);return qc.parse(await f.json())}async function hx(e,{metadata:t,clientInformation:n,refreshToken:r,resource:o,addClientAuthentication:s,fetchFn:a}){var i;const l="refresh_token";let u;if(t){if(u=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else u=new URL("/token",e);const c=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),w=new URLSearchParams({grant_type:l,refresh_token:r});if(s)s(c,w,e,t);else{const d=(i=t==null?void 0:t.token_endpoint_auth_methods_supported)!==null&&i!==void 0?i:[],f=Bc(n,d);Vc(f,n,c,w)}o&&w.set("resource",o.href);const _=await(a??fetch)(u,{method:"POST",headers:c,body:w});if(!_.ok)throw await Ls(_);return qc.parse({refresh_token:r,...await _.json()})}async function fx(e,{metadata:t,clientMetadata:n,fetchFn:r}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await(r??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw await Ls(s);return Kb.parse(await s.json())}const mx={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Fs extends Error{constructor(t,n){super(`Streamable HTTP error: ${n}`),this.code=t}}class gx{constructor(t,n){var r;this._url=t,this._resourceMetadataUrl=void 0,this._requestInit=n==null?void 0:n.requestInit,this._authProvider=n==null?void 0:n.authProvider,this._fetch=n==null?void 0:n.fetch,this._sessionId=n==null?void 0:n.sessionId,this._reconnectionOptions=(r=n==null?void 0:n.reconnectionOptions)!==null&&r!==void 0?r:mx}async _authThenStart(){var t;if(!this._authProvider)throw new nr("No auth provider");let n;try{n=await qs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(r){throw(t=this.onerror)===null||t===void 0||t.call(this,r),r}if(n!=="AUTHORIZED")throw new nr;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var t;const n={};if(this._authProvider){const o=await this._authProvider.tokens();o&&(n.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(n["mcp-session-id"]=this._sessionId),this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const r=this._normalizeHeaders((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...r})}async _startOrAuthSse(t){var n,r,o;const{resumptionToken:s}=t;try{const a=await this._commonHeaders();a.set("Accept","text/event-stream"),s&&a.set("last-event-id",s);const i=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,{method:"GET",headers:a,signal:(r=this._abortController)===null||r===void 0?void 0:r.signal});if(!i.ok){if(i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Fs(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,t,!0)}catch(a){throw(o=this.onerror)===null||o===void 0||o.call(this,a),a}}_getNextReconnectionDelay(t){const n=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(n*Math.pow(r,t),o)}_normalizeHeaders(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}_scheduleReconnection(t,n=0){var r;const o=this._reconnectionOptions.maxRetries;if(o>0&&n>=o){(r=this.onerror)===null||r===void 0||r.call(this,new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}const s=this._getNextReconnectionDelay(n);setTimeout(()=>{this._startOrAuthSse(t).catch(a=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect SSE stream: ${a instanceof Error?a.message:String(a)}`)),this._scheduleReconnection(t,n+1)})},s)}_handleSseStream(t,n,r){if(!t)return;const{onresumptiontoken:o,replayMessageId:s}=n;let a;(async()=>{var l,u,c,w;try{const _=t.pipeThrough(new TextDecoderStream).pipeThrough(new yr).getReader();for(;;){const{value:d,done:f}=await _.read();if(f)break;if(d.id&&(a=d.id,o==null||o(d.id)),!d.event||d.event==="message")try{const y=ks.parse(JSON.parse(d.data));s!==void 0&&j0(y)&&(y.id=s),(l=this.onmessage)===null||l===void 0||l.call(this,y)}catch(y){(u=this.onerror)===null||u===void 0||u.call(this,y)}}}catch(_){if((c=this.onerror)===null||c===void 0||c.call(this,new Error(`SSE stream disconnected: ${_}`)),r&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(d){(w=this.onerror)===null||w===void 0||w.call(this,new Error(`Failed to reconnect: ${d instanceof Error?d.message:String(d)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new nr("No auth provider");if(await qs(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new nr("Failed to authorize")}async close(){var t,n;(t=this._abortController)===null||t===void 0||t.abort(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(t,n){var r,o,s,a;try{const{resumptionToken:i,onresumptiontoken:l}=n||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:$0(t)?t.id:void 0}).catch(v=>{var p;return(p=this.onerror)===null||p===void 0?void 0:p.call(this,v)});return}const u=await this._commonHeaders();u.set("content-type","application/json"),u.set("accept","application/json, text/event-stream");const c={...this._requestInit,method:"POST",headers:u,body:JSON.stringify(t),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},w=await((o=this._fetch)!==null&&o!==void 0?o:fetch)(this._url,c),_=w.headers.get("mcp-session-id");if(_&&(this._sessionId=_),!w.ok){if(w.status===401&&this._authProvider){if(this._resourceMetadataUrl=ox(w),await qs(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new nr;return this.send(t)}const v=await w.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${w.status}): ${v}`)}if(w.status===202){B0(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(v=>{var p;return(p=this.onerror)===null||p===void 0?void 0:p.call(this,v)});return}const f=(Array.isArray(t)?t:[t]).filter(v=>"method"in v&&"id"in v&&v.id!==void 0).length>0,y=w.headers.get("content-type");if(f)if(y!=null&&y.includes("text/event-stream"))this._handleSseStream(w.body,{onresumptiontoken:l},!1);else if(y!=null&&y.includes("application/json")){const v=await w.json(),p=Array.isArray(v)?v.map(b=>ks.parse(b)):[ks.parse(v)];for(const b of p)(s=this.onmessage)===null||s===void 0||s.call(this,b)}else throw new Fs(-1,`Unexpected content type: ${y}`)}catch(i){throw(a=this.onerror)===null||a===void 0||a.call(this,i),i}}get sessionId(){return this._sessionId}async terminateSession(){var t,n,r;if(this._sessionId)try{const o=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:o,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal},a=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,s);if(!a.ok&&a.status!==405)throw new Fs(a.status,`Failed to terminate session: ${a.statusText}`);this._sessionId=void 0}catch(o){throw(r=this.onerror)===null||r===void 0||r.call(this,o),o}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}}function dt(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}function rr(e){return Object.fromEntries([...e.headers])}var yx=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const s=n.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=n[Math.random()*s|0];return a.join("")};if(e==null)return o;if(n.includes(r))throw new _o({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},tt=yx();function Hs(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var vx=["fetch failed","failed to fetch"];function _x({error:e,url:t,requestBodyValues:n}){if(Hs(e))return e;if(e instanceof TypeError&&vx.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new pe({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}function wx(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!=null))}function Hc({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if(typeof e=="string")return e;if(e!=null)throw new gr({message:`${r} API key must be a string.`});if(typeof process>"u")throw new gr({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 gr({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new gr({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var bx=/"__proto__"\s*:/,xx=/"constructor"\s*:/;function kx(e){const t=JSON.parse(e);return t===null||typeof t!="object"||bx.test(e)===!1&&xx.test(e)===!1?t:Tx(t)}function Tx(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}function Js(e){const{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return kx(e)}finally{Error.stackTraceLimit=t}}var Gs=Symbol.for("vercel.ai.validator");function Sx(e){return{[Gs]:!0,validate:e}}function Ix(e){return typeof e=="object"&&e!==null&&Gs in e&&e[Gs]===!0&&"validate"in e}function Cx(e){return Ix(e)?e:Ex(e)}function Ex(e){return Sx(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new yt({value:t,cause:n.issues})}})}async function Rx({value:e,schema:t}){const n=await or({value:e,schema:t});if(!n.success)throw yt.wrap({value:e,cause:n.error});return n.value}async function or({value:e,schema:t}){const n=Cx(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const r=await n.validate(e);return r.success?{success:!0,value:r.value,rawValue:e}:{success:!1,error:yt.wrap({value:e,cause:r.error}),rawValue:e}}catch(r){return{success:!1,error:yt.wrap({value:e,cause:r}),rawValue:e}}}async function Ax({text:e,schema:t}){try{const n=Js(e);return t==null?n:Rx({value:n,schema:t})}catch(n){throw zt.isInstance(n)||yt.isInstance(n)?n:new zt({text:e,cause:n})}}async function Jc({text:e,schema:t}){try{const n=Js(e);return t==null?{success:!0,value:n,rawValue:n}:await or({value:n,schema:t})}catch(n){return{success:!1,error:zt.isInstance(n)?n:new zt({text:e,cause:n}),rawValue:void 0}}}function ao(e){try{return Js(e),!0}catch{return!1}}function Ox({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new yr).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await Jc({text:n,schema:t}))}}))}async function kt({provider:e,providerOptions:t,schema:n}){if((t==null?void 0:t[e])==null)return;const r=await or({value:t[e],schema:n});if(!r.success)throw new _o({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}var Nx=()=>globalThis.fetch,mt=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Gc({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),Mx=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a})=>Gc({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:s,fetch:a}),Gc=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:s,fetch:a=Nx()})=>{try{const i=await a(e,{method:"POST",headers:wx(t),body:n.content,signal:s}),l=rr(i);if(!i.ok){let u;try{u=await o({response:i,url:e,requestBodyValues:n.values})}catch(c){throw Hs(c)||pe.isInstance(c)?c:new pe({message:"Failed to process error response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw u.value}try{return await r({response:i,url:e,requestBodyValues:n.values})}catch(u){throw u instanceof Error&&(Hs(u)||pe.isInstance(u))?u:new pe({message:"Failed to process successful response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(i){throw _x({error:i,url:e,requestBodyValues:n.values})}};function QT(e){return e}function Ws({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l,...u})=>({type:"provider-defined",id:e,name:t,args:u,inputSchema:n,outputSchema:o,execute:r,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l})}var Wc=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:s})=>{const a=await r.text(),i=rr(r);if(a.trim()==="")return{responseHeaders:i,value:new pe({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,isRetryable:n==null?void 0:n(r)})};try{const l=await Ax({text:a,schema:e});return{responseHeaders:i,value:new pe({message:t(l),url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,data:l,isRetryable:n==null?void 0:n(r,l)})}}catch{return{responseHeaders:i,value:new pe({message:r.statusText,url:o,requestBodyValues:s,statusCode:r.status,responseHeaders:i,responseBody:a,isRetryable:n==null?void 0:n(r)})}}},io=e=>async({response:t})=>{const n=rr(t);if(t.body==null)throw new Ta({});return{responseHeaders:n,value:Ox({stream:t.body,schema:e})}},on=e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await t.text(),s=await Jc({text:o,schema:e}),a=rr(t);if(!s.success)throw new pe({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}},Px=()=>async({response:e,url:t,requestBodyValues:n})=>{const r=rr(e);if(!e.body)throw new pe({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 pe({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:o})}},{btoa:$x,atob:zx}=globalThis;function jx(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=zx(t);return Uint8Array.from(n,r=>r.codePointAt(0))}function Dx(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return $x(t)}function sn(e){return e instanceof Uint8Array?Dx(e):e}function Kc(e){return e==null?void 0:e.replace(/\/$/,"")}var Ks=x({error:x({message:h(),type:h().nullish(),param:pt().nullish(),code:ee([h(),R()]).nullish()})}),Tt=Wc({errorSchema:Ks,errorToMessage:e=>e.error.message});function Zx({prompt:e,systemMessageMode:t="system"}){const n=[],r=[];for(const{role:o,content:s}of e)switch(o){case"system":{switch(t){case"system":{n.push({role:"system",content:s});break}case"developer":{n.push({role:"developer",content:s});break}case"remove":{r.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=t;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(s.length===1&&s[0].type==="text"){n.push({role:"user",content:s[0].text});break}n.push({role:"user",content:s.map((a,i)=>{var l,u,c;switch(a.type){case"text":return{type:"text",text:a.text};case"file":if(a.mediaType.startsWith("image/")){const w=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${w};base64,${sn(a.data)}`,detail:(u=(l=a.providerOptions)==null?void 0:l.openai)==null?void 0:u.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new at({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:sn(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:sn(a.data),format:"mp3"}};default:throw new at({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new at({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof a.data=="string"&&a.data.startsWith("file-")?{file_id:a.data}:{filename:(c=a.filename)!=null?c:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${sn(a.data)}`}}}else throw new at({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const i=[];for(const l of s)switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}n.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const a of s){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}n.push({role:"tool",tool_call_id:a.toolCallId,content:l})}break}default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return{messages:n,warnings:r}}function Yc({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function Xc(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"unknown"}}var Ux=x({logitBias:We(_g(),R()).optional(),logprobs:ee([re(),R()]).optional(),parallelToolCalls:re().optional(),user:h().optional(),reasoningEffort:qe(["minimal","low","medium","high"]).optional(),maxCompletionTokens:R().optional(),store:re().optional(),metadata:We(h().max(64),h().max(512)).optional(),prediction:We(h(),pt()).optional(),structuredOutputs:re().optional(),serviceTier:qe(["auto","flex","priority"]).optional(),strictJsonSchema:re().optional(),textVerbosity:qe(["low","medium","high"]).optional(),promptCacheKey:h().optional(),safetyIdentifier:h().optional()}),Qc=x({key:h(),type:qe(["eq","ne","gt","gte","lt","lte"]),value:ee([h(),R(),re()])}),ed=x({type:qe(["and","or"]),filters:Z(ee([Qc,Ji(()=>ed)]))}),Lx=ee([Qc,ed]),td=x({vectorStoreIds:Z(h()).optional(),maxNumResults:R().optional(),ranking:x({ranker:qe(["auto","default-2024-08-21"]).optional()}).optional(),filters:Lx.optional()}),qx=Ws({id:"openai.file_search",name:"file_search",inputSchema:x({query:h()})}),nd=x({searchContextSize:qe(["low","medium","high"]).optional(),userLocation:x({type:A("approximate"),country:h().optional(),city:h().optional(),region:h().optional(),timezone:h().optional()}).optional()}),Bx=Ws({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:x({})});function Vx({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){e=e!=null&&e.length?e:void 0;const o=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const s=[];for(const i of e)switch(i.type){case"function":s.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:n?r:void 0}});break;case"provider-defined":switch(i.id){case"openai.file_search":{const l=td.parse(i.args);s.push({type:"file_search",vector_store_ids:l.vectorStoreIds,max_num_results:l.maxNumResults,ranking_options:l.ranking?{ranker:l.ranking.ranker}:void 0,filters:l.filters});break}case"openai.web_search_preview":{const l=nd.parse(i.args);s.push({type:"web_search_preview",search_context_size:l.searchContextSize,user_location:l.userLocation});break}default:o.push({type:"unsupported-tool",tool:i});break}break;default:o.push({type:"unsupported-tool",tool:i});break}if(t==null)return{tools:s,toolChoice:void 0,toolWarnings:o};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:s,toolChoice:a,toolWarnings:o};case"tool":return{tools:s,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:o};default:{const i=a;throw new at({functionality:`tool choice type: ${i}`})}}}var Fx=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,seed:u,tools:c,toolChoice:w,providerOptions:_}){var d,f,y,v;const p=[],b=(d=await kt({provider:"openai",providerOptions:_,schema:Ux}))!=null?d:{},g=(f=b.structuredOutputs)!=null?f:!0;o!=null&&p.push({type:"unsupported-setting",setting:"topK"}),(l==null?void 0:l.type)==="json"&&l.schema!=null&&!g&&p.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:m,warnings:E}=Zx({prompt:e,systemMessageMode:Kx(this.modelId)});p.push(...E);const S=(y=b.strictJsonSchema)!=null?y:!1,T={model:this.modelId,logit_bias:b.logitBias,logprobs:b.logprobs===!0||typeof b.logprobs=="number"?!0:void 0,top_logprobs:typeof b.logprobs=="number"?b.logprobs:typeof b.logprobs=="boolean"&&b.logprobs?0:void 0,user:b.user,parallel_tool_calls:b.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,response_format:(l==null?void 0:l.type)==="json"?g&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:S,name:(v=l.name)!=null?v:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:u,verbosity:b.textVerbosity,max_completion_tokens:b.maxCompletionTokens,store:b.store,metadata:b.metadata,prediction:b.prediction,reasoning_effort:b.reasoningEffort,service_tier:b.serviceTier,prompt_cache_key:b.promptCacheKey,safety_identifier:b.safetyIdentifier,messages:m};od(this.modelId)?(T.temperature!=null&&(T.temperature=void 0,p.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),T.top_p!=null&&(T.top_p=void 0,p.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),T.frequency_penalty!=null&&(T.frequency_penalty=void 0,p.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),T.presence_penalty!=null&&(T.presence_penalty=void 0,p.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),T.logit_bias!=null&&(T.logit_bias=void 0,p.push({type:"other",message:"logitBias is not supported for reasoning models"})),T.logprobs!=null&&(T.logprobs=void 0,p.push({type:"other",message:"logprobs is not supported for reasoning models"})),T.top_logprobs!=null&&(T.top_logprobs=void 0,p.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),T.max_tokens!=null&&(T.max_completion_tokens==null&&(T.max_completion_tokens=T.max_tokens),T.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&T.temperature!=null&&(T.temperature=void 0,p.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),b.serviceTier==="flex"&&!Gx(this.modelId)&&(p.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),T.service_tier=void 0),b.serviceTier==="priority"&&!Wx(this.modelId)&&(p.push({type:"unsupported-setting",setting:"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"}),T.service_tier=void 0);const{tools:P,toolChoice:V,toolWarnings:H}=Vx({tools:c,toolChoice:w,structuredOutputs:g,strictJsonSchema:S});return{args:{...T,tools:P,tool_choice:V},warnings:[...p,...H]}}async doGenerate(e){var t,n,r,o,s,a,i,l,u,c,w,_,d,f;const{args:y,warnings:v}=await this.getArgs(e),{responseHeaders:p,value:b,rawValue:g}=await mt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:y,failedResponseHandler:Tt,successfulResponseHandler:on(Hx),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=b.choices[0],E=[],S=m.message.content;S!=null&&S.length>0&&E.push({type:"text",text:S});for(const H of(t=m.message.tool_calls)!=null?t:[])E.push({type:"tool-call",toolCallId:(n=H.id)!=null?n:tt(),toolName:H.function.name,input:H.function.arguments});for(const H of(r=m.message.annotations)!=null?r:[])E.push({type:"source",sourceType:"url",id:tt(),url:H.url,title:H.title});const T=(o=b.usage)==null?void 0:o.completion_tokens_details,P=(s=b.usage)==null?void 0:s.prompt_tokens_details,V={openai:{}};return(T==null?void 0:T.accepted_prediction_tokens)!=null&&(V.openai.acceptedPredictionTokens=T==null?void 0:T.accepted_prediction_tokens),(T==null?void 0:T.rejected_prediction_tokens)!=null&&(V.openai.rejectedPredictionTokens=T==null?void 0:T.rejected_prediction_tokens),((a=m.logprobs)==null?void 0:a.content)!=null&&(V.openai.logprobs=m.logprobs.content),{content:E,finishReason:Xc(m.finish_reason),usage:{inputTokens:(l=(i=b.usage)==null?void 0:i.prompt_tokens)!=null?l:void 0,outputTokens:(c=(u=b.usage)==null?void 0:u.completion_tokens)!=null?c:void 0,totalTokens:(_=(w=b.usage)==null?void 0:w.total_tokens)!=null?_:void 0,reasoningTokens:(d=T==null?void 0:T.reasoning_tokens)!=null?d:void 0,cachedInputTokens:(f=P==null?void 0:P.cached_tokens)!=null?f:void 0},request:{body:y},response:{...Yc(b),headers:p,body:g},warnings:v,providerMetadata:V}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await mt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:r,failedResponseHandler:Tt,successfulResponseHandler:io(Jx),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let i="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0,c=!1;const w={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:n})},transform(_,d){var f,y,v,p,b,g,m,E,S,T,P,V,H,B,oe,F,be,Ee,Ne,Xe,I,ie,me,de;if(e.includeRawChunks&&d.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){i="error",d.enqueue({type:"error",error:_.error});return}const Q=_.value;if("error"in Q){i="error",d.enqueue({type:"error",error:Q.error});return}u&&(u=!1,d.enqueue({type:"response-metadata",...Yc(Q)})),Q.usage!=null&&(l.inputTokens=(f=Q.usage.prompt_tokens)!=null?f:void 0,l.outputTokens=(y=Q.usage.completion_tokens)!=null?y:void 0,l.totalTokens=(v=Q.usage.total_tokens)!=null?v:void 0,l.reasoningTokens=(b=(p=Q.usage.completion_tokens_details)==null?void 0:p.reasoning_tokens)!=null?b:void 0,l.cachedInputTokens=(m=(g=Q.usage.prompt_tokens_details)==null?void 0:g.cached_tokens)!=null?m:void 0,((E=Q.usage.completion_tokens_details)==null?void 0:E.accepted_prediction_tokens)!=null&&(w.openai.acceptedPredictionTokens=(S=Q.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens),((T=Q.usage.completion_tokens_details)==null?void 0:T.rejected_prediction_tokens)!=null&&(w.openai.rejectedPredictionTokens=(P=Q.usage.completion_tokens_details)==null?void 0:P.rejected_prediction_tokens));const fe=Q.choices[0];if((fe==null?void 0:fe.finish_reason)!=null&&(i=Xc(fe.finish_reason)),((V=fe==null?void 0:fe.logprobs)==null?void 0:V.content)!=null&&(w.openai.logprobs=fe.logprobs.content),(fe==null?void 0:fe.delta)==null)return;const Ze=fe.delta;if(Ze.content!=null&&(c||(d.enqueue({type:"text-start",id:"0"}),c=!0),d.enqueue({type:"text-delta",id:"0",delta:Ze.content})),Ze.tool_calls!=null)for(const se of Ze.tool_calls){const It=se.index;if(a[It]==null){if(se.type!=="function")throw new In({data:se,message:"Expected 'function' type."});if(se.id==null)throw new In({data:se,message:"Expected 'id' to be a string."});if(((H=se.function)==null?void 0:H.name)==null)throw new In({data:se,message:"Expected 'function.name' to be a string."});d.enqueue({type:"tool-input-start",id:se.id,toolName:se.function.name}),a[It]={id:se.id,type:"function",function:{name:se.function.name,arguments:(B=se.function.arguments)!=null?B:""},hasFinished:!1};const Re=a[It];((oe=Re.function)==null?void 0:oe.name)!=null&&((F=Re.function)==null?void 0:F.arguments)!=null&&(Re.function.arguments.length>0&&d.enqueue({type:"tool-input-delta",id:Re.id,delta:Re.function.arguments}),ao(Re.function.arguments)&&(d.enqueue({type:"tool-input-end",id:Re.id}),d.enqueue({type:"tool-call",toolCallId:(be=Re.id)!=null?be:tt(),toolName:Re.function.name,input:Re.function.arguments}),Re.hasFinished=!0));continue}const Se=a[It];Se.hasFinished||(((Ee=se.function)==null?void 0:Ee.arguments)!=null&&(Se.function.arguments+=(Xe=(Ne=se.function)==null?void 0:Ne.arguments)!=null?Xe:""),d.enqueue({type:"tool-input-delta",id:Se.id,delta:(I=se.function.arguments)!=null?I:""}),((ie=Se.function)==null?void 0:ie.name)!=null&&((me=Se.function)==null?void 0:me.arguments)!=null&&ao(Se.function.arguments)&&(d.enqueue({type:"tool-input-end",id:Se.id}),d.enqueue({type:"tool-call",toolCallId:(de=Se.id)!=null?de:tt(),toolName:Se.function.name,input:Se.function.arguments}),Se.hasFinished=!0))}if(Ze.annotations!=null)for(const se of Ze.annotations)d.enqueue({type:"source",sourceType:"url",id:tt(),url:se.url,title:se.title})},flush(_){c&&_.enqueue({type:"text-end",id:"0"}),_.enqueue({type:"finish",finishReason:i,usage:l,...w!=null?{providerMetadata:w}:{}})}})),request:{body:r},response:{headers:o}}}},rd=x({prompt_tokens:R().nullish(),completion_tokens:R().nullish(),total_tokens:R().nullish(),prompt_tokens_details:x({cached_tokens:R().nullish()}).nullish(),completion_tokens_details:x({reasoning_tokens:R().nullish(),accepted_prediction_tokens:R().nullish(),rejected_prediction_tokens:R().nullish()}).nullish()}).nullish(),Hx=x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({message:x({role:A("assistant").nullish(),content:h().nullish(),tool_calls:Z(x({id:h().nullish(),type:A("function"),function:x({name:h(),arguments:h()})})).nullish(),annotations:Z(x({type:A("url_citation"),start_index:R(),end_index:R(),url:h(),title:h()})).nullish()}),index:R(),logprobs:x({content:Z(x({token:h(),logprob:R(),top_logprobs:Z(x({token:h(),logprob:R()}))})).nullish()}).nullish(),finish_reason:h().nullish()})),usage:rd}),Jx=ee([x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({delta:x({role:qe(["assistant"]).nullish(),content:h().nullish(),tool_calls:Z(x({index:R(),id:h().nullish(),type:A("function").nullish(),function:x({name:h().nullish(),arguments:h().nullish()})})).nullish(),annotations:Z(x({type:A("url_citation"),start_index:R(),end_index:R(),url:h(),title:h()})).nullish()}).nullish(),logprobs:x({content:Z(x({token:h(),logprob:R(),top_logprobs:Z(x({token:h(),logprob:R()}))})).nullish()}).nullish(),finish_reason:h().nullish(),index:R()})),usage:rd}),Ks]);function od(e){return(e.startsWith("o")||e.startsWith("gpt-5"))&&!e.startsWith("gpt-5-chat")}function Gx(e){return e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat")}function Wx(e){return 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")}function Kx(e){var t,n;return od(e)?(n=(t=Yx[e])==null?void 0:t.systemMessageMode)!=null?n:"developer":"system"}var Yx={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function Xx({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
67
67
 
68
68
  `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new Ht({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const a=s.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");r+=`${t}:
69
69
  ${a}
@@ -73,14 +73,14 @@ ${a}
73
73
 
74
74
  `;break}case"tool":throw new at({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return r+=`${n}:
75
75
  `,{prompt:r,stopSequences:[`
76
- ${t}:`]}}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}}function ad(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"unknown"}}var id=x({echo:re().optional(),logitBias:We(h(),R()).optional(),suffix:h().optional(),user:h().optional(),logprobs:ee([re(),R()]).optional()}),ek=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,tools:u,toolChoice:c,seed:w,providerOptions:_}){const d=[],f={...await kt({provider:"openai",providerOptions:_,schema:id}),...await kt({provider:this.providerOptionsName,providerOptions:_,schema:id})};o!=null&&d.push({type:"unsupported-setting",setting:"topK"}),u!=null&&u.length&&d.push({type:"unsupported-setting",setting:"tools"}),c!=null&&d.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:y,stopSequences:v}=Qx({prompt:e}),p=[...v??[],...i??[]];return{args:{model:this.modelId,echo:f.echo,logit_bias:f.logitBias,logprobs:(f==null?void 0:f.logprobs)===!0?0:(f==null?void 0:f.logprobs)===!1||f==null?void 0:f.logprobs,suffix:f.suffix,user:f.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,seed:w,prompt:y,stop:p.length>0?p:void 0},warnings:d}}async doGenerate(e){var t,n,r;const{args:o,warnings:s}=await this.getArgs(e),{responseHeaders:a,value:i,rawValue:l}=await mt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:o,failedResponseHandler:Tt,successfulResponseHandler:on(tk),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=i.choices[0],c={openai:{}};return u.logprobs!=null&&(c.openai.logprobs=u.logprobs),{content:[{type:"text",text:u.text}],usage:{inputTokens:(t=i.usage)==null?void 0:t.prompt_tokens,outputTokens:(n=i.usage)==null?void 0:n.completion_tokens,totalTokens:(r=i.usage)==null?void 0:r.total_tokens},finishReason:ad(u.finish_reason),request:{body:o},response:{...sd(i),headers:a,body:l},providerMetadata:c,warnings:s}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await mt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:r,failedResponseHandler:Tt,successfulResponseHandler:io(nk),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0;return{stream:s.pipeThrough(new TransformStream({start(c){c.enqueue({type:"stream-start",warnings:n})},transform(c,w){if(e.includeRawChunks&&w.enqueue({type:"raw",rawValue:c.rawValue}),!c.success){a="error",w.enqueue({type:"error",error:c.error});return}const _=c.value;if("error"in _){a="error",w.enqueue({type:"error",error:_.error});return}u&&(u=!1,w.enqueue({type:"response-metadata",...sd(_)}),w.enqueue({type:"text-start",id:"0"})),_.usage!=null&&(l.inputTokens=_.usage.prompt_tokens,l.outputTokens=_.usage.completion_tokens,l.totalTokens=_.usage.total_tokens);const d=_.choices[0];(d==null?void 0:d.finish_reason)!=null&&(a=ad(d.finish_reason)),(d==null?void 0:d.logprobs)!=null&&(i.openai.logprobs=d.logprobs),(d==null?void 0:d.text)!=null&&d.text.length>0&&w.enqueue({type:"text-delta",id:"0",delta:d.text})},flush(c){u||c.enqueue({type:"text-end",id:"0"}),c.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:l})}})),request:{body:r},response:{headers:o}}}},ld=x({prompt_tokens:R(),completion_tokens:R(),total_tokens:R()}),tk=x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({text:h(),finish_reason:h(),logprobs:x({tokens:Z(h()),token_logprobs:Z(R()),top_logprobs:Z(We(h(),R())).nullish()}).nullish()})),usage:ld.nullish()}),nk=ee([x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({text:h(),finish_reason:h().nullish(),index:R(),logprobs:x({tokens:Z(h()),token_logprobs:Z(R()),top_logprobs:Z(We(h(),R())).nullish()}).nullish()})),usage:ld.nullish()}),Ks]),rk=x({dimensions:R().optional(),user:h().optional()}),ok=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new hp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await kt({provider:"openai",providerOptions:r,schema:rk}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await mt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:dt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Tt,successfulResponseHandler:on(sk),abortSignal:n,fetch:this.config.fetch});return{embeddings:i.data.map(u=>u.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},sk=x({data:Z(x({embedding:Z(R())})),usage:x({prompt_tokens:R()}).nullish()}),ak={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},ik=new Set(["gpt-image-1"]),lk=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return(e=ak[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:o,providerOptions:s,headers:a,abortSignal:i}){var l,u,c,w;const _=[];r!=null&&_.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&_.push({type:"unsupported-setting",setting:"seed"});const d=(c=(u=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:u.call(l))!=null?c:new Date,{value:f,responseHeaders:y}=await mt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:dt(this.config.headers(),a),body:{model:this.modelId,prompt:e,n:t,size:n,...(w=s.openai)!=null?w:{},...ik.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Tt,successfulResponseHandler:on(uk),abortSignal:i,fetch:this.config.fetch});return{images:f.data.map(v=>v.b64_json),warnings:_,response:{timestamp:d,modelId:this.modelId,headers:y},providerMetadata:{openai:{images:f.data.map(v=>v.revised_prompt?{revisedPrompt:v.revised_prompt}:null)}}}}},uk=x({data:Z(x({b64_json:h(),revised_prompt:h().optional()}))}),ck=x({container:ee([h(),x({fileIds:Z(h()).optional()})]).optional()}),dk=Ws({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:x({})}),pk={codeInterpreter:dk,fileSearch:Bx,webSearchPreview:Vx};function ud(e,t){return t?t.some(n=>e.startsWith(n)):!1}async function hk({prompt:e,systemMessageMode:t,fileIdPrefixes:n}){var r,o,s,a,i,l;const u=[],c=[];for(const{role:w,content:_}of e)switch(w){case"system":{switch(t){case"system":{u.push({role:"system",content:_});break}case"developer":{u.push({role:"developer",content:_});break}case"remove":{c.push({type:"other",message:"system messages are removed for this model"});break}default:{const d=t;throw new Error(`Unsupported system message mode: ${d}`)}}break}case"user":{u.push({role:"user",content:_.map((d,f)=>{var y,v,p;switch(d.type){case"text":return{type:"input_text",text:d.text};case"file":if(d.mediaType.startsWith("image/")){const b=d.mediaType==="image/*"?"image/jpeg":d.mediaType;return{type:"input_image",...d.data instanceof URL?{image_url:d.data.toString()}:typeof d.data=="string"&&ud(d.data,n)?{file_id:d.data}:{image_url:`data:${b};base64,${sn(d.data)}`},detail:(v=(y=d.providerOptions)==null?void 0:y.openai)==null?void 0:v.imageDetail}}else if(d.mediaType==="application/pdf"){if(d.data instanceof URL)throw new at({functionality:"PDF file parts with URLs"});return{type:"input_file",...typeof d.data=="string"&&ud(d.data,n)?{file_id:d.data}:{filename:(p=d.filename)!=null?p:`part-${f}.pdf`,file_data:`data:application/pdf;base64,${sn(d.data)}`}}}else throw new at({functionality:`file part media type ${d.mediaType}`})}})});break}case"assistant":{const d={};for(const f of _)switch(f.type){case"text":{u.push({role:"assistant",content:[{type:"output_text",text:f.text}],id:(s=(o=(r=f.providerOptions)==null?void 0:r.openai)==null?void 0:o.itemId)!=null?s:void 0});break}case"tool-call":{if(f.providerExecuted)break;u.push({type:"function_call",call_id:f.toolCallId,name:f.toolName,arguments:JSON.stringify(f.input),id:(l=(i=(a=f.providerOptions)==null?void 0:a.openai)==null?void 0:i.itemId)!=null?l:void 0});break}case"tool-result":{c.push({type:"other",message:"tool result parts in assistant messages are not supported for OpenAI responses"});break}case"reasoning":{const y=await kt({provider:"openai",providerOptions:f.providerOptions,schema:fk}),v=y==null?void 0:y.itemId;if(v!=null){const p=d[v],b=[];f.text.length>0?b.push({type:"summary_text",text:f.text}):p!==void 0&&c.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(f)}.`}),p===void 0?(d[v]={type:"reasoning",id:v,encrypted_content:y==null?void 0:y.reasoningEncryptedContent,summary:b},u.push(d[v])):p.summary.push(...b)}else c.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(f)}.`});break}}break}case"tool":{for(const d of _){const f=d.output;let y;switch(f.type){case"text":case"error-text":y=f.value;break;case"content":case"json":case"error-json":y=JSON.stringify(f.value);break}u.push({type:"function_call_output",call_id:d.toolCallId,output:y})}break}default:{const d=w;throw new Error(`Unsupported role: ${d}`)}}return{messages:u,warnings:c}}var fk=x({itemId:h().nullish(),reasoningEncryptedContent:h().nullish()});function cd({finishReason:e,hasToolCalls: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":"unknown"}}function mk({tools:e,toolChoice:t,strictJsonSchema:n}){e=e!=null&&e.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const o=[];for(const a of e)switch(a.type){case"function":o.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:n});break;case"provider-defined":{switch(a.id){case"openai.file_search":{const i=td.parse(a.args);o.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker}:void 0,filters:i.filters});break}case"openai.web_search_preview":{const i=nd.parse(a.args);o.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=ck.parse(a.args);o.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}default:{r.push({type:"unsupported-tool",tool:a});break}}break}default:r.push({type:"unsupported-tool",tool:a});break}if(t==null)return{tools:o,toolChoice:void 0,toolWarnings:r};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:o,toolChoice:s,toolWarnings:r};case"tool":return{tools:o,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="web_search_preview"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:{const a=s;throw new at({functionality:`tool choice type: ${a}`})}}}var dd=20,pd=Z(x({token:h(),logprob:R(),top_logprobs:Z(x({token:h(),logprob:R()}))})),gk=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:o,presencePenalty:s,frequencyPenalty:a,seed:i,prompt:l,providerOptions:u,tools:c,toolChoice:w,responseFormat:_}){var d,f;const y=[],v=Dk(this.modelId);o!=null&&y.push({type:"unsupported-setting",setting:"topK"}),i!=null&&y.push({type:"unsupported-setting",setting:"seed"}),s!=null&&y.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&y.push({type:"unsupported-setting",setting:"frequencyPenalty"}),n!=null&&y.push({type:"unsupported-setting",setting:"stopSequences"});const{messages:p,warnings:b}=await hk({prompt:l,systemMessageMode:v.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});y.push(...b);const g=await kt({provider:"openai",providerOptions:u,schema:Zk}),m=(d=g==null?void 0:g.strictJsonSchema)!=null?d:!1,E=typeof(g==null?void 0:g.logprobs)=="number"?g==null?void 0:g.logprobs:(g==null?void 0:g.logprobs)===!0?dd:void 0,S=E?Array.isArray(g==null?void 0:g.include)?[...g==null?void 0:g.include,"message.output_text.logprobs"]:["message.output_text.logprobs"]:g==null?void 0:g.include,T={model:this.modelId,input:p,temperature:t,top_p:r,max_output_tokens:e,...((_==null?void 0:_.type)==="json"||(g==null?void 0:g.textVerbosity))&&{text:{...(_==null?void 0:_.type)==="json"&&{format:_.schema!=null?{type:"json_schema",strict:m,name:(f=_.name)!=null?f:"response",description:_.description,schema:_.schema}:{type:"json_object"}},...(g==null?void 0:g.textVerbosity)&&{verbosity:g.textVerbosity}}},metadata:g==null?void 0:g.metadata,parallel_tool_calls:g==null?void 0:g.parallelToolCalls,previous_response_id:g==null?void 0:g.previousResponseId,store:g==null?void 0:g.store,user:g==null?void 0:g.user,instructions:g==null?void 0:g.instructions,service_tier:g==null?void 0:g.serviceTier,include:S,prompt_cache_key:g==null?void 0:g.promptCacheKey,safety_identifier:g==null?void 0:g.safetyIdentifier,top_logprobs:E,...v.isReasoningModel&&((g==null?void 0:g.reasoningEffort)!=null||(g==null?void 0:g.reasoningSummary)!=null)&&{reasoning:{...(g==null?void 0:g.reasoningEffort)!=null&&{effort:g.reasoningEffort},...(g==null?void 0:g.reasoningSummary)!=null&&{summary:g.reasoningSummary}}},...v.requiredAutoTruncation&&{truncation:"auto"}};v.isReasoningModel?(T.temperature!=null&&(T.temperature=void 0,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),T.top_p!=null&&(T.top_p=void 0,y.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):((g==null?void 0:g.reasoningEffort)!=null&&y.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(g==null?void 0:g.reasoningSummary)!=null&&y.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(g==null?void 0:g.serviceTier)==="flex"&&!v.supportsFlexProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete T.service_tier),(g==null?void 0:g.serviceTier)==="priority"&&!v.supportsPriorityProcessing&&(y.push({type:"unsupported-setting",setting:"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 T.service_tier);const{tools:P,toolChoice:V,toolWarnings:H}=mk({tools:c,toolChoice:w,strictJsonSchema:m});return{args:{...T,tools:P,tool_choice:V},warnings:[...y,...H]}}async doGenerate(e){var t,n,r,o,s,a,i,l,u,c,w,_,d,f,y,v,p;const{args:b,warnings:g}=await this.getArgs(e),m=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:E,value:S,rawValue:T}=await mt({url:m,headers:dt(this.config.headers(),e.headers),body:b,failedResponseHandler:Tt,successfulResponseHandler:on(x({id:h(),created_at:R(),error:x({code:h(),message:h()}).nullish(),model:h(),output:Z(cn("type",[x({type:A("message"),role:A("assistant"),id:h(),content:Z(x({type:A("output_text"),text:h(),logprobs:pd.nullish(),annotations:Z(cn("type",[x({type:A("url_citation"),start_index:R(),end_index:R(),url:h(),title:h()}),x({type:A("file_citation"),start_index:R(),end_index:R(),file_id:h(),quote:h()})]))}))}),x({type:A("function_call"),call_id:h(),name:h(),arguments:h(),id:h()}),x({type:A("web_search_call"),id:h(),status:h().optional(),action:x({type:A("search"),query:h().optional()}).nullish()}),x({type:A("computer_call"),id:h(),status:h().optional()}),x({type:A("file_search_call"),id:h(),status:h().optional(),queries:Z(h()).nullish(),results:Z(x({attributes:x({file_id:h(),filename:h(),score:R(),text:h()})})).nullish()}),x({type:A("reasoning"),id:h(),encrypted_content:h().nullish(),summary:Z(x({type:A("summary_text"),text:h()}))})])),incomplete_details:x({reason:h()}).nullable(),usage:hd})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(S.error)throw new pe({message:S.error.message,url:m,requestBodyValues:b,statusCode:400,responseHeaders:E,responseBody:T,isRetryable:!1});const P=[],V=[];for(const B of S.output)switch(B.type){case"reasoning":{B.summary.length===0&&B.summary.push({type:"summary_text",text:""});for(const oe of B.summary)P.push({type:"reasoning",text:oe.text,providerMetadata:{openai:{itemId:B.id,reasoningEncryptedContent:(t=B.encrypted_content)!=null?t:null}}});break}case"message":{for(const oe of B.content){(r=(n=e.providerOptions)==null?void 0:n.openai)!=null&&r.logprobs&&oe.logprobs&&V.push(oe.logprobs),P.push({type:"text",text:oe.text,providerMetadata:{openai:{itemId:B.id}}});for(const F of oe.annotations)F.type==="url_citation"?P.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:tt(),url:F.url,title:F.title}):F.type==="file_citation"&&P.push({type:"source",sourceType:"document",id:(u=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?u:tt(),mediaType:"text/plain",title:F.quote,filename:F.file_id})}break}case"function_call":{P.push({type:"tool-call",toolCallId:B.call_id,toolName:B.name,input:B.arguments,providerMetadata:{openai:{itemId:B.id}}});break}case"web_search_call":{P.push({type:"tool-call",toolCallId:B.id,toolName:"web_search_preview",input:(w=(c=B.action)==null?void 0:c.query)!=null?w:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:B.id,toolName:"web_search_preview",result:{status:B.status||"completed",...((_=B.action)==null?void 0:_.query)&&{query:B.action.query}},providerExecuted:!0});break}case"computer_call":{P.push({type:"tool-call",toolCallId:B.id,toolName:"computer_use",input:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:B.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:B.status||"completed"},providerExecuted:!0});break}case"file_search_call":{P.push({type:"tool-call",toolCallId:B.id,toolName:"file_search",input:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:B.id,toolName:"file_search",result:{type:"file_search_tool_result",status:B.status||"completed",...B.queries&&{queries:B.queries},...B.results&&{results:B.results}},providerExecuted:!0});break}}const H={openai:{responseId:S.id}};return V.length>0&&(H.openai.logprobs=V),{content:P,finishReason:cd({finishReason:(d=S.incomplete_details)==null?void 0:d.reason,hasToolCalls:P.some(B=>B.type==="tool-call")}),usage:{inputTokens:S.usage.input_tokens,outputTokens:S.usage.output_tokens,totalTokens:S.usage.input_tokens+S.usage.output_tokens,reasoningTokens:(y=(f=S.usage.output_tokens_details)==null?void 0:f.reasoning_tokens)!=null?y:void 0,cachedInputTokens:(p=(v=S.usage.input_tokens_details)==null?void 0:v.cached_tokens)!=null?p:void 0},request:{body:b},response:{id:S.id,timestamp:new Date(S.created_at*1e3),modelId:S.model,headers:E,body:T},providerMetadata:H,warnings:g}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:o}=await mt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Tt,successfulResponseHandler:io(Ck),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=this;let a="unknown";const i={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[];let u=null;const c={};let w=!1;const _={};return{stream:o.pipeThrough(new TransformStream({start(d){d.enqueue({type:"stream-start",warnings:n})},transform(d,f){var y,v,p,b,g,m,E,S,T,P,V,H,B,oe,F,be,Ee,Ne,Xe;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:d.rawValue}),!d.success){a="error",f.enqueue({type:"error",error:d.error});return}const I=d.value;if(md(I))I.item.type==="function_call"?(c[I.output_index]={toolName:I.item.name,toolCallId:I.item.call_id},f.enqueue({type:"tool-input-start",id:I.item.call_id,toolName:I.item.name})):I.item.type==="web_search_call"?(c[I.output_index]={toolName:"web_search_preview",toolCallId:I.item.id},f.enqueue({type:"tool-input-start",id:I.item.id,toolName:"web_search_preview"})):I.item.type==="computer_call"?(c[I.output_index]={toolName:"computer_use",toolCallId:I.item.id},f.enqueue({type:"tool-input-start",id:I.item.id,toolName:"computer_use"})):I.item.type==="file_search_call"?(c[I.output_index]={toolName:"file_search",toolCallId:I.item.id},f.enqueue({type:"tool-input-start",id:I.item.id,toolName:"file_search"})):I.item.type==="message"?f.enqueue({type:"text-start",id:I.item.id,providerMetadata:{openai:{itemId:I.item.id}}}):Mk(I)&&(_[I.item.id]={encryptedContent:I.item.encrypted_content,summaryParts:[0]},f.enqueue({type:"reasoning-start",id:`${I.item.id}:0`,providerMetadata:{openai:{itemId:I.item.id,reasoningEncryptedContent:(y=I.item.encrypted_content)!=null?y:null}}}));else if(fd(I)){if(I.item.type==="function_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.call_id}),f.enqueue({type:"tool-call",toolCallId:I.item.call_id,toolName:I.item.name,input:I.item.arguments,providerMetadata:{openai:{itemId:I.item.id}}});else if(I.item.type==="web_search_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.id}),f.enqueue({type:"tool-call",toolCallId:I.item.id,toolName:"web_search_preview",input:(p=(v=I.item.action)==null?void 0:v.query)!=null?p:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:I.item.id,toolName:"web_search_preview",result:{type:"web_search_tool_result",status:I.item.status||"completed",...((b=I.item.action)==null?void 0:b.query)&&{query:I.item.action.query}},providerExecuted:!0});else if(I.item.type==="computer_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.id}),f.enqueue({type:"tool-call",toolCallId:I.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:I.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:I.item.status||"completed"},providerExecuted:!0});else if(I.item.type==="file_search_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.id}),f.enqueue({type:"tool-call",toolCallId:I.item.id,toolName:"file_search",input:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:I.item.id,toolName:"file_search",result:{type:"file_search_tool_result",status:I.item.status||"completed",...I.item.queries&&{queries:I.item.queries},...I.item.results&&{results:I.item.results}},providerExecuted:!0});else if(I.item.type==="message")f.enqueue({type:"text-end",id:I.item.id});else if(Rk(I)){const ie=_[I.item.id];for(const me of ie.summaryParts)f.enqueue({type:"reasoning-end",id:`${I.item.id}:${me}`,providerMetadata:{openai:{itemId:I.item.id,reasoningEncryptedContent:(g=I.item.encrypted_content)!=null?g:null}}});delete _[I.item.id]}}else if(Nk(I)){const ie=c[I.output_index];ie!=null&&f.enqueue({type:"tool-input-delta",id:ie.toolCallId,delta:I.delta})}else Ok(I)?(u=I.response.id,f.enqueue({type:"response-metadata",id:I.response.id,timestamp:new Date(I.response.created_at*1e3),modelId:I.response.model})):Ek(I)?(f.enqueue({type:"text-delta",id:I.item_id,delta:I.delta}),I.logprobs&&l.push(I.logprobs)):$k(I)?I.summary_index>0&&((m=_[I.item_id])==null||m.summaryParts.push(I.summary_index),f.enqueue({type:"reasoning-start",id:`${I.item_id}:${I.summary_index}`,providerMetadata:{openai:{itemId:I.item_id,reasoningEncryptedContent:(S=(E=_[I.item_id])==null?void 0:E.encryptedContent)!=null?S:null}}})):zk(I)?f.enqueue({type:"reasoning-delta",id:`${I.item_id}:${I.summary_index}`,delta:I.delta,providerMetadata:{openai:{itemId:I.item_id}}}):Ak(I)?(a=cd({finishReason:(T=I.response.incomplete_details)==null?void 0:T.reason,hasToolCalls:w}),i.inputTokens=I.response.usage.input_tokens,i.outputTokens=I.response.usage.output_tokens,i.totalTokens=I.response.usage.input_tokens+I.response.usage.output_tokens,i.reasoningTokens=(V=(P=I.response.usage.output_tokens_details)==null?void 0:P.reasoning_tokens)!=null?V:void 0,i.cachedInputTokens=(B=(H=I.response.usage.input_tokens_details)==null?void 0:H.cached_tokens)!=null?B:void 0):Pk(I)?I.annotation.type==="url_citation"?f.enqueue({type:"source",sourceType:"url",id:(be=(F=(oe=s.config).generateId)==null?void 0:F.call(oe))!=null?be:tt(),url:I.annotation.url,title:I.annotation.title}):I.annotation.type==="file_citation"&&f.enqueue({type:"source",sourceType:"document",id:(Xe=(Ne=(Ee=s.config).generateId)==null?void 0:Ne.call(Ee))!=null?Xe:tt(),mediaType:"text/plain",title:I.annotation.quote,filename:I.annotation.file_id}):jk(I)&&f.enqueue({type:"error",error:I})},flush(d){const f={openai:{responseId:u}};l.length>0&&(f.openai.logprobs=l),d.enqueue({type:"finish",finishReason:a,usage:i,providerMetadata:f})}})),request:{body:t},response:{headers:r}}}},hd=x({input_tokens:R(),input_tokens_details:x({cached_tokens:R().nullish()}).nullish(),output_tokens:R(),output_tokens_details:x({reasoning_tokens:R().nullish()}).nullish()}),yk=x({type:A("response.output_text.delta"),item_id:h(),delta:h(),logprobs:pd.nullish()}),vk=x({type:A("error"),code:h(),message:h(),param:h().nullish(),sequence_number:R()}),_k=x({type:qe(["response.completed","response.incomplete"]),response:x({incomplete_details:x({reason:h()}).nullish(),usage:hd})}),wk=x({type:A("response.created"),response:x({id:h(),created_at:R(),model:h()})}),bk=x({type:A("response.output_item.added"),output_index:R(),item:cn("type",[x({type:A("message"),id:h()}),x({type:A("reasoning"),id:h(),encrypted_content:h().nullish()}),x({type:A("function_call"),id:h(),call_id:h(),name:h(),arguments:h()}),x({type:A("web_search_call"),id:h(),status:h(),action:x({type:A("search"),query:h().optional()}).nullish()}),x({type:A("computer_call"),id:h(),status:h()}),x({type:A("file_search_call"),id:h(),status:h(),queries:Z(h()).nullish(),results:Z(x({attributes:x({file_id:h(),filename:h(),score:R(),text:h()})})).optional()})])}),xk=x({type:A("response.output_item.done"),output_index:R(),item:cn("type",[x({type:A("message"),id:h()}),x({type:A("reasoning"),id:h(),encrypted_content:h().nullish()}),x({type:A("function_call"),id:h(),call_id:h(),name:h(),arguments:h(),status:A("completed")}),x({type:A("web_search_call"),id:h(),status:A("completed"),action:x({type:A("search"),query:h().optional()}).nullish()}),x({type:A("computer_call"),id:h(),status:A("completed")}),x({type:A("file_search_call"),id:h(),status:A("completed"),queries:Z(h()).nullish(),results:Z(x({attributes:x({file_id:h(),filename:h(),score:R(),text:h()})})).nullish()})])}),kk=x({type:A("response.function_call_arguments.delta"),item_id:h(),output_index:R(),delta:h()}),Tk=x({type:A("response.output_text.annotation.added"),annotation:cn("type",[x({type:A("url_citation"),url:h(),title:h()}),x({type:A("file_citation"),file_id:h(),quote:h()})])}),Sk=x({type:A("response.reasoning_summary_part.added"),item_id:h(),summary_index:R()}),Ik=x({type:A("response.reasoning_summary_text.delta"),item_id:h(),summary_index:R(),delta:h()}),Ck=ee([yk,_k,wk,bk,xk,kk,Tk,Sk,Ik,vk,x({type:h()}).loose()]);function Ek(e){return e.type==="response.output_text.delta"}function fd(e){return e.type==="response.output_item.done"}function Rk(e){return fd(e)&&e.item.type==="reasoning"}function Ak(e){return e.type==="response.completed"||e.type==="response.incomplete"}function Ok(e){return e.type==="response.created"}function Nk(e){return e.type==="response.function_call_arguments.delta"}function md(e){return e.type==="response.output_item.added"}function Mk(e){return md(e)&&e.item.type==="reasoning"}function Pk(e){return e.type==="response.output_text.annotation.added"}function $k(e){return e.type==="response.reasoning_summary_part.added"}function zk(e){return e.type==="response.reasoning_summary_text.delta"}function jk(e){return e.type==="error"}function Dk(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={requiredAutoTruncation:!1,systemMessageMode:"system",supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith("gpt-5-chat")?{...r,isReasoningModel:!1}:e.startsWith("o")||e.startsWith("gpt-5")||e.startsWith("codex-")||e.startsWith("computer-use")?e.startsWith("o1-mini")||e.startsWith("o1-preview")?{...r,isReasoningModel:!0,systemMessageMode:"remove"}:{...r,isReasoningModel:!0,systemMessageMode:"developer"}:{...r,isReasoningModel:!1}}var Zk=x({metadata:pt().nullish(),parallelToolCalls:re().nullish(),previousResponseId:h().nullish(),store:re().nullish(),user:h().nullish(),reasoningEffort:h().nullish(),strictJsonSchema:re().nullish(),instructions:h().nullish(),reasoningSummary:h().nullish(),serviceTier:qe(["auto","flex","priority"]).nullish(),include:Z(qe(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),textVerbosity:qe(["low","medium","high"]).nullish(),promptCacheKey:h().nullish(),safetyIdentifier:h().nullish(),logprobs:ee([re(),R().min(1).max(dd)]).optional()}),Uk=x({instructions:h().nullish(),speed:R().min(.25).max(4).default(1).nullish()}),Lk=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:n="mp3",speed:r,instructions:o,language:s,providerOptions:a}){const i=[],l=await kt({provider:"openai",providerOptions:a,schema:Uk}),u={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:o};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?u.response_format=n:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),l){const c={};for(const w in c){const _=c[w];_!==void 0&&(u[w]=_)}}return s&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:u,warnings:i}}async doGenerate(e){var t,n,r;const o=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{requestBody:s,warnings:a}=await this.getArgs(e),{value:i,responseHeaders:l,rawValue:u}=await mt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:s,failedResponseHandler:Tt,successfulResponseHandler:$x(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:a,request:{body:JSON.stringify(s)},response:{timestamp:o,modelId:this.modelId,headers:l,body:u}}}},qk=x({include:Z(h()).optional(),language:h().optional(),prompt:h().optional(),temperature:R().min(0).max(1).default(0).optional(),timestampGranularities:Z(qe(["word","segment"])).default(["segment"]).optional()}),gd={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"},Bk=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){const r=[],o=await kt({provider:"openai",providerOptions:n,schema:qk}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([Dx(e)]);if(s.append("model",this.modelId),s.append("file",new File([a],"audio",{type:t})),o){const i={include:o.include,language:o.language,prompt:o.prompt,response_format:"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[l,u]of Object.entries(i))u!=null&&s.append(l,String(u))}return{formData:s,warnings:r}}async doGenerate(e){var t,n,r,o,s,a,i,l;const u=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{formData:c,warnings:w}=await this.getArgs(e),{value:_,responseHeaders:d,rawValue:f}=await Px({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),formData:c,failedResponseHandler:Tt,successfulResponseHandler:on(Vk),abortSignal:e.abortSignal,fetch:this.config.fetch}),y=_.language!=null&&_.language in gd?gd[_.language]:void 0;return{text:_.text,segments:(i=(a=(o=_.segments)==null?void 0:o.map(v=>({text:v.text,startSecond:v.start,endSecond:v.end})))!=null?a:(s=_.words)==null?void 0:s.map(v=>({text:v.word,startSecond:v.start,endSecond:v.end})))!=null?i:[],language:y,durationInSeconds:(l=_.duration)!=null?l:void 0,warnings:w,response:{timestamp:u,modelId:this.modelId,headers:d,body:f}}}},Vk=x({text:h(),language:h().nullish(),duration:R().nullish(),words:Z(x({word:h(),start:R(),end:R()})).nullish(),segments:Z(x({id:R(),seek:R(),start:R(),end:R(),text:h(),tokens:Z(R()),temperature:R(),avg_logprob:R(),compression_ratio:R(),no_speech_prob:R()})).nullish()});function yd(e={}){var t,n;const r=(t=Kc(e.baseURL))!=null?t:"https://api.openai.com/v1",o=(n=e.name)!=null?n:"openai",s=()=>({Authorization:`Bearer ${Hc({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),a=y=>new Hx(y,{provider:`${o}.chat`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),i=y=>new ek(y,{provider:`${o}.completion`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),l=y=>new ok(y,{provider:`${o}.embedding`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),u=y=>new lk(y,{provider:`${o}.image`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),c=y=>new Bk(y,{provider:`${o}.transcription`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),w=y=>new Lk(y,{provider:`${o}.speech`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),_=y=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(y)},d=y=>new gk(y,{provider:`${o}.responses`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),f=function(y){return _(y)};return f.languageModel=_,f.chat=a,f.completion=i,f.responses=d,f.embedding=l,f.textEmbedding=l,f.textEmbeddingModel=l,f.image=u,f.imageModel=u,f.transcription=c,f.transcriptionModel=c,f.speech=w,f.speechModel=w,f.tools=pk,f}yd();function sr(e){var t,n;return(n=(t=e==null?void 0:e.providerOptions)==null?void 0:t.openaiCompatible)!=null?n:{}}function Fk(e){const t=[];for(const{role:n,content:r,...o}of e){const s=sr({...o});switch(n){case"system":{t.push({role:"system",content:r,...s});break}case"user":{if(r.length===1&&r[0].type==="text"){t.push({role:"user",content:r[0].text,...sr(r[0])});break}t.push({role:"user",content:r.map(a=>{const i=sr(a);switch(a.type){case"text":return{type:"text",text:a.text,...i};case"file":if(a.mediaType.startsWith("image/")){const l=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${l};base64,${sn(a.data)}`},...i}}else throw new at({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of r){const u=sr(l);switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...u});break}}}t.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const a of r){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const u=sr(a);t.push({role:"tool",tool_call_id:a.toolCallId,content:l,...u})}break}default:{const a=n;throw new Error(`Unsupported role: ${a}`)}}}return t}function vd({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function _d(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"unknown"}}var wd=x({user:h().optional(),reasoningEffort:h().optional()}),Hk=x({error:x({message:h(),type:h().nullish(),param:pt().nullish(),code:ee([h(),R()]).nullish()})}),Jk={errorSchema:Hk,errorToMessage:e=>e.error.message};function Gk({tools:e,toolChoice:t}){e=e!=null&&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-defined"?n.push({type:"unsupported-tool",tool:s}):r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});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 at({functionality:`tool choice type: ${s}`})}}}var Wk=class{constructor(e,t){this.specificationVersion="v2";var n,r;this.modelId=e,this.config=t;const o=(n=t.errorStructure)!=null?n:Jk;this.chunkSchema=Yk(o.errorSchema),this.failedResponseHandler=Wc(o),this.supportsStructuredOutputs=(r=t.supportsStructuredOutputs)!=null?r:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:a,providerOptions:i,stopSequences:l,responseFormat:u,seed:c,toolChoice:w,tools:_}){var d,f,y;const v=[],p=Object.assign((d=await kt({provider:"openai-compatible",providerOptions:i,schema:wd}))!=null?d:{},(f=await kt({provider:this.providerOptionsName,providerOptions:i,schema:wd}))!=null?f:{});o!=null&&v.push({type:"unsupported-setting",setting:"topK"}),(u==null?void 0:u.type)==="json"&&u.schema!=null&&!this.supportsStructuredOutputs&&v.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:b,toolChoice:g,toolWarnings:m}=Gk({tools:_,toolChoice:w});return{args:{model:this.modelId,user:p.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,response_format:(u==null?void 0:u.type)==="json"?this.supportsStructuredOutputs===!0&&u.schema!=null?{type:"json_schema",json_schema:{schema:u.schema,name:(y=u.name)!=null?y:"response",description:u.description}}:{type:"json_object"}:void 0,stop:l,seed:c,...i==null?void 0:i[this.providerOptionsName],reasoning_effort:p.reasoningEffort,messages:Fk(e),tools:b,tool_choice:g},warnings:[...v,...m]}}async doGenerate(e){var t,n,r,o,s,a,i,l,u,c,w,_,d,f,y,v,p;const{args:b,warnings:g}=await this.getArgs({...e}),m=JSON.stringify(b),{responseHeaders:E,value:S,rawValue:T}=await mt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:b,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:on(Kk),abortSignal:e.abortSignal,fetch:this.config.fetch}),P=S.choices[0],V=[],H=P.message.content;H!=null&&H.length>0&&V.push({type:"text",text:H});const B=(t=P.message.reasoning_content)!=null?t:P.message.reasoning;if(B!=null&&B.length>0&&V.push({type:"reasoning",text:B}),P.message.tool_calls!=null)for(const be of P.message.tool_calls)V.push({type:"tool-call",toolCallId:(n=be.id)!=null?n:tt(),toolName:be.function.name,input:be.function.arguments});const oe={[this.providerOptionsName]:{},...await((o=(r=this.config.metadataExtractor)==null?void 0:r.extractMetadata)==null?void 0:o.call(r,{parsedBody:T}))},F=(s=S.usage)==null?void 0:s.completion_tokens_details;return(F==null?void 0:F.accepted_prediction_tokens)!=null&&(oe[this.providerOptionsName].acceptedPredictionTokens=F==null?void 0:F.accepted_prediction_tokens),(F==null?void 0:F.rejected_prediction_tokens)!=null&&(oe[this.providerOptionsName].rejectedPredictionTokens=F==null?void 0:F.rejected_prediction_tokens),{content:V,finishReason:_d(P.finish_reason),usage:{inputTokens:(i=(a=S.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(u=(l=S.usage)==null?void 0:l.completion_tokens)!=null?u:void 0,totalTokens:(w=(c=S.usage)==null?void 0:c.total_tokens)!=null?w:void 0,reasoningTokens:(f=(d=(_=S.usage)==null?void 0:_.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(p=(v=(y=S.usage)==null?void 0:y.prompt_tokens_details)==null?void 0:v.cached_tokens)!=null?p:void 0},providerMetadata:oe,request:{body:m},response:{...vd(S),headers:E,body:T},warnings:g}}async doStream(e){var t;const{args:n,warnings:r}=await this.getArgs({...e}),o={...n,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:a,value:i}=await mt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:io(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let u="unknown";const c={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let w=!0;const _=this.providerOptionsName;let d=!1,f=!1;return{stream:i.pipeThrough(new TransformStream({start(y){y.enqueue({type:"stream-start",warnings:r})},transform(y,v){var p,b,g,m,E,S,T,P,V,H,B,oe,F;if(e.includeRawChunks&&v.enqueue({type:"raw",rawValue:y.rawValue}),!y.success){u="error",v.enqueue({type:"error",error:y.error});return}const be=y.value;if(s==null||s.processChunk(y.rawValue),"error"in be){u="error",v.enqueue({type:"error",error:be.error.message});return}if(w&&(w=!1,v.enqueue({type:"response-metadata",...vd(be)})),be.usage!=null){const{prompt_tokens:I,completion_tokens:ie,total_tokens:me,prompt_tokens_details:de,completion_tokens_details:Q}=be.usage;c.promptTokens=I??void 0,c.completionTokens=ie??void 0,c.totalTokens=me??void 0,(Q==null?void 0:Q.reasoning_tokens)!=null&&(c.completionTokensDetails.reasoningTokens=Q==null?void 0:Q.reasoning_tokens),(Q==null?void 0:Q.accepted_prediction_tokens)!=null&&(c.completionTokensDetails.acceptedPredictionTokens=Q==null?void 0:Q.accepted_prediction_tokens),(Q==null?void 0:Q.rejected_prediction_tokens)!=null&&(c.completionTokensDetails.rejectedPredictionTokens=Q==null?void 0:Q.rejected_prediction_tokens),(de==null?void 0:de.cached_tokens)!=null&&(c.promptTokensDetails.cachedTokens=de==null?void 0:de.cached_tokens)}const Ee=be.choices[0];if((Ee==null?void 0:Ee.finish_reason)!=null&&(u=_d(Ee.finish_reason)),(Ee==null?void 0:Ee.delta)==null)return;const Ne=Ee.delta,Xe=(p=Ne.reasoning_content)!=null?p:Ne.reasoning;if(Xe&&(d||(v.enqueue({type:"reasoning-start",id:"reasoning-0"}),d=!0),v.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:Xe})),Ne.content&&(f||(v.enqueue({type:"text-start",id:"txt-0"}),f=!0),v.enqueue({type:"text-delta",id:"txt-0",delta:Ne.content})),Ne.tool_calls!=null)for(const I of Ne.tool_calls){const ie=I.index;if(l[ie]==null){if(I.id==null)throw new In({data:I,message:"Expected 'id' to be a string."});if(((b=I.function)==null?void 0:b.name)==null)throw new In({data:I,message:"Expected 'function.name' to be a string."});v.enqueue({type:"tool-input-start",id:I.id,toolName:I.function.name}),l[ie]={id:I.id,type:"function",function:{name:I.function.name,arguments:(g=I.function.arguments)!=null?g:""},hasFinished:!1};const de=l[ie];((m=de.function)==null?void 0:m.name)!=null&&((E=de.function)==null?void 0:E.arguments)!=null&&(de.function.arguments.length>0&&v.enqueue({type:"tool-input-start",id:de.id,toolName:de.function.name}),ao(de.function.arguments)&&(v.enqueue({type:"tool-input-end",id:de.id}),v.enqueue({type:"tool-call",toolCallId:(S=de.id)!=null?S:tt(),toolName:de.function.name,input:de.function.arguments}),de.hasFinished=!0));continue}const me=l[ie];me.hasFinished||(((T=I.function)==null?void 0:T.arguments)!=null&&(me.function.arguments+=(V=(P=I.function)==null?void 0:P.arguments)!=null?V:""),v.enqueue({type:"tool-input-delta",id:me.id,delta:(H=I.function.arguments)!=null?H:""}),((B=me.function)==null?void 0:B.name)!=null&&((oe=me.function)==null?void 0:oe.arguments)!=null&&ao(me.function.arguments)&&(v.enqueue({type:"tool-input-end",id:me.id}),v.enqueue({type:"tool-call",toolCallId:(F=me.id)!=null?F:tt(),toolName:me.function.name,input:me.function.arguments}),me.hasFinished=!0))}},flush(y){var v,p,b,g,m,E;d&&y.enqueue({type:"reasoning-end",id:"reasoning-0"}),f&&y.enqueue({type:"text-end",id:"txt-0"});for(const T of l.filter(P=>!P.hasFinished))y.enqueue({type:"tool-input-end",id:T.id}),y.enqueue({type:"tool-call",toolCallId:(v=T.id)!=null?v:tt(),toolName:T.function.name,input:T.function.arguments});const S={[_]:{},...s==null?void 0:s.buildMetadata()};c.completionTokensDetails.acceptedPredictionTokens!=null&&(S[_].acceptedPredictionTokens=c.completionTokensDetails.acceptedPredictionTokens),c.completionTokensDetails.rejectedPredictionTokens!=null&&(S[_].rejectedPredictionTokens=c.completionTokensDetails.rejectedPredictionTokens),y.enqueue({type:"finish",finishReason:u,usage:{inputTokens:(p=c.promptTokens)!=null?p:void 0,outputTokens:(b=c.completionTokens)!=null?b:void 0,totalTokens:(g=c.totalTokens)!=null?g:void 0,reasoningTokens:(m=c.completionTokensDetails.reasoningTokens)!=null?m:void 0,cachedInputTokens:(E=c.promptTokensDetails.cachedTokens)!=null?E:void 0},providerMetadata:S})}})),request:{body:o},response:{headers:a}}}},bd=x({prompt_tokens:R().nullish(),completion_tokens:R().nullish(),total_tokens:R().nullish(),prompt_tokens_details:x({cached_tokens:R().nullish()}).nullish(),completion_tokens_details:x({reasoning_tokens:R().nullish(),accepted_prediction_tokens:R().nullish(),rejected_prediction_tokens:R().nullish()}).nullish()}).nullish(),Kk=x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({message:x({role:A("assistant").nullish(),content:h().nullish(),reasoning_content:h().nullish(),reasoning:h().nullish(),tool_calls:Z(x({id:h().nullish(),function:x({name:h(),arguments:h()})})).nullish()}),finish_reason:h().nullish()})),usage:bd}),Yk=e=>ee([x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({delta:x({role:qe(["assistant"]).nullish(),content:h().nullish(),reasoning_content:h().nullish(),reasoning:h().nullish(),tool_calls:Z(x({index:R(),id:h().nullish(),function:x({name:h().nullish(),arguments:h().nullish()})})).nullish()}).nullish(),finish_reason:h().nullish()})),usage:bd}),e]);x({echo:re().optional(),logitBias:We(h(),R()).optional(),suffix:h().optional(),user:h().optional()});var Xk=x({prompt_tokens:R(),completion_tokens:R(),total_tokens:R()});x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({text:h(),finish_reason:h()})),usage:Xk.nullish()}),x({dimensions:R().optional(),user:h().optional()}),x({data:Z(x({embedding:Z(R())})),usage:x({prompt_tokens:R()}).nullish(),providerMetadata:We(h(),We(h(),pt())).optional()}),x({data:Z(x({b64_json:h()}))});var xd=e=>{var t,n;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(n=e.prompt_cache_miss_tokens)!=null?n:NaN}}},Qk={extractMetadata:async({parsedBody:e})=>{const t=await or({value:e,schema:eT});return!t.success||t.value.usage==null?void 0:xd(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var n,r;const o=await or({value:t,schema:tT});o.success&&((r=(n=o.value.choices)==null?void 0:n[0])==null?void 0:r.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>xd(e)}}},kd=x({prompt_cache_hit_tokens:R().nullish(),prompt_cache_miss_tokens:R().nullish()}),eT=x({usage:kd.nullish()}),tT=x({choices:Z(x({finish_reason:h().nullish()})).nullish(),usage:kd.nullish()});function Td(e={}){var t;const n=Kc((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),r=()=>({Authorization:`Bearer ${Hc({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers}),o=a=>new Wk(a,{provider:"deepseek.chat",url:({path:i})=>`${n}${i}`,headers:r,fetch:e.fetch,metadataExtractor:Qk}),s=a=>o(a);return s.languageModel=o,s.chat=o,s.textEmbeddingModel=a=>{throw new wo({modelId:a,modelType:"textEmbeddingModel"})},s.imageModel=a=>{throw new wo({modelId:a,modelType:"imageModel"})},s}Td();const nT={openai:yd,deepseek:Td};class rT{constructor({llmConfig:t,mcpServers:n,llm:r}){if(this.mcpServers=[],this.mcpClients=[],this.mcpTools=[],this.ignoreToolnames=[],this.messages=[],this.mcpServers=n||[],r)this.llm=r;else if(t){let o;typeof t.providerType=="string"?o=nT[t.providerType]:o=t.providerType,this.llm=o({apiKey:t.apiKey,baseURL:t.baseURL})}else throw new Error("Either llmConfig or llm must be provided")}async _createOneClient(t){try{let n;return"type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"?n=new yx(new URL(t.url)):n=t,await M0({transport:n})}catch(n){return this.onError&&this.onError((n==null?void 0:n.message)||"Failed to create MCP client",n),console.error("Failed to create MCP client",t,n),null}}async _createMpcClients(){this.mcpClients=await Promise.all(this.mcpServers.map(async t=>this._createOneClient(t)))}async _createMpcTools(){this.mcpTools=await Promise.all(this.mcpClients.map(async t=>{var n;try{return t?await((n=t==null?void 0:t.tools)==null?void 0:n.call(t)):null}catch(r){return this.onError&&this.onError((r==null?void 0:r.message)||"Failed to query tools",r),console.error("Failed to query tools",r),null}}))}async closeAll(){await Promise.all(this.mcpClients.map(async t=>{try{await(t==null?void 0:t.close())}catch(n){this.onError&&this.onError((n==null?void 0:n.message)||"Failed to close client",n),console.error("Failed to close client",n)}}))}async initClientsAndTools(){await this._createMpcClients(),await this._createMpcTools()}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t,await this.initClientsAndTools()}async insertMcpServer(t){var r;if(!this.mcpServers.find(o=>"url"in o&&"url"in t&&o.url===t.url)){this.mcpServers=[...this.mcpServers,t];const o=await this._createOneClient(t);return this.mcpClients.push(o),this.mcpTools.push(await((r=o==null?void 0:o.tools)==null?void 0:r.call(o))),!0}return!1}removeMcpServer(t){const n=this.mcpServers.findIndex(s=>s===t);this.mcpServers.splice(n,1);const r=this.mcpClients[n];this.mcpClients.splice(n,1);try{r==null||r.close()}catch{}const o=this.mcpTools[n];this.mcpTools.splice(n,1),o&&Object.keys(o).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(a=>a!==s)})}_tempMergeTools(t={}){const n=this.mcpTools.reduce((r,o)=>({...r,...o}),{});return Object.assign(n,t),this.ignoreToolnames.forEach(r=>{delete n[r]}),n}async _chat(t,{model:n,maxSteps:r=5,...o}){var i,l;if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools(),(i=this.onUpdatedTools)==null||i.call(this);const s={model:this.llm(n),stopWhen:vs(r),...o,tools:this._tempMergeTools(o.tools)};o.message&&!o.messages&&(this.messages.push({role:"user",content:o.message}),s.messages=[...this.messages]);const a=t(s);return(l=a==null?void 0:a.response)==null||l.then(u=>{this.messages.push(...u.messages)}),a}async chat(t){return this._chat(Dw,t)}async chatStream(t){return this._chat(o0,t)}}var vn={},oT=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},Sd={},nt={};let Ys;const sT=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];nt.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17},nt.getSymbolTotalCodewords=function(t){return sT[t]},nt.getBCHDigit=function(e){let t=0;for(;e!==0;)t++,e>>>=1;return t},nt.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');Ys=t},nt.isKanjiModeEnabled=function(){return typeof Ys<"u"},nt.toSJIS=function(t){return Ys(t)};var lo={};(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+n)}}e.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},e.from=function(r,o){if(e.isValid(r))return r;try{return t(r)}catch{return o}}})(lo);function Id(){this.buffer=[],this.length=0}Id.prototype={get:function(e){const t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)===1},put:function(e,t){for(let n=0;n<t;n++)this.putBit((e>>>t-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var aT=Id;function ar(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}ar.prototype.set=function(e,t,n,r){const o=e*this.size+t;this.data[o]=n,r&&(this.reservedBit[o]=!0)},ar.prototype.get=function(e,t){return this.data[e*this.size+t]},ar.prototype.xor=function(e,t,n){this.data[e*this.size+t]^=n},ar.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]};var iT=ar,Cd={};(function(e){const t=nt.getSymbolSize;e.getRowColCoords=function(r){if(r===1)return[];const o=Math.floor(r/7)+2,s=t(r),a=s===145?26:Math.ceil((s-13)/(2*o-2))*2,i=[s-7];for(let l=1;l<o-1;l++)i[l]=i[l-1]-a;return i.push(6),i.reverse()},e.getPositions=function(r){const o=[],s=e.getRowColCoords(r),a=s.length;for(let i=0;i<a;i++)for(let l=0;l<a;l++)i===0&&l===0||i===0&&l===a-1||i===a-1&&l===0||o.push([s[i],s[l]]);return o}})(Cd);var Ed={};const lT=nt.getSymbolSize,Rd=7;Ed.getPositions=function(t){const n=lT(t);return[[0,0],[n-Rd,0],[0,n-Rd]]};var Ad={};(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.getPenaltyN1=function(o){const s=o.size;let a=0,i=0,l=0,u=null,c=null;for(let w=0;w<s;w++){i=l=0,u=c=null;for(let _=0;_<s;_++){let d=o.get(w,_);d===u?i++:(i>=5&&(a+=t.N1+(i-5)),u=d,i=1),d=o.get(_,w),d===c?l++:(l>=5&&(a+=t.N1+(l-5)),c=d,l=1)}i>=5&&(a+=t.N1+(i-5)),l>=5&&(a+=t.N1+(l-5))}return a},e.getPenaltyN2=function(o){const s=o.size;let a=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const u=o.get(i,l)+o.get(i,l+1)+o.get(i+1,l)+o.get(i+1,l+1);(u===4||u===0)&&a++}return a*t.N2},e.getPenaltyN3=function(o){const s=o.size;let a=0,i=0,l=0;for(let u=0;u<s;u++){i=l=0;for(let c=0;c<s;c++)i=i<<1&2047|o.get(u,c),c>=10&&(i===1488||i===93)&&a++,l=l<<1&2047|o.get(c,u),c>=10&&(l===1488||l===93)&&a++}return a*t.N3},e.getPenaltyN4=function(o){let s=0;const a=o.data.length;for(let l=0;l<a;l++)s+=o.data[l];return Math.abs(Math.ceil(s*100/a/5)-10)*t.N4};function n(r,o,s){switch(r){case e.Patterns.PATTERN000:return(o+s)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return s%3===0;case e.Patterns.PATTERN011:return(o+s)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case e.Patterns.PATTERN101:return o*s%2+o*s%3===0;case e.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case e.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}e.applyMask=function(o,s){const a=s.size;for(let i=0;i<a;i++)for(let l=0;l<a;l++)s.isReserved(l,i)||s.xor(l,i,n(o,l,i))},e.getBestMask=function(o,s){const a=Object.keys(e.Patterns).length;let i=0,l=1/0;for(let u=0;u<a;u++){s(u),e.applyMask(u,o);const c=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(u,o),c<l&&(l=c,i=u)}return i}})(Ad);var uo={};const Lt=lo,co=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],po=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];uo.getBlocksCount=function(t,n){switch(n){case Lt.L:return co[(t-1)*4+0];case Lt.M:return co[(t-1)*4+1];case Lt.Q:return co[(t-1)*4+2];case Lt.H:return co[(t-1)*4+3];default:return}},uo.getTotalCodewordsCount=function(t,n){switch(n){case Lt.L:return po[(t-1)*4+0];case Lt.M:return po[(t-1)*4+1];case Lt.Q:return po[(t-1)*4+2];case Lt.H:return po[(t-1)*4+3];default:return}};var Od={},ho={};const ir=new Uint8Array(512),fo=new Uint8Array(256);(function(){let t=1;for(let n=0;n<255;n++)ir[n]=t,fo[t]=n,t<<=1,t&256&&(t^=285);for(let n=255;n<512;n++)ir[n]=ir[n-255]})(),ho.log=function(t){if(t<1)throw new Error("log("+t+")");return fo[t]},ho.exp=function(t){return ir[t]},ho.mul=function(t,n){return t===0||n===0?0:ir[fo[t]+fo[n]]},function(e){const t=ho;e.mul=function(r,o){const s=new Uint8Array(r.length+o.length-1);for(let a=0;a<r.length;a++)for(let i=0;i<o.length;i++)s[a+i]^=t.mul(r[a],o[i]);return s},e.mod=function(r,o){let s=new Uint8Array(r);for(;s.length-o.length>=0;){const a=s[0];for(let l=0;l<o.length;l++)s[l]^=t.mul(o[l],a);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},e.generateECPolynomial=function(r){let o=new Uint8Array([1]);for(let s=0;s<r;s++)o=e.mul(o,new Uint8Array([1,t.exp(s)]));return o}}(Od);const Nd=Od;function Xs(e){this.genPoly=void 0,this.degree=e,this.degree&&this.initialize(this.degree)}Xs.prototype.initialize=function(t){this.degree=t,this.genPoly=Nd.generateECPolynomial(this.degree)},Xs.prototype.encode=function(t){if(!this.genPoly)throw new Error("Encoder not initialized");const n=new Uint8Array(t.length+this.degree);n.set(t);const r=Nd.mod(n,this.genPoly),o=this.degree-r.length;if(o>0){const s=new Uint8Array(this.degree);return s.set(r,o),s}return r};var uT=Xs,Md={},qt={},Qs={};Qs.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var St={};const Pd="[0-9]+",cT="[A-Z $%*+\\-./:]+";let lr="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";lr=lr.replace(/u/g,"\\u");const dT="(?:(?![A-Z0-9 $%*+\\-./:]|"+lr+`)(?:.|[\r
77
- ]))+`;St.KANJI=new RegExp(lr,"g"),St.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),St.BYTE=new RegExp(dT,"g"),St.NUMERIC=new RegExp(Pd,"g"),St.ALPHANUMERIC=new RegExp(cT,"g");const pT=new RegExp("^"+lr+"$"),hT=new RegExp("^"+Pd+"$"),fT=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");St.testKanji=function(t){return pT.test(t)},St.testNumeric=function(t){return hT.test(t)},St.testAlphanumeric=function(t){return fT.test(t)},function(e){const t=Qs,n=St;e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(s,a){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!t.isValid(a))throw new Error("Invalid version: "+a);return a>=1&&a<10?s.ccBits[0]:a<27?s.ccBits[1]:s.ccBits[2]},e.getBestModeForData=function(s){return n.testNumeric(s)?e.NUMERIC:n.testAlphanumeric(s)?e.ALPHANUMERIC:n.testKanji(s)?e.KANJI:e.BYTE},e.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},e.isValid=function(s){return s&&s.bit&&s.ccBits};function r(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+o)}}e.from=function(s,a){if(e.isValid(s))return s;try{return r(s)}catch{return a}}}(qt),function(e){const t=nt,n=uo,r=lo,o=qt,s=Qs,a=7973,i=t.getBCHDigit(a);function l(_,d,f){for(let y=1;y<=40;y++)if(d<=e.getCapacity(y,f,_))return y}function u(_,d){return o.getCharCountIndicator(_,d)+4}function c(_,d){let f=0;return _.forEach(function(y){const v=u(y.mode,d);f+=v+y.getBitsLength()}),f}function w(_,d){for(let f=1;f<=40;f++)if(c(_,f)<=e.getCapacity(f,d,o.MIXED))return f}e.from=function(d,f){return s.isValid(d)?parseInt(d,10):f},e.getCapacity=function(d,f,y){if(!s.isValid(d))throw new Error("Invalid QR Code version");typeof y>"u"&&(y=o.BYTE);const v=t.getSymbolTotalCodewords(d),p=n.getTotalCodewordsCount(d,f),b=(v-p)*8;if(y===o.MIXED)return b;const g=b-u(y,d);switch(y){case o.NUMERIC:return Math.floor(g/10*3);case o.ALPHANUMERIC:return Math.floor(g/11*2);case o.KANJI:return Math.floor(g/13);case o.BYTE:default:return Math.floor(g/8)}},e.getBestVersionForData=function(d,f){let y;const v=r.from(f,r.M);if(Array.isArray(d)){if(d.length>1)return w(d,v);if(d.length===0)return 1;y=d[0]}else y=d;return l(y.mode,y.getLength(),v)},e.getEncodedBits=function(d){if(!s.isValid(d)||d<7)throw new Error("Invalid QR Code version");let f=d<<12;for(;t.getBCHDigit(f)-i>=0;)f^=a<<t.getBCHDigit(f)-i;return d<<12|f}}(Md);var $d={};const ea=nt,zd=1335,mT=21522,jd=ea.getBCHDigit(zd);$d.getEncodedBits=function(t,n){const r=t.bit<<3|n;let o=r<<10;for(;ea.getBCHDigit(o)-jd>=0;)o^=zd<<ea.getBCHDigit(o)-jd;return(r<<10|o)^mT};var Dd={};const gT=qt;function _n(e){this.mode=gT.NUMERIC,this.data=e.toString()}_n.getBitsLength=function(t){return 10*Math.floor(t/3)+(t%3?t%3*3+1:0)},_n.prototype.getLength=function(){return this.data.length},_n.prototype.getBitsLength=function(){return _n.getBitsLength(this.data.length)},_n.prototype.write=function(t){let n,r,o;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),o=parseInt(r,10),t.put(o,10);const s=this.data.length-n;s>0&&(r=this.data.substr(n),o=parseInt(r,10),t.put(o,s*3+1))};var yT=_n;const vT=qt,ta=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function wn(e){this.mode=vT.ALPHANUMERIC,this.data=e}wn.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)},wn.prototype.getLength=function(){return this.data.length},wn.prototype.getBitsLength=function(){return wn.getBitsLength(this.data.length)},wn.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=ta.indexOf(this.data[n])*45;r+=ta.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(ta.indexOf(this.data[n]),6)};var _T=wn;const wT=qt;function bn(e){this.mode=wT.BYTE,typeof e=="string"?this.data=new TextEncoder().encode(e):this.data=new Uint8Array(e)}bn.getBitsLength=function(t){return t*8},bn.prototype.getLength=function(){return this.data.length},bn.prototype.getBitsLength=function(){return bn.getBitsLength(this.data.length)},bn.prototype.write=function(e){for(let t=0,n=this.data.length;t<n;t++)e.put(this.data[t],8)};var bT=bn;const xT=qt,kT=nt;function xn(e){this.mode=xT.KANJI,this.data=e}xn.getBitsLength=function(t){return t*13},xn.prototype.getLength=function(){return this.data.length},xn.prototype.getBitsLength=function(){return xn.getBitsLength(this.data.length)},xn.prototype.write=function(e){let t;for(t=0;t<this.data.length;t++){let n=kT.toSJIS(this.data[t]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[t]+`
78
- Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),e.put(n,13)}};var TT=xn,Zd={exports:{}};(function(e){var t={single_source_shortest_paths:function(n,r,o){var s={},a={};a[r]=0;var i=t.PriorityQueue.make();i.push(r,0);for(var l,u,c,w,_,d,f,y,v;!i.empty();){l=i.pop(),u=l.value,w=l.cost,_=n[u]||{};for(c in _)_.hasOwnProperty(c)&&(d=_[c],f=w+d,y=a[c],v=typeof a[c]>"u",(v||y>f)&&(a[c]=f,i.push(c,f),s[c]=u))}if(typeof o<"u"&&typeof a[o]>"u"){var p=["Could not find a path from ",r," to ",o,"."].join("");throw new Error(p)}return s},extract_shortest_path_from_predecessor_list:function(n,r){for(var o=[],s=r;s;)o.push(s),n[s],s=n[s];return o.reverse(),o},find_path:function(n,r,o){var s=t.single_source_shortest_paths(n,r,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(n){var r=t.PriorityQueue,o={},s;n=n||{};for(s in r)r.hasOwnProperty(s)&&(o[s]=r[s]);return o.queue=[],o.sorter=n.sorter||r.default_sorter,o},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var o={value:n,cost:r};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(Zd);var ST=Zd.exports;(function(e){const t=qt,n=yT,r=_T,o=bT,s=TT,a=St,i=nt,l=ST;function u(p){return unescape(encodeURIComponent(p)).length}function c(p,b,g){const m=[];let E;for(;(E=p.exec(g))!==null;)m.push({data:E[0],index:E.index,mode:b,length:E[0].length});return m}function w(p){const b=c(a.NUMERIC,t.NUMERIC,p),g=c(a.ALPHANUMERIC,t.ALPHANUMERIC,p);let m,E;return i.isKanjiModeEnabled()?(m=c(a.BYTE,t.BYTE,p),E=c(a.KANJI,t.KANJI,p)):(m=c(a.BYTE_KANJI,t.BYTE,p),E=[]),b.concat(g,m,E).sort(function(T,P){return T.index-P.index}).map(function(T){return{data:T.data,mode:T.mode,length:T.length}})}function _(p,b){switch(b){case t.NUMERIC:return n.getBitsLength(p);case t.ALPHANUMERIC:return r.getBitsLength(p);case t.KANJI:return s.getBitsLength(p);case t.BYTE:return o.getBitsLength(p)}}function d(p){return p.reduce(function(b,g){const m=b.length-1>=0?b[b.length-1]:null;return m&&m.mode===g.mode?(b[b.length-1].data+=g.data,b):(b.push(g),b)},[])}function f(p){const b=[];for(let g=0;g<p.length;g++){const m=p[g];switch(m.mode){case t.NUMERIC:b.push([m,{data:m.data,mode:t.ALPHANUMERIC,length:m.length},{data:m.data,mode:t.BYTE,length:m.length}]);break;case t.ALPHANUMERIC:b.push([m,{data:m.data,mode:t.BYTE,length:m.length}]);break;case t.KANJI:b.push([m,{data:m.data,mode:t.BYTE,length:u(m.data)}]);break;case t.BYTE:b.push([{data:m.data,mode:t.BYTE,length:u(m.data)}])}}return b}function y(p,b){const g={},m={start:{}};let E=["start"];for(let S=0;S<p.length;S++){const T=p[S],P=[];for(let V=0;V<T.length;V++){const H=T[V],B=""+S+V;P.push(B),g[B]={node:H,lastCount:0},m[B]={};for(let oe=0;oe<E.length;oe++){const F=E[oe];g[F]&&g[F].node.mode===H.mode?(m[F][B]=_(g[F].lastCount+H.length,H.mode)-_(g[F].lastCount,H.mode),g[F].lastCount+=H.length):(g[F]&&(g[F].lastCount=H.length),m[F][B]=_(H.length,H.mode)+4+t.getCharCountIndicator(H.mode,b))}}E=P}for(let S=0;S<E.length;S++)m[E[S]].end=0;return{map:m,table:g}}function v(p,b){let g;const m=t.getBestModeForData(p);if(g=t.from(b,m),g!==t.BYTE&&g.bit<m.bit)throw new Error('"'+p+'" cannot be encoded with mode '+t.toString(g)+`.
79
- Suggested mode is: `+t.toString(m));switch(g===t.KANJI&&!i.isKanjiModeEnabled()&&(g=t.BYTE),g){case t.NUMERIC:return new n(p);case t.ALPHANUMERIC:return new r(p);case t.KANJI:return new s(p);case t.BYTE:return new o(p)}}e.fromArray=function(b){return b.reduce(function(g,m){return typeof m=="string"?g.push(v(m,null)):m.data&&g.push(v(m.data,m.mode)),g},[])},e.fromString=function(b,g){const m=w(b,i.isKanjiModeEnabled()),E=f(m),S=y(E,g),T=l.find_path(S.map,"start","end"),P=[];for(let V=1;V<T.length-1;V++)P.push(S.table[T[V]].node);return e.fromArray(d(P))},e.rawSplit=function(b){return e.fromArray(w(b,i.isKanjiModeEnabled()))}})(Dd);const mo=nt,na=lo,IT=aT,CT=iT,ET=Cd,RT=Ed,ra=Ad,oa=uo,AT=uT,go=Md,OT=$d,NT=qt,sa=Dd;function MT(e,t){const n=e.size,r=RT.getPositions(t);for(let o=0;o<r.length;o++){const s=r[o][0],a=r[o][1];for(let i=-1;i<=7;i++)if(!(s+i<=-1||n<=s+i))for(let l=-1;l<=7;l++)a+l<=-1||n<=a+l||(i>=0&&i<=6&&(l===0||l===6)||l>=0&&l<=6&&(i===0||i===6)||i>=2&&i<=4&&l>=2&&l<=4?e.set(s+i,a+l,!0,!0):e.set(s+i,a+l,!1,!0))}}function PT(e){const t=e.size;for(let n=8;n<t-8;n++){const r=n%2===0;e.set(n,6,r,!0),e.set(6,n,r,!0)}}function $T(e,t){const n=ET.getPositions(t);for(let r=0;r<n.length;r++){const o=n[r][0],s=n[r][1];for(let a=-2;a<=2;a++)for(let i=-2;i<=2;i++)a===-2||a===2||i===-2||i===2||a===0&&i===0?e.set(o+a,s+i,!0,!0):e.set(o+a,s+i,!1,!0)}}function zT(e,t){const n=e.size,r=go.getEncodedBits(t);let o,s,a;for(let i=0;i<18;i++)o=Math.floor(i/3),s=i%3+n-8-3,a=(r>>i&1)===1,e.set(o,s,a,!0),e.set(s,o,a,!0)}function aa(e,t,n){const r=e.size,o=OT.getEncodedBits(t,n);let s,a;for(s=0;s<15;s++)a=(o>>s&1)===1,s<6?e.set(s,8,a,!0):s<8?e.set(s+1,8,a,!0):e.set(r-15+s,8,a,!0),s<8?e.set(8,r-s-1,a,!0):s<9?e.set(8,15-s-1+1,a,!0):e.set(8,15-s-1,a,!0);e.set(r-8,8,1,!0)}function jT(e,t){const n=e.size;let r=-1,o=n-1,s=7,a=0;for(let i=n-1;i>0;i-=2)for(i===6&&i--;;){for(let l=0;l<2;l++)if(!e.isReserved(o,i-l)){let u=!1;a<t.length&&(u=(t[a]>>>s&1)===1),e.set(o,i-l,u),s--,s===-1&&(a++,s=7)}if(o+=r,o<0||n<=o){o-=r,r=-r;break}}}function DT(e,t,n){const r=new IT;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),NT.getCharCountIndicator(l.mode,e)),l.write(r)});const o=mo.getSymbolTotalCodewords(e),s=oa.getTotalCodewordsCount(e,t),a=(o-s)*8;for(r.getLengthInBits()+4<=a&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);const i=(a-r.getLengthInBits())/8;for(let l=0;l<i;l++)r.put(l%2?17:236,8);return ZT(r,e,t)}function ZT(e,t,n){const r=mo.getSymbolTotalCodewords(t),o=oa.getTotalCodewordsCount(t,n),s=r-o,a=oa.getBlocksCount(t,n),i=r%a,l=a-i,u=Math.floor(r/a),c=Math.floor(s/a),w=c+1,_=u-c,d=new AT(_);let f=0;const y=new Array(a),v=new Array(a);let p=0;const b=new Uint8Array(e.buffer);for(let T=0;T<a;T++){const P=T<l?c:w;y[T]=b.slice(f,f+P),v[T]=d.encode(y[T]),f+=P,p=Math.max(p,P)}const g=new Uint8Array(r);let m=0,E,S;for(E=0;E<p;E++)for(S=0;S<a;S++)E<y[S].length&&(g[m++]=y[S][E]);for(E=0;E<_;E++)for(S=0;S<a;S++)g[m++]=v[S][E];return g}function UT(e,t,n,r){let o;if(Array.isArray(e))o=sa.fromArray(e);else if(typeof e=="string"){let u=t;if(!u){const c=sa.rawSplit(e);u=go.getBestVersionForData(c,n)}o=sa.fromString(e,u||40)}else throw new Error("Invalid data");const s=go.getBestVersionForData(o,n);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!t)t=s;else if(t<s)throw new Error(`
76
+ ${t}:`]}}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}}function ad(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"unknown"}}var id=x({echo:re().optional(),logitBias:We(h(),R()).optional(),suffix:h().optional(),user:h().optional(),logprobs:ee([re(),R()]).optional()}),Qx=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,tools:u,toolChoice:c,seed:w,providerOptions:_}){const d=[],f={...await kt({provider:"openai",providerOptions:_,schema:id}),...await kt({provider:this.providerOptionsName,providerOptions:_,schema:id})};o!=null&&d.push({type:"unsupported-setting",setting:"topK"}),u!=null&&u.length&&d.push({type:"unsupported-setting",setting:"tools"}),c!=null&&d.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:y,stopSequences:v}=Xx({prompt:e}),p=[...v??[],...i??[]];return{args:{model:this.modelId,echo:f.echo,logit_bias:f.logitBias,logprobs:(f==null?void 0:f.logprobs)===!0?0:(f==null?void 0:f.logprobs)===!1||f==null?void 0:f.logprobs,suffix:f.suffix,user:f.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,seed:w,prompt:y,stop:p.length>0?p:void 0},warnings:d}}async doGenerate(e){var t,n,r;const{args:o,warnings:s}=await this.getArgs(e),{responseHeaders:a,value:i,rawValue:l}=await mt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:o,failedResponseHandler:Tt,successfulResponseHandler:on(ek),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=i.choices[0],c={openai:{}};return u.logprobs!=null&&(c.openai.logprobs=u.logprobs),{content:[{type:"text",text:u.text}],usage:{inputTokens:(t=i.usage)==null?void 0:t.prompt_tokens,outputTokens:(n=i.usage)==null?void 0:n.completion_tokens,totalTokens:(r=i.usage)==null?void 0:r.total_tokens},finishReason:ad(u.finish_reason),request:{body:o},response:{...sd(i),headers:a,body:l},providerMetadata:c,warnings:s}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await mt({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:r,failedResponseHandler:Tt,successfulResponseHandler:io(tk),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let u=!0;return{stream:s.pipeThrough(new TransformStream({start(c){c.enqueue({type:"stream-start",warnings:n})},transform(c,w){if(e.includeRawChunks&&w.enqueue({type:"raw",rawValue:c.rawValue}),!c.success){a="error",w.enqueue({type:"error",error:c.error});return}const _=c.value;if("error"in _){a="error",w.enqueue({type:"error",error:_.error});return}u&&(u=!1,w.enqueue({type:"response-metadata",...sd(_)}),w.enqueue({type:"text-start",id:"0"})),_.usage!=null&&(l.inputTokens=_.usage.prompt_tokens,l.outputTokens=_.usage.completion_tokens,l.totalTokens=_.usage.total_tokens);const d=_.choices[0];(d==null?void 0:d.finish_reason)!=null&&(a=ad(d.finish_reason)),(d==null?void 0:d.logprobs)!=null&&(i.openai.logprobs=d.logprobs),(d==null?void 0:d.text)!=null&&d.text.length>0&&w.enqueue({type:"text-delta",id:"0",delta:d.text})},flush(c){u||c.enqueue({type:"text-end",id:"0"}),c.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:l})}})),request:{body:r},response:{headers:o}}}},ld=x({prompt_tokens:R(),completion_tokens:R(),total_tokens:R()}),ek=x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({text:h(),finish_reason:h(),logprobs:x({tokens:Z(h()),token_logprobs:Z(R()),top_logprobs:Z(We(h(),R())).nullish()}).nullish()})),usage:ld.nullish()}),tk=ee([x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({text:h(),finish_reason:h().nullish(),index:R(),logprobs:x({tokens:Z(h()),token_logprobs:Z(R()),top_logprobs:Z(We(h(),R())).nullish()}).nullish()})),usage:ld.nullish()}),Ks]),nk=x({dimensions:R().optional(),user:h().optional()}),rk=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new pp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await kt({provider:"openai",providerOptions:r,schema:nk}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await mt({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:dt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Tt,successfulResponseHandler:on(ok),abortSignal:n,fetch:this.config.fetch});return{embeddings:i.data.map(u=>u.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},ok=x({data:Z(x({embedding:Z(R())})),usage:x({prompt_tokens:R()}).nullish()}),sk={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},ak=new Set(["gpt-image-1"]),ik=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return(e=sk[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:o,providerOptions:s,headers:a,abortSignal:i}){var l,u,c,w;const _=[];r!=null&&_.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&_.push({type:"unsupported-setting",setting:"seed"});const d=(c=(u=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:u.call(l))!=null?c:new Date,{value:f,responseHeaders:y}=await mt({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:dt(this.config.headers(),a),body:{model:this.modelId,prompt:e,n:t,size:n,...(w=s.openai)!=null?w:{},...ak.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Tt,successfulResponseHandler:on(lk),abortSignal:i,fetch:this.config.fetch});return{images:f.data.map(v=>v.b64_json),warnings:_,response:{timestamp:d,modelId:this.modelId,headers:y},providerMetadata:{openai:{images:f.data.map(v=>v.revised_prompt?{revisedPrompt:v.revised_prompt}:null)}}}}},lk=x({data:Z(x({b64_json:h(),revised_prompt:h().optional()}))}),uk=x({container:ee([h(),x({fileIds:Z(h()).optional()})]).optional()}),ck=Ws({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:x({})}),dk={codeInterpreter:ck,fileSearch:qx,webSearchPreview:Bx};function ud(e,t){return t?t.some(n=>e.startsWith(n)):!1}async function pk({prompt:e,systemMessageMode:t,fileIdPrefixes:n}){var r,o,s,a,i,l;const u=[],c=[];for(const{role:w,content:_}of e)switch(w){case"system":{switch(t){case"system":{u.push({role:"system",content:_});break}case"developer":{u.push({role:"developer",content:_});break}case"remove":{c.push({type:"other",message:"system messages are removed for this model"});break}default:{const d=t;throw new Error(`Unsupported system message mode: ${d}`)}}break}case"user":{u.push({role:"user",content:_.map((d,f)=>{var y,v,p;switch(d.type){case"text":return{type:"input_text",text:d.text};case"file":if(d.mediaType.startsWith("image/")){const b=d.mediaType==="image/*"?"image/jpeg":d.mediaType;return{type:"input_image",...d.data instanceof URL?{image_url:d.data.toString()}:typeof d.data=="string"&&ud(d.data,n)?{file_id:d.data}:{image_url:`data:${b};base64,${sn(d.data)}`},detail:(v=(y=d.providerOptions)==null?void 0:y.openai)==null?void 0:v.imageDetail}}else if(d.mediaType==="application/pdf"){if(d.data instanceof URL)throw new at({functionality:"PDF file parts with URLs"});return{type:"input_file",...typeof d.data=="string"&&ud(d.data,n)?{file_id:d.data}:{filename:(p=d.filename)!=null?p:`part-${f}.pdf`,file_data:`data:application/pdf;base64,${sn(d.data)}`}}}else throw new at({functionality:`file part media type ${d.mediaType}`})}})});break}case"assistant":{const d={};for(const f of _)switch(f.type){case"text":{u.push({role:"assistant",content:[{type:"output_text",text:f.text}],id:(s=(o=(r=f.providerOptions)==null?void 0:r.openai)==null?void 0:o.itemId)!=null?s:void 0});break}case"tool-call":{if(f.providerExecuted)break;u.push({type:"function_call",call_id:f.toolCallId,name:f.toolName,arguments:JSON.stringify(f.input),id:(l=(i=(a=f.providerOptions)==null?void 0:a.openai)==null?void 0:i.itemId)!=null?l:void 0});break}case"tool-result":{c.push({type:"other",message:"tool result parts in assistant messages are not supported for OpenAI responses"});break}case"reasoning":{const y=await kt({provider:"openai",providerOptions:f.providerOptions,schema:hk}),v=y==null?void 0:y.itemId;if(v!=null){const p=d[v],b=[];f.text.length>0?b.push({type:"summary_text",text:f.text}):p!==void 0&&c.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(f)}.`}),p===void 0?(d[v]={type:"reasoning",id:v,encrypted_content:y==null?void 0:y.reasoningEncryptedContent,summary:b},u.push(d[v])):p.summary.push(...b)}else c.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(f)}.`});break}}break}case"tool":{for(const d of _){const f=d.output;let y;switch(f.type){case"text":case"error-text":y=f.value;break;case"content":case"json":case"error-json":y=JSON.stringify(f.value);break}u.push({type:"function_call_output",call_id:d.toolCallId,output:y})}break}default:{const d=w;throw new Error(`Unsupported role: ${d}`)}}return{messages:u,warnings:c}}var hk=x({itemId:h().nullish(),reasoningEncryptedContent:h().nullish()});function cd({finishReason:e,hasToolCalls: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":"unknown"}}function fk({tools:e,toolChoice:t,strictJsonSchema:n}){e=e!=null&&e.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const o=[];for(const a of e)switch(a.type){case"function":o.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:n});break;case"provider-defined":{switch(a.id){case"openai.file_search":{const i=td.parse(a.args);o.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker}:void 0,filters:i.filters});break}case"openai.web_search_preview":{const i=nd.parse(a.args);o.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=uk.parse(a.args);o.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}default:{r.push({type:"unsupported-tool",tool:a});break}}break}default:r.push({type:"unsupported-tool",tool:a});break}if(t==null)return{tools:o,toolChoice:void 0,toolWarnings:r};const s=t.type;switch(s){case"auto":case"none":case"required":return{tools:o,toolChoice:s,toolWarnings:r};case"tool":return{tools:o,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="web_search_preview"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:{const a=s;throw new at({functionality:`tool choice type: ${a}`})}}}var dd=20,pd=Z(x({token:h(),logprob:R(),top_logprobs:Z(x({token:h(),logprob:R()}))})),mk=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:o,presencePenalty:s,frequencyPenalty:a,seed:i,prompt:l,providerOptions:u,tools:c,toolChoice:w,responseFormat:_}){var d,f;const y=[],v=jk(this.modelId);o!=null&&y.push({type:"unsupported-setting",setting:"topK"}),i!=null&&y.push({type:"unsupported-setting",setting:"seed"}),s!=null&&y.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&y.push({type:"unsupported-setting",setting:"frequencyPenalty"}),n!=null&&y.push({type:"unsupported-setting",setting:"stopSequences"});const{messages:p,warnings:b}=await pk({prompt:l,systemMessageMode:v.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});y.push(...b);const g=await kt({provider:"openai",providerOptions:u,schema:Dk}),m=(d=g==null?void 0:g.strictJsonSchema)!=null?d:!1,E=typeof(g==null?void 0:g.logprobs)=="number"?g==null?void 0:g.logprobs:(g==null?void 0:g.logprobs)===!0?dd:void 0,S=E?Array.isArray(g==null?void 0:g.include)?[...g==null?void 0:g.include,"message.output_text.logprobs"]:["message.output_text.logprobs"]:g==null?void 0:g.include,T={model:this.modelId,input:p,temperature:t,top_p:r,max_output_tokens:e,...((_==null?void 0:_.type)==="json"||(g==null?void 0:g.textVerbosity))&&{text:{...(_==null?void 0:_.type)==="json"&&{format:_.schema!=null?{type:"json_schema",strict:m,name:(f=_.name)!=null?f:"response",description:_.description,schema:_.schema}:{type:"json_object"}},...(g==null?void 0:g.textVerbosity)&&{verbosity:g.textVerbosity}}},metadata:g==null?void 0:g.metadata,parallel_tool_calls:g==null?void 0:g.parallelToolCalls,previous_response_id:g==null?void 0:g.previousResponseId,store:g==null?void 0:g.store,user:g==null?void 0:g.user,instructions:g==null?void 0:g.instructions,service_tier:g==null?void 0:g.serviceTier,include:S,prompt_cache_key:g==null?void 0:g.promptCacheKey,safety_identifier:g==null?void 0:g.safetyIdentifier,top_logprobs:E,...v.isReasoningModel&&((g==null?void 0:g.reasoningEffort)!=null||(g==null?void 0:g.reasoningSummary)!=null)&&{reasoning:{...(g==null?void 0:g.reasoningEffort)!=null&&{effort:g.reasoningEffort},...(g==null?void 0:g.reasoningSummary)!=null&&{summary:g.reasoningSummary}}},...v.requiredAutoTruncation&&{truncation:"auto"}};v.isReasoningModel?(T.temperature!=null&&(T.temperature=void 0,y.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),T.top_p!=null&&(T.top_p=void 0,y.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):((g==null?void 0:g.reasoningEffort)!=null&&y.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(g==null?void 0:g.reasoningSummary)!=null&&y.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(g==null?void 0:g.serviceTier)==="flex"&&!v.supportsFlexProcessing&&(y.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete T.service_tier),(g==null?void 0:g.serviceTier)==="priority"&&!v.supportsPriorityProcessing&&(y.push({type:"unsupported-setting",setting:"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 T.service_tier);const{tools:P,toolChoice:V,toolWarnings:H}=fk({tools:c,toolChoice:w,strictJsonSchema:m});return{args:{...T,tools:P,tool_choice:V},warnings:[...y,...H]}}async doGenerate(e){var t,n,r,o,s,a,i,l,u,c,w,_,d,f,y,v,p;const{args:b,warnings:g}=await this.getArgs(e),m=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:E,value:S,rawValue:T}=await mt({url:m,headers:dt(this.config.headers(),e.headers),body:b,failedResponseHandler:Tt,successfulResponseHandler:on(x({id:h(),created_at:R(),error:x({code:h(),message:h()}).nullish(),model:h(),output:Z(cn("type",[x({type:A("message"),role:A("assistant"),id:h(),content:Z(x({type:A("output_text"),text:h(),logprobs:pd.nullish(),annotations:Z(cn("type",[x({type:A("url_citation"),start_index:R(),end_index:R(),url:h(),title:h()}),x({type:A("file_citation"),start_index:R(),end_index:R(),file_id:h(),quote:h()})]))}))}),x({type:A("function_call"),call_id:h(),name:h(),arguments:h(),id:h()}),x({type:A("web_search_call"),id:h(),status:h().optional(),action:x({type:A("search"),query:h().optional()}).nullish()}),x({type:A("computer_call"),id:h(),status:h().optional()}),x({type:A("file_search_call"),id:h(),status:h().optional(),queries:Z(h()).nullish(),results:Z(x({attributes:x({file_id:h(),filename:h(),score:R(),text:h()})})).nullish()}),x({type:A("reasoning"),id:h(),encrypted_content:h().nullish(),summary:Z(x({type:A("summary_text"),text:h()}))})])),incomplete_details:x({reason:h()}).nullable(),usage:hd})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(S.error)throw new pe({message:S.error.message,url:m,requestBodyValues:b,statusCode:400,responseHeaders:E,responseBody:T,isRetryable:!1});const P=[],V=[];for(const B of S.output)switch(B.type){case"reasoning":{B.summary.length===0&&B.summary.push({type:"summary_text",text:""});for(const oe of B.summary)P.push({type:"reasoning",text:oe.text,providerMetadata:{openai:{itemId:B.id,reasoningEncryptedContent:(t=B.encrypted_content)!=null?t:null}}});break}case"message":{for(const oe of B.content){(r=(n=e.providerOptions)==null?void 0:n.openai)!=null&&r.logprobs&&oe.logprobs&&V.push(oe.logprobs),P.push({type:"text",text:oe.text,providerMetadata:{openai:{itemId:B.id}}});for(const F of oe.annotations)F.type==="url_citation"?P.push({type:"source",sourceType:"url",id:(a=(s=(o=this.config).generateId)==null?void 0:s.call(o))!=null?a:tt(),url:F.url,title:F.title}):F.type==="file_citation"&&P.push({type:"source",sourceType:"document",id:(u=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?u:tt(),mediaType:"text/plain",title:F.quote,filename:F.file_id})}break}case"function_call":{P.push({type:"tool-call",toolCallId:B.call_id,toolName:B.name,input:B.arguments,providerMetadata:{openai:{itemId:B.id}}});break}case"web_search_call":{P.push({type:"tool-call",toolCallId:B.id,toolName:"web_search_preview",input:(w=(c=B.action)==null?void 0:c.query)!=null?w:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:B.id,toolName:"web_search_preview",result:{status:B.status||"completed",...((_=B.action)==null?void 0:_.query)&&{query:B.action.query}},providerExecuted:!0});break}case"computer_call":{P.push({type:"tool-call",toolCallId:B.id,toolName:"computer_use",input:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:B.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:B.status||"completed"},providerExecuted:!0});break}case"file_search_call":{P.push({type:"tool-call",toolCallId:B.id,toolName:"file_search",input:"",providerExecuted:!0}),P.push({type:"tool-result",toolCallId:B.id,toolName:"file_search",result:{type:"file_search_tool_result",status:B.status||"completed",...B.queries&&{queries:B.queries},...B.results&&{results:B.results}},providerExecuted:!0});break}}const H={openai:{responseId:S.id}};return V.length>0&&(H.openai.logprobs=V),{content:P,finishReason:cd({finishReason:(d=S.incomplete_details)==null?void 0:d.reason,hasToolCalls:P.some(B=>B.type==="tool-call")}),usage:{inputTokens:S.usage.input_tokens,outputTokens:S.usage.output_tokens,totalTokens:S.usage.input_tokens+S.usage.output_tokens,reasoningTokens:(y=(f=S.usage.output_tokens_details)==null?void 0:f.reasoning_tokens)!=null?y:void 0,cachedInputTokens:(p=(v=S.usage.input_tokens_details)==null?void 0:v.cached_tokens)!=null?p:void 0},request:{body:b},response:{id:S.id,timestamp:new Date(S.created_at*1e3),modelId:S.model,headers:E,body:T},providerMetadata:H,warnings:g}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:o}=await mt({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Tt,successfulResponseHandler:io(Ik),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=this;let a="unknown";const i={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[];let u=null;const c={};let w=!1;const _={};return{stream:o.pipeThrough(new TransformStream({start(d){d.enqueue({type:"stream-start",warnings:n})},transform(d,f){var y,v,p,b,g,m,E,S,T,P,V,H,B,oe,F,be,Ee,Ne,Xe;if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:d.rawValue}),!d.success){a="error",f.enqueue({type:"error",error:d.error});return}const I=d.value;if(md(I))I.item.type==="function_call"?(c[I.output_index]={toolName:I.item.name,toolCallId:I.item.call_id},f.enqueue({type:"tool-input-start",id:I.item.call_id,toolName:I.item.name})):I.item.type==="web_search_call"?(c[I.output_index]={toolName:"web_search_preview",toolCallId:I.item.id},f.enqueue({type:"tool-input-start",id:I.item.id,toolName:"web_search_preview"})):I.item.type==="computer_call"?(c[I.output_index]={toolName:"computer_use",toolCallId:I.item.id},f.enqueue({type:"tool-input-start",id:I.item.id,toolName:"computer_use"})):I.item.type==="file_search_call"?(c[I.output_index]={toolName:"file_search",toolCallId:I.item.id},f.enqueue({type:"tool-input-start",id:I.item.id,toolName:"file_search"})):I.item.type==="message"?f.enqueue({type:"text-start",id:I.item.id,providerMetadata:{openai:{itemId:I.item.id}}}):Nk(I)&&(_[I.item.id]={encryptedContent:I.item.encrypted_content,summaryParts:[0]},f.enqueue({type:"reasoning-start",id:`${I.item.id}:0`,providerMetadata:{openai:{itemId:I.item.id,reasoningEncryptedContent:(y=I.item.encrypted_content)!=null?y:null}}}));else if(fd(I)){if(I.item.type==="function_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.call_id}),f.enqueue({type:"tool-call",toolCallId:I.item.call_id,toolName:I.item.name,input:I.item.arguments,providerMetadata:{openai:{itemId:I.item.id}}});else if(I.item.type==="web_search_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.id}),f.enqueue({type:"tool-call",toolCallId:I.item.id,toolName:"web_search_preview",input:(p=(v=I.item.action)==null?void 0:v.query)!=null?p:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:I.item.id,toolName:"web_search_preview",result:{type:"web_search_tool_result",status:I.item.status||"completed",...((b=I.item.action)==null?void 0:b.query)&&{query:I.item.action.query}},providerExecuted:!0});else if(I.item.type==="computer_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.id}),f.enqueue({type:"tool-call",toolCallId:I.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:I.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:I.item.status||"completed"},providerExecuted:!0});else if(I.item.type==="file_search_call")c[I.output_index]=void 0,w=!0,f.enqueue({type:"tool-input-end",id:I.item.id}),f.enqueue({type:"tool-call",toolCallId:I.item.id,toolName:"file_search",input:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:I.item.id,toolName:"file_search",result:{type:"file_search_tool_result",status:I.item.status||"completed",...I.item.queries&&{queries:I.item.queries},...I.item.results&&{results:I.item.results}},providerExecuted:!0});else if(I.item.type==="message")f.enqueue({type:"text-end",id:I.item.id});else if(Ek(I)){const ie=_[I.item.id];for(const me of ie.summaryParts)f.enqueue({type:"reasoning-end",id:`${I.item.id}:${me}`,providerMetadata:{openai:{itemId:I.item.id,reasoningEncryptedContent:(g=I.item.encrypted_content)!=null?g:null}}});delete _[I.item.id]}}else if(Ok(I)){const ie=c[I.output_index];ie!=null&&f.enqueue({type:"tool-input-delta",id:ie.toolCallId,delta:I.delta})}else Ak(I)?(u=I.response.id,f.enqueue({type:"response-metadata",id:I.response.id,timestamp:new Date(I.response.created_at*1e3),modelId:I.response.model})):Ck(I)?(f.enqueue({type:"text-delta",id:I.item_id,delta:I.delta}),I.logprobs&&l.push(I.logprobs)):Pk(I)?I.summary_index>0&&((m=_[I.item_id])==null||m.summaryParts.push(I.summary_index),f.enqueue({type:"reasoning-start",id:`${I.item_id}:${I.summary_index}`,providerMetadata:{openai:{itemId:I.item_id,reasoningEncryptedContent:(S=(E=_[I.item_id])==null?void 0:E.encryptedContent)!=null?S:null}}})):$k(I)?f.enqueue({type:"reasoning-delta",id:`${I.item_id}:${I.summary_index}`,delta:I.delta,providerMetadata:{openai:{itemId:I.item_id}}}):Rk(I)?(a=cd({finishReason:(T=I.response.incomplete_details)==null?void 0:T.reason,hasToolCalls:w}),i.inputTokens=I.response.usage.input_tokens,i.outputTokens=I.response.usage.output_tokens,i.totalTokens=I.response.usage.input_tokens+I.response.usage.output_tokens,i.reasoningTokens=(V=(P=I.response.usage.output_tokens_details)==null?void 0:P.reasoning_tokens)!=null?V:void 0,i.cachedInputTokens=(B=(H=I.response.usage.input_tokens_details)==null?void 0:H.cached_tokens)!=null?B:void 0):Mk(I)?I.annotation.type==="url_citation"?f.enqueue({type:"source",sourceType:"url",id:(be=(F=(oe=s.config).generateId)==null?void 0:F.call(oe))!=null?be:tt(),url:I.annotation.url,title:I.annotation.title}):I.annotation.type==="file_citation"&&f.enqueue({type:"source",sourceType:"document",id:(Xe=(Ne=(Ee=s.config).generateId)==null?void 0:Ne.call(Ee))!=null?Xe:tt(),mediaType:"text/plain",title:I.annotation.quote,filename:I.annotation.file_id}):zk(I)&&f.enqueue({type:"error",error:I})},flush(d){const f={openai:{responseId:u}};l.length>0&&(f.openai.logprobs=l),d.enqueue({type:"finish",finishReason:a,usage:i,providerMetadata:f})}})),request:{body:t},response:{headers:r}}}},hd=x({input_tokens:R(),input_tokens_details:x({cached_tokens:R().nullish()}).nullish(),output_tokens:R(),output_tokens_details:x({reasoning_tokens:R().nullish()}).nullish()}),gk=x({type:A("response.output_text.delta"),item_id:h(),delta:h(),logprobs:pd.nullish()}),yk=x({type:A("error"),code:h(),message:h(),param:h().nullish(),sequence_number:R()}),vk=x({type:qe(["response.completed","response.incomplete"]),response:x({incomplete_details:x({reason:h()}).nullish(),usage:hd})}),_k=x({type:A("response.created"),response:x({id:h(),created_at:R(),model:h()})}),wk=x({type:A("response.output_item.added"),output_index:R(),item:cn("type",[x({type:A("message"),id:h()}),x({type:A("reasoning"),id:h(),encrypted_content:h().nullish()}),x({type:A("function_call"),id:h(),call_id:h(),name:h(),arguments:h()}),x({type:A("web_search_call"),id:h(),status:h(),action:x({type:A("search"),query:h().optional()}).nullish()}),x({type:A("computer_call"),id:h(),status:h()}),x({type:A("file_search_call"),id:h(),status:h(),queries:Z(h()).nullish(),results:Z(x({attributes:x({file_id:h(),filename:h(),score:R(),text:h()})})).optional()})])}),bk=x({type:A("response.output_item.done"),output_index:R(),item:cn("type",[x({type:A("message"),id:h()}),x({type:A("reasoning"),id:h(),encrypted_content:h().nullish()}),x({type:A("function_call"),id:h(),call_id:h(),name:h(),arguments:h(),status:A("completed")}),x({type:A("web_search_call"),id:h(),status:A("completed"),action:x({type:A("search"),query:h().optional()}).nullish()}),x({type:A("computer_call"),id:h(),status:A("completed")}),x({type:A("file_search_call"),id:h(),status:A("completed"),queries:Z(h()).nullish(),results:Z(x({attributes:x({file_id:h(),filename:h(),score:R(),text:h()})})).nullish()})])}),xk=x({type:A("response.function_call_arguments.delta"),item_id:h(),output_index:R(),delta:h()}),kk=x({type:A("response.output_text.annotation.added"),annotation:cn("type",[x({type:A("url_citation"),url:h(),title:h()}),x({type:A("file_citation"),file_id:h(),quote:h()})])}),Tk=x({type:A("response.reasoning_summary_part.added"),item_id:h(),summary_index:R()}),Sk=x({type:A("response.reasoning_summary_text.delta"),item_id:h(),summary_index:R(),delta:h()}),Ik=ee([gk,vk,_k,wk,bk,xk,kk,Tk,Sk,yk,x({type:h()}).loose()]);function Ck(e){return e.type==="response.output_text.delta"}function fd(e){return e.type==="response.output_item.done"}function Ek(e){return fd(e)&&e.item.type==="reasoning"}function Rk(e){return e.type==="response.completed"||e.type==="response.incomplete"}function Ak(e){return e.type==="response.created"}function Ok(e){return e.type==="response.function_call_arguments.delta"}function md(e){return e.type==="response.output_item.added"}function Nk(e){return md(e)&&e.item.type==="reasoning"}function Mk(e){return e.type==="response.output_text.annotation.added"}function Pk(e){return e.type==="response.reasoning_summary_part.added"}function $k(e){return e.type==="response.reasoning_summary_text.delta"}function zk(e){return e.type==="error"}function jk(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={requiredAutoTruncation:!1,systemMessageMode:"system",supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith("gpt-5-chat")?{...r,isReasoningModel:!1}:e.startsWith("o")||e.startsWith("gpt-5")||e.startsWith("codex-")||e.startsWith("computer-use")?e.startsWith("o1-mini")||e.startsWith("o1-preview")?{...r,isReasoningModel:!0,systemMessageMode:"remove"}:{...r,isReasoningModel:!0,systemMessageMode:"developer"}:{...r,isReasoningModel:!1}}var Dk=x({metadata:pt().nullish(),parallelToolCalls:re().nullish(),previousResponseId:h().nullish(),store:re().nullish(),user:h().nullish(),reasoningEffort:h().nullish(),strictJsonSchema:re().nullish(),instructions:h().nullish(),reasoningSummary:h().nullish(),serviceTier:qe(["auto","flex","priority"]).nullish(),include:Z(qe(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),textVerbosity:qe(["low","medium","high"]).nullish(),promptCacheKey:h().nullish(),safetyIdentifier:h().nullish(),logprobs:ee([re(),R().min(1).max(dd)]).optional()}),Zk=x({instructions:h().nullish(),speed:R().min(.25).max(4).default(1).nullish()}),Uk=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:n="mp3",speed:r,instructions:o,language:s,providerOptions:a}){const i=[],l=await kt({provider:"openai",providerOptions:a,schema:Zk}),u={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:o};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?u.response_format=n:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),l){const c={};for(const w in c){const _=c[w];_!==void 0&&(u[w]=_)}}return s&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:u,warnings:i}}async doGenerate(e){var t,n,r;const o=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{requestBody:s,warnings:a}=await this.getArgs(e),{value:i,responseHeaders:l,rawValue:u}=await mt({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:s,failedResponseHandler:Tt,successfulResponseHandler:Px(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:a,request:{body:JSON.stringify(s)},response:{timestamp:o,modelId:this.modelId,headers:l,body:u}}}},Lk=x({include:Z(h()).optional(),language:h().optional(),prompt:h().optional(),temperature:R().min(0).max(1).default(0).optional(),timestampGranularities:Z(qe(["word","segment"])).default(["segment"]).optional()}),gd={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"},qk=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){const r=[],o=await kt({provider:"openai",providerOptions:n,schema:Lk}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([jx(e)]);if(s.append("model",this.modelId),s.append("file",new File([a],"audio",{type:t})),o){const i={include:o.include,language:o.language,prompt:o.prompt,response_format:"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[l,u]of Object.entries(i))u!=null&&s.append(l,String(u))}return{formData:s,warnings:r}}async doGenerate(e){var t,n,r,o,s,a,i,l;const u=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{formData:c,warnings:w}=await this.getArgs(e),{value:_,responseHeaders:d,rawValue:f}=await Mx({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),formData:c,failedResponseHandler:Tt,successfulResponseHandler:on(Bk),abortSignal:e.abortSignal,fetch:this.config.fetch}),y=_.language!=null&&_.language in gd?gd[_.language]:void 0;return{text:_.text,segments:(i=(a=(o=_.segments)==null?void 0:o.map(v=>({text:v.text,startSecond:v.start,endSecond:v.end})))!=null?a:(s=_.words)==null?void 0:s.map(v=>({text:v.word,startSecond:v.start,endSecond:v.end})))!=null?i:[],language:y,durationInSeconds:(l=_.duration)!=null?l:void 0,warnings:w,response:{timestamp:u,modelId:this.modelId,headers:d,body:f}}}},Bk=x({text:h(),language:h().nullish(),duration:R().nullish(),words:Z(x({word:h(),start:R(),end:R()})).nullish(),segments:Z(x({id:R(),seek:R(),start:R(),end:R(),text:h(),tokens:Z(R()),temperature:R(),avg_logprob:R(),compression_ratio:R(),no_speech_prob:R()})).nullish()});function yd(e={}){var t,n;const r=(t=Kc(e.baseURL))!=null?t:"https://api.openai.com/v1",o=(n=e.name)!=null?n:"openai",s=()=>({Authorization:`Bearer ${Hc({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),a=y=>new Fx(y,{provider:`${o}.chat`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),i=y=>new Qx(y,{provider:`${o}.completion`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),l=y=>new rk(y,{provider:`${o}.embedding`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),u=y=>new ik(y,{provider:`${o}.image`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),c=y=>new qk(y,{provider:`${o}.transcription`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),w=y=>new Uk(y,{provider:`${o}.speech`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch}),_=y=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(y)},d=y=>new mk(y,{provider:`${o}.responses`,url:({path:v})=>`${r}${v}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),f=function(y){return _(y)};return f.languageModel=_,f.chat=a,f.completion=i,f.responses=d,f.embedding=l,f.textEmbedding=l,f.textEmbeddingModel=l,f.image=u,f.imageModel=u,f.transcription=c,f.transcriptionModel=c,f.speech=w,f.speechModel=w,f.tools=dk,f}yd();function sr(e){var t,n;return(n=(t=e==null?void 0:e.providerOptions)==null?void 0:t.openaiCompatible)!=null?n:{}}function Vk(e){const t=[];for(const{role:n,content:r,...o}of e){const s=sr({...o});switch(n){case"system":{t.push({role:"system",content:r,...s});break}case"user":{if(r.length===1&&r[0].type==="text"){t.push({role:"user",content:r[0].text,...sr(r[0])});break}t.push({role:"user",content:r.map(a=>{const i=sr(a);switch(a.type){case"text":return{type:"text",text:a.text,...i};case"file":if(a.mediaType.startsWith("image/")){const l=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${l};base64,${sn(a.data)}`},...i}}else throw new at({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of r){const u=sr(l);switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...u});break}}}t.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const a of r){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const u=sr(a);t.push({role:"tool",tool_call_id:a.toolCallId,content:l,...u})}break}default:{const a=n;throw new Error(`Unsupported role: ${a}`)}}}return t}function vd({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function _d(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"unknown"}}var wd=x({user:h().optional(),reasoningEffort:h().optional()}),Fk=x({error:x({message:h(),type:h().nullish(),param:pt().nullish(),code:ee([h(),R()]).nullish()})}),Hk={errorSchema:Fk,errorToMessage:e=>e.error.message};function Jk({tools:e,toolChoice:t}){e=e!=null&&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-defined"?n.push({type:"unsupported-tool",tool:s}):r.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});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 at({functionality:`tool choice type: ${s}`})}}}var Gk=class{constructor(e,t){this.specificationVersion="v2";var n,r;this.modelId=e,this.config=t;const o=(n=t.errorStructure)!=null?n:Hk;this.chunkSchema=Kk(o.errorSchema),this.failedResponseHandler=Wc(o),this.supportsStructuredOutputs=(r=t.supportsStructuredOutputs)!=null?r:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?n:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:s,presencePenalty:a,providerOptions:i,stopSequences:l,responseFormat:u,seed:c,toolChoice:w,tools:_}){var d,f,y;const v=[],p=Object.assign((d=await kt({provider:"openai-compatible",providerOptions:i,schema:wd}))!=null?d:{},(f=await kt({provider:this.providerOptionsName,providerOptions:i,schema:wd}))!=null?f:{});o!=null&&v.push({type:"unsupported-setting",setting:"topK"}),(u==null?void 0:u.type)==="json"&&u.schema!=null&&!this.supportsStructuredOutputs&&v.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:b,toolChoice:g,toolWarnings:m}=Jk({tools:_,toolChoice:w});return{args:{model:this.modelId,user:p.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:s,presence_penalty:a,response_format:(u==null?void 0:u.type)==="json"?this.supportsStructuredOutputs===!0&&u.schema!=null?{type:"json_schema",json_schema:{schema:u.schema,name:(y=u.name)!=null?y:"response",description:u.description}}:{type:"json_object"}:void 0,stop:l,seed:c,...i==null?void 0:i[this.providerOptionsName],reasoning_effort:p.reasoningEffort,messages:Vk(e),tools:b,tool_choice:g},warnings:[...v,...m]}}async doGenerate(e){var t,n,r,o,s,a,i,l,u,c,w,_,d,f,y,v,p;const{args:b,warnings:g}=await this.getArgs({...e}),m=JSON.stringify(b),{responseHeaders:E,value:S,rawValue:T}=await mt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:b,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:on(Wk),abortSignal:e.abortSignal,fetch:this.config.fetch}),P=S.choices[0],V=[],H=P.message.content;H!=null&&H.length>0&&V.push({type:"text",text:H});const B=(t=P.message.reasoning_content)!=null?t:P.message.reasoning;if(B!=null&&B.length>0&&V.push({type:"reasoning",text:B}),P.message.tool_calls!=null)for(const be of P.message.tool_calls)V.push({type:"tool-call",toolCallId:(n=be.id)!=null?n:tt(),toolName:be.function.name,input:be.function.arguments});const oe={[this.providerOptionsName]:{},...await((o=(r=this.config.metadataExtractor)==null?void 0:r.extractMetadata)==null?void 0:o.call(r,{parsedBody:T}))},F=(s=S.usage)==null?void 0:s.completion_tokens_details;return(F==null?void 0:F.accepted_prediction_tokens)!=null&&(oe[this.providerOptionsName].acceptedPredictionTokens=F==null?void 0:F.accepted_prediction_tokens),(F==null?void 0:F.rejected_prediction_tokens)!=null&&(oe[this.providerOptionsName].rejectedPredictionTokens=F==null?void 0:F.rejected_prediction_tokens),{content:V,finishReason:_d(P.finish_reason),usage:{inputTokens:(i=(a=S.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(u=(l=S.usage)==null?void 0:l.completion_tokens)!=null?u:void 0,totalTokens:(w=(c=S.usage)==null?void 0:c.total_tokens)!=null?w:void 0,reasoningTokens:(f=(d=(_=S.usage)==null?void 0:_.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(p=(v=(y=S.usage)==null?void 0:y.prompt_tokens_details)==null?void 0:v.cached_tokens)!=null?p:void 0},providerMetadata:oe,request:{body:m},response:{...vd(S),headers:E,body:T},warnings:g}}async doStream(e){var t;const{args:n,warnings:r}=await this.getArgs({...e}),o={...n,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:a,value:i}=await mt({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:dt(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:io(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let u="unknown";const c={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let w=!0;const _=this.providerOptionsName;let d=!1,f=!1;return{stream:i.pipeThrough(new TransformStream({start(y){y.enqueue({type:"stream-start",warnings:r})},transform(y,v){var p,b,g,m,E,S,T,P,V,H,B,oe,F;if(e.includeRawChunks&&v.enqueue({type:"raw",rawValue:y.rawValue}),!y.success){u="error",v.enqueue({type:"error",error:y.error});return}const be=y.value;if(s==null||s.processChunk(y.rawValue),"error"in be){u="error",v.enqueue({type:"error",error:be.error.message});return}if(w&&(w=!1,v.enqueue({type:"response-metadata",...vd(be)})),be.usage!=null){const{prompt_tokens:I,completion_tokens:ie,total_tokens:me,prompt_tokens_details:de,completion_tokens_details:Q}=be.usage;c.promptTokens=I??void 0,c.completionTokens=ie??void 0,c.totalTokens=me??void 0,(Q==null?void 0:Q.reasoning_tokens)!=null&&(c.completionTokensDetails.reasoningTokens=Q==null?void 0:Q.reasoning_tokens),(Q==null?void 0:Q.accepted_prediction_tokens)!=null&&(c.completionTokensDetails.acceptedPredictionTokens=Q==null?void 0:Q.accepted_prediction_tokens),(Q==null?void 0:Q.rejected_prediction_tokens)!=null&&(c.completionTokensDetails.rejectedPredictionTokens=Q==null?void 0:Q.rejected_prediction_tokens),(de==null?void 0:de.cached_tokens)!=null&&(c.promptTokensDetails.cachedTokens=de==null?void 0:de.cached_tokens)}const Ee=be.choices[0];if((Ee==null?void 0:Ee.finish_reason)!=null&&(u=_d(Ee.finish_reason)),(Ee==null?void 0:Ee.delta)==null)return;const Ne=Ee.delta,Xe=(p=Ne.reasoning_content)!=null?p:Ne.reasoning;if(Xe&&(d||(v.enqueue({type:"reasoning-start",id:"reasoning-0"}),d=!0),v.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:Xe})),Ne.content&&(f||(v.enqueue({type:"text-start",id:"txt-0"}),f=!0),v.enqueue({type:"text-delta",id:"txt-0",delta:Ne.content})),Ne.tool_calls!=null)for(const I of Ne.tool_calls){const ie=I.index;if(l[ie]==null){if(I.id==null)throw new In({data:I,message:"Expected 'id' to be a string."});if(((b=I.function)==null?void 0:b.name)==null)throw new In({data:I,message:"Expected 'function.name' to be a string."});v.enqueue({type:"tool-input-start",id:I.id,toolName:I.function.name}),l[ie]={id:I.id,type:"function",function:{name:I.function.name,arguments:(g=I.function.arguments)!=null?g:""},hasFinished:!1};const de=l[ie];((m=de.function)==null?void 0:m.name)!=null&&((E=de.function)==null?void 0:E.arguments)!=null&&(de.function.arguments.length>0&&v.enqueue({type:"tool-input-start",id:de.id,toolName:de.function.name}),ao(de.function.arguments)&&(v.enqueue({type:"tool-input-end",id:de.id}),v.enqueue({type:"tool-call",toolCallId:(S=de.id)!=null?S:tt(),toolName:de.function.name,input:de.function.arguments}),de.hasFinished=!0));continue}const me=l[ie];me.hasFinished||(((T=I.function)==null?void 0:T.arguments)!=null&&(me.function.arguments+=(V=(P=I.function)==null?void 0:P.arguments)!=null?V:""),v.enqueue({type:"tool-input-delta",id:me.id,delta:(H=I.function.arguments)!=null?H:""}),((B=me.function)==null?void 0:B.name)!=null&&((oe=me.function)==null?void 0:oe.arguments)!=null&&ao(me.function.arguments)&&(v.enqueue({type:"tool-input-end",id:me.id}),v.enqueue({type:"tool-call",toolCallId:(F=me.id)!=null?F:tt(),toolName:me.function.name,input:me.function.arguments}),me.hasFinished=!0))}},flush(y){var v,p,b,g,m,E;d&&y.enqueue({type:"reasoning-end",id:"reasoning-0"}),f&&y.enqueue({type:"text-end",id:"txt-0"});for(const T of l.filter(P=>!P.hasFinished))y.enqueue({type:"tool-input-end",id:T.id}),y.enqueue({type:"tool-call",toolCallId:(v=T.id)!=null?v:tt(),toolName:T.function.name,input:T.function.arguments});const S={[_]:{},...s==null?void 0:s.buildMetadata()};c.completionTokensDetails.acceptedPredictionTokens!=null&&(S[_].acceptedPredictionTokens=c.completionTokensDetails.acceptedPredictionTokens),c.completionTokensDetails.rejectedPredictionTokens!=null&&(S[_].rejectedPredictionTokens=c.completionTokensDetails.rejectedPredictionTokens),y.enqueue({type:"finish",finishReason:u,usage:{inputTokens:(p=c.promptTokens)!=null?p:void 0,outputTokens:(b=c.completionTokens)!=null?b:void 0,totalTokens:(g=c.totalTokens)!=null?g:void 0,reasoningTokens:(m=c.completionTokensDetails.reasoningTokens)!=null?m:void 0,cachedInputTokens:(E=c.promptTokensDetails.cachedTokens)!=null?E:void 0},providerMetadata:S})}})),request:{body:o},response:{headers:a}}}},bd=x({prompt_tokens:R().nullish(),completion_tokens:R().nullish(),total_tokens:R().nullish(),prompt_tokens_details:x({cached_tokens:R().nullish()}).nullish(),completion_tokens_details:x({reasoning_tokens:R().nullish(),accepted_prediction_tokens:R().nullish(),rejected_prediction_tokens:R().nullish()}).nullish()}).nullish(),Wk=x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({message:x({role:A("assistant").nullish(),content:h().nullish(),reasoning_content:h().nullish(),reasoning:h().nullish(),tool_calls:Z(x({id:h().nullish(),function:x({name:h(),arguments:h()})})).nullish()}),finish_reason:h().nullish()})),usage:bd}),Kk=e=>ee([x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({delta:x({role:qe(["assistant"]).nullish(),content:h().nullish(),reasoning_content:h().nullish(),reasoning:h().nullish(),tool_calls:Z(x({index:R(),id:h().nullish(),function:x({name:h().nullish(),arguments:h().nullish()})})).nullish()}).nullish(),finish_reason:h().nullish()})),usage:bd}),e]);x({echo:re().optional(),logitBias:We(h(),R()).optional(),suffix:h().optional(),user:h().optional()});var Yk=x({prompt_tokens:R(),completion_tokens:R(),total_tokens:R()});x({id:h().nullish(),created:R().nullish(),model:h().nullish(),choices:Z(x({text:h(),finish_reason:h()})),usage:Yk.nullish()}),x({dimensions:R().optional(),user:h().optional()}),x({data:Z(x({embedding:Z(R())})),usage:x({prompt_tokens:R()}).nullish(),providerMetadata:We(h(),We(h(),pt())).optional()}),x({data:Z(x({b64_json:h()}))});var xd=e=>{var t,n;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(n=e.prompt_cache_miss_tokens)!=null?n:NaN}}},Xk={extractMetadata:async({parsedBody:e})=>{const t=await or({value:e,schema:Qk});return!t.success||t.value.usage==null?void 0:xd(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var n,r;const o=await or({value:t,schema:eT});o.success&&((r=(n=o.value.choices)==null?void 0:n[0])==null?void 0:r.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>xd(e)}}},kd=x({prompt_cache_hit_tokens:R().nullish(),prompt_cache_miss_tokens:R().nullish()}),Qk=x({usage:kd.nullish()}),eT=x({choices:Z(x({finish_reason:h().nullish()})).nullish(),usage:kd.nullish()});function Td(e={}){var t;const n=Kc((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),r=()=>({Authorization:`Bearer ${Hc({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers}),o=a=>new Gk(a,{provider:"deepseek.chat",url:({path:i})=>`${n}${i}`,headers:r,fetch:e.fetch,metadataExtractor:Xk}),s=a=>o(a);return s.languageModel=o,s.chat=o,s.textEmbeddingModel=a=>{throw new wo({modelId:a,modelType:"textEmbeddingModel"})},s.imageModel=a=>{throw new wo({modelId:a,modelType:"imageModel"})},s}Td();const tT={openai:yd,deepseek:Td};class nT{constructor({llmConfig:t,mcpServers:n,llm:r}){if(this.mcpServers={},this.mcpClients=[],this.mcpTools=[],this.ignoreToolnames=[],this.messages=[],this.mcpServers=n||{},r)this.llm=r;else if(t){let o;typeof t.providerType=="string"?o=tT[t.providerType]:o=t.providerType,this.llm=o({apiKey:t.apiKey,baseURL:t.baseURL})}else throw new Error("Either llmConfig or llm must be provided")}async _createOneClient(t){try{let n;"type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"?n=new gx(new URL(t.url)):n=t;const r=await N0({transport:n});return r.__transport__=n,r}catch(n){return this.onError&&this.onError((n==null?void 0:n.message)||"Failed to create MCP client",n),console.error("Failed to create MCP client",t,n),null}}async _closeOneClient(t){var n,r,o,s,a;try{await((r=(n=t.__transport__)==null?void 0:n.terminateSession)==null?void 0:r.call(n)),await((s=(o=t.__transport__)==null?void 0:o.close)==null?void 0:s.call(o)),await((a=t==null?void 0:t.close)==null?void 0:a.call(t))}catch{}}async _createMpcClients(){this.mcpClients=await Promise.all(Object.values(this.mcpServers).map(async t=>this._createOneClient(t)))}async _createMpcTools(){this.mcpTools=await Promise.all(this.mcpClients.map(async t=>{var n;try{return t?await((n=t==null?void 0:t.tools)==null?void 0:n.call(t)):null}catch(r){return this.onError&&this.onError((r==null?void 0:r.message)||"Failed to query tools",r),console.error("Failed to query tools",r),null}}))}async closeAll(){await Promise.all(this.mcpClients.map(async t=>{try{await this._closeOneClient(t)}catch(n){this.onError&&this.onError((n==null?void 0:n.message)||"Failed to close client",n),console.error("Failed to close client",n)}}))}async initClientsAndTools(){var t;await this._createMpcClients(),await this._createMpcTools(),(t=this.onUpdatedTools)==null||t.call(this)}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(t,n){var o,s;if(this.mcpServers[t])return!1;this.mcpServers[t]=n;const r=await this._createOneClient(n);return this.mcpClients.push(r),this.mcpTools.push(await((o=r==null?void 0:r.tools)==null?void 0:o.call(r))),(s=this.onUpdatedTools)==null||s.call(this),!0}async removeMcpServer(t){if(!this.mcpServers[t])return;const r=Object.keys(this.mcpServers).indexOf(t);delete this.mcpServers[t];const o=this.mcpClients[r];this.mcpClients.splice(r,1);try{await this._closeOneClient(o)}catch{}const s=this.mcpTools[r];this.mcpTools.splice(r,1),s&&Object.keys(s).forEach(a=>{this.ignoreToolnames=this.ignoreToolnames.filter(i=>i!==a)})}_tempMergeTools(t={}){const n=this.mcpTools.reduce((r,o)=>({...r,...o}),{});return Object.assign(n,t),this.ignoreToolnames.forEach(r=>{delete n[r]}),n}async _chat(t,{model:n,maxSteps:r=5,...o}){var i;if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s={model:this.llm(n),stopWhen:vs(r),...o,tools:this._tempMergeTools(o.tools)};o.message&&!o.messages&&(this.messages.push({role:"user",content:o.message}),s.messages=[...this.messages]);const a=t(s);return(i=a==null?void 0:a.response)==null||i.then(l=>{this.messages.push(...l.messages)}),a}async chat(t){return this._chat(jw,t)}async chatStream(t){return this._chat(r0,t)}}var vn={},rT=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},Sd={},nt={};let Ys;const oT=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];nt.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17},nt.getSymbolTotalCodewords=function(t){return oT[t]},nt.getBCHDigit=function(e){let t=0;for(;e!==0;)t++,e>>>=1;return t},nt.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');Ys=t},nt.isKanjiModeEnabled=function(){return typeof Ys<"u"},nt.toSJIS=function(t){return Ys(t)};var lo={};(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+n)}}e.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},e.from=function(r,o){if(e.isValid(r))return r;try{return t(r)}catch{return o}}})(lo);function Id(){this.buffer=[],this.length=0}Id.prototype={get:function(e){const t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)===1},put:function(e,t){for(let n=0;n<t;n++)this.putBit((e>>>t-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var sT=Id;function ar(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}ar.prototype.set=function(e,t,n,r){const o=e*this.size+t;this.data[o]=n,r&&(this.reservedBit[o]=!0)},ar.prototype.get=function(e,t){return this.data[e*this.size+t]},ar.prototype.xor=function(e,t,n){this.data[e*this.size+t]^=n},ar.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]};var aT=ar,Cd={};(function(e){const t=nt.getSymbolSize;e.getRowColCoords=function(r){if(r===1)return[];const o=Math.floor(r/7)+2,s=t(r),a=s===145?26:Math.ceil((s-13)/(2*o-2))*2,i=[s-7];for(let l=1;l<o-1;l++)i[l]=i[l-1]-a;return i.push(6),i.reverse()},e.getPositions=function(r){const o=[],s=e.getRowColCoords(r),a=s.length;for(let i=0;i<a;i++)for(let l=0;l<a;l++)i===0&&l===0||i===0&&l===a-1||i===a-1&&l===0||o.push([s[i],s[l]]);return o}})(Cd);var Ed={};const iT=nt.getSymbolSize,Rd=7;Ed.getPositions=function(t){const n=iT(t);return[[0,0],[n-Rd,0],[0,n-Rd]]};var Ad={};(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.getPenaltyN1=function(o){const s=o.size;let a=0,i=0,l=0,u=null,c=null;for(let w=0;w<s;w++){i=l=0,u=c=null;for(let _=0;_<s;_++){let d=o.get(w,_);d===u?i++:(i>=5&&(a+=t.N1+(i-5)),u=d,i=1),d=o.get(_,w),d===c?l++:(l>=5&&(a+=t.N1+(l-5)),c=d,l=1)}i>=5&&(a+=t.N1+(i-5)),l>=5&&(a+=t.N1+(l-5))}return a},e.getPenaltyN2=function(o){const s=o.size;let a=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const u=o.get(i,l)+o.get(i,l+1)+o.get(i+1,l)+o.get(i+1,l+1);(u===4||u===0)&&a++}return a*t.N2},e.getPenaltyN3=function(o){const s=o.size;let a=0,i=0,l=0;for(let u=0;u<s;u++){i=l=0;for(let c=0;c<s;c++)i=i<<1&2047|o.get(u,c),c>=10&&(i===1488||i===93)&&a++,l=l<<1&2047|o.get(c,u),c>=10&&(l===1488||l===93)&&a++}return a*t.N3},e.getPenaltyN4=function(o){let s=0;const a=o.data.length;for(let l=0;l<a;l++)s+=o.data[l];return Math.abs(Math.ceil(s*100/a/5)-10)*t.N4};function n(r,o,s){switch(r){case e.Patterns.PATTERN000:return(o+s)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return s%3===0;case e.Patterns.PATTERN011:return(o+s)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case e.Patterns.PATTERN101:return o*s%2+o*s%3===0;case e.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case e.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}e.applyMask=function(o,s){const a=s.size;for(let i=0;i<a;i++)for(let l=0;l<a;l++)s.isReserved(l,i)||s.xor(l,i,n(o,l,i))},e.getBestMask=function(o,s){const a=Object.keys(e.Patterns).length;let i=0,l=1/0;for(let u=0;u<a;u++){s(u),e.applyMask(u,o);const c=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(u,o),c<l&&(l=c,i=u)}return i}})(Ad);var uo={};const Lt=lo,co=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],po=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];uo.getBlocksCount=function(t,n){switch(n){case Lt.L:return co[(t-1)*4+0];case Lt.M:return co[(t-1)*4+1];case Lt.Q:return co[(t-1)*4+2];case Lt.H:return co[(t-1)*4+3];default:return}},uo.getTotalCodewordsCount=function(t,n){switch(n){case Lt.L:return po[(t-1)*4+0];case Lt.M:return po[(t-1)*4+1];case Lt.Q:return po[(t-1)*4+2];case Lt.H:return po[(t-1)*4+3];default:return}};var Od={},ho={};const ir=new Uint8Array(512),fo=new Uint8Array(256);(function(){let t=1;for(let n=0;n<255;n++)ir[n]=t,fo[t]=n,t<<=1,t&256&&(t^=285);for(let n=255;n<512;n++)ir[n]=ir[n-255]})(),ho.log=function(t){if(t<1)throw new Error("log("+t+")");return fo[t]},ho.exp=function(t){return ir[t]},ho.mul=function(t,n){return t===0||n===0?0:ir[fo[t]+fo[n]]},function(e){const t=ho;e.mul=function(r,o){const s=new Uint8Array(r.length+o.length-1);for(let a=0;a<r.length;a++)for(let i=0;i<o.length;i++)s[a+i]^=t.mul(r[a],o[i]);return s},e.mod=function(r,o){let s=new Uint8Array(r);for(;s.length-o.length>=0;){const a=s[0];for(let l=0;l<o.length;l++)s[l]^=t.mul(o[l],a);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},e.generateECPolynomial=function(r){let o=new Uint8Array([1]);for(let s=0;s<r;s++)o=e.mul(o,new Uint8Array([1,t.exp(s)]));return o}}(Od);const Nd=Od;function Xs(e){this.genPoly=void 0,this.degree=e,this.degree&&this.initialize(this.degree)}Xs.prototype.initialize=function(t){this.degree=t,this.genPoly=Nd.generateECPolynomial(this.degree)},Xs.prototype.encode=function(t){if(!this.genPoly)throw new Error("Encoder not initialized");const n=new Uint8Array(t.length+this.degree);n.set(t);const r=Nd.mod(n,this.genPoly),o=this.degree-r.length;if(o>0){const s=new Uint8Array(this.degree);return s.set(r,o),s}return r};var lT=Xs,Md={},qt={},Qs={};Qs.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var St={};const Pd="[0-9]+",uT="[A-Z $%*+\\-./:]+";let lr="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";lr=lr.replace(/u/g,"\\u");const cT="(?:(?![A-Z0-9 $%*+\\-./:]|"+lr+`)(?:.|[\r
77
+ ]))+`;St.KANJI=new RegExp(lr,"g"),St.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),St.BYTE=new RegExp(cT,"g"),St.NUMERIC=new RegExp(Pd,"g"),St.ALPHANUMERIC=new RegExp(uT,"g");const dT=new RegExp("^"+lr+"$"),pT=new RegExp("^"+Pd+"$"),hT=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");St.testKanji=function(t){return dT.test(t)},St.testNumeric=function(t){return pT.test(t)},St.testAlphanumeric=function(t){return hT.test(t)},function(e){const t=Qs,n=St;e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(s,a){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!t.isValid(a))throw new Error("Invalid version: "+a);return a>=1&&a<10?s.ccBits[0]:a<27?s.ccBits[1]:s.ccBits[2]},e.getBestModeForData=function(s){return n.testNumeric(s)?e.NUMERIC:n.testAlphanumeric(s)?e.ALPHANUMERIC:n.testKanji(s)?e.KANJI:e.BYTE},e.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},e.isValid=function(s){return s&&s.bit&&s.ccBits};function r(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+o)}}e.from=function(s,a){if(e.isValid(s))return s;try{return r(s)}catch{return a}}}(qt),function(e){const t=nt,n=uo,r=lo,o=qt,s=Qs,a=7973,i=t.getBCHDigit(a);function l(_,d,f){for(let y=1;y<=40;y++)if(d<=e.getCapacity(y,f,_))return y}function u(_,d){return o.getCharCountIndicator(_,d)+4}function c(_,d){let f=0;return _.forEach(function(y){const v=u(y.mode,d);f+=v+y.getBitsLength()}),f}function w(_,d){for(let f=1;f<=40;f++)if(c(_,f)<=e.getCapacity(f,d,o.MIXED))return f}e.from=function(d,f){return s.isValid(d)?parseInt(d,10):f},e.getCapacity=function(d,f,y){if(!s.isValid(d))throw new Error("Invalid QR Code version");typeof y>"u"&&(y=o.BYTE);const v=t.getSymbolTotalCodewords(d),p=n.getTotalCodewordsCount(d,f),b=(v-p)*8;if(y===o.MIXED)return b;const g=b-u(y,d);switch(y){case o.NUMERIC:return Math.floor(g/10*3);case o.ALPHANUMERIC:return Math.floor(g/11*2);case o.KANJI:return Math.floor(g/13);case o.BYTE:default:return Math.floor(g/8)}},e.getBestVersionForData=function(d,f){let y;const v=r.from(f,r.M);if(Array.isArray(d)){if(d.length>1)return w(d,v);if(d.length===0)return 1;y=d[0]}else y=d;return l(y.mode,y.getLength(),v)},e.getEncodedBits=function(d){if(!s.isValid(d)||d<7)throw new Error("Invalid QR Code version");let f=d<<12;for(;t.getBCHDigit(f)-i>=0;)f^=a<<t.getBCHDigit(f)-i;return d<<12|f}}(Md);var $d={};const ea=nt,zd=1335,fT=21522,jd=ea.getBCHDigit(zd);$d.getEncodedBits=function(t,n){const r=t.bit<<3|n;let o=r<<10;for(;ea.getBCHDigit(o)-jd>=0;)o^=zd<<ea.getBCHDigit(o)-jd;return(r<<10|o)^fT};var Dd={};const mT=qt;function _n(e){this.mode=mT.NUMERIC,this.data=e.toString()}_n.getBitsLength=function(t){return 10*Math.floor(t/3)+(t%3?t%3*3+1:0)},_n.prototype.getLength=function(){return this.data.length},_n.prototype.getBitsLength=function(){return _n.getBitsLength(this.data.length)},_n.prototype.write=function(t){let n,r,o;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),o=parseInt(r,10),t.put(o,10);const s=this.data.length-n;s>0&&(r=this.data.substr(n),o=parseInt(r,10),t.put(o,s*3+1))};var gT=_n;const yT=qt,ta=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function wn(e){this.mode=yT.ALPHANUMERIC,this.data=e}wn.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)},wn.prototype.getLength=function(){return this.data.length},wn.prototype.getBitsLength=function(){return wn.getBitsLength(this.data.length)},wn.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=ta.indexOf(this.data[n])*45;r+=ta.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(ta.indexOf(this.data[n]),6)};var vT=wn;const _T=qt;function bn(e){this.mode=_T.BYTE,typeof e=="string"?this.data=new TextEncoder().encode(e):this.data=new Uint8Array(e)}bn.getBitsLength=function(t){return t*8},bn.prototype.getLength=function(){return this.data.length},bn.prototype.getBitsLength=function(){return bn.getBitsLength(this.data.length)},bn.prototype.write=function(e){for(let t=0,n=this.data.length;t<n;t++)e.put(this.data[t],8)};var wT=bn;const bT=qt,xT=nt;function xn(e){this.mode=bT.KANJI,this.data=e}xn.getBitsLength=function(t){return t*13},xn.prototype.getLength=function(){return this.data.length},xn.prototype.getBitsLength=function(){return xn.getBitsLength(this.data.length)},xn.prototype.write=function(e){let t;for(t=0;t<this.data.length;t++){let n=xT.toSJIS(this.data[t]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[t]+`
78
+ Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),e.put(n,13)}};var kT=xn,Zd={exports:{}};(function(e){var t={single_source_shortest_paths:function(n,r,o){var s={},a={};a[r]=0;var i=t.PriorityQueue.make();i.push(r,0);for(var l,u,c,w,_,d,f,y,v;!i.empty();){l=i.pop(),u=l.value,w=l.cost,_=n[u]||{};for(c in _)_.hasOwnProperty(c)&&(d=_[c],f=w+d,y=a[c],v=typeof a[c]>"u",(v||y>f)&&(a[c]=f,i.push(c,f),s[c]=u))}if(typeof o<"u"&&typeof a[o]>"u"){var p=["Could not find a path from ",r," to ",o,"."].join("");throw new Error(p)}return s},extract_shortest_path_from_predecessor_list:function(n,r){for(var o=[],s=r;s;)o.push(s),n[s],s=n[s];return o.reverse(),o},find_path:function(n,r,o){var s=t.single_source_shortest_paths(n,r,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(n){var r=t.PriorityQueue,o={},s;n=n||{};for(s in r)r.hasOwnProperty(s)&&(o[s]=r[s]);return o.queue=[],o.sorter=n.sorter||r.default_sorter,o},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var o={value:n,cost:r};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(Zd);var TT=Zd.exports;(function(e){const t=qt,n=gT,r=vT,o=wT,s=kT,a=St,i=nt,l=TT;function u(p){return unescape(encodeURIComponent(p)).length}function c(p,b,g){const m=[];let E;for(;(E=p.exec(g))!==null;)m.push({data:E[0],index:E.index,mode:b,length:E[0].length});return m}function w(p){const b=c(a.NUMERIC,t.NUMERIC,p),g=c(a.ALPHANUMERIC,t.ALPHANUMERIC,p);let m,E;return i.isKanjiModeEnabled()?(m=c(a.BYTE,t.BYTE,p),E=c(a.KANJI,t.KANJI,p)):(m=c(a.BYTE_KANJI,t.BYTE,p),E=[]),b.concat(g,m,E).sort(function(T,P){return T.index-P.index}).map(function(T){return{data:T.data,mode:T.mode,length:T.length}})}function _(p,b){switch(b){case t.NUMERIC:return n.getBitsLength(p);case t.ALPHANUMERIC:return r.getBitsLength(p);case t.KANJI:return s.getBitsLength(p);case t.BYTE:return o.getBitsLength(p)}}function d(p){return p.reduce(function(b,g){const m=b.length-1>=0?b[b.length-1]:null;return m&&m.mode===g.mode?(b[b.length-1].data+=g.data,b):(b.push(g),b)},[])}function f(p){const b=[];for(let g=0;g<p.length;g++){const m=p[g];switch(m.mode){case t.NUMERIC:b.push([m,{data:m.data,mode:t.ALPHANUMERIC,length:m.length},{data:m.data,mode:t.BYTE,length:m.length}]);break;case t.ALPHANUMERIC:b.push([m,{data:m.data,mode:t.BYTE,length:m.length}]);break;case t.KANJI:b.push([m,{data:m.data,mode:t.BYTE,length:u(m.data)}]);break;case t.BYTE:b.push([{data:m.data,mode:t.BYTE,length:u(m.data)}])}}return b}function y(p,b){const g={},m={start:{}};let E=["start"];for(let S=0;S<p.length;S++){const T=p[S],P=[];for(let V=0;V<T.length;V++){const H=T[V],B=""+S+V;P.push(B),g[B]={node:H,lastCount:0},m[B]={};for(let oe=0;oe<E.length;oe++){const F=E[oe];g[F]&&g[F].node.mode===H.mode?(m[F][B]=_(g[F].lastCount+H.length,H.mode)-_(g[F].lastCount,H.mode),g[F].lastCount+=H.length):(g[F]&&(g[F].lastCount=H.length),m[F][B]=_(H.length,H.mode)+4+t.getCharCountIndicator(H.mode,b))}}E=P}for(let S=0;S<E.length;S++)m[E[S]].end=0;return{map:m,table:g}}function v(p,b){let g;const m=t.getBestModeForData(p);if(g=t.from(b,m),g!==t.BYTE&&g.bit<m.bit)throw new Error('"'+p+'" cannot be encoded with mode '+t.toString(g)+`.
79
+ Suggested mode is: `+t.toString(m));switch(g===t.KANJI&&!i.isKanjiModeEnabled()&&(g=t.BYTE),g){case t.NUMERIC:return new n(p);case t.ALPHANUMERIC:return new r(p);case t.KANJI:return new s(p);case t.BYTE:return new o(p)}}e.fromArray=function(b){return b.reduce(function(g,m){return typeof m=="string"?g.push(v(m,null)):m.data&&g.push(v(m.data,m.mode)),g},[])},e.fromString=function(b,g){const m=w(b,i.isKanjiModeEnabled()),E=f(m),S=y(E,g),T=l.find_path(S.map,"start","end"),P=[];for(let V=1;V<T.length-1;V++)P.push(S.table[T[V]].node);return e.fromArray(d(P))},e.rawSplit=function(b){return e.fromArray(w(b,i.isKanjiModeEnabled()))}})(Dd);const mo=nt,na=lo,ST=sT,IT=aT,CT=Cd,ET=Ed,ra=Ad,oa=uo,RT=lT,go=Md,AT=$d,OT=qt,sa=Dd;function NT(e,t){const n=e.size,r=ET.getPositions(t);for(let o=0;o<r.length;o++){const s=r[o][0],a=r[o][1];for(let i=-1;i<=7;i++)if(!(s+i<=-1||n<=s+i))for(let l=-1;l<=7;l++)a+l<=-1||n<=a+l||(i>=0&&i<=6&&(l===0||l===6)||l>=0&&l<=6&&(i===0||i===6)||i>=2&&i<=4&&l>=2&&l<=4?e.set(s+i,a+l,!0,!0):e.set(s+i,a+l,!1,!0))}}function MT(e){const t=e.size;for(let n=8;n<t-8;n++){const r=n%2===0;e.set(n,6,r,!0),e.set(6,n,r,!0)}}function PT(e,t){const n=CT.getPositions(t);for(let r=0;r<n.length;r++){const o=n[r][0],s=n[r][1];for(let a=-2;a<=2;a++)for(let i=-2;i<=2;i++)a===-2||a===2||i===-2||i===2||a===0&&i===0?e.set(o+a,s+i,!0,!0):e.set(o+a,s+i,!1,!0)}}function $T(e,t){const n=e.size,r=go.getEncodedBits(t);let o,s,a;for(let i=0;i<18;i++)o=Math.floor(i/3),s=i%3+n-8-3,a=(r>>i&1)===1,e.set(o,s,a,!0),e.set(s,o,a,!0)}function aa(e,t,n){const r=e.size,o=AT.getEncodedBits(t,n);let s,a;for(s=0;s<15;s++)a=(o>>s&1)===1,s<6?e.set(s,8,a,!0):s<8?e.set(s+1,8,a,!0):e.set(r-15+s,8,a,!0),s<8?e.set(8,r-s-1,a,!0):s<9?e.set(8,15-s-1+1,a,!0):e.set(8,15-s-1,a,!0);e.set(r-8,8,1,!0)}function zT(e,t){const n=e.size;let r=-1,o=n-1,s=7,a=0;for(let i=n-1;i>0;i-=2)for(i===6&&i--;;){for(let l=0;l<2;l++)if(!e.isReserved(o,i-l)){let u=!1;a<t.length&&(u=(t[a]>>>s&1)===1),e.set(o,i-l,u),s--,s===-1&&(a++,s=7)}if(o+=r,o<0||n<=o){o-=r,r=-r;break}}}function jT(e,t,n){const r=new ST;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),OT.getCharCountIndicator(l.mode,e)),l.write(r)});const o=mo.getSymbolTotalCodewords(e),s=oa.getTotalCodewordsCount(e,t),a=(o-s)*8;for(r.getLengthInBits()+4<=a&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);const i=(a-r.getLengthInBits())/8;for(let l=0;l<i;l++)r.put(l%2?17:236,8);return DT(r,e,t)}function DT(e,t,n){const r=mo.getSymbolTotalCodewords(t),o=oa.getTotalCodewordsCount(t,n),s=r-o,a=oa.getBlocksCount(t,n),i=r%a,l=a-i,u=Math.floor(r/a),c=Math.floor(s/a),w=c+1,_=u-c,d=new RT(_);let f=0;const y=new Array(a),v=new Array(a);let p=0;const b=new Uint8Array(e.buffer);for(let T=0;T<a;T++){const P=T<l?c:w;y[T]=b.slice(f,f+P),v[T]=d.encode(y[T]),f+=P,p=Math.max(p,P)}const g=new Uint8Array(r);let m=0,E,S;for(E=0;E<p;E++)for(S=0;S<a;S++)E<y[S].length&&(g[m++]=y[S][E]);for(E=0;E<_;E++)for(S=0;S<a;S++)g[m++]=v[S][E];return g}function ZT(e,t,n,r){let o;if(Array.isArray(e))o=sa.fromArray(e);else if(typeof e=="string"){let u=t;if(!u){const c=sa.rawSplit(e);u=go.getBestVersionForData(c,n)}o=sa.fromString(e,u||40)}else throw new Error("Invalid data");const s=go.getBestVersionForData(o,n);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!t)t=s;else if(t<s)throw new Error(`
80
80
  The chosen QR Code version cannot contain this amount of data.
81
81
  Minimum version required to store current data is: `+s+`.
82
- `);const a=DT(t,n,o),i=mo.getSymbolSize(t),l=new CT(i);return MT(l,t),PT(l),$T(l,t),aa(l,n,0),t>=7&&zT(l,t),jT(l,a),isNaN(r)&&(r=ra.getBestMask(l,aa.bind(null,l,n))),ra.applyMask(r,l),aa(l,n,r),{modules:l,version:t,errorCorrectionLevel:n,maskPattern:r,segments:o}}Sd.create=function(t,n){if(typeof t>"u"||t==="")throw new Error("No input text");let r=na.M,o,s;return typeof n<"u"&&(r=na.from(n.errorCorrectionLevel,na.M),o=go.from(n.version),s=ra.from(n.maskPattern),n.toSJISFunc&&mo.setToSJISFunction(n.toSJISFunc)),UT(t,o,r,s)};var Ud={},ia={};(function(e){function t(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(s){return[s,s]}))),r.length===6&&r.push("F","F");const o=parseInt(r.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+r.slice(0,6).join("")}}e.getOptions=function(r){r||(r={}),r.color||(r.color={});const o=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,s=r.width&&r.width>=21?r.width:void 0,a=r.scale||4;return{width:s,scale:s?4:a,margin:o,color:{dark:t(r.color.dark||"#000000ff"),light:t(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},e.getScale=function(r,o){return o.width&&o.width>=r+o.margin*2?o.width/(r+o.margin*2):o.scale},e.getImageWidth=function(r,o){const s=e.getScale(r,o);return Math.floor((r+o.margin*2)*s)},e.qrToImageData=function(r,o,s){const a=o.modules.size,i=o.modules.data,l=e.getScale(a,s),u=Math.floor((a+s.margin*2)*l),c=s.margin*l,w=[s.color.light,s.color.dark];for(let _=0;_<u;_++)for(let d=0;d<u;d++){let f=(_*u+d)*4,y=s.color.light;if(_>=c&&d>=c&&_<u-c&&d<u-c){const v=Math.floor((_-c)/l),p=Math.floor((d-c)/l);y=w[i[v*a+p]?1:0]}r[f++]=y.r,r[f++]=y.g,r[f++]=y.b,r[f]=y.a}}})(ia),function(e){const t=ia;function n(o,s,a){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=a,s.width=a,s.style.height=a+"px",s.style.width=a+"px"}function r(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(s,a,i){let l=i,u=a;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),a||(u=r()),l=t.getOptions(l);const c=t.getImageWidth(s.modules.size,l),w=u.getContext("2d"),_=w.createImageData(c,c);return t.qrToImageData(_.data,s,l),n(w,u,c),w.putImageData(_,0,0),u},e.renderToDataURL=function(s,a,i){let l=i;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),l||(l={});const u=e.render(s,a,l),c=l.type||"image/png",w=l.rendererOpts||{};return u.toDataURL(c,w.quality)}}(Ud);var Ld={};const LT=ia;function qd(e,t){const n=e.a/255,r=t+'="'+e.hex+'"';return n<1?r+" "+t+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function la(e,t,n){let r=e+t;return typeof n<"u"&&(r+=" "+n),r}function qT(e,t,n){let r="",o=0,s=!1,a=0;for(let i=0;i<e.length;i++){const l=Math.floor(i%t),u=Math.floor(i/t);!l&&!s&&(s=!0),e[i]?(a++,i>0&&l>0&&e[i-1]||(r+=s?la("M",l+n,.5+u+n):la("m",o,0),o=0,s=!1),l+1<t&&e[i+1]||(r+=la("h",a),a=0)):o++}return r}Ld.render=function(t,n,r){const o=LT.getOptions(n),s=t.modules.size,a=t.modules.data,i=s+o.margin*2,l=o.color.light.a?"<path "+qd(o.color.light,"fill")+' d="M0 0h'+i+"v"+i+'H0z"/>':"",u="<path "+qd(o.color.dark,"stroke")+' d="'+qT(a,s,o.margin)+'"/>',c='viewBox="0 0 '+i+" "+i+'"',_='<svg xmlns="http://www.w3.org/2000/svg" '+(o.width?'width="'+o.width+'" height="'+o.width+'" ':"")+c+' shape-rendering="crispEdges">'+l+u+`</svg>
83
- `;return typeof r=="function"&&r(null,_),_};const BT=oT,ua=Sd,Bd=Ud,VT=Ld;function ca(e,t,n,r,o){const s=[].slice.call(arguments,1),a=s.length,i=typeof s[a-1]=="function";if(!i&&!BT())throw new Error("Callback required as last argument");if(i){if(a<2)throw new Error("Too few arguments provided");a===2?(o=n,n=t,t=r=void 0):a===3&&(t.getContext&&typeof o>"u"?(o=r,r=void 0):(o=r,r=n,n=t,t=void 0))}else{if(a<1)throw new Error("Too few arguments provided");return a===1?(n=t,t=r=void 0):a===2&&!t.getContext&&(r=n,n=t,t=void 0),new Promise(function(l,u){try{const c=ua.create(n,r);l(e(c,t,r))}catch(c){u(c)}})}try{const l=ua.create(n,r);o(null,e(l,t,r))}catch(l){o(l)}}vn.create=ua.create,vn.toCanvas=ca.bind(null,Bd.render),vn.toDataURL=ca.bind(null,Bd.renderToDataURL),vn.toString=ca.bind(null,function(e,t,n){return VT.render(e,n)});class Vd{constructor(t,{size:n=200,margin:r=4,color:o="#000",bgColor:s="#fff"}){this.value=t,this.size=n,this.margin=r,this.color=o,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return vn.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return vn.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const Fd="https://agent.opentiny.design/tiny-robot",Hd="https://ai.opentiny.design/next-remoter",Jd=e=>[{action:"qr-code",show:!0,text:"弹出二维码",icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
82
+ `);const a=jT(t,n,o),i=mo.getSymbolSize(t),l=new IT(i);return NT(l,t),MT(l),PT(l,t),aa(l,n,0),t>=7&&$T(l,t),zT(l,a),isNaN(r)&&(r=ra.getBestMask(l,aa.bind(null,l,n))),ra.applyMask(r,l),aa(l,n,r),{modules:l,version:t,errorCorrectionLevel:n,maskPattern:r,segments:o}}Sd.create=function(t,n){if(typeof t>"u"||t==="")throw new Error("No input text");let r=na.M,o,s;return typeof n<"u"&&(r=na.from(n.errorCorrectionLevel,na.M),o=go.from(n.version),s=ra.from(n.maskPattern),n.toSJISFunc&&mo.setToSJISFunction(n.toSJISFunc)),ZT(t,o,r,s)};var Ud={},ia={};(function(e){function t(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(s){return[s,s]}))),r.length===6&&r.push("F","F");const o=parseInt(r.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+r.slice(0,6).join("")}}e.getOptions=function(r){r||(r={}),r.color||(r.color={});const o=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,s=r.width&&r.width>=21?r.width:void 0,a=r.scale||4;return{width:s,scale:s?4:a,margin:o,color:{dark:t(r.color.dark||"#000000ff"),light:t(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},e.getScale=function(r,o){return o.width&&o.width>=r+o.margin*2?o.width/(r+o.margin*2):o.scale},e.getImageWidth=function(r,o){const s=e.getScale(r,o);return Math.floor((r+o.margin*2)*s)},e.qrToImageData=function(r,o,s){const a=o.modules.size,i=o.modules.data,l=e.getScale(a,s),u=Math.floor((a+s.margin*2)*l),c=s.margin*l,w=[s.color.light,s.color.dark];for(let _=0;_<u;_++)for(let d=0;d<u;d++){let f=(_*u+d)*4,y=s.color.light;if(_>=c&&d>=c&&_<u-c&&d<u-c){const v=Math.floor((_-c)/l),p=Math.floor((d-c)/l);y=w[i[v*a+p]?1:0]}r[f++]=y.r,r[f++]=y.g,r[f++]=y.b,r[f]=y.a}}})(ia),function(e){const t=ia;function n(o,s,a){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=a,s.width=a,s.style.height=a+"px",s.style.width=a+"px"}function r(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(s,a,i){let l=i,u=a;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),a||(u=r()),l=t.getOptions(l);const c=t.getImageWidth(s.modules.size,l),w=u.getContext("2d"),_=w.createImageData(c,c);return t.qrToImageData(_.data,s,l),n(w,u,c),w.putImageData(_,0,0),u},e.renderToDataURL=function(s,a,i){let l=i;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),l||(l={});const u=e.render(s,a,l),c=l.type||"image/png",w=l.rendererOpts||{};return u.toDataURL(c,w.quality)}}(Ud);var Ld={};const UT=ia;function qd(e,t){const n=e.a/255,r=t+'="'+e.hex+'"';return n<1?r+" "+t+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function la(e,t,n){let r=e+t;return typeof n<"u"&&(r+=" "+n),r}function LT(e,t,n){let r="",o=0,s=!1,a=0;for(let i=0;i<e.length;i++){const l=Math.floor(i%t),u=Math.floor(i/t);!l&&!s&&(s=!0),e[i]?(a++,i>0&&l>0&&e[i-1]||(r+=s?la("M",l+n,.5+u+n):la("m",o,0),o=0,s=!1),l+1<t&&e[i+1]||(r+=la("h",a),a=0)):o++}return r}Ld.render=function(t,n,r){const o=UT.getOptions(n),s=t.modules.size,a=t.modules.data,i=s+o.margin*2,l=o.color.light.a?"<path "+qd(o.color.light,"fill")+' d="M0 0h'+i+"v"+i+'H0z"/>':"",u="<path "+qd(o.color.dark,"stroke")+' d="'+LT(a,s,o.margin)+'"/>',c='viewBox="0 0 '+i+" "+i+'"',_='<svg xmlns="http://www.w3.org/2000/svg" '+(o.width?'width="'+o.width+'" height="'+o.width+'" ':"")+c+' shape-rendering="crispEdges">'+l+u+`</svg>
83
+ `;return typeof r=="function"&&r(null,_),_};const qT=rT,ua=Sd,Bd=Ud,BT=Ld;function ca(e,t,n,r,o){const s=[].slice.call(arguments,1),a=s.length,i=typeof s[a-1]=="function";if(!i&&!qT())throw new Error("Callback required as last argument");if(i){if(a<2)throw new Error("Too few arguments provided");a===2?(o=n,n=t,t=r=void 0):a===3&&(t.getContext&&typeof o>"u"?(o=r,r=void 0):(o=r,r=n,n=t,t=void 0))}else{if(a<1)throw new Error("Too few arguments provided");return a===1?(n=t,t=r=void 0):a===2&&!t.getContext&&(r=n,n=t,t=void 0),new Promise(function(l,u){try{const c=ua.create(n,r);l(e(c,t,r))}catch(c){u(c)}})}try{const l=ua.create(n,r);o(null,e(l,t,r))}catch(l){o(l)}}vn.create=ua.create,vn.toCanvas=ca.bind(null,Bd.render),vn.toDataURL=ca.bind(null,Bd.renderToDataURL),vn.toString=ca.bind(null,function(e,t,n){return BT.render(e,n)});class Vd{constructor(t,{size:n=200,margin:r=4,color:o="#000",bgColor:s="#fff"}){this.value=t,this.size=n,this.margin=r,this.color=o,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return vn.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return vn.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const VT="https://agent.opentiny.design/tiny-robot",Fd="https://ai.opentiny.design/next-remoter",Hd=e=>[{action:"qr-code",show:!0,text:"弹出二维码",icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
84
84
  <rect x="3" y="3" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
85
85
  <rect x="15" y="3" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
86
86
  <rect x="3" y="15" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
@@ -107,9 +107,9 @@ Minimum version required to store current data is: `+s+`.
107
107
  </svg>`},{action:"remote-url",show:!0,text:`${e.remoteUrl}`,tip:e.remoteUrl,showCopyIcon:!0,icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
108
108
  <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
109
109
  <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
110
- </svg>`}];class FT{constructor(t){if(this.isExpanded=!1,!t.sessionId)throw new Error("sessionId is required");this.options={...t,qrCodeUrl:t.qrCodeUrl||Hd,remoteUrl:t.remoteUrl||Fd},this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){var t;return(t=this.options.qrCodeUrl)!=null&&t.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){return t?Jd(this.options).map(n=>{const r=t.find(o=>o.action===n.action);return r?{...n,...r,show:r.show!==void 0?r.show:n.show}:n}):Jd(this.options)}init(){this.createFloatingBlock(),this.createDropdownMenu(),this.bindEvents(),this.addStyles()}createFloatingBlock(){this.floatingBlock=document.createElement("div"),this.floatingBlock.className="tiny-remoter-floating-block",this.floatingBlock.innerHTML=`
110
+ </svg>`}];class FT{constructor(t){if(this.isExpanded=!1,!t.sessionId)throw new Error("sessionId is required");this.options={...t,qrCodeUrl:t.qrCodeUrl||Fd,remoteUrl:t.remoteUrl||VT},this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){var t;return(t=this.options.qrCodeUrl)!=null&&t.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){return t?Hd(this.options).map(n=>{const r=t.find(o=>o.action===n.action);return r?{...n,...r,show:r.show!==void 0?r.show:n.show}:n}):Hd(this.options)}init(){this.createFloatingBlock(),this.createDropdownMenu(),this.bindEvents(),this.addStyles()}createFloatingBlock(){this.floatingBlock=document.createElement("div"),this.floatingBlock.className="tiny-remoter-floating-block",this.floatingBlock.innerHTML=`
111
111
  <div class="tiny-remoter-floating-block__icon">
112
- <img style="display: block; width: 56px;" src="${Hd}/svgs/logo-next-no-bg-left.svg" alt="icon" />
112
+ <img style="display: block; width: 56px;" src="${Fd}/svgs/logo-next-no-bg-left.svg" alt="icon" />
113
113
  </div>
114
114
  `,document.body.appendChild(this.floatingBlock)}createDropdownMenu(){this.dropdownMenu=document.createElement("div"),this.dropdownMenu.className="tiny-remoter-floating-dropdown";const t=this.menuItems.filter(n=>n.show!==!1).map(n=>`
115
115
  <div class="tiny-remoter-dropdown-item" data-action="${n.action}">
@@ -125,7 +125,7 @@ Minimum version required to store current data is: `+s+`.
125
125
  </div>
126
126
  `:""}
127
127
  </div>
128
- `).join("");this.dropdownMenu.innerHTML=t,document.body.appendChild(this.dropdownMenu)}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.toggleDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const n=t.target,r=n.closest(".tiny-remoter-copy-icon");if(r){t.stopPropagation();const a=r.dataset.action;a&&this.handleAction(a);return}const o=n.closest(".tiny-remoter-dropdown-item"),s=o==null?void 0:o.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",t=>{const n=t.target;!this.floatingBlock.contains(n)&&!this.dropdownMenu.contains(n)&&this.closeDropdown()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.closeDropdown()})}toggleDropdown(){this.isExpanded?this.closeDropdown():this.openDropdown()}openDropdown(){this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show")}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(t){switch(t){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard((this.options.remoteUrl||Fd)+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.left="-999999px",n.style.top="-999999px",document.body.appendChild(n),n.focus(),n.select();const r=document.execCommand("copy");document.body.removeChild(n),r?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(n){console.error("复制失败:",n),this.showCopyFeedback(!1)}}showCopyFeedback(t){const n=t?"复制成功!":"复制失败,请手动复制",r=document.createElement("div");r.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,r.textContent=n,document.body.appendChild(r),setTimeout(()=>r.classList.add("show"),10),setTimeout(()=>{r.classList.remove("show"),setTimeout(()=>{r.parentNode&&r.parentNode.removeChild(r)},300)},1500)}async showQRCode(){const n=await new Vd((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),r=this.createModal("扫码前往智能遥控器",`
128
+ `).join("");this.dropdownMenu.innerHTML=t,document.body.appendChild(this.dropdownMenu)}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.toggleDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const n=t.target,r=n.closest(".tiny-remoter-copy-icon");if(r){t.stopPropagation();const a=r.dataset.action;a&&this.handleAction(a);return}const o=n.closest(".tiny-remoter-dropdown-item"),s=o==null?void 0:o.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",t=>{const n=t.target;!this.floatingBlock.contains(n)&&!this.dropdownMenu.contains(n)&&this.closeDropdown()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.closeDropdown()})}toggleDropdown(){this.isExpanded?this.closeDropdown():this.openDropdown()}openDropdown(){this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show")}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(t){switch(t){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.left="-999999px",n.style.top="-999999px",document.body.appendChild(n),n.focus(),n.select();const r=document.execCommand("copy");document.body.removeChild(n),r?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(n){console.error("复制失败:",n),this.showCopyFeedback(!1)}}showCopyFeedback(t){const n=t?"复制成功!":"复制失败,请手动复制",r=document.createElement("div");r.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,r.textContent=n,document.body.appendChild(r),setTimeout(()=>r.classList.add("show"),10),setTimeout(()=>{r.classList.remove("show"),setTimeout(()=>{r.parentNode&&r.parentNode.removeChild(r)},300)},1500)}async showQRCode(){const n=await new Vd((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),r=this.createModal("扫码前往智能遥控器",`
129
129
  <div style="text-align: center; padding: 32px;">
130
130
  <!-- 二维码容器 - 添加渐变背景和阴影效果 -->
131
131
  <div style="
@@ -526,4 +526,4 @@ Minimum version required to store current data is: `+s+`.
526
526
  color: white;
527
527
  }
528
528
  }
529
- `,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const HT=(e={})=>new FT(e),JT=async e=>{const t={};try{const n=await e.listTools();for(const{name:r,description:o,inputSchema:s}of n.tools){const a=async(i,l)=>e.callTool({name:r,arguments:i},{signal:l==null?void 0:l.abortSignal});t[r]=_l({description:o,inputSchema:Bn({...s,properties:s.properties??{},additionalProperties:!1}),execute:a})}return t}catch(n){throw n}};Rt.AgentModelProvider=rT,Rt.QrCode=Vd,Rt.createRemoter=HT,Rt.getAISDKTools=JT,Object.defineProperty(Rt,Symbol.toStringTag,{value:"Module"})});
529
+ `,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const HT=(e={})=>new FT(e),JT=async e=>{const t={};try{const n=await e.listTools();for(const{name:r,description:o,inputSchema:s}of n.tools){const a=async(i,l)=>e.callTool({name:r,arguments:i},{signal:l==null?void 0:l.abortSignal});t[r]=_l({description:o,inputSchema:Bn({...s,properties:s.properties??{},additionalProperties:!1}),execute:a})}return t}catch(n){throw n}};Rt.AgentModelProvider=nT,Rt.QrCode=Vd,Rt.createRemoter=HT,Rt.getAISDKTools=JT,Object.defineProperty(Rt,Symbol.toStringTag,{value:"Module"})});